﻿/*
    IMAGE ROTATOR
    - Script used on home page in order to rotate the main image
*/
var ImageRotator = {
    next: function() {//Gets reference to next image to be displayed
        var pos = 0;
        $('.main-img img').each(function($key, $value) {//Loop through images
            if ($(this).hasClass('active'))pos = $key;//If this is the current image
        });
        if (pos == ($('.main-img img').length - 1)) return $('.main-img img').eq(0);//If last image is active return the first image
        return $('.main-img img').eq(pos + 1);//return next image
    },
    rotate: function() {//Rotates image
        var oNext = this.next();//Get reference to next image to be displayed
        $('.main-img').css({//Set next image as background of parent before fading current image
            'background-image': 'url(' + $(oNext).attr('src') + ')'
        });
        $('.main-img img.active').animate({//fade current image
            opacity: 0
        }, 1500, 'linear', function() {//Once image is faded
            $(this).css({//hide current image
                display: 'none',
                opacity: 1
            }).removeClass('active');//Make current image inactive
            $(oNext).css({//Display next image
                display: 'block'
            }).addClass('active');//Set next image as active
        });
    },
    
    start: function(){
        setInterval('ImageRotator.rotate()', 6000); //Set interval to rotate images
    },
    
    init: function() {//Initialize
        $('.main-img img:first').addClass('active');//Set the first image as active
        $('.main-img img').not(':first').css({//Hide all other images
            display: 'none'
        });
        
    }
};

function createXHR() //create cross-browser XHR object
{
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var aVersions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0"];
        for (var i = 0; i < aVersions.length; i++) {
            try {
                var oXHR = new ActiveXObject(aVersions[i]);
                return oXHR;
            } catch (oError) {
                //Do nothing
            }
        }
    }
    throw new Error("XMLHttp object could not be created.");
}








var GalleryFormatter = {//function which checks for the existance of gallery items for the current page

    countImages: function() {//Counts images in specified folder
        var error = null;
        var count = 0;
        while (!error) {
            count = count + 1;
            var http = createXHR();
            http.open('HEAD', this.folderPath + '/img-' + count + '.jpg', false);
            http.send();
            if (http.status == 404) error = true;
        }
        this.count = (count - 1);
    },

    resetImageRotator: function() {//Removes images from default gallery
        $('.main-img img').remove();
    },

    getImagePaths: function() {
        this.imgPaths = new Array();
        //this.imgPaths.push($('.main-img img:first').attr('src'));
        for (var i = 1; i <= this.count; i++) {
            this.imgPaths.push(this.folderPath + '/img-' + i + '.jpg');
        }
    },

    attachNewImages: function() {//Attaches new images to gallery holder on page
        var gf = this;
        this.getImagePaths();
        for (var i = 0; i < this.imgPaths.length; i++) {
            $('<img />').load(function() {
                $(this).unbind('load');
                gf.checkLoad($(this).attr('src'));
            }).attr('src', this.imgPaths[i]).appendTo($('.main-img'));
        }
    },

    checkLoad: function(src) {
        if (!this.loadCount) this.loadCount = 0;
        this.loadCount = this.loadCount + 1;
        if (this.count == this.loadCount) {
            ImageRotator.start();
        }
    },

    init: function() {//Initializes the script
        if (typeof pageContentName == 'string' && pageContentName.length > 0) {//If the folder name has been specified
            this.folderPath = '/asset/cms/gallery/' + pageContentName; //Set the path to the gallery
            this.countImages(); //Count images in folder
            if (this.count < 1) {
                this.folderPath = '/asset/cms/gallery/default'; //Set the path to the gallery
                this.countImages(); //Count images in folder
            }

            if (this.count > 0) {//If there are images
                //this.resetImageRotator(); //Remove default images from the gallery on page
                this.attachNewImages(); //Attach new images
            }
            ImageRotator.init(); //Start rotating the images
        }
    }
};


//Remove images from page



$(document).ready(function() {//when document has loaded
   GalleryFormatter.init();//Initialize the gallery script   
});