var timeout         = 50;
var closetimer		= 0;
var ddmenuitem      = 0;

function jsddm_open()
{
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');
}

function jsddm_close()
{
    if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer()
{
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer()
{
    if(closetimer)

    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

$(document).ready(function()
{
    $('.jsddm > li').bind('mouseover', jsddm_open);
    $('.jsddm > li').bind('mouseout',  jsddm_timer);
});

document.onclick = jsddm_close;



//rowijanie faqa

$(document).ready(function(){
    $(".faq > li > a").click(function ()
    {
        $(this).toggleClass("faq_cz").next().toggle("fast");
	
    });

});

//-----------------------------------------------------------------

function wwAddLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function searchAndFocus(eleArr, editName) {
    for (var i = 0; i < eleArr.length; i++) {
        var ele = eleArr[i];
        if (ele.name == editName) {
            ele.focus();
            return true;
        }
    }
    return false;
}

function setInitialFocus(editName) {
    wwAddLoadEvent(function () {
        searchAndFocus(document.getElementsByTagName('input'), editName) ||
        searchAndFocus(document.getElementsByTagName('textarea'), editName);
    });
}

// {"selector1": "html1", "selector2": "html2"}
// { "#u100": "<div>dupa</div>"}
function updatePageElems(updItems) {
    var mustAjaxifyAll = false;

    $.each(updItems, function (key, val) {
        /*if (key == "") {
            alert("empty key");
            return;
        }*/
        //logDebug("before replace: key=" + key + ", val=" + val);
        if (key != "") {
            $(key).fadeOut(function () {
                //$(this).replaceWith(val);
                //ajaxify($(val).replaceAll(this));
                ajaxify(
                    $(val).replaceAll(this).parent()
                    );
            
            });
        } else {
            mustAjaxifyAll = true;
        }
    //logDebug("after replace: key=" + key + ", val=" + val);
    });

    if (mustAjaxifyAll) {
        ajaxify();
    }
//$("#test-ajax").replaceWith("<span>REPLACED</span>");
}

function logDebugEnabled() {
    return false;
}

function logDebug(msg, forceLog) {
    if (forceLog || logDebugEnabled()) {
        alert("logDebug: " + msg);
    }
}

// eval("{'aaa':10, 'bbb':20}") ---> {'aaa':10, 'bbb':20}.each(...)
function naqnaqAjaxCall(ajaxUrl) {
    //alert("before ajaxCall: " + ajaxUrl);
    $.ajax({
        type: "POST",
        url: ajaxUrl,
        success: function(msg){
            logDebug("naqnaqAjaxCall (url=" + ajaxUrl + "): success, msg=" + msg);
            var obj = eval("(" + msg + ")");
            //logDebug( "Data Saved: " + msg + "\n\nobj=\n" + obj );
            updatePageElems(obj);
        //logDebug("after update");
        }
    });
}

function wwTestAjaxCall() {
    $.ajax({
        type: "POST",
        url: ajaxBaseUrl,
        data: {
            "xxx": "jacek i agatka"
        },
        success: function(msg){
            var obj = eval(msg);
            //logDebug( "Data Saved: " + msg + "\n\nobj=\n" + obj );
            updatePageElems(obj);
        //logDebug("after update");
        }
    });
}

// /page=action_votePositiv&objKind=q&objId=100
// /page=action_ajaxSuperAction&act=action_votePositiv&objKind=q&objId=100
function ajaxifyUrl(url) {
    //return //"http://localhost:8084" +
    return url.replace(/([&?])page=([^&]+)/, "$1page=action_ajaxSuperAction&act=$2").
    replace(new RegExp('([.]*)/(pl|en)/([^/]+)'), '$1/$2/action_ajaxSuperAction/act_$3');
}

function ajaxify(optCont) {
    if (logDebugEnabled()) {
        var sss = null;
        if (optCont != null) {
            sss = "";
            var arr = optCont.get();
            for (var i = 0; i < arr.length; i++) {
                sss += " " + $(arr[i]).html();
            }
        }
        logDebug("called ajaxify, with optCont=" + sss);
    }

    $(".ajaxifiable a, a.ajaxifiable", optCont).each(
        function () {
            if ($(this).hasClass("ajaxified")) {
                return;
            }
            logDebug("called for unajaxified: " + $(this).attr("href"));
            $(this).click(function () {
                var url = this.getAttribute("href");
                var ajaxifiedUrl = ajaxifyUrl(url);
                logDebug("clicked on ajaxifiable url=" + url +
                    "\najaxified url=" + ajaxifiedUrl);
                naqnaqAjaxCall(ajaxifiedUrl);
                logDebug("after ajax call (async pending!)");
                return false;
            }).addClass("ajaxified");
        }
        );
    $(".ajaxifiable input[type='submit'], input[type='submit'].ajaxifiable", optCont).each(
        function () {
            //alert('uuu');
            //alert('found ajaxifiable submit button, value=' + this.value +
            //', of form with action=' + this.form.action);
            if ($(this).hasClass("ajaxified")) {
                return;
            }
            logDebug("called for unajaxified: " + $(this).attr("href"));
            $(this).click(function () {
                var url = this.form.action;
                var ajaxifiedUrl = ajaxifyUrl(url) + '&' + $(this.form).serialize();
                //logDebug("clicked on ajaxifiable submit button, form url=" + url +
                //    "\najaxified url=" + ajaxifiedUrl, true);
                naqnaqAjaxCall(ajaxifiedUrl);
                logDebug("after ajax call (async pending!)");
                return false;
            }).addClass("ajaxified");
        }
        );
//click();
}

$(document).ready(function () {
    ajaxify();
});



function wwGrowl(title, message, timeout, onClose) {
    var $m = $('<div class="growlUI"></div>');
    if (title) $m.append('<h1>'+title+'</h1>');
    if (message) $m.append('<h2>'+message+'</h2>');
    if (timeout == undefined) timeout = 3000;
    $.blockUI({
        message: $m,
        fadeIn: 700,
        fadeOut: 1000,
        centerY: false,
        timeout: timeout,
        showOverlay: false,
        onUnblock: onClose,
        css: {
            width:  	'350px',
            top:		'10px',
            left:   	'',
            right:  	'10px',
            border: 	'none',
            padding:	'5px',
            opacity:	0.9,
            cursor: 	'default',
            color:		'#fff',
            backgroundColor: '#444',
            '-webkit-border-radius': '10px',
            '-moz-border-radius':	 '10px',
            'border-radius': 		 '10px'
        }
    });
}

function showNaqnaqMsg(msg) {
    //alert("mesydż from naqnaq: " + msg);
    wwGrowl(null,//'Let\'s growl!',
        msg);
}

function showNaqnaqModal(html) {
    $.blockUI({
        message: $("<div class='naqnaqModalContainter'>" + html + "</div>"), //"<div>aqq</div>",
        css: {
            cursor: 'arrow',
            width: '800px',
            height: '800px',
            top: '100px',
            left: '100px'
        },
        centerY: true,
        centerX: true,
        overlayCSS:  {
            cursor: 'arrow'
        }
    });

/*
    alert("showNaqnaqModal: " + html);
    var ele = $(html);
    alert("showNaqnaqModal: ele evaluated" + ele);
    $.blockUI(ele);
    alert("showNaqnaqModal: after ui block invoked");
*/
}

function hhhblockui() {
    $.blockUI({
        message: $("#loginHolder"), //"<div>aqq</div>",
        css: {
            cursor: 'arrow',
            width: '800px',
            height: '800px'
        },
        overlayCSS:  {
            cursor: 'arrow'
        }
    });
/*
    //$.blockUI(".zboczekBottom");
    $.blockUI({
        message: $(".zboczekBottom"), //"<div>aqq</div>",
        css: {
            cursor: 'arrow',
            width: '500px',
            height: '500px'
        },
        overlayCSS:  {
            cursor: 'arrow'
        }
    });
    */
}

function makeUrlToAjaxAction(actName) {
    return ajaxActionBaseUrl + "&act=" + actName;
}

function performAjaxLogin() {
    $(".errorMsgOnForm").fadeOut();
    //alert('ajax login start');
    var s = $("#loginForm").serialize();
    //alert('ajax login start, serialized form: ' + s);

    naqnaqAjaxCall(makeUrlToAjaxAction("action_login") + "&" + s);

    return false;
}

function ajaxifyLoginForm() {
    $('#loginSubmitBtn').click(performAjaxLogin);    
}

var isChangingPageStarted = false;

function reloadCurrentPage() {
    isChangingPageStarted = true;
    window.location.reload();
}

function internalShowFormNotification(forError, msg) {
    $(".errorMsgOnForm").html(msg).fadeIn();
}

function showFormErrorNotification(msg) {
    internalShowFormNotification(true, msg);
}

function showFormInfoNotification(msg) {
    internalShowFormNotification(false, msg);
}

function openNaqnaqPopup(url) {
    //alert("aaaaa");
    var naqnaqPopupWindow = window.open(url, 'loginPopup', 'width=500,height=500');
    var x = 0;

    var f = function () {
        if (naqnaqPopupWindow && !naqnaqPopupWindow.closed) {
            //showFormInfoNotification("w is still there #" + (x++));
            showFormInfoNotification("Czekam na dokończenie procesu logowania w nowym oknie...");
            setTimeout(f, 1000);
        } else {
            showFormInfoNotification("Nowe okno z logowaniem zamknięte, kontynuuję proces...");
            naqnaqAjaxCall(makeUrlToAjaxAction("afterLoginPopupClose"));
        }
    }

    setTimeout(f, 1000);

    //alert('timeout is set, before finish of openNaqnaqPopup()');
    
    if (window.focus) {
        naqnaqPopupWindow.focus()
    };
    
    return false;
}

function closeModalBox() {
    $.unblockUI();
    return false;
}

$(document).ready(function() {
    var eles =
    $('[title]').filter(function(){
        return this.title != "";
    });

    eles.each(function(){
        var grav = $.fn.tipsy.autoNS;
        if ($(this).hasClass("tipsyW")) {
            grav = "w";
        } else if ($(this).hasClass("tipsyE")) {
            grav = "e";
        } else if ($(this).hasClass("tipsyS")) {
            grav = "s";
        }
        $(this).tipsy({
            gravity: grav,
            fade: true
        });
    });

/*.not(".tipsyW, .tipsyS, .tipsyE").tipsy({
        }
        gravity: $.fn.tipsy.autoNS,
        fade: true
    });
    $('[title].tipsyW').tipsy({
        gravity: 'w',
        fade: true
    });
    $('[title].tipsyE').tipsy({
        gravity: 'e',
        fade: true
    });
    $('[title].tipsyS').tipsy({
        gravity: 's',
        fade: true
    });
    */
});

var isUserLoggedIn = loggedUserName != "";

/*
if (isUserLoggedIn) {
    alert('logged user: ' + loggedUserName);
} else {
    alert('no logged user!');
}
*/

function openLoginRegisterRemindModal(activeTab) {
    //alert('openLoginRegisterRemindModal: ' + activeTab);
    //$('#loginRegisterRemindBoxInnerHolder').empty().append($('#loginRegisterRemindBox_' + activeTab).clone());
    setLoginRegisterRemindModalActiveTab(activeTab);
    //alert('openLoginRegisterRemindModal: ' + activeTab + " #2");

    var w = 700;
    var h = 374;
    var wW = getWindowWidth();
    var wH = getWindowHeight();

    $.blockUI({
        message: //$("<div class='naqnaqModalContainter'>" + html + "</div>"), //"<div>aqq</div>",
        $('#loginRegisterRemindModal'),
        css: {
            cursor: 'arrow',
            width: w + 'px',
            height: h + 'px',
            top: ((wH - h) / 2) + 'px',
            left: ((wW - w) / 2) + 'px'
        },
        centerY: true,
        centerX: true,
        overlayCSS:  {
            cursor: 'arrow'
        }
    });
//alert('openLoginRegisterRemindModal: ' + activeTab + " #3");
}

function setLoginRegisterRemindModalActiveTab(activeTab) {
    //alert('setLoginRegisterRemindModalActiveTab: ' + activeTab);
    //$('#loginRegisterRemindBoxInnerHolder').empty().append($('#loginRegisterRemindBox_' + activeTab).clone());
    $('#loginRegisterRemindBoxInnerHolder').fadeOut(100, function () {
        $(".errorMsgOnForm").html("")//.hide()
        ;
        $('#loginRegisterRemindBoxInnerHolder').empty().append($('#loginRegisterRemindBox_' + activeTab).clone(true));
        $('#loginRegisterRemindBoxInnerHolder').fadeIn(100);
    });

    //alert('setLoginRegisterRemindModalActiveTab: ' + activeTab + '#2');
    $('.lrrbh_tab_link').each(function () {
        if (this.id.indexOf(activeTab) != -1) {
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
}

function setupLoginRegisterRemindModal() {
    //    $('#abcXYZ_123').click(function() {
    //        alert('#abcXYZ_123');
    //    });

    //    $('#forgotPassLink').click(function() {
    //        alert('aaaXXX');
    //        setLoginRegisterRemindModalActiveTab('remind');
    //        return false;
    //    });
    $('.login_link').click(function() {
        //try {
        openLoginRegisterRemindModal('login');
        //} catch(e) {
        //    alert('error: ' + e.message);
        //}
        return false;
    });
    $('.register_link').click(function() {
        openLoginRegisterRemindModal('register');
        return false;
    });

    $('.login_tab_link').click(function() {
        setLoginRegisterRemindModalActiveTab('login');
        return false;
    });
    $('.register_tab_link').click(function() {
        setLoginRegisterRemindModalActiveTab('register');
        return false;
    });
    //    alert('uuu');
    //    $('.remind_tab_link').each(function () {
    //        alert('abc: class=' + this.className);
    //        //this.text(this.text() + 'aqq!');
    //    });
    //    alert('uuu2');
    $('.remind_tab_link').click(function() {
        //        alert('aaa');
        setLoginRegisterRemindModalActiveTab('remind');
        return false;
    });

}

if (!isUserLoggedIn) {
    $(document).ready(function() {
        setupLoginRegisterRemindModal();
    });
}

//var h = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
//var w = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;

function getWindowHeight() {
    return window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
}

function getWindowWidth() {
    return window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
}

