/**
* Prototype/Scriptaculous Scrolling/Fading Image Gallery
*
* Version: 1.0
*
**/
var url2= "http://www.clarks.com.cn/minisite/ss12_women";
var url1 = "http://www.clarks.com.cn/minisite/ss12_man";


var Gallery = Class.create({
    initialize: function(id, defaultImage, json) {
        this.gallery = $(id);
        current = 0;
        this.imageBlock = "";
        //this.json = json;
        totalPanes = 0;
        slideshowTimeout = "";
        this.paginationScrollPos = 0;
        this.newPaginationWidth = 0;
        //this.galleryDefaults = "";
        this.options = {
            imageNum: "imageNumber",
            imagePrev: "imagePrev",
            imageNext: "imageNext"
        }
        //alert(jsonURL);

        var imageBlock = "";
        var paginationBlock = "";

        //Build the initial view for the images and get gallery defaults
        json.images.each(function(s, imageCount) {
            totalPanes++;
            //Build image list
            //Check for alt text on image so you don't get 'undefined'
            imageAlt = (json.images[imageCount]['alt'] != "") ? json.images[imageCount]['alt'] : "";

            imageBlock += '<div id="galleryImage' + imageCount + '">';

            imageBlock += '<img src="' + json.images[imageCount]['src'] + '" title="' + json.images[imageCount]['alt'] + '" alt="' + json.images[imageCount]['alt'] + '" />';

            imageBlock += '</div>';
            //Build pagination list
            var paginationClass = "imageNumber";
            if (imageCount == 0) { paginationClass += ' selected' }
            paginationBlock += '<div class="paginationLink" id="link' + imageCount + '"><a href="javascript:void(0)" class="' + paginationClass + '" id="image' + imageCount + '"><img src="' + json.images[imageCount]['src'].replace('history/', 'history/_thumbs/thumb_') + '" width="60" height="40" /></a></div>\n';

        });
        //$$('#wrapper").append("<div style='width:100px;height:100px;top:500px'><div>");
        $('imageContainer').update(imageBlock);
        if ($('galleryDescriptionCaption')) {
            $('galleryDescriptionCaption').innerHTML = json.images[0]['title'];
        }

        if (totalPanes > 1) {
            if ($('gallery-navigation-scroller')) {
                $('gallery-navigation-scroller').update(paginationBlock);
            }
            this.slideShow(json);
        }

        this.galleryInitialise(json);



        if (totalPanes == 1) {
            $$('.loading').each(function(i) {
                i.hide();
            });
        }

    },
    galleryInitialise: function(json) {
        //Configure the containers for the gallery to be the correct width and height
        //$('bottomPanel').setStyle({'height': json.galleryDefaults['bottomPanelHeight']+'px'});
        $('imageContainer').setStyle({ 'width': (json.galleryDefaults['galleryWidth'] * totalPanes) + json.galleryDefaults['galleryWidth'] + 'px' });
        $('galleryContainer').setStyle({ 'width': json.galleryDefaults['galleryWidth'] + 'px', 'height': json.galleryDefaults['galleryHeight'] + 'px' });
        $('imageOuterContainer').setStyle({ 'width': json.galleryDefaults['galleryWidth'] + 'px', 'height': json.galleryDefaults['galleryHeight'] + 'px' });
        //$('pagination').setStyle({'max-width':json.galleryDefaults['galleryWidth']+'px','width':json.galleryDefaults['galleryWidth']+'px'});

        //$('homeClick').setAttribute('href', json.images[0]['href']);

        //Get gallery info
        var clickHandler = this.clickHandler.bindAsEventListener(this, json);
        this.gallery.observe('click', clickHandler);

        //Add galleryType specific style for positioning
        for (var i = 0; i < totalPanes; i++) {
            Element.addClassName('galleryImage' + i, json.galleryDefaults['galleryType'] + 'Image');
        }

        //Add extra styles needed for fading
        if (json.galleryDefaults['galleryType'] == "fade" && totalPanes > 0) {
            Element.removeClassName('galleryImage0', 'fadeImage');
            Element.addClassName('galleryImage0', 'fadeImage-initial');
            for (var fadeBuilder = 1; fadeBuilder < totalPanes; fadeBuilder++) {
                $('galleryImage' + fadeBuilder).setStyle({ display: 'none' });
            }
        }

        if ($('gallery-navigation-scroller')) {
            newPaginationWidth = (json.galleryDefaults['paginationCount'] * json.galleryDefaults['paginationButtonWidth']);
            $('galleryPaginationContainer').setStyle({ 'width': newPaginationWidth + 'px' });
            var buttonWidth = json.galleryDefaults['paginationButtonWidth'];
            $('galleryPaginationScroller').select('div.paginationLink').each(function(w) {
                w.setStyle({ 'width': buttonWidth + 'px' });
            });
            $('gallery-navigation-counter').innerHTML = "1/" + json.images.length;
        }
    },

    clickHandler: function(e, json) {
        var el = e.element().up(0);
        if (el.hasClassName(this.options.imageNum)) {
            this.endSlideShow();
            $$('.loading').each(function(i) {
                i.setAttribute('style', 'visibility: hidden;');
            });
            this.changeImage(el, true, json);
        } else if (el.hasClassName(this.options.imagePrev)) {
            this.endSlideShow();
            this.prevImage(json);
        } else if (el.hasClassName(this.options.imageNext)) {
            this.endSlideShow();
            this.nextImage(json);
        }
    },

    changeImage: function(el, getAttr, json) {
        if (getAttr == true) {
            var elementId = el.getAttribute('id');
            var newcurrent = elementId.replace("image", "");
        } else {
            var newcurrent = el;
        }

        var newImageId = newcurrent;
        var oldXPos = current;


        if (json.galleryDefaults['galleryType'] == "slide") {

            //if(newcurrent > current) {

            new Effect.Move("imageContainer", {
                x: -(newcurrent * json.galleryDefaults['galleryWidth']),
                duration: json.galleryDefaults['changeSpeed'],
                delay: 0,
                y: 0,
                mode: 'absolute',
                queue: 'front',
                transition: Effect.Transitions.sinoidal,
                beforeStart: function() {
                    $('imageContainer').setStyle({ 'width': (((totalPanes + oldXPos) * json.galleryDefaults['galleryWidth']) + json.galleryDefaults['galleryWidth']) + 'px' });
                },
                afterFinish: function() {
                    /*json.images.each(function(s, imageCount) {
                    totalPanes++;
                    //Build image list
                    //Check for alt text on image so you don't get 'undefined'
                    imageAlt = (json.images[imageCount]['alt'] != "") ? json.images[imageCount]['alt'] : "";
                    imageBlock+= '<div id="galleryImage'+(totalPanes-1)+'" class="slideImage">';
                    imageBlock+= '<img src="'+json.images[imageCount]['src']+'" title="'+json.images[imageCount]['alt']+'" alt="'+json.images[imageCount]['alt']+'" />';				
                    imageBlock+= '</div>';
                    });*/

                }

            });
            /*
            } else if(newcurrent < current) {
            console.log('end');
            new Effect.Move("imageContainer", {
            x: ((current-newcurrent)*json.galleryDefaults['galleryWidth']), 
            duration:json.galleryDefaults['changeSpeed'], 
            delay:0, 
            y: 0, 
            mode: 'relative', 
            queue: 'front',
            transition: Effect.Transitions.sinoidal
				
				});
            }/**/
        } else if (json.galleryDefaults['galleryType'] == "fade") {
            if (oldXPos != newImageId) {
                $('galleryImage' + newImageId).appear({ duration: json.galleryDefaults['changeSpeed'], queue: { scope: 'galleryScope'} });
                if ($('image' + newImageId)) {
                    $('image' + newImageId).addClassName('selected');
                } else {
                    $('galleryImage' + newImageId).addClassName('selected');
                }
                $('galleryImage' + oldXPos).fade({ duration: json.galleryDefaults['changeSpeed'], queue: { scope: 'galleryScope'} });
                if ($('image' + oldXPos)) {
                    $('image' + oldXPos).removeClassName('selected');
                } else {
                    $('galleryImage' + oldXPos).removeClassName('selected');
                }
                if ($('galleryDescriptionCaption')) {
                    $('galleryDescriptionCaption').innerHTML = json.images[newImageId]['title'];
                    $('gallery-navigation-counter').innerHTML = (parseInt(newImageId) + 1) + "/" + json.images.length;
                }
            }
        }
        var _url = "javascript:void window.open ('" + json.images[newImageId]['href'] + "');";
        if (json.images[newImageId]['href'] == '') {
            _url = '#';
        }

        //Set new current value
        current = newcurrent;
        var url = url1;
   
        if (jQuery('#anonymous_element_2').attr("href") == url1) {
            url = url2;
        }
        jQuery('#anonymous_element_2').attr("href", url);
    },

    prevImage: function(json) {
        if (current > 0 && totalPanes > 0) {
            this.changeImage(parseInt(current) - 1, false, json);
        }
    },

    nextImage: function(json) {
        if (slideshowTimeout && current == (totalPanes - 1)) {
            //current = 0;
            this.changeImage(0, false, json);
        } else {
            this.changeImage(parseInt(current) + 1, false, json);
        }
    },
    changePagination: function(elNum, oldelNum, getAttr, resetPagination, json) { },
    changeTitle: function(el, json) { },
    slideShow: function(json) {
        slideshowTimeout = setInterval(function() { gallery.nextImage(json); }, json.galleryDefaults['changeInterval']);

    },

    endSlideShow: function() {
        clearInterval(slideshowTimeout);
    }

});


document.observe("dom:loaded", function() {
	try {
    	if(jsonObj) {
			
			gallery = new Gallery("galleryContainer", 1,jsonObj);
		}
	} catch(e) {
      variablename=[];
	}
});
