/// <reference path="jquery-1.4.1.min.js" />
var MousePos = {};
var changeLoc_pop;

function showLoad() {
    $('#loading')
	    .css(
	    {
	        'top': [MousePos.Y, 'px'].join(''),
	        'left': [MousePos.X, 'px'].join('')
	    })
	    .fadeIn('fast');

}

function closeLoad() {
    $('#loading').fadeOut('fast');
}

var logreg;

$(document).ready(function() {

    $('body').bind('mousemove', function(e) {
        MousePos = { X: e.pageX, Y: e.pageY };
    });

    logreg = $('#logreg').overlay({
        oneInstance: true,
        zIndex: 999,
        closeOnClick: false,
        api: true
    });

    $("#logout").live('click', function() {
        $.ajaxSetup({ cache: false });
        $.getJSON("/User/Logout", "",
                    function(data) {
                        window.location='/';
                    });
    });

    var pop_after_reg = $('#pop_after_reg').overlay({
        oneInstance: true,
        zIndex: 999,
        closeOnClick: false,
        api: true
    });

    $("#pop_after_reg_ok").click(function() {
        pop_after_reg.close();
    });

    var pass_reminder_pop = $('#pass_reminder_pop').overlay({
        oneInstance: true,
        zIndex: 999,
        api: true,
        closeOnClick: false,        
    });
    $('#exit_pop').click(function() {
        pop_after_reg.close();
        //window.location.reload();
    });

    $('#registration').click(function() {
        $('#header-box-registering').css('display', 'block');
    });

    $('#registerTab').click(function() {
        $('#header-box-registering').css('display', 'block');
    });

    $('#registeLink').click(function() {
        $('#header-box-logging').css('display', 'none');
        $('#header-box-registering').css('display', 'block');
    });

    $('#login').click(function() {
        $('#header-box-logging').css('display', 'block');
    });

    $('#loginTab').click(function() {
        $('#header-box-logging').css('display', 'block');
    });

    $(document).click(function(event) {
        if ($(event.target).closest('#registerTab').length == 0 && $(event.target).closest('#header-box-registering').length == 0 && $(event.target).closest('#header-box').length != 1 && $(event.target).closest('#registeLink').length != 1 && $(event.target).closest('#regPop').length != 1)
            $('#header-box-registering').css('display', 'none');
    });

    $(document).click(function(event) {
        if ($(event.target).closest('#loginTab').length == 0 && $(event.target).closest('#header-box-logging').length == 0 && $(event.target).closest('#header-box').length != 1 && $(event.target).closest('#logPop').length != 1)
            $('#header-box-logging').css('display', 'none');
    });

    var returnReg = true;

    $('#errorReg').hide();
    $("#sub_reg").click(function() {
        returnReg = true;
        $('#errorReg').hide();

        try {
            if ($('#pers_data_accept:checked').val() != 'on') {
                $("#errorReg").html('Wyraź zgodę na przetwarzanie danych');
                $('#errorReg').show();
                returnReg = false;
            }
            if ($('#reg_accept:checked').val() != 'on') {
                $("#errorReg").html('Zaakceptuj regulamin');
                $('#errorReg').show();
                returnReg = false;
            }

        } catch (err) { }

        if ($('#passwordReg').val().length < 6) {
            $("#errorReg").html('Hasło jest za krótkie');
            $('#errorReg').show();
            returnReg = false;
        }

        if ($('#user_nameReg').val().length < 3) {
            $("#errorReg").html('Nazwa jest za krótka');
            $('#errorReg').show();
            returnReg = false;
        }

        $.ajaxSetup({ cache: false });
        var data = { 'emailReg': $('#emailReg').val() }
        $.getJSON("/User/CheckEmail", data,
                function(data) {
                    if (data[0] == "ERROR") {
                        $("#errorReg").html('Podany adres e-mail istnieje w Portalu!');
                        $('#errorReg').show();
                        returnReg = false;
                    }
                });

        var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test($('#emailReg').val()) == false) {

            $("#errorReg").html('Niepoprawny adres e-mail');
            $('#errorReg').show();
            returnReg = false;
        }

        if (returnReg == true) {
            $.ajaxSetup({ cache: false });
            var data = { 'emailReg': $('#emailReg').val(), 'passwordReg': $('#passwordReg').val(), 'user_nameReg': $('#user_nameReg').val(), 'course_accept': $('#course_accept:checked').val(), 'remember_me': $('#remember_me:checked').val() }
            showLoad();
            $.getJSON("/User/Registration", data,
                function(data) {
                    closeLoad();
                    if (data[0] == 'NickNoAvailable') {
                        $("#errorReg").html('Nazwa użytkownika jest już niedostępna');
                        $('#errorReg').show();
                        return false;
                    }
                    if (data[0] == "ERROR") {
                        $("#errorReg").html('Adres email jest już zarejestrowany w serwisie');
                        $('#errorReg').show();
                        return false;
                    }
                    if (data[0] == "OK") {
                        $('#errorReg').hide();
                        $("#logA").val('1');
                            if ($("#next2").css("display") == "block") 
                            {
                                $("#addReqAlert").html('Kliknij Dalej by dokończyć dodawanie prośby');
                            }
                        pop_after_reg.load();
                    }
                });
        } else {
            return false;
        }
    });

    $('#loginForm').submit(function() {
        returnReg = true;
        $('#errorLog').hide();
        var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test($('#emailLog').val()) == false) {
            $("#errorLog").html('Niepoprawny adres Email');
            $('#errorLog').show();
            returnReg = false;
        }

        if ($('#passLog').val().length < 1) {
            $("#errorLog").html('Uzupełnij hasło');
            $('#errorLog').show();
            returnReg = false;
        }


        if (returnReg == true) {
            $.ajaxSetup({ cache: false });
            var data = { 'emailLog': $('#emailLog').val(), 'passLog': $('#passLog').val(), 'remember_me_log': $('#remember_me_log:checked').val(),'page':window.location.pathname,'redirect':window.location.search.toString()};
            showLoad();
            $.getJSON("/User/LoginUser", data,
                function(data) {
                    closeLoad();
                    if (data[0] == 'ERROR') {
                        $("#errorLog").html(data[1]);
                        $('#errorLog').show();
                       
                    }
                    if (data[0] == 'OK') {
                        $('#errorLog').hide();

                        if ($("#add").val() != "1")
                            window.location.reload();
                        else {
                            $("#header-box").html(data[1]);
                            $("#header-box").removeClass("logout");
                            $("#header-box").addClass("login");
                        }
                        $("#logA").val('1');
                        $('#header-box-logging').css('display', 'none');
                        
                    }
                    if(data[0]=='REDIRECT'){
                        window.location=data[1];
                    }
                });
        } 

        return false;
    });

    $('#pass_reminder').click(function() {
        $('#RemContent2').css("display","none");                        
        $('#RemContent').css("display","block");           
        pass_reminder_pop.load();
    });

    $('#closeRem').click(function() {
        pass_reminder_pop.close();
    });

    $('#RemContent2_ok').click(function() {
        pass_reminder_pop.close();
    });



    $('#SendRemind').click(function() {

        var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test($('#emailRem').val()) == false) {
            $("#errorRem").html('Niepoprawny adres Email');
            $('#errorRem').show();
            returnReg = false;
        } else {
            $('#errorRem').hide();
            $.ajaxSetup({ cache: false });
            var data = { 'emailRem': $('#emailRem').val() }
            $.getJSON("/User/PassRem", data,
                function(data) {
                    if (data[0] == "ERROR") {
                        $("#errorRem").html(data[1]);
                        $('#errorRem').show();
                        return false;
                    }
                    if (data[0] == "OK") {
                        $('#errorRem').hide();
                        $('#RemContent').css("display","none");                        
                        $('#RemContent2').css("display","block");                        
                    }
                });
        }
    });

   

    var big_baloon = $('.big_baloon');
    var zoom;
    $('.zoom').live('click', function() {
        zoom = $(this);
        $('.big_baloon').each(function() {
            $(this).css('display', 'none');
        });
        big_baloon = $(this).parent().next();
        big_baloon.css('display', 'block');
    });

    $(document).click(function(event) {
        if ($(event.target).closest('.zoom_out').length != 0 || ($(event.target).closest('.big_baloon').length == 0 && $(event.target).closest('.zoom').length != 1))
            big_baloon.css('display', 'none');
    });

    $(".user-info").live('mouseenter', function() {
        var baloon2 = $(this).next().next().next().html();
        var baloon1 = $(this).next().html();
        $(this).next().next().next().html(baloon1);
        $(this).next().html(baloon2);
    });

    $(".user-info").live('mouseleave', function() {
        var baloon2 = $(this).next().next().next().html();
        var baloon1 = $(this).next().html();
        $(this).next().next().next().html(baloon1);
        $(this).next().html(baloon2);
    });

    

    $("#closePop").click(function() {
        logreg.close();
    });

    $("#logPop").click(function() {
        logreg.close();
        $('#header-box-logging').css('display', 'block');
        $('#emailLog').focus();
    });

    $("#regPop").click(function() {
        logreg.close();
        $('#header-box-registering').css('display', 'block');
    });

    

    $("#back1").live('click', function() {
        $("#categories").css('display', 'block');
        $("#tagsChoose").css('display', 'none');
        $("#LastStep").css('display', 'none');
    });

    $("#back2").live('click', function() {
        $("#categories").css('display', 'none');
        $("#tagsChoose").css('display', 'block');
        $("#LastStep").css('display', 'none');
        //$("#next2").css("display", "none");
    });

    $("#want_help").live('click', function() {
        if ($("#want_help").is(":checked")) {
            showLoad();
            $.ajaxSetup({ cache: false });
            var data = { 'decide': 3 };
            $.getJSON("/User/IWantHelp", data,
                function(data) {
                    if (data[0] == "OK") {

                        closeLoad();
                    }
                });
        } else {
            showLoad();
            $.ajaxSetup({ cache: false });
            var data = { 'decide': 2 };
            $.getJSON("/User/IWantHelp", data,
                    function(data) {
                        if (data[0] == "OK") {

                            closeLoad();
                        }
                    });
        }
    });

    $("#phrase").live('click', function() {
        $("#hs_cloud").fadeIn('slow');
    });

    $(document).click(function(event) {
        if ($(event.target).closest('#search_form_master').length == 0)
            $("#hs_cloud").fadeOut('slow');
    });

    $(".i_help").live('click', function() {
        $("#jp_cloud").fadeIn('slow');
    });

    $(document).click(function(event) {
        if ($(event.target).closest('.i_help').length == 0)
            $("#jp_cloud").fadeOut('slow');
    });

    $(".help_me").live('click', function() {
        $("#mp_cloud").fadeIn('slow');
    });

    $(document).click(function(event) {
        if ($(event.target).closest('.help_me').length == 0)
            $("#mp_cloud").fadeOut('slow');
    });


    $("#saveLocalization").click(function() {
        showLoad();
        $.ajaxSetup({ cache: false });
        var data = { 'x': $("#x").val(), 'y': $("#y").val(),'showLocal':$('#showLocal:checked').val()};
        $.post("/User/SaveLoc", data,
                    function(data) {
                        closeLoad();
                        if (data[0] == "OK") {
                            $("#okLocalization").html("zmiany zapisane");
                            changeLoc_pop.close();
                            $("#optionReq").submit();
                        }
                    });
    });

    changeLoc_pop = $('#localizationLayer').overlay({
        oneInstance: true,
        zIndex: 999,
        closeOnClick: false,
        api: true
    });

    $('#closeLayerLoc, #closeLocalization').click(function() {
        changeLoc_pop.close();
    });
    
    var query = window.location.search;    if (query.indexOf('?redirect=') >= 0) {        logreg.load();    }            if($("#logA").val()=='1'){        setTimeout(beacon,1000);    }
});


