﻿var XMLgallery;
var GalleryPosition = 0;
var GallerySliderPosition = 0;
var GalleryMaxPosition = 0;
var GalleryHeight = 249;
var GalleryImages = new Array();
var mainGalleryImage;
var GalleryImageElements = new Array();
var GalleryImagesPerPage = 6;
var p;
var SliderTimer;
var LoadSlider = false;

//Global Effects Holders
var FxMoveGallery;  //Used to slide the image sets up and down;
var FxGalleryNextLink;
var FxGalleryBackLink;
var OldImageMorph;

//Add Images 

function InitSlideshow()
{
    FxGalleryNextLink = new Fx.Tween('GallerySetNext', { duration: 'short' });
    FxGalleryBackLink = new Fx.Tween('GallerySetBack', { duration: 'short' });

    b = true;
    //Do Initial Checks and alert of not correct 
    ['GallerySetControlsPositioner', 'imageGallery', 'GallerySetControls',
  'GallerySetNext', 'GalleryNextLink', 'GalleryBackLink',
  'GallerySetBack', 'GallerySetControls'].each(function(item, index)
  {
      //alert(index + " = " + item);
      if (!$chk($(item)))
      {
          //alert('DIV : ' + item + ' does not exist.');
          b = false;
      }
  });

    if (b)
    {
        LoadSlider = true;
        //PreLoader 
        p = new Preloader();

        //Setup var for Effects 
        FxMoveGallery = new Fx.Tween('GallerySetControls', { duration: 'long' });

        GalleryImages.each(function(item, index)
        {

            var temparr = GalleryImages[index].split("|");


            //main, thumb, description, index (0 based)
            CreateImageThumbDiv(temparr[0], temparr[1], temparr[2], index)
        });

        //alert(GalleryMaxPosition);

        GalleryMaxPosition = (GalleryImages.length / GalleryImagesPerPage) - 1;
        //alert(GalleryMaxPosition);

        //alert(GalleryMaxPosition);

        GalleryImageElements = $$('.GalleryImage');

        //Set Global Variable to the GalleryMainImage var
        mainGalleryImage = $('mainGalleryImage').getFirst('img');

        //Setup initial position of the galleryMainImage Element
        //mainGalleryImage.setStyle('position', 'absolute');
        mainGalleryImage.setStyle('left', '570px');

        //Create and Load main Image into imageGallery
        UpdateGalleryNavigation();

        OldImageMorph = new Fx.Tween(mainGalleryImage, { duration: 900, transition: Fx.Transitions.Sine.easeInOut });
        //OldImageMorph2 = new Fx.Tween(mainGalleryImage, { duration: 900, transition: Fx.Transitions.Sine.easeInOut });
    }
    else
    {
        //alert('Issues were found, slider has not been initiated.');
    }

}

//Start the slide when all the stuff has loaded

window.addEvent('load', function()
{
    if (LoadSlider)
    {
        SliderTimer = NextSlide.periodical(7000);
    }
});

function UpdateGalleryNavigation()
{

    if (GallerySliderPosition <= 0)
    {
        FxGalleryBackLink.start('opacity', '0');
    }
    else
    {
        $('GallerySetBack').setStyle('opacity', '0');
        $('GallerySetBack').setStyle('display', '');
        FxGalleryBackLink.start('opacity', '1');
    }

    if (GallerySliderPosition >= GalleryMaxPosition)
    {
        FxGalleryNextLink.start('opacity', '0');
    }
    else
    {

        $('GallerySetNext').setStyle('opacity', '0');
        $('GallerySetNext').setStyle('display', '');
        FxGalleryNextLink.start('opacity', '1');
    }
}

function CreateImageThumbDiv(LargeFileName, FileName, FileDescription, iIndex)
{
    //alert(FileName + ' - ' + FileDescription)

    //Check for index 0, as this will be the one that animates in! 
    var NewImage = new Element('img', {
        'width': '110',
        'alt': FileDescription,
        'title': FileDescription,
        'style': 'display: none;',
        'src': GalleryImageThumbPath + FileName,
        'class': 'GalleryImage'
    });



    var myThumbImage = new Asset.image([NewImage.src],
        {
            onload: function()
            {
                //set thumb to 1 opacity, and add on click event to thumb
                NewImage.setStyle('opacity', 1);
            }
        });



    p.addEventOnLoad(NewImage.src, function()
    {
        //NewImage.getParent().setStyle('background', 'none');
        NewImage.setStyle('opacity', 0)
        NewImage.style.display = 'block';
        var imgLoadedEffect = new Fx.Tween(NewImage, { duration: 'long' });
        imgLoadedEffect.start('opacity', 1);
    });

    p.addToQueue(NewImage.src);

    NewImage.store('index', iIndex);

    var NewImageDiv = new Element('div', { 'class': 'ImageThumb' });

    //Add To Preloader
    if (iIndex == 0)
    {
        var myImage = new Asset.image(
        [GalleryImagePath + LargeFileName],
        {
            onload: function()
            {
                //set thumb to 1 opacity, and add on click event to thumb
                SwapDisplayImages(myImage, NewImageDiv, iIndex);
                NewImage.addEvent('click', function()
                {
                    $clear(SliderTimer)
                    SliderTimer = NextSlide.periodical(15000);
                    SwapDisplayImages(myImage, NewImageDiv, iIndex);
                });
            }
        });
    }
    else
    {
        var myImage = new Asset.image([GalleryImagePath + LargeFileName],
        {
            onload: function()
            {
                //set thumb to 1 opacity, and add on click event to thumb
                NewImage.addEvent('click', function()
                {
                    $clear(SliderTimer)
                    SliderTimer = NextSlide.periodical(15000);
                    SwapDisplayImages(myImage, NewImageDiv, iIndex);
                });
            }
        });
    }

    NewImageDiv.store('index', iIndex);

    //Populate the size bar with images 
    NewImage.inject(NewImageDiv)
    NewImageDiv.inject($('GallerySetControls'));
}

