﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

$(document).ready(function() {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    //vars
    imageArray = new Array();
    photoArray = new Array();
    var galleryId;
    var activeImage = 0;
    var currentPage = 0;
    var currentPageLoaded = -1;
    var currentLoaded = 0;
    var pagesize = 7;
    var globalUrl;
    //div vars
    var loading;
    var photolinksplace;
    var messagebox;
    var pagingplace;
    var backurl = "http://devilinside.miross.pl/section/photogal/#page=";
    var backid = 1;

    if ($('.PhotoGalSection').is(':visible')) {
        messagebox = $('.messages');
        loading = $("#loading");
        photolinksplace = $('#photolinksplace');
        pagingplace = $('#pagingplace');
        messagebox.hide();
        pagingplace.hide();
        if ($('.RatingControl').is(':visible')) {
            loadRatingControl(5);
        }
        galleryId = $('#GalleryIdDiv > *').text();
        if (galleryId.length == 0) galleryId = getGalId(window.location.hash);
        //PhotoService.GetPhotos(galleryId, onSuccess, onFailed);
        //getPhotos(galleryId);
    }
    function onSuccess(data) {
        $.each(data, function(i, data) {
            imageArray.push(new Array(data.PhotoId, data.Caption));
        });
        loadNavPhotos(pagesize);
        var maxpages = Math.ceil(imageArray.length / pagesize);
        loadPages(0, maxpages, pagesize);
    }
    function onFailed(result) {
        alert('Error');
    }
    function EndRequestHandler(sender, args) {
        if (args.get_error() != undefined) {
            alert(args.get_error().message);
        } else {

        }
    }
    function getPhotos(galleryId) {
        var data = '{"galleryId":"' + galleryId + '"}';
        $.ajax({
            type: "POST",
            url: "/services/PhotoService.asmx/GetPhotos",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                $.each(data.d, function(i, d) {
                    imageArray.push(new Array(d.PhotoId, d.Caption));
                });
                if (imageArray.length > 0) {
                    getHistoryVars(globalUrl);
                    loadNavPhotos(pagesize);
                    var maxpages = Math.ceil(imageArray.length / pagesize);
                    loadPages(currentPage, maxpages, pagesize);
                } else { alert('Galeria w przygotowaniu'); }
            }
        });
    }
    function getGalId(hash) {
        var table = hash.split("&");
        for (var i = 0; i < table.length; i++) {
            if (table[i].indexOf("galid") > -1) {
                var t = table[i].split("=");
                return t[1];
            }
        }
        return -1;
    }
    function showLoading() {
        loading.css({ visibility: "visible" });
        $('.navigate-next').hide();
        $('.navigate-prev').hide();
    }
    function hideLoading() {
        loading.css({ visibility: "hidden" });
        $(".image1").fadeTo(10, 1);
        $('.navigate-next').show();
        $('.navigate-prev').show();
    }
    $('.navigate-prev').live('click', function() {
        if (activeImage > 0) {
            activeImage--;
            if (activeImage < (currentPage) * pagesize) {
                currentPage--;
            }
            var hash = activeImage + ',' + currentPage+','+backid;
            window.location.hash = hash;
            //            if (activeImage < (currentPage) * pagesize) {
            //                currentPage--;
            //                photolinksplace.empty();
            //                showLoading();
            //                $('.image1').fadeTo(200, 0.5);
            //                loadNavPhotos(7);
            //                var maxpages = Math.ceil(imageArray.length / pagesize);
            //                pagingplace.empty();
            //                loadPages(currentPage, maxpages, pagesize);
            //            } else {
            //                showBigPhoto(activeImage);
            //            }
        }
    });
    $('.navigate-next').live('click', function() {
        if (activeImage < imageArray.length - 1) {
            activeImage++;
            if (parseInt(activeImage) + 1 > (parseInt(currentPage) + 1) * pagesize) {
                currentPage++;
            }
            var hash = activeImage + ',' + currentPage+','+backid;
            window.location.hash = hash;
            //            if (parseInt(activeImage) + 1 > (parseInt(currentPage) + 1) * pagesize) {
            //                currentPage++;
            //                photolinksplace.empty();
            //                showLoading();
            //                $('.image1').fadeTo(200, 0.5);
            //                loadNavPhotos(7);
            //                pagingplace.empty();
            //                var maxpages = Math.ceil(imageArray.length / pagesize);
            //                loadPages(currentPage, maxpages, pagesize);
            //            } else {
            //                showBigPhoto(activeImage);
            //            }
        }
    });
    $('.navigate-prev').live('mouseover', function() {
        if (activeImage > 0) { $('.button-prev').css('visibility', 'visible'); }
    });
    $('.navigate-prev').live('mouseout', function() {
        $('.button-prev').css('visibility', 'hidden');
    });
    $('.navigate-next').live('mouseover', function() {
        if (activeImage < imageArray.length - 1) { $('.button-next').css('visibility', 'visible'); }
    });
    $('.navigate-next').live('mouseout', function() {
        $('.button-next').css('visibility', 'hidden');
    });
    function showBigPhoto(id) {
        var img = $(".image1");
        if (loading.is(':visible')) showLoading();
        var imgurl = "/handlers/ShowpicHandler.ashx?fotoid=" + imageArray[id][0];
        $(img).fadeTo(100, 0.5, function() {
            var imgpre = new Image();
            imgpre.onload = function() {
                $(img).attr('src', imgurl);
                $('.imgplace').css("width", img.width());
                $('.imgplace').css({ 'border': 'solid 1px #D3D3D3', 'padding': '6px' });
                //activeImage++;
                $('.photoinfo').html((parseInt(activeImage) + 1) + " of " + imageArray.length);
                //activeImage--;
                imgpre.onload = function() { };
                hideLoading();
            };
            imgpre.src = imgurl;
        });
    }
    function loadNavPhotos(count) {
        var imgurl;
        var title;
        pagingplace.slideUp();
        messagebox.slideDown();
        $('#photolinksplace > span').unbind("click", photolinkClick);
        if (currentLoaded < count) {
            if (count * currentPage + currentLoaded < imageArray.length) {
                imgurl = "/handlers/GalleryThumbs.ashx?fotoid=" + imageArray[(currentPage * count) + currentLoaded][0] + "&size=100";
                var imgpre = new Image();
                imgpre.onload = function() {
                    var img = new Image();
                    $(img).attr('src', imgurl);
                    $(img).attr('alt', currentLoaded);
                    $(img).addClass('miniature');
                    var ndiv = document.createElement('span');
                    ndiv.setAttribute('id', (currentPage * count) + currentLoaded);
                    ndiv.className = "photobackground";
                    ndiv.appendChild(img);
                    photolinksplace.append(ndiv);
                    $(ndiv).fadeTo(300, 0.4);
                    $(ndiv).fadeTo(300, 1);
                    currentLoaded++
                    loadNavPhotos(count);
                    imgpre.onload = function() { };
                };
                imgpre.src = imgurl;
            } else {
                navigationloaded()
            }
        } else {
            navigationloaded()
        }
    }
    function navigationloaded() {
        showBigPhoto(activeImage);
        currentLoaded = 0;
        pagingplace.slideDown();
        messagebox.slideUp();
        $('#photolinksplace > span').bind('click', photolinkClick);
    }
    function photolinkClick() {
        activeImage = $(this).attr('id');
        var hash = activeImage + ',' + currentPage+','+backid;
        window.location.hash = hash;
        showBigPhoto(activeImage);
    }
    function loadPages(current, allpages, pagesize) {
        var offset = 5;
        var numberoflinks = 11;
        currentPageLoaded = current;
        if (current > numberoflinks - offset - 1) {
            addLink(0);
            var el = document.createElement("span");
            el.innerHTML = "...";
            pagingplace.append(el);
        }
        if (allpages < numberoflinks) numberoflinks = allpages;
        for (var i = 0; i < numberoflinks; i++) {
            if (current < offset) {
                addLink(i);
            } else {
                if (current - offset + i < allpages) { addLink(current - offset + i); }
            }
        }
        if (allpages > numberoflinks) {
            if (current < allpages - offset - 1) {
                var el = document.createElement("span");
                el.innerHTML = "...";
                pagingplace.append(el);
                addLink(allpages - 1);
            }
        }
    }
    function addLink(i) {
        if (i == currentPage) {
            var el = document.createElement("span");
            el.className = "pagingbuttonselected";
            el.innerHTML = i + 1;
            pagingplace.append(el);
        } else {
            var el = document.createElement("a");
            el.rel = i;
            el.href = "javascript:void(0)";
            el.onclick = function() {
                currentPage = this.rel;
                activeImage = currentPage * pagesize;
                var hash = activeImage + ',' + currentPage+','+backid;
                window.location.hash = hash;
                /*
                photolinksplace.empty();
                showLoading();
                $('.image1').fadeTo(200, 0.5);
                loadNavPhotos(7);
                var maxpages = Math.ceil(imageArray.length / pagesize);
                pagingplace.empty();
                loadPages(currentPage, maxpages, pagesize);*/
            };
            el.innerHTML = i + 1;
            pagingplace.append(el);
        }
    }
    function loadRatingControl(count) {
        $('.RatingControl').empty();
        for (var i = 1; i < count + 1; i++) {
            addStar(i);
        }
    }
    function RateOk(data) {
        $('.RatingControl').text(data);
    }
    function RateFailed(ret) {
        alert('error');
    }
    function addStar(i) {
        var ratingplace = $('.RatingControl');
        var star = document.createElement("div");
        star.id = i;
        star.className = "emptyRatingStar";
        star.onclick = function() {
            var rate = this.id;
            var guid = $('.UserGuid').text();
            if (guid.length > 0) {
                $('.RatingControl').empty();
                $('.RatingControl').text("Trwa ocenianie...");
                PhotoService.RateGallery(rate, galleryId, guid, RateOk, RateFailed);
            }
        }
        ratingplace.append(star);
    }
    $('.RatingControl > *').live('mouseover', function() {
        var id = $(this).attr('id');
        id++;
        for (var i = 1; i < id; i++) {
            $('.RatingControl > #' + i).attr('class', 'filledRatingStar');
        }
    });
    $('.RatingControl > *').live('mouseout', function() {
        var id = $(this).attr('id');
        id++;
        for (var i = 1; i < id; i++) {
            $('.RatingControl > #' + i).attr('class', 'emptyRatingStar');
        }
    });
    //Historia
    function getHistoryVars(url) {
        var histVar = url.split(',');
        if (histVar != '') {
            activeImage = histVar[0];
            currentPage = histVar[1];
            backid = histVar[2];
        } else {
            activeImage = 0;
            currentPage = 0;
        }
        $('#backToGallery').attr('href',backurl+backid);
    }
    $(window).bind('hashchange', function(e) {
        $('#historyDiv').each(function() {
            var url = $.param.fragment();
            globalUrl = url;
            if (imageArray.length > 0) {
                getHistoryVars(url);
                if (currentPage != currentPageLoaded) {
                    photolinksplace.empty();
                    showLoading();
                    $('.image1').fadeTo(200, 0.5);
                    loadNavPhotos(7);
                    var maxpages = Math.ceil(imageArray.length / pagesize);
                    pagingplace.empty();
                    loadPages(currentPage, maxpages, pagesize);
                } else {
                    showBigPhoto(activeImage);
                }
            } else {
                getPhotos(galleryId);
            }
        });
    });
    $(window).trigger('hashchange');
});
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