function beacon(){
    $.get('/user/beacon',function(){
        setTimeout(beacon,60000);
    });
}

$(function() {
    $('#menuSendRequest>textarea').focus(function() {

        if ($(this).val() == 'Tutaj wpisz treść swojej prośby...') {
            $(this).val('');
        }
    });

    $('#menuSendRequest>textarea').blur(function() {
        if ($(this).val().length > 0) {
        } else {
            $(this).val('Tutaj wpisz treść swojej prośby...');
        }

    });
    //fix for chrome
    var MenuIdActElem;
    $('#newRequestContent').mouseover(function() {
        clearTimeout(Menu.time);
        Menu.$navContent.find(Menu.translation(MenuIdActElem, 'button')).addClass('act');
    });

    var Menu =
    {
        hideBox: 1,
        time: null,
        $navContent: $('#nav-content'),
        fadeSpeed: 150,
        translation: function(from, type) {
            switch (type) {
                case 'box':
                    return ['#', from.substring(0, from.length - 1), 'area'].join('');
                    break;

                case 'button':
                    return ['#', from.substring(0, from.length - 4), 'b'].join('');
                    break;
            }
        },
        init: function() {
            Menu.$navContent.find('>div').css({ 'opacity': '0' });
            Menu.$navContent.bind('mouseover mouseout', function(e) {
                var This = e.target,
		$this = $(This),
		boxId = Menu.translation(This.id, 'box');

                switch (e.type) {
                    case 'mouseover':
                        if ($this.is('a.menu-button')) {
                            if (Menu.hideBox == '#' + This.id && Menu.$navContent.find(boxId).css('display')=='block') {
                                clearTimeout(Menu.time);
                                Menu.$navContent.find('>div:not(#' + boxId + ')').hide();
                                $this.addClass('act');
                                return;
                            }
                            Menu.$navContent.find('>div:not(#' + boxId + ')').hide();
                            $this.addClass('act');
                            Menu.$navContent.find(boxId).css({ 'display': 'block', 'opacity': '0' }).animate({ 'opacity': '1' }, { duration: Menu.fadeSpeed, queue: false });
                        }

                        if ($this.is('div.top')) {
                            clearTimeout(Menu.time);
                            Menu.$navContent.find(Menu.translation($this.parent('div.menuBox').attr('id'), 'button')).addClass('act');
                        }
                        break;

                    case 'mouseout':
                        if ($this.is('a')) {
                            $this.removeClass('act');
                            Menu.time = setTimeout(function() {
                                Menu.$navContent.find(boxId).fadeOut(Menu.fadeSpeed);
                            }, 50);
                        }
                        break;
                }
            });

            Menu.$navContent.find('div.menuBox').bind('mouseleave', function() {
                var $this = $(this),
                thisId = this.id;
                MenuIdActElem = thisId;
                Menu.$navContent.find(Menu.translation(thisId, 'button')).removeClass('act');
                Menu.hideBox = Menu.translation(thisId, 'button'); //this.id;
                Menu.time = setTimeout(function() {
                    $this.fadeOut(Menu.fadeSpeed);

                }, 100);
                Menu.hideBox = Menu.translation(thisId, 'button');
            });
        }
    };
    Menu.init();
});