function SlideGallery(absolutePosition)
{

    //0=start
    GallerySliderPosition = absolutePosition;
    if (GallerySliderPosition < 0)
    { GallerySliderPosition = 0; }

    if (GallerySliderPosition > GallerySliderPosition)
    { GallerySliderPosition = 0; }

    FxMoveGallery.cancel();
    FxMoveGallery.start('margin-top', -GallerySliderPosition * GalleryHeight);

    //alert(-position*GalleryHeight);

    //Set Variable
    //GalleryPosition = position;
    //alert(GallerySliderPosition)
    UpdateGalleryNavigation();

}

function NudgeGallery(modifier)
{

    GallerySliderPosition = GallerySliderPosition + modifier;
    SlideGallery(GallerySliderPosition);
}

function SwapDisplayImages(NewImageObject, ThumbImageObject, index) {
    
    if (ThumbImageObject)
    {
        if (isNaN(index))
        {
            index = 0;
            GalleryPosition = 0
        }
        //$('clickStopper').setStyle('display', 'block');
        //$('clickStopper').setStyle('left', '778px');

        var NewImageMorph = new Fx.Tween(NewImageObject, { duration: 900, transition: Fx.Transitions.Sine.easeInOut });
        var NewImageMorphBack = new Fx.Tween(GalleryImageElements[GalleryPosition], { duration: 900, transition: Fx.Transitions.Sine.easeInOut });
        var tempImageMorphBack;
        var NewThumbOut = new Fx.Tween(ThumbImageObject.getFirst(), { duration: 900, transition: Fx.Transitions.Sine.easeInOut });

        NewImageMorph.removeEvents('complete');
        OldImageMorph.removeEvents('complete');
        mainGalleryImage.get('morph').cancel();
        OldImageMorph.cancel();
        GalleryPosition = index
        
        //First Animate main image out of view
        $$('.GalleryImage').each(function(Element, index) {
            //alert("index : " + Element.retrieve('index') + ", pos : " + GalleryPosition + ", margin left : " + Element.getStyle('margin-left'));

            if (Element.getStyle('margin-left') != "0px" && Element.retrieve('index') != GalleryPosition) {
                //alert('element ' + Element.retrieve('index') + "not at 0px and not GalleryPosition");
            }

            if (Element.getStyle('margin-left') != "0px" && Element.retrieve('index') != GalleryPosition) {
                //alert('animating back ' + Element.retrieve('index'));
                Element.set('morph', { duration: '900' });
                Element.get('morph').cancel();
                Element.morph({ 'margin-left': '0' });
                //alert('sdfsfd');
                //OldImageMorph.start({'margin-left': '0px'});
                //tempImageMorphBack = new Fx.Tween(Element, { duration: 900, transition: Fx.Transitions.Sine.easeInOut });
                //tempImageMorphBack.start('margin-left', '0px');
            }
        });

        //Animate thumb out of view
        //alert(ThumbImageObject.getParent().get('html'))
        OldImageMorph.start('left', 570);

        //Then Change the source of th4 amin display to the new image, and
        OldImageMorph.addEvent('complete', function() {
            //alert(NewImageObject.getProperty('src'));
            mainGalleryImage.setProperty('src', NewImageObject.getProperty('src'));
            //NewImageMorph.start("margin-left", "0px");

            mainGalleryImage.get('morph').cancel();
            mainGalleryImage.set('morph', { duration: '900' });
            mainGalleryImage.morph({ 'left': 0 });
            //OldImageMorph2.start('left', '0px');
            ThumbImageObject.getFirst().tween('margin-left', '-110px');
            //NewThumbOut.start('margin-left', '-110px')
        });

        
        
        NewImageMorph.addEvent('complete', function()
        {
            //$('clickStopper').setStyle('display', 'none');
            //$('clickStopper').setStyle('left', '478px');
        });
    }
}

var NextSlide = function()
{
    $clear(SliderTimer);
    SliderTimer = NextSlide.periodical(10000);

    //NewImage src
    var imgSrc;
    //Check for last image in sequence
    //alert('Slider status : \n\nGalleryImages.length : ' + GalleryImages.length + "\nGalleryPosition:" + GalleryPosition + "");

    //alert(GalleryPosition);
    var ImageToChange;
    if (GalleryPosition + 1 == GalleryImages.length)
    {
        //Ok we are at the last image, shoot to first
        SlideGallery(0);
        var img = new Element('img', { 'src': GalleryImagePath + GalleryImages[0].split("|")[0] });

        ImgSrc = GalleryImagePath + GalleryImages[0].split("|")[0]
        Thumb = $('GallerySetControls').getChildren()[0];
        SwapDisplayImages(img, Thumb, 0);
    }
    else //Normal
    {
        if ((GalleryPosition + 1) % GalleryImagesPerPage == 0)
        {
            //Ok about to cross over
            SlideGallery((GalleryPosition + 1) / GalleryImagesPerPage);
        }
        var img = new Element('img', { 'src': GalleryImagePath + GalleryImages[GalleryPosition + 1].split("|")[0] });
        Thumb = $('GallerySetControls').getChildren()[GalleryPosition + 1];
        SwapDisplayImages(img, Thumb, GalleryPosition + 1);

        //        SwapDisplayImages(myImage, NewImage);
        //        SwapDisplayImages(mainGalleryImage, GalleryImageElements[++GalleryPosition]);
    }
}
