﻿/// <reference path="jquery-jtemplates.js" />

var records = 0;
var pagesize = 5;
var currentPage = 0;

function pageLoad() {
    if ($('.homesection').is(':visible')) {
        getHomePage();
    }
    if ($('.photogalsection').is(':visible')) {
        var pg = window.location.hash.split("=");
        if (pg[0] == '#page') {
            $("#loadinggal").show();
            currentPage = parseInt(pg[1]) - 1;
            getRecords(currentPage);
            getGallery(currentPage, pagesize);
        }
    }
    if ($('.videogalsection').is(':visible')) {
        var pg = window.location.hash.split("=");
        if (pg[0] == '#page') {
            $("#loadinggal").show();
            currentPage = parseInt(pg[1]) - 1;
            getRecordsVid(currentPage);
            getGalleryVid(currentPage, pagesize);
        }    
    }
    if ($('.kontaktsection').is(':visible')) alert('kontakt');
    Sys.Application.add_navigate(UserNavigate);
}
function UserNavigate(sender, e) {
    var state = e.get_state();
    var url = window.location.toString();
    $("#loadinggal").show();
    if (url.indexOf("photogal") > 0) {
        if (state.page != undefined) {
            $('#repeater').empty();
            var maxpages = Math.ceil(records / pagesize);
            $(".Navigationa").empty();
            $(".Navigationb").empty();
            currentPage = parseInt(state.page) - 1;
            loadPages(currentPage, maxpages, pagesize, $(".Navigationa"), $(".upperpageinfo"));
            loadPages(currentPage, maxpages, pagesize, $(".Navigationb"), $(".bottompageinfo"));
            getGallery(state.page - 1, pagesize);
        } else {
        }
    }
    if (url.indexOf("videogal") > 0) {
        if (state.page != undefined) {
            $('#repeater').empty();
            var maxpages = Math.ceil(records / pagesize);
            $(".Navigationa").empty();
            $(".Navigationb").empty();
            currentPage = parseInt(state.page) - 1;
            loadPages(currentPage, maxpages, pagesize, $(".Navigationa"), $(".upperpageinfo"));
            loadPages(currentPage, maxpages, pagesize, $(".Navigationb"), $(".bottompageinfo"));
            getGalleryVid(state.page - 1, pagesize);
        } else {
        }
    }    
}
function getRecords(current) {
    $.ajax({
        type: "POST",
        url: "/services/PhotoService.asmx/GetRecordsCount",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            records = data.d;
            loadPages(current, Math.ceil(records / pagesize), pagesize, $(".Navigationa"), $(".upperpageinfo"));
            loadPages(current, Math.ceil(records / pagesize), pagesize, $(".Navigationb"), $(".bottompageinfo"));
        }
    });
}
function getRecordsVid(current) {
    $.ajax({
        type: "POST",
        url: "/services/VideoService.asmx/GetRecordsCount",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            records = data.d;
            loadPages(current, Math.ceil(records / pagesize), pagesize, $(".Navigationa"), $(".upperpageinfo"));
            loadPages(current, Math.ceil(records / pagesize), pagesize, $(".Navigationb"), $(".bottompageinfo"));
        }
    });
}
function getGallery(page, pagesize) {
    var data = '{"page":"' + page + '",' + '"pagesize":"' + pagesize + '"}';
    $.ajax({
        type: "POST",
        url: "/services/PhotoService.asmx/FillRepeater",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            ApplyTemplate(data, "photogal");
        }
    });
}
function getGalleryVid(page, pagesize) {
    var data = '{"page":"' + page + '",' + '"pagesize":"' + pagesize + '"}';
    $.ajax({
        type: "POST",
        url: "/services/VideoService.asmx/FillRepeater",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            ApplyTemplate(data, "videogal");
        }
    });
}
function loadPages(current, allpages, pagesize, navplace, pageinfo) {
    var offset = 2;
    var numberoflinks = 5;

    var sp = document.createElement("span");
    sp.innerHTML = "Pages: ";
    navplace.append(sp);
    pageinfo.text((parseInt(currentPage)+1) + ' of ' + allpages);
    if (current > numberoflinks - offset - 1) {
        addLink(0, navplace, pageinfo);
        var el = document.createElement("span");
        el.innerHTML = "...";
        navplace.append(el);
    }
    if (allpages < numberoflinks) numberoflinks = allpages;
    for (var i = 0; i < numberoflinks; i++) {
        if (current < offset) {
            addLink(i, navplace, pageinfo);
        } else {
            if (current - offset + i < allpages) {addLink(current - offset + i, navplace); }
        }
    }
    if (allpages > numberoflinks) {
        if (current < allpages - offset - 1) {
            var el = document.createElement("span");
            el.innerHTML = "...";
            navplace.append(el);
            addLink(allpages - 1, navplace, pageinfo);
        }
    }
}
function addLink(i, navplace, pageinfo) {
    if (i == currentPage) {
        var el = document.createElement("span");
        el.className = "pagingbuttonselected";
        el.innerHTML = i + 1;
        navplace.append(el);
    } else {
        var el = document.createElement("a");
        el.rel = i;
        el.onclick = function() {
            currentPage = this.rel;
            Sys.Application.addHistoryPoint({ 'page': parseInt(currentPage) + 1 }, null);
        };
        el.innerHTML = i + 1;
        navplace.append(el);
        el.href = "javascript:void(0)";
    }
}
function getHomePage() {
    $.ajax({
        type: "POST",
        url: "/services/PhotoService.asmx/FillRecent",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            ApplyTemplate(data, "home");
        }
    });
    $.ajax({
        type: "POST",
        url: "/services/VideoService.asmx/FillRecent",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            ApplyTemplate(data, "homevideo");
        }
    });    
}
function ApplyTemplate(data, temp) {
    if (temp == "photogal") {
        $('#repeater').setTemplateURL('/templates/photogaltable.htm', null, { filter_data: false });
        $('#repeater').processTemplate(data);
    }
    if (temp == "home") {
        $('.latelyaddedp').setTemplateURL('/templates/hometemp.htm', null, { filter_data: false });
        $('.latelyaddedp').processTemplate(data);
    }
    if (temp == "homevideo") {
        $('.latelyaddedv').setTemplateURL('/templates/hometempvideo.htm', null, { filter_data: false });
        $('.latelyaddedv').processTemplate(data);
    }
    if (temp == "videogal") {
        $('#repeater').setTemplateURL('/templates/videogal.htm', null, { filter_data: false });
        $('#repeater').processTemplate(data);
    }
    $("#loadinggal").hide();
}

