﻿







/**
 * Product viewer object and utilities
*/

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' ?
                r.replace(/\$/g, '&#36;') : a;
        }
    );
};
var ProductViewer = Object.extend({}, {
    THUMBSTAG: '<img class="{className}" onclick="objPO.productViewer.setLargeImage(\'{group}\',{index}, \'{view}\');" onmouseover="objPO.productViewer.chgPreviewImg(\'{group}\',{index}, \'{view}\', this);" onmouseout="objPO.productViewer.chgPreviewImg(this);" alt="{altText}" id="thumbImage{group}{index}{view}" src="{src}" width="' + brandConst.PRODUCT_THUMB_WIDTH + '" height="' + brandConst.PRODUCT_THUMB_HEIGHT + '" />',

    NO_ZOOM_MSG :
            '<div class="top clearfix outer"><div class="topLeft"></div><div class="topCenter inner"></div><div class="topRight"></div></div><div id="productSoldOutMsgCenter" class="inner">{msg}</div><div class="bottom clearfix outer"><div class="bottomLeft"></div><div class="bottomCenter inner"></div><div class="bottomRight"></div></div>',

    init : function(s) {
        this.imgHolderStyle = $(s.drag + 'Layer').style;
        this.background = $(s.bg + '_bg');
        this.tint = $(s.tint);
        this.tintStyle = this.tint.style;
		this.dragBox = $(s.drag + 'Box');
        this.zoomBox = $(s.zoom + 'Layer');
        this.dragStyle = this.dragBox.style;
		this.zoomStyle = $(s.zoom + 'Layer').style;
		this.bgImg = $(s.bg);
		this.dragImg = $(s.drag + 'Img');
		this.dragImgStyle = this.dragImg.style;
		this.zoomImg = $(s.zoom + 'Img');
		this.zoomImgStyle = this.zoomImg.style;
        this.swatchHoder = $('swatchHolder');
        this.thumbContainer = $('imageThumbs');
        this.imgTools = $('imageTools');
        
        this.isImgLoaded = false;
        this.altViews = brandConst.ALT_VIEWS;
        this.thumbCounter = 1;       

        var sDeltaW = this.background.offsetWidth - this.dragBox.offsetWidth;
		var sDeltaH = this.background.offsetHeight - this.dragBox.offsetHeight;

        var zDeltaH = this.zoomImg.height - this.zoomBox.offsetHeight;
        var zDeltaW = this.zoomImg.width - this.zoomBox.offsetWidth;

        this.hScale = zDeltaH / sDeltaH;
		this.wScale = zDeltaW / sDeltaW;

        this.halfW = this.dragBox.offsetWidth / 2;
		this.halfH = this.dragBox.offsetHeight / 2;

        var thumb, large, swatch;
        this.enableZoom = true;
        this.setupBoundBox();
        this._mouseover = this.mouseOverHandler.bindAsEventListener(this);
		this._mouseout = this.mouseOutHandler.bindAsEventListener(this);
		this._mousemove = this.mouseMoveHandler.bindAsEventListener(this);
		
        Event.observe(this.tint, "mouseover", this._mouseover );
		Event.observe(this.tint, "mouseout", this._mouseout );
        Event.observe(this.dragBox, 'mouseout', this._mouseout );
    },
    loadProductImg : function() {
        this.groups = [];

        var prodStyleImgs = objP.objProductStyleImages;
        //this.bgImg.alt = objP.strProductStyleName;

        this.groups['Color'] = this.getColorImages();

        if ( prodStyleImgs.arrayAlternateViewImages.length > 0) this.groups['Alt'] = this.getArrayImages(prodStyleImgs.arrayAlternateViewImages);
        if (prodStyleImgs.arrayWaysToWearImages.length > 0) this.groups['WaysToWear'] = this.getArrayImages(prodStyleImgs.arrayWaysToWearImages);

        if( objP.objCrossSellInfo && objP.objCrossSellInfo.isPhotoOutfit ) {//alert("fdf");
            var thumb, large;

            thumb = new Image();
            large = new Image();

            thumb.src = objP.objCrossSellInfo.strImageSrc;
            large.src = thumb.src.replace('-01.jpg','-03.jpg');
            this.groups['Outfit'] = [{img : large, imgThumb:thumb}];
        }

        this.isImgLoaded = true;
    },

    getColorImages : function() {
        var styColorLen = objV.arrayVariantStyleColors.length;
        var colorThumbs = [];

        for (var i = 0; i<styColorLen; i++) {
            var objColor = objV.arrayVariantStyleColors[i];
            var variantImgs = objColor.arrayVariantStyleColorImages;

            colorThumbs[colorThumbs.length] = this.getArrayImages(variantImgs);
        }

        return colorThumbs;
    },
    getArrayImages : function(altViewImgs) {
        var image, imgThumb, imgSrc, imgThumbSrc, altViewCounter, view;
        var altViewImg, altViewThumb;

        altViewCounter = 0;
        var viewArray = [];

        var isAltView = (altViewImgs['Main'] == undefined);

        if( isAltView ) {
            for( var i = 0; i < altViewImgs.length; i++ ) {
                altViewImg = altViewImgs[i].strImagePath;
                altViewThumb = altViewImgs[i].strThumbImagePath;

                if( altViewImg != '' && altViewThumb != '' ) {
                    image = new Image();
                    imgThumb = new Image();

                    image.src = altViewImgs[i].strImagePath;
                    imgThumb.src = altViewImgs[i].strThumbImagePath;

                    viewArray[i] = {img : image, imgThumb : imgThumb };
                }
            }
        } else {
            this.hasRotational = altViewImgs['Left'].strImagePath != '';

            for(var i = 0; i < this.altViews.length; i++) {
                view = this.altViews[i];

                imgSrc = altViewImgs[view].strImagePath;

                if( view == 'Main' )
                    imgThumbSrc = this.hasRotational || !this.isPiperlime ? altViewImgs['MainThumb'].strImagePath : '';
                else
                    imgThumbSrc = altViewImgs[view].strThumbImagePath;

                if( imgSrc != '' ) {
                    image = new Image();
                    image.src = imgSrc;

                    if( imgThumbSrc != '' ) {
                        imgThumb = new Image();
                        imgThumb.src = imgThumbSrc;
                    } else {
                        imgThumb = null;
                    }

                    viewArray[view] = { img : image, imgThumb : imgThumb };
                }

            }
        }
        
        return viewArray;
    },    
    generateColorThumbs : function(imgs) {
        if( !imgs ) return '';

        this.colorArray = [];
        var strHTML = [];
        var colorImg, colorVariant;

        var i = objV.arrayVariantStyleColors.length - 1;
        do {
            colorVariant = imgs[i];
            this.thumbCounter = 0;
            strHTML.push('<div id="colorThumbs">')
            for( var view in colorVariant) {
                if (!colorVariant.hasOwnProperty(view) || view == 'Large') continue;
                colorImg = colorVariant[view];
                if( colorImg && colorImg.imgThumb ) {
                    strHTML.push(this.THUMBSTAG.supplant(
                        {
                            className:'thumbs',
                            group : 'Color',
                            index : i + '',
                            src : colorImg.imgThumb.src,
                            altText : '点击此图查看放大效果 ' + (this.thumbCounter + 1),
                            view : view
                        }));
                    this.thumbCounter++;
                }
                if( this.thumbCounter % 5 == 0 && !this.isPiperlime) strHTML.push('<div class="clear"></div>');
            }
            strHTML.push('</div>');
            this.colorArray[i] = strHTML.join('');
            strHTML.length = 0;
        } while (i--);

        return this.colorArray[objPO.selectedColor];
    },

    generateAltThumbs : function(imgs, groupName) {
        if( !imgs ) return '';

        var strHTML = [];
        var altImg;

        for( var i = 0; i < imgs.length; i++ ) {
            altImg = imgs[i];
            if( altImg && altImg.imgThumb ) {
                strHTML.push(this.THUMBSTAG.supplant(
                    {
                        className: 'thumbs',
                        group : groupName,
                        index : i + '',
                        src : altImg.imgThumb.src,
                        altText : groupName == 'Outfit' ? '此图没有放大效果' : '点击此图查看放大效果 ' + (this.thumbCounter + 1),
                        view : i + ''
                    }));
                this.thumbCounter++;
            }
            if( this.thumbCounter % 5 == 0 ) strHTML.push('<div class="clear"></div>');
        }

        return strHTML.join('');
    },
    renderThumbs : function() {
        this.thumbContainer.style.visibility = 'visible';
    },
    generateThumbs :  function() {
        if(!this.isImgLoaded) return;
        this.zoomToolPic = $('zoomToolPic');
        var options = arguments[0]

        var strHTML = [];

        strHTML.push( this.generateColorThumbs(this.groups['Color']));

        var altHTML = this.generateAltThumbs(this.groups['Alt'], 'Alt');
        var outfitHTML = this.generateAltThumbs(this.groups['Outfit'], 'Outfit');

        this.showThumbs = altHTML != '' || outfitHTML != '' || this.hasRotational;

        if( this.showThumbs ) {
            strHTML.push( altHTML );
            strHTML.push( this.generateAltThumbs(this.groups['WaysToWear'], 'WaysToWear') );
            strHTML.push( outfitHTML);

            strHTML.push('<div class="clear"></div>');
            setObjInnerHTML(this.thumbContainer, strHTML.join(''));
        }

        this.selectedGroup = 'Color';
        this.selectedIndex = objPO.selectedColor;
        this.selectedView = 'Main';
        this.selectedThumb = this.showThumbs ? $('thumbImageColor' + objPO.selectedColor + 'Main') : null;
        this.colorThumbs = $('colorThumbs');
        this.setLargeImage('Color', objPO.selectedColor, 'Main');
    },
    

    setImages : function(group, index, view) {
        var selected, selectedBgImg, selectedZoomImg;
     
        selected = this.groups[group][index];

        switch( group ) {
            case 'Color':
                selectedBgImg = selected[view].img;
                selectedZoomImg = selected[view == 'Main' ? 'Large' : view].img;
                //alert(this.enableZoom);
                var DominUrl="http://" + location.hostname + "/no.jpg";
                //alert(DominUrl);
                if(selectedZoomImg.src==DominUrl)
                {
                  //alert("没有图片");
                  this.enableZoom = false;
                  }
                break;
            case 'Alt':
            case 'WaysToWear':
            case 'Outfit':
                selectedBgImg = selected.img;
                selectedZoomImg = selected.img;
                break;
        }        
        this.bgImg.src = selectedBgImg.src;
        
        if( group != 'Outfit') {
            this.zoomImg.src = selectedZoomImg.src;
            this.dragImg.src = selectedBgImg.src;
            //this.enableZoom = true;
        } else {
            this.enableZoom = false;
        }

        if( !objPO.nanoViewClicked && view != 'Main') {
            objPO.nanoViewClicked = true;            
        }
    },
    chgPreviewImg : function() {
        var group, index, view, btn;
        if( arguments.length == 4 ) {
            group = arguments[0];
            index = arguments[1];
            view = arguments[2];
            btn = arguments[3];
            btn.className = 'thumbSelected';
        } else {
            btn = arguments[0];
            group = this.selectedGroup;
            index = this.selectedIndex;
            view = this.selectedView;
            if( this.selectedThumb != btn )
                btn.className = 'thumbs';
        }
        this.setImages(group, index, view);

    },
    setNoZoomMsg : function(msg) {
        objPO.initializeSoldOutMsg();
        var errMsg = msg != '' ? this.NO_ZOOM_MSG.supplant({msg : msg}) : '';
        objPO.setSoldOutMsgStatus(errMsg);
    },
    setLargeImage : function(group, index, view) {
        var selected, selectedBgImg, selectedZoomImg;

        if( this.showThumbs ) {
            this.selectedThumb.className = 'thumbs';
            this.selectedThumb = $('thumbImage' + group + index + view );
            this.selectedThumb.className = 'thumbSelected'
        }

        this.selectedGroup = group;
        this.selectedIndex = index;
        this.selectedView = view;

        this.setImages(group, index, view);

    },

    setupBoundBox : function() {

        var bgPos = returnObjPosition(this.background);
		this.boundBox = {
				left:bgPos.x + 1,
				top:bgPos.y + 1,
				right: bgPos.x + this.background.offsetWidth,
				btm: bgPos.y + this.background.offsetHeight
			};

		this.dragBound = {
				left: 0,
				right: this.background.offsetWidth - 2 * this.halfW,
				top: 0,
				btm: this.background.offsetHeight - 2 * this.halfH
			};

        this.imgHolderStyle.left = bgPos.x + 'px';
        this.imgHolderStyle.top = bgPos.y + 'px';
        this.imgHolderStyle.display = 'block';

        this.zoomStyle.left = (bgPos.x + this.background.offsetWidth) + 'px';
        this.zoomStyle.top = (bgPos.y + this.background.offsetHeight - this.zoomBox.offsetHeight) + 'px';

    },

	mouseOutHandler : function(e) {
        if( !this.isImgLoaded ) return;              
        if( !this.isMouseOut(e, this.boundBox)) { return };
        
        if( !this.enableZoom ) {
            this.setNoZoomMsg('');
            return;

        }        
		Event.stopObserving(document.body, "mousemove", this._mousemove );
        var time = new Date();
        var outtime = time.getTime();

        if( !this.hasEngaged ) {

            var shouldFireOmniture = outtime - this.engageTime > 2000;//此刻时间离OverHandler响应时间是否大于2000毫秒

            if( shouldFireOmniture ) {               
                this.hasEngaged = true;
            }
        }
        this.dragStyle.visibility = 'hidden';
        this.zoomStyle.zIndex = '100';
        this.zoomStyle.visibility='hidden';
        if( this.fadeEffect )
            this.fadeEffect.cancel();
        this.zoomStyle.opacity = 0;
        this.zoomStyle.filter = 'alpha(opacity:0)';
        this.tintStyle.opacity = 0;
		this.tintStyle.filter = "alpha(opacity:0)";
		
		//$('selectProSize').style.visibility = 'visible';       
		
        this.zoomToolPic.src = '/Images/zoomOver.gif';
        this.zoomToolPic.alt = '移动鼠标进入放大图像区域';
        
    },
	mouseOverHandler : function(e) {
        if( !this.isImgLoaded ) return;
        if( !this.enableZoom ) {
            this.setNoZoomMsg('没有图片可以放大.');
            return;
        }
        this.setupBoundBox();
        this.dragStyle.visibility = 'visible';
        //if(outstr)alert("nn");
		this.zoomStyle.zIndex = '10';
        this.zoomStyle.opacity = 0;
        this.zoomStyle.filter = 'alpha(opacity:0)';
        this.zoomStyle.visibility = 'visible';
        this.fadeEffect = new Effect.Opacity(this.zoomBox.id, {duration:0.5, from:0, to:1});
        this.tintStyle.opacity = .45;
		this.tintStyle.filter = "alpha(opacity:45)";      
        //$('selectProSize').style.visibility = 'hidden';
        Event.observe(document.body, "mousemove", this._mousemove );
        this.zoomToolPic.src = '/Images/zoomOut.gif';
        this.zoomToolPic.alt = '移动鼠标离开放大图像区域';

        if( !this.hasEngaged ) {
            var time = new Date();
            this.engageTime = time.getTime();
        }
    },

	mouseMoveHandler : function(e) {
        if( !Event.pointerX ) return;

        var x = Event.pointerX(e) - this.halfW - this.boundBox.left;
        var y = Event.pointerY(e) - this.halfH - this.boundBox.top;

        var left = x > this.dragBound.right ? this.dragBound.right : x < this.dragBound.left ? 0 : x;
		var top = y > this.dragBound.btm ? this.dragBound.btm : y < this.dragBound.top ? 0 : y;


		this.dragStyle.left = left + 'px';
		this.dragStyle.top = top + 'px';

		this.dragImgStyle.left = (-left - 1) + 'px';
		this.dragImgStyle.top =  -top + 'px';

		this.zoomImgStyle.left = -left * this.wScale + 'px';
		this.zoomImgStyle.top = -top * this.hScale + 'px';
    },

	/****************************** UTILITY METHODS *****************************/

	isMouseOut : function(e, boundBox) {
        if( !Event.pointerX ) return true;
        var x = Event.pointerX(e);
		var y = Event.pointerY(e);
        
		return (x <= boundBox.left ) ||
			(x >= boundBox.right) ||
			(y <= boundBox.top ) ||
			(y >= boundBox.btm) ;

	}

});


