﻿/*
    IMAGE ROTATOR
    - Script used on home page in order to rotate the main image
*/
var ImageRotator = {

    start: function () {
        setInterval('ImageRotator.rotate()', 6000); //Set interval to rotate images
    },

    
    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
        });
    },



    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 = 'http://cdn.delkorglobal.com/Asset/cms/gallery/' + pageContentName; //Set the path to the gallery
            this.countImages(); //Count images in folder
            if (this.count < 1) {
                this.folderPath = 'http://cdn.delkorglobal.com/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


imgRorator = {
    totalCount: 0,
    count: 1,
    loadImg: function () {
        if (pageContentName === 'none') {
            return;
        }
        $('.main-img').addClass('loading');
        var folderPath = 'http://cdn.delkorglobal.com/asset/cms/gallery/' + pageContentName + "/";
        var img = new Image();
        $(img).load(function () {
            $(this).css('display', 'none'); // since .hide() failed in safari
            $('.main-img').removeClass('loading').append(this);
            if (imgRorator.totalCount == imgRorator.count) {
                imgRorator.count = 1;
            } else {
                imgRorator.count = (imgRorator.totalCount == 0 || imgRorator.totalCount > imgRorator.count) ? imgRorator.count + 1 : imgRorator.count;
            }
            $(this).fadeIn(1500);

            $(this).prevAll('img').fadeOut(1000, function () {
                $(this).remove();
            })

            //console.log(imgRorator.count + " count -- totalt " + imgRorator.totalCount);
        }).error(function () {
            if (imgRorator.count === 1) {
                pageContentName = "default";
                imgRorator.loadImg();
                return;
            }
            imgRorator.totalCount = imgRorator.count - 1;
            imgRorator.count = 1;
            imgRorator.loadImg();
            //console.log(imgRorator.totalCount+ "err " +imgRorator.count);
        }).attr('src', (folderPath + "img-" + imgRorator.count + ".jpg"));

    },
    start: function () {
        imgRorator.loadImg();
        setInterval('imgRorator.loadImg()', 6000);
    }


}



$(document).ready(function () {//when document has loaded
//    var folderPath = '/asset/cms/gallery/' + pageContentName + "/";
//    var img = document.createElement('img');
//    img.setAttribute('scr', "http://localhost:61002/asset/cms/gallery/filtration/img-1.jpg");
//    img.setAttribute('alt', 'na');
//    img.setAttribute('height', '200');
//    img.setAttribute('width', '500');
//    var imgHolder = document.getElementById('main-img-rotator');
//    imgHolder.appendChild(img);
    // image onload
   
    imgRorator.start();
    
  //  GalleryFormatter.init();//Initialize the gallery script   
});