$(document).ready(function() {
    var linklogowanie = $("#logbut a:last");
    var linkrejestracja = $("#logbut a:first");
    var modallogin = $('#modallogin');
    var modalloginrej = $('#modalloginrej');
    var loginbutton = $('#modallogin :submit');
    var username = $('#' + usernameID);
    var password = $('#' + passwordID);
    var loader = $('#loader');
    var close = $('#' + closeID);
    var closerej = $('#' + closerejID);
    var label1 = $('#' + label1ID);
    var logoutButton = $('.LogoutButton');
    var register = $('#ctl00_CreateUserWizard1___CustomNav0_StepNextButtonButton');
    var us = $('#ctl00_CreateUserWizard1_CreateUserStepContainer_UserName');
    var ps = $('#ctl00_CreateUserWizard1_CreateUserStepContainer_Password');
    var psc = $('#ctl00_CreateUserWizard1_CreateUserStepContainer_ConfirmPassword');
    var email = $('#ctl00_CreateUserWizard1_CreateUserStepContainer_Email');

    $("#LinkButton1").live("click", function(e) {
        window.location = $(this).attr('rel')+ '/#0,0,'+(currentPage+1);
    });
    $("#LinkButton2").live("click", function(e) {
        window.location = $(this).attr('rel')+ '/#0,0,'+(currentPage+1);
    });
    $(".photosingal").live("click", function(e) {
        window.location = $(this).attr('alt')+ '/#0,0,'+(currentPage+1);
    });
    $("#LinkButton1vid").live("click", function(e) {
        window.location = $(this).attr('rel')+ '/';
    });
    $("#LinkButton2vid").live("click", function(e) {
        window.location = $(this).attr('rel')+ '/';
    });
    $(".photosinvid").live("click", function(e) {
        window.location = $(this).attr('alt')+ '/';
    });    
    $(".latelyadded > img").live("click", function(e) {
        window.location = '/section/photogal/'+$(this).attr('alt')+ '/';
    });
    $(".latelyaddedvid > img").live("click", function(e) {
        window.location = '/section/videogal/'+$(this).attr('alt')+ '/';
    });    
    linklogowanie.live("click", function(e) {
        e.preventDefault();
        $('#overlay').show().fadeTo('normal', 0.8, function() {
            var wh = $(window).height();
            var ww = $(window).width();
            var lh = modallogin.height() + 150;
            var lw = modallogin.width();

            modallogin.css({
                top: wh / 2 - lh / 2,
                left: ww / 2 - lw / 2
            }).show();
            setTimeout(function() {
                $('#danelog').slideDown();
            }, 300);
        });
    });

    linkrejestracja.live("click", function(e) {
        e.preventDefault();
        $('#overlay').show().fadeTo('normal', 0.8, function() {
            var wh = $(window).height();
            var ww = $(window).width();
            var lh = modalloginrej.height() + 150;
            var lw = modalloginrej.width();

            modalloginrej.css({
                top: wh / 2 - lh / 2,
                left: ww / 2 - lw / 2
            }).show();
            setTimeout(function() {
                $('#danerej').slideDown();
            }, 300);
        });
    });
    loginbutton.live("click", function(e) {
        e.preventDefault();

        if (username.val() == '') {
            return -1;
        }
        if (password.val() == '') {
            return -1;
        }
        doLogin(username.val(), password.val());
    });
    close.live("click", function(e) {
        e.preventDefault();
        $('#danelog').slideUp(600, function() {
            modallogin.hide();
            $('#overlay').fadeOut('normal');
        });
    });
    closerej.live("click", function(e) {
        e.preventDefault();
        $('#danerej').slideUp(600, function() {
            modalloginrej.hide();
            $('#overlay').fadeOut('normal');
        });
    });
    register.live("click", function(e) {
        e.preventDefault();
        if (us.val() == '') {
            return -1;
        }
        if (ps.val() == '') {
            return -1;
        }
        if (psc.val() == '') {
            return -1;
        }
        if (email.val() == '') {
            return -1;
        }
        if (ps.val() != psc.val()) {
            return -1;
        }
        label1.html('Sprawdzanie...');
        $('#loaderrej').fadeIn();
        $('#messagerej').slideDown();
        CreateUser.CheckLogin(us.val(), email.val(), onCheckOk, onCheckFailed);
    });
    $('#menu a').live("click", function(e) {

    });
    function onCheckOk(ret) {
        if (ret == "ok") {
            label1.html('Rejestracja...');
            $('#loaderrej').fadeIn();
            $('#messagerej').slideDown();
            //var data = $('#danerej :input').serializeArray();
            CreateUser.Create(us.val(), ps.val(), email.val(), onSuccess, onFailed);
        }
        if (ret == "loginfail") {
            label1.html('Login jest juz zajęty');
            $('#loaderrej').fadeOut();
        }
        if (ret == "emailfail") {
            label1.html('Email został już użyty');
            $('#loaderrej').fadeOut();
        }
    }
    function onCheckFailed(ret) {
        label1.html('Wystąpił błąd.');
        $('#loaderrej').fadeOut();
    }
    function onSuccess(ret) {
        if (ret == "ok") {
            label1.html('Konto zostało założone.');
            $('#loaderrej').fadeOut();
            setTimeout(function() {
                $('#danerej').slideUp(600, function() {
                    modalloginrej.hide();
                    $('#overlay').fadeOut('normal');
                });
            }, 2000);
        } else {
        }
    }
    function onFailed(ret) {
        label1.html('Wystąpił błąd.');
        $('#loaderrej').fadeOut();
    }
    function doLogin(UserName, Password) {
        $('#ctl00_msg').html('Weryfikacja...');
        loader.fadeIn();
        $('#message').slideDown();
        Sys.Services.AuthenticationService.login(
	            UserName,
	            Password,
	            false,
	            null,
	            null,
	            OnLoginComplete,
	            OnAuthenticationFailed,
	            "UserContext.");
    }
    logoutButton.live('click', function(e) {
        //e.preventDefault();
        setTimeout(function() {
            parent.location.reload();
        }, 1000);
    });
    function OnLoginComplete(validCredentials, userContext, methodName) {
        if (validCredentials == true) {
            $('#ctl00_msg').html('Zalogowano');
            loader.fadeOut();
            setTimeout(function() {
                window.location.reload();
            }, 1000);
        }
        else {
            $('#ctl00_msg').html('Nazwa lub hasło niepoprawne');
            loader.fadeOut();
        }
    }
    function OnAuthenticationFailed(error_object, userContext, methodName) {
        //alert("Authentication failed with this error: " + error_object.get_message());
    }
});
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
