$(document).ready(function() {LoadGallery();});

var root = new String(document.location);
var slashone = root.substring(root.indexOf('/')+1);
var slashtwo = slashone.substring(slashone.indexOf('/')+1);
var slashthree = slashtwo.substring(slashtwo.indexOf('/'));
    root = root.replace(slashthree, '');
    

var galleryData;
var activeIndex;
var slideshowTimer=null;
var sstip=false; //slideshow toggle in progress

function LoadGallery()
{
    if ($('input#GalleryID').length > 0)
    {
        // load gallery content info                
        $.getJSON(root+"/utils/galleryService.php?rq=LoadGallery&gid="+$('input#GalleryID').attr('value'),
        function(data){                
            galleryData = data;
            LoadImage(parseInt($('#ImageOrder').get(0).value), 1, 5);
            if (parseInt($('#ImageOrder').get(0).value) <= (galleryData.length-1))
            {
                LoadImage(parseInt($('#ImageOrder').get(0).value), -1, 3);
            }
            $("#Loading").css("display", "inline");            
            //DisplayImage(0); 
        });        
    }
}

function DisplayPreviousImage()
{
    
    var prevCookie = readCookie("PreviousImageData");    
    if (prevCookie != null){
        var imageData = JSON.parse(prevCookie.replace(/'/g,'"'));
        $("#ImageHolder2").empty();
        $("#ImageHolder2").append('<img id="PreviousGalleryImage" src="'+root+"/images/gallery"+imageData.ImagePath+'" alt="" />');
        var shieldHeight = $('div#Shield').height();
        var shieldWidth = $('div#Shield').width();            
        $("img#PreviousGalleryImage").css("margin-top",Math.floor((shieldHeight-imageData.ImageHeight)/2.0)+"px");
        $("img#PreviousGalleryImage").css("margin-left",Math.floor((shieldWidth-imageData.ImageWidth)/2.0)+"px");
        //$("#ImageHolder").animate({opacity : 1}, galleryShiftSpeed*1000);
            
        if (imageData.CurrentMark)
        {                    
            $("#NewCorner2").css("height", (parseInt(imageData.ImageHeight)+16)+"px");
            $("#NewCorner2").css("width", (parseInt(imageData.ImageWidth)+16)+"px");
            $("#NewCorner2").css("margin-left",Math.floor((shieldWidth-imageData.ImageWidth-16)/2.0)+"px");
            $("#NewCorner2").css("margin-top",Math.floor((shieldHeight-imageData.ImageHeight-16)/2.0)+"px");
            //$("#NewCorner").css("filter","alpha(opacity=0)");
            //$("#NewCorner").animate({opacity : 1}, galleryShiftSpeed*1000);
        }
    }    
}

function DisplayImage(op, animationFunc)
{
    if ($('#ImageOrder').length > 0)
    {
        var index = $('#ImageOrder').get(0).value;    
        if ((typeof(galleryData) != "undefined") && (galleryData.length > 0))
        {        
            if (op || (galleryData[index].status == 2))
            {
                //save imageData for future generations            
                createCookie("PreviousImageData", JSON.stringify(galleryData[index]).replace(/"/g, '\''),1); //
                
                if (typeof(animationFunc) == 'function') animationFunc();
                activeIndex = index;
                $("#ImageHolder").css("opacity",0);
                $("#Loading").css("display", "none");
                $("#ImageHolder").empty();
                $("#ImageHolder").append('<img id="GalleryImage" src="'+root+"/images/gallery"+galleryData[index].ImagePath+'" alt=""/>');
                var shieldHeight = $('div#Shield').height();
                var shieldWidth = $('div#Shield').width();            
                $("img#GalleryImage").css("margin-top",Math.floor((shieldHeight-galleryData[index].ImageHeight)/2.0)+"px");
                $("img#GalleryImage").css("margin-left",Math.floor((shieldWidth-galleryData[index].ImageWidth)/2.0)+"px");
                $("#ImageHolder").animate({opacity : 1}, galleryShiftSpeed*1000);
                $("#ImageHolder2").animate({opacity : 0}, galleryShiftSpeed*1000);
                    
                if (galleryData[index].CurrentMark)
                {                    
                    $("#NewCorner").css("height", (parseInt(galleryData[index].ImageHeight)+16)+"px");
                    $("#NewCorner").css("width", (parseInt(galleryData[index].ImageWidth)+16)+"px");
                    $("#NewCorner").css("margin-left",Math.floor((shieldWidth-galleryData[index].ImageWidth-16)/2.0)+"px");
                    $("#NewCorner").css("margin-top",Math.floor((shieldHeight-galleryData[index].ImageHeight-16)/2.0)+"px");
                    $("#NewCorner").css("filter","alpha(opacity=0)");
                    $("#NewCorner").animate({opacity : 1}, galleryShiftSpeed*1000);                
                }
                $("#NewCorner2").animate({opacity : 0}, galleryShiftSpeed*1000);
            }        
            else setTimeout(function(){DisplayImage(op, animationFunc);}, 150);
        }
        else
        {        
            setTimeout(function(){DisplayImage(op, animationFunc);}, 500);
        }
    }
}

function LoadImage(index, step, counter)
{    
    if (galleryData.length > 0)
    {            
        if ((typeof(galleryData[index].status) == 'undefined') || (galleryData[index].status == null) )
        {            
            galleryData[index].status="1";
            $.get(root+"/images/gallery"+galleryData[index].ImagePath,
            function(data)
            {                
                galleryData[index].status="2";
                var newIndex = (step > 0)?
                                    (((index+step) < galleryData.length)?(index+step):0):
                                    (((index+step) < 0)?galleryData.length-1:(index+step));                
                if ((counter > 0))
                {                    
                    LoadImage(newIndex,step,counter-1);
                }
            });
        }
        else
        {            
            var newIndex = (step > 0)?
                                    (((index+step) < galleryData.length)?(index+step):0):
                                    (((index+step) < 0)?galleryData.length-1:(index+step));                
                if ((counter > 0))
                {                    
                    LoadImage(newIndex,step,counter-1);
                }
        }
    }
}

function Shift(step)
{
    var str = window.location.href;    
    var pattern = /[-_a-zA-Z0-9]*\.html/;    
    var galleryAddress = str.match(pattern);
    
    var index = parseInt($('#ImageOrder').get(0).value)+step;
    if (index >= galleryData.length) index = 0;
    if (index < 0) index = galleryData.length-1;
    var imageName = galleryData[index].ImagePath.match(/[^\/]*$/);
    GalleryToGalleryLeave(galleryAddress+"?img="+imageName, true);
    //window.location.href = galleryAddress+"?img="+imageName;
}

function Skip(index)
{
    var str = window.location.href;    
    var pattern = /[-_a-zA-Z0-9]*\.html/;    
    var galleryAddress = str.match(pattern);
        
    if (index >= galleryData.length) index = 0;
    if (index < 0) index = galleryData.length-1;
    var imageName = galleryData[index].ImagePath.match(/[^\/]*$/);
    GalleryToGalleryLeave(galleryAddress+"?img="+imageName, true);
    //window.location.href = galleryAddress+"?img="+imageName;
}

function SlideShowToggle()
{
    sstip = true;    
    if (slideshowTimer == null)
    {         
        KeepSlidesShowing();
        createCookie("SlideshowRunning", true, (1.0/24));
        $('.SSPlay').stop();
        $('.SSPlay').animate({opacity: 0}, 300, "linear", function(){
            $('.SSPlay').css("visibility", "hidden");
            $('.SSStop').css("visibility", "visible");
            $('.SSStop').css("opacity", "0");
            $('.SSStop').css("filter", "alpha(opacity=0)");
            $('.SSStop').stop();
            $('.SSStop').animate({opacity: 0.2}, 300, "linear", function(){sstip = false;});            
        });
        
    }
    else
    {
        clearTimeout(slideshowTimer);
        CancelSlideShow();
        slideshowTimer = null;
        $('.SSStop').stop();
        $('.SSStop').animate({opacity: 0}, 300, "linear", function(){
            $('.SSStop').css("visibility", "hidden");
            $('.SSPlay').css("visibility", "visible");
            $('.SSPlay').stop();                        
            $('.SSPlay').animate({opacity: 0.2}, 300, "linear", function(){sstip = false;});
        });
        
    }
}

function KeepSlidesShowing()
{
    slideshowTimer = setTimeout(function(){Shift(1);}, gallerySlideshowSpeed*1000);    
}

function CancelSlideShow()
{
    createCookie("SlideshowRunning", false, (1.0/24));    
}

/*
function SlideShow()
{
    DisplayImage(activeIndex+1);
    if (slideshowTimer != null)
    {
        slideshowTimer = setTimeout(SlideShow, 4000);
    }
}*/

function LoadGalleryThumbs(keepShift)
{
    if ((typeof(galleryData) != "undefined") && (galleryData.length > 0))
    {
        if ($('#GECarouselContent').contents().length == 0)
        {
            //$('#GECarouselContent').empty();
            //if (!keepShift) $('#GECarouselContent').css("left","0px");    
            var gid = $('#GalleryID').get(0).value;
            var currentOrder = $('#ImageOrder').get(0).value;
            $('#GECarouselContent').append('<span id="CurrentPosition"></span>');    
            
            for (var i=0; i < galleryData.length; i++)              
             {        
                 //decompose path
                 var splits = galleryData[i].ImagePath.split('/');    
                 var safePath = "";
                 for (j=1; j < (splits.length-1); j++)
                 {    
                     if (safePath != "") safePath = safePath + ":";
                     safePath = safePath + splits[j];
                 }                        
                 safePath = safePath + ":" + splits[splits.length-1];
                 var style = ' style="';
                 var style2 = ' style="';
                 
                 style = style + ((parseInt(galleryData[i].ThumbHeight) < parseInt(galleryData[i].ThumbWidth))?' margin-top: '+Math.floor((120-galleryData[i].ThumbHeight)/2)+'px; margin-bottom: '+Math.floor((120-galleryData[i].ThumbHeight)/2)+'px;':"");
                 //style = style + ((galleryData[i].CurrentMark)?' border-color: #8c0808; border-width: 2px;':"");
                 var newClass = (galleryData[i].CurrentMark)?'NewThumb':"";
                 var currentClass = ' class="'+((i==currentOrder)?"CurrentThumb":"")+'"';
                 style = style + " width: "+galleryData[i].ThumbWidth+"px;";
                 style = style + " height: "+galleryData[i].ThumbHeight+"px;";         
                 style2 = style2 + " height: "+galleryData[i].ThumbHeight+"px;"+'"';         
                 style = style + " background: url('../images/gallery-thumbs"+galleryData[i].ImagePath+"') no-repeat center;"+'"';
                 var destinationContainer = (i<=currentOrder)?"#CurrentPosition":'#GECarouselContent';
                 //var destinationContainer = '#GECarouselContent';
                 $(destinationContainer).append(
                     '<a id="img_'+i+'"'+currentClass+' '+style+
                           ' onclick="CancelSlideShow(); Skip('+i+');" ><span class="'+newClass+'" '+style2+'></span></a>');         
             }
        }
        var shift = (($('#CurrentPosition').width()-400)<$('#GECarouselContent').width()-729)?($('#CurrentPosition').width()-400):$('#GECarouselContent').width()-729;
        if (shift < 0) shift = 0;
        $('#GECarouselContent').css("left","-"+shift+"px");        
        $('#ThumbnailStripe').bind('mousewheel', DeltaAccumulator);
        
    }
    else
    {        
        setTimeout(function(){LoadGalleryThumbs(keepShift);}, 500);
    }
}


function ScrollBellStart(bell)
{    
    if (Math.abs(bell) == 2) scrollBell = true;
    if (scrollBell)
    {        
        if (bell > 0) {
            DeltaAccumulator(null, 1.0);
            setTimeout('ScrollBellStart(1);', 50)
        }
        else
        {
            DeltaAccumulator(null, -1.0);
            setTimeout('ScrollBellStart(-1);', 50)
        }
    }
}

function ScrollBellStop()
{
    scrollBell = false;
}

function DeltaAccumulator(event, delta)
{    
    lifespan = 200;
    var temp = new Array();    
    temp[0] = new Date().getTime();
    temp[1] = delta;    
    deltas[deltas.length] = temp;    
    UpdateCurrentSpeed();
    return false;
}

function UpdateCurrentSpeed()
{
    currentSpeed = 0;
    var new_deltas = new Array();
    for (i=0; i<deltas.length;i++)
    {
        var now = new Date().getTime();
        if ((deltas[i][0]+lifespan) > now)
        {
            currentSpeed = currentSpeed + deltas[i][1];
            new_deltas[new_deltas.length] = deltas[i];
        }
    }
    deltas = new_deltas;
     
    if ((currentSpeed != 0) && (!animationFlag))
    {
        ScrollGallery(currentSpeed);
    }
}

function ScrollGallery(distance)
{
    var c = carouselWidthCorrection;
    var left = $('#GECarouselContent').css("left");    
    left = left.substr(0,left.length-2);    
    width = $('#GECarouselContent').width() - $('#GECarouselClip').width() + c;
    
    var new_left = left - distance*(-5);
    if (new_left < (-width)) new_left = -width;
    if (new_left > 0) new_left = 0;
    
    if (left != new_left)
    {
        animationFlag = true;
        $('#GECarouselContent').animate({left: new_left+"px"}, 20, "linear", function(){
            animationFlag = false;
            UpdateCurrentSpeed();
        });
    }
}

function ShowGalleryThumbs()
{
    $('#ThumbnailStripe').unbind("mouseenter");        
    if (isIE) $('#ThumbnailStripe').css("display","block");        
    LoadGalleryThumbs(false);    
    $('#ThumbnailStripe').stop();
    if (!isIE) $('#ThumbnailStripe').css("display","block");            
    $('#ThumbnailStripe').bind("mouseleave", function(){HideGalleryThumbs();});    
    $('#ThumbnailStripe').animate({opacity:1}, 500);    
    
}

function HideGalleryThumbs()
{
    $('#ThumbnailStripe').unbind("mouseleave");
    $('#ThumbnailStripe').bind("mouseenter", function(){ShowGalleryThumbs();});
    $('#ThumbnailStripe').stop();    
    $('#ThumbnailStripe').animate({opacity:0}, 500, function(){
        $('#ThumbnailStripe').css("display","none");
    });
}