$(function() {

    var act_req;

    $(".home_req_page").click(function() {

        clicked_req = $(this).html();
        act_req = $(".act").html();

        if (act_req != clicked_req) {
            $("#req" + act_req).css("display", "none")
            $("#req" + clicked_req).fadeIn("slow");
            $(".act").removeClass("act");
            $(this).addClass("act");
        }

    });

    $(".prev_req").click(function() {

        act_req = parseInt($(".act").html());
        if (act_req == 1)
            prev_req = 10;
        else
            prev_req = act_req - 1;

        $("#req" + act_req).css("display", "none")
        $("#req" + prev_req).fadeIn("slow");
        $(".act").removeClass("act");
        $("#req_link" + prev_req).addClass("act");
    });

    $(".next_req").click(function() {

        act_req = parseInt($(".act").html());
        if (act_req == 10)
            next_req = 1;
        else
            next_req = act_req + 1;
     
        $("#req" + act_req).css("display", "none")
        $("#req" + next_req).fadeIn("slow");
        $(".act").removeClass("act");
        $("#req_link" + next_req).addClass("act");
    });
    
    //Taby
    $('li[ref]').click(function() {
        $(this).siblings().removeClass('act');
        $(this).addClass('act');
        $('div.'+$(this).parent().attr('ref')).css('display', 'none');
        $('div[ref="' + $(this).attr('ref') + '"]').css('display', 'block');
    });
    
    
    var hash = window.location.hash;
    if (hash.indexOf('login') >= 0) {
        $('#login').click();
    } else if (hash.indexOf('register') >= 0) {
        $('#registeLink').click();
    }
    

});


$(function() {
               
         $('#sendInv').click(function() {
            $('#tAlert').css('display', 'none');
             $('#sendInv').attr('disabled','disabled');
             var emails = $('#emailsAddr').val();
             var emailList = emails.split(',');
             var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
             for (var i=0;i<emailList.length;i++) {
                 if (reg.test(emailList[i].trim()) == false) {
                    $('#tAlert').css('display', 'block');
                    $('#sendInv').removeAttr('disabled');
                    return;
                 }
             }
             
           
             
             
             var data={'emails': emails,'text':$('#InvateText').val()};
             
             $.post('/ludzie/sendInv',data,function(data){
                if(data[0]=="OK"){
                    OkPopup.load();
                    $('#sendInv').removeAttr('disabled');
                    
                }
             });
             

         });
         
         $('#emailsAddr').focus(function(){
            $('#tAlert').css('display', 'none');            
         });
     });
