﻿var JSExt  = {};

JSExt.$    = jQuery.noConflict();

JSExt.init = function (config) {
	//JSExt.$ = config.$ ? config.$ : null;
};


/******************************** 变量处理 ****************************************/

JSExt.variable = {};
JSExt.$V       = function(name, val) {
	if (val == null) {
		return JSExt.variable[name];
	} else {
		JSExt.variable[name] = val;
		return true;
	}
};


/******************************** Util ****************************************/

JSExt.Util     = {
	// 获取文件扩展名
	getFileExtName: function(fileName) {
        var extName = null;
        var extPos  = fileName.lastIndexOf('.') + 1;

        if (extPos > 0) {
            extName = fileName.substr(extPos).toLowerCase();
        } else {
            extName = '';
        }

        return extName;
    },
    // 获取 Url 中的所有参数
    getUrlParams: function(url) {
        var szUrl    = url == null ? document.location.href : url;
        var cacheKey = 'cache.JSExt.Util.getUrlParams.' + szUrl;

        if (!JSExt.$V(cacheKey)) {
            var aryParam = szUrl.substring(szUrl.indexOf('?') + 1).split('&');
            var params   = {};

            for(var i = 0, length = aryParam.length; i < length; i++) {
                var paramPos = aryParam[i].indexOf('=');
                if (paramPos >= 0) {
                    params[aryParam[i].substr(0, paramPos)] = aryParam[i].substr(paramPos + 1);
                } else {
                    params[aryParam[i]] = '';
                }
            }

            JSExt.$V(cacheKey, params);
        }

        return JSExt.$V(cacheKey);
    },
    // 获取 Url 中的某个参数
    getUrlParam: function(paramName) {
        return this.getUrlParams()[paramName];
    },
    // 设置 Tab
    setToTab: function(tabElms) {
    	tabElms.find('[callTab]').click(function(){
    		tabElms.children('ul').children('li').removeClass('tab_selected');
            JSExt.$(this).parent().addClass('tab_selected');
            tabElms.children('div').removeClass('tab_selected');
            tabElms.children('div').filter('[tabId=' + JSExt.$(this).attr('callTab') + ']').addClass('tab_selected');
        });
    },
    // 设置 Tab
    setToWindow: function(tabElms) {
    	tabElms.find('[callTab]').click(function(){
    		tabElms.children('ul').children('li').removeClass('tab_selected');
            JSExt.$(this).parent().addClass('tab_selected');
            tabElms.children('div').removeClass('tab_selected');
            tabElms.children('div').filter('[tabId=' + JSExt.$(this).attr('callTab') + ']').addClass('tab_selected');
        });
    },
    getGMTTime: function(dateObj) {
        var gmtOffset = parseInt(dateObj.getTimezoneOffset()) * 60 * 1000;
        var timestamp = parseInt(dateObj.getTime()) + gmtOffset;

        return timestamp;
    }
};


/******************************** 事件处理 ****************************************/

JSExt.Event = {
    bind: function(oTarget, sEventType, fnHandler) {
        if(oTarget.addEventListener){
            oTarget.addEventListener(sEventType, fnHandler, false);
        }else if(oTarget.attachEvent){
            oTarget.attachEvent("on" + sEventType, fnHandler);
        }else{
            oTarget["on" + sEventType] = fnHandler;
        }
    },
    unbind: function(oTarget, sEventType, fnHandler) {
        if(oTarget.removeEventListener){
            oTarget.removeEventListener(sEventType, fnHandler, false);
        }else if(oTarget.detachEvent){
            oTarget.detachEvent("on" + sEventType, fnHandler);
        }else{
            oTarget["on" + sEventType] = null;
        }
    },
    getEvent: function() {
        if(window.event){
            return window.event;
        }else{
            return JSExt.Event.getEvent.caller.arguments[0];
        }
    },
    getSrcElement: function(evt) {
        return evt.srcElement ? evt.srcElement : evt.target;
    },
    fire: function(element, eventName) {
        if (element) {
            if (document.all && navigator.userAgent.toLowerCase().match(/msie ([\d.]+)/)[1] < 9) {
                element.fireEvent('on' + eventName);
            } else {
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent(eventName, true, true);
                element.dispatchEvent(evt);
            }
        }
    }
};


/******************************** 模板处理 ****************************************/

JSExt.Template = function(containerId, templateTagName, templateNameAttr) {
	this.list = function (containerId, templateTagName, templateNameAttr) {
		containerId      = containerId ? containerId : 'attributeTemplateList';
		templateTagName  = templateTagName ? templateTagName : 'div';
		templateNameAttr = templateNameAttr ? templateNameAttr : 'templateName';
		var cacheName    = 'cache.templateList.' + containerId + templateTagName + templateNameAttr;

		if (!JSExt.$V(cacheName)) {
			var templateElmList = document.getElementById(containerId).getElementsByTagName(templateTagName);
		    var templateList = {};
		    for (var i = 0, length = templateElmList.length; i < length; i++) {
		    	if (templateElmList[i].getAttribute(templateNameAttr)) {
		    		templateList[templateElmList[i].getAttribute(templateNameAttr)] = templateElmList[i];
		    	}
		    }

		    JSExt.$V(cacheName, templateList);
		}

	    return JSExt.$V(cacheName);
	};
	this.get = function (name, data) {
        var templateList = this.list(this.containerId, this.templateTagName, this.templateNameAttr);
        if (data.code && templateList[name + '_' + data.code] != null && templateList[name].innerHTML.length > 0) {
            name = name + '_' + data.code;
        } else if (templateList[name] == null || templateList[name].innerHTML.length == 0) {
            templateList[name] = {innerHTML: '<' + templateTagName + '></' + templateTagName + '>'};
        }
        var template = templateList[name].innerHTML;

        // 处理变量
        var pattern = '({\\$[a-zA-Z0-9_\.]{1,}})|(%7B\\$[a-zA-Z0-9_\.]{1,}%7D)';
        var regex   = new RegExp(pattern, 'g');
        var templateVarList = template.match(regex);
        if (templateVarList != null) {
            for (var i = 0, length = templateVarList.length; i < length; i++) {
                template = template.replace(templateVarList[i], this.Util.getData(templateVarList[i], data));
            }
        }

        // 处理常量
        var pattern = '{\\@([a-zA-Z0-9_\.]{1,})}|%7B\\@([a-zA-Z0-9_\.]{1,})%7D';
        var regex   = new RegExp(pattern, 'g');
        template    = template.replace(regex, '$1');

        return template;
	};
	this.Util = {
		getData: function (name, data) {
	        var result = null;
	        var key    = name.substr(0,1) == '{' ? name.substr(2, name.length - 3) : name.substr(4, name.length - 7);
	        key        = key.indexOf('.') == -1 ? key : key.split('.');

	        if (JSExt.$.isArray(key)) {
	            var tempVar = data;
	            for (var i = 0, length = key.length; i < length; i++) {
	                if (tempVar[key[i]]) {
	                    tempVar = tempVar[key[i]];
	                }
	            }
	            if (JSExt.$.inArray(typeof tempVar, ['string', 'number', 'boolean']) >= 0) {
	                result = tempVar;
	            }
	        } else if (data[key]) {
	            result = data[key];
	        }

	        return result == null ? '' : result;
		}
	};
};


/******************************** 商品类 ****************************************/

JSExt.Product = {};

//产品画册
JSExt.Product.Image = {
	isInit: false, 
	config: {}, 
	// 初始化
	init: function(configData) {
		this.setColorListData(configData.colorData.list);
		if (typeof configData.bindLoadGallery == 'boolean' && configData.bindLoadGallery) {
			JSExt.Product.Attr.Event.postEvent.optionClick.loadCurrentGalleryImage = JSExt.Product.Image.loadCurrentGallery;
		} else if (typeof configData.bindLoadGallery == 'function') {
			JSExt.Product.Attr.Event.postEvent.optionClick.loadCurrentGalleryImage = configData.bindLoadGallery;
		}
		this.loadingEnable=false;
		if(configData.loadingEnable){
			this.loadingEnable=true;
		}
		this.isInit = true;
	}, 
	setColorListData: function(colorData) {
		this.config.colorListData = colorData;
	}, 
	getLoadingEnable:function(){
		return this.loadingEnable;
	},
	getColorListData: function() {
		return this.config.colorListData;
	}, 
	// 选择图片
	select: function(elm) {
	    try {
	    	if (!JSExt.Product.Image.isInit) {
	    		throw 'Please initialize object first!';
	    	}
	        var obj     = JSExt.$(elm);
	        var colorId = obj.attr('imgColorId');
	        obj.parent("li").hide().siblings().show();
			// 如果找不到属性，则加载
	        if (!elm.bigImg) {
	            var galleryImagesData = JSExt.Product.Image.getColorListData()[colorId].galleryImages;
	            for (var i = 0, length = galleryImagesData.length; i < length; i++) {
	                if (galleryImagesData[i].info.id == elm.imgId) {
	                	elm.baseImg  = galleryImagesData[i].image.base;
	                	elm.bigImg   = galleryImagesData[i].image.big;
	                	elm.fileType = galleryImagesData[i].info.fileType;
	                    break;
	                }
	            }
	        }

	        // 读取数据
	        var productImageBoxClass = '.product-img-box-' + elm.attr.getProductId();
	        var galleryImage = JSExt.$(productImageBoxClass + ' > div > div > div > #gallery-image');
	        var galleryFlash = JSExt.$(productImageBoxClass + ' > div > div > div > #gallery-flash');
	        var imageContainerInner = JSExt.$(productImageBoxClass + ' > div > div > #image-container-inner');
	        var flashContainerInner = JSExt.$(productImageBoxClass + ' > div > div > #flash-container-inner');
	        if (elm.fileType && elm.fileType != 'swf') {
	        	galleryImage.attr('alt',   obj.attr('alt'));
	        	galleryImage.attr('title', obj.attr('title'));
	        	if(this.loadingEnable){
					this.loadImage(galleryImage,obj.attr('baseImg'),elm.attr.getProductId());
				}else{
					galleryImage.attr('src',   elm.baseImg);
				}
	        	galleryImage.attr('jqImg', elm.bigImg);
	        	flashContainerInner.css('display', 'none');
				imageContainerInner.css('display', 'block');
	        } else {
	        	galleryFlash.children('param[name=movie]').val(elm.baseImg);
	        	galleryFlash.children('embed:first').attr('src', elm.baseImg);
	            imageContainerInner.css('display', 'none');
	            flashContainerInner.css('display', 'block');
	        }
	    } catch (e) { throw e; }
	}, 
	/*********************************************************/
	loadImage:function(elm,baseImg,productId){
		var img = new Image();
		img.src=baseImg;
		if(img.complete){
			elm.attr('src', baseImg);
			return;
		}
		this.elmDisabled(elm,productId);
		JSExt.$(img).load(function(){
				elm.attr('src', baseImg);
				JSExt.Product.Image.loadingDivHide(productId);
				elm.parent().addClass('jqzoom');
				if(loadingTimeId){
					clearTimeout(loadingTimeId);
				}
				return false;
		});
		var loadingTimeId=setTimeout(function(){
			elm.attr('src', baseImg);
			JSExt.Product.Image.loadingDivHide(productId);
			if(!elm.parent().hasClass('jqzoom')){
				elm.parent().addClass('jqzoom');
			}
		},10000);
		
	},
	elmDisabled:function(elm,productId){
		this.galleryImageLoading(elm,productId);
		this.moreviewsDisabled(productId);
		this.attributeReloadContainerDisabled(productId);
	},
	galleryImageLoading:function(elm,productId){
		var height=parseInt(elm.css('height'));
		var width=parseInt(elm.css('width'));
		var loadingElm='.gallery-image-loading-'+productId;
		JSExt.$(loadingElm)
					.css({'width':width+2+'px','height':height+2+'px'})
					.css({'opacity': '0.4','filter': 'alpha(opacity=40)','-moz-opacity': '0.4'})
					.show();
		var marginValue=(height-90)/2+'px auto';
		JSExt.$(loadingElm).children('img').css('margin',marginValue);
		elm.parent().removeClass('jqzoom');
	},
	moreviewsDisabled:function(productId){
		var elm=JSExt.$('.more-views');
		var height=elm.height();
		var width=elm.width();
		JSExt.$('.more-views-disabled-'+productId)
				.css({'width':width+'px','height':height+'px'}).show()
				.css({'opacity': '0.4','filter': 'alpha(opacity=40)','-moz-opacity': '0.4'});
	},
	attributeReloadContainerDisabled:function(productId){
		var elm=JSExt.$('.product-info-'+productId);
		var height=elm.height();
		var width=elm.width();
		JSExt.$('.attributeReloadContainer-disabled-'+productId)
				.css({'width':width+'px','height':height+'px','z-index':'100'}).show()
				.css({'opacity': '0.4','filter': 'alpha(opacity=40)','-moz-opacity': '0.4'});
	},
	loadingDivHide:function(productId){
		JSExt.$('.attributeReloadContainer-disabled-'+productId).hide();
		JSExt.$('.more-views-disabled-'+productId).hide();
		JSExt.$('.gallery-image-loading-'+productId).hide();
	},
	/*********************************************************/
	//列表页切换
	turnSecondImg:function(elm, isSecond){
	/*
		if (!elm.isInitSecondData) {
			var imgSecondSrc = elm.getAttribute("second_img");
			elm.secondImage = imgSecondSrc ? imgSecondSrc : null;
			elm.smallImage  = elm.src;
			elm.isInitSecondData = true;
		}
		elm.isSecond = isSecond ? true : false;
		if (elm.isSecond && elm.secondImage){
		    if (elm.existSecondImage == undefined) {
				var Img = new Image;
				Img.src = imgSecondSrc;
				Img.onload = function(){
					elm.existSecondImage = true;
					if (elm.isSecond) {
						elm.src = elm.secondImage;
					}
				};
				Img.onerror = function(){
					elm.existSecondImage = false;
				};
			} else if (elm.existSecondImage) {
				elm.src = elm.secondImage;
			}
		} else {
			elm.src = elm.smallImage;
		}
		*/
		var elm=JSExt.$(elm);
		var elm_img_url=elm.attr('src');
		var second_url=elm.attr('second_img');
		if(second_url.indexOf('second_image.jpg')==-1){
			elm.attr('src',second_url);
			elm.attr('second_img',elm_img_url);		
		}
	},
	// 加载当前列表
	loadCurrentGallery: function() {
	    try {
			var attr = this.opt.attr;
			var opt  = this.opt;
			var productId = attr.getProductId();
			JSExt.Product.Image.setColorListData(attr.getColorData().list);
	    	if (!JSExt.Product.Image.isInit) {
	    		throw 'Please initialize object first!';
	    	}
	        var colorId  = attr.getValByCode('color');
	        var moreView = JSExt.$('.product-img-box-' + productId + ' > .more-views > ul');
	        if (moreView.attr('colorId') == colorId) {
	        	return ;
	        }
	        var tempElm  = moreView.children('li').eq(0);
	        var template = tempElm.html();
	        if (colorId > 0 && template != null && template.length > 0) {
	            moreView.html('');
	            var galleryImagesData = JSExt.Product.Image.getColorListData()[colorId].galleryImages;
				var imageLabel        = null;
				var productName       =JSExt.$('.product-2col-right .product-shop .product-name h1').val();
	            for (var i = 0, length = galleryImagesData.length; i < length; i++) {
		            var templateObj  = JSExt.$(template);
					templateObj.removeAttr('src');
		            var templateElm  = templateObj.get(0);
		            templateElm.attr = attr;
					if(galleryImagesData[i].info.label=="nozoom" || !galleryImagesData[i].info.label){
						imageLabel = productName+"-"+JSExt.Product.Image.getColorListData()[colorId].label;
					} else {
						imageLabel = galleryImagesData[i].info.label;
					}
					templateObj.attr('alt',        imageLabel);
					templateObj.attr('title',      imageLabel);
					templateObj.attr('src',        galleryImagesData[i].image.thumbnail);
					templateElm.fileType   = galleryImagesData[i].info.fileType;
					templateElm.baseImg    = galleryImagesData[i].image.base;
					templateElm.bigImg     = galleryImagesData[i].image.big;
					templateElm.imgId      = galleryImagesData[i].image.id;
					templateElm.imgColorId = galleryImagesData[i].image.colorId;
					if(length==1){
						moreView.hide();
					}else{
						moreView.show();
					}
	                var tempElm = JSExt.$('<li></li>').append(templateObj);
					moreView.append(tempElm);
	            }
	        }
	        moreView.attr('colorId', colorId);
	        if (moreView.children('li').children('img').length > 0) {
	            JSExt.Event.fire(moreView.children('li').children('img').get(0), 'click');
	        }
	    } catch (e) { throw e; }
	}
};


//////////////////////////////////////////////////////////////////////////
// 产品属性
JSExt.Product.Attr = function(config) {
	this.tpl       = null;
	this.dataCache = {};
	this.cache = function(key, data) {
		if (typeof(data) != 'undefined') {
			this.dataCache[key] = data;
		}

		return this.dataCache[key];
	};
	// 初始化数据
	this.init = function(config) {
		this.tpl = config.tpl ? config.tpl : this.tpl;
		this.opt = new JSExt.Product.Attr.Option(this);
		if (config.attributeData) {
			if (config.attributeDataIndex) {
				this.getFormatedData(config.attributeData, config.attributeDataIndex);
			} else {
				this.getFormatedData(config.attributeData);
			}
		} else {
			throw 'attribute data source not found!';
		}
		if (config.colorData) {
			this.setColorData(config.colorData);
			var mergeColorData = this.mergeColorData4AttrData(this.getFormatedData(), config.colorData);
			this.setFormatedData(mergeColorData);
			this.selectColor='';
			if(config.colorData.selectColor){
				if(config.colorData.selectColor.length>0){
					this.selectColor=config.colorData.selectColor;
				}
			}
		}
		if (config.defaultShow) {
			this.show();
		}
	};
	this.config = {
		showTipIn: 'after', // before, after, null
		showAllOption: false,
		defaultSelect: false,
		attributeContainerType: 'reload'
	};
	this.formatData = function(sourceData, attributeConfigIndex) {
        // 初始化数据
        if (sourceData == null) {
            return false;
        }
        var formatedData  = [];
        var attributeKeys = [];

        // 取得所有Key
        for (var key in sourceData.attributes) {
            attributeKeys.push(key);
        }

        // 格式化数据
        var attributeKeysCount = attributeKeys.length;
        for (var i = 0; i < attributeKeysCount; i++) {
            var tempDataObj     = {};

            // 取得节点信息
            tempDataObj.info    = {id:    sourceData.attributes[attributeKeys[i]].id,
                                   code:  sourceData.attributes[attributeKeys[i]].code,
                                   label: sourceData.attributes[attributeKeys[i]].label};

            // 取得节点选项信息
            tempDataObj.options = [];
            JSExt.$.each(sourceData.attributes[attributeKeys[i]].options, function(key, obj){
                var tempObj = {};
                tempObj.info = {id:    obj.id,
                                label: obj.label,
                                code:  sourceData.attributes[attributeKeys[i]].code};
                tempObj.products = obj.products;

                tempDataObj.options.push(tempObj);
            });

            formatedData.push(tempDataObj);
        }

        // 重组数据排序
        if (attributeConfigIndex != null) {
            var tempFormatedData = [];
            for (var i = 0, length = formatedData.length; i < length; i++) {
                for (var key in attributeConfigIndex) {
                    if (formatedData[i].info.id == key) {
                        tempFormatedData[attributeConfigIndex[key]] = formatedData[i];
                    }
                }
            }
            formatedData = tempFormatedData;
        }

        return formatedData;
	};
	this.getProductId = function () {
		return this.getSourceData()['productId'];
	};
	this.setColorData = function (data) {
		this.cache('colorData', data);
		return true;
	};
	this.getColorData = function () {
		return this.cache('colorData');
	};
	this.setFormatedData = function (data) {
		this.cache('formatedData', data);
		return true;
	};
	this.getSourceData = function () {
		return this.cache('sourceData');
	};
	this.getFormatedData = function (sourceData, attributeConfigIndex) {
		if (sourceData) {
			this.cache('sourceData', sourceData);
			this.cache('formatedData', this.formatData(sourceData, attributeConfigIndex));
		} else if (!this.cache('formatedData')) {
			throw 'format data is not found!';
		}

		return this.cache('formatedData');
	};
	this.mergeColorData4AttrData = function(attrData, colorData) {
        for (var i = 0, attrLength = attrData.length; i < attrLength; i++) {
            if (attrData[i].info.code == 'color') {
            	for (var key = 0, optLength = attrData[i].options.length; key < optLength; key++) {
                    if (colorData.list[attrData[i].options[key].info.id] != null) {
                    	attrData[i].options[key].info.colorData = colorData.list[attrData[i].options[key].info.id];
						if(colorData.list[attrData[i].options[key].info.id].colorName){
							var colorNameTmp=colorData.list[attrData[i].options[key].info.id].colorName;
							colorNameTmp=colorNameTmp.replace(' ','-');
							colorNameTmp=colorNameTmp.replace('/','-');
							colorNameTmp=colorNameTmp.replace('.','-');
							attrData[i].options[key].info.colorName = colorNameTmp.toLowerCase();
						}
                    }
                }

                break;
            }
        }

        return attrData;
    };
    this.getAttributeContainer = function() {
    	return document.getElementById('attributeReloadContainer-' + this.getProductId());
    };
    this.getLastAttribute = function() {
        var attributeReloadContainer = this.getAttributeContainer();
        var attributeElms = attributeReloadContainer.childNodes;
        for (var i = attributeElms.length - 1; i >= 0; i--) {
            if (attributeElms[i].nodeType == 1 && attributeElms[i].getAttribute('isOptionContainer') != null) {
                return attributeElms[i];
            }
        }

        return null;
    };
	// 获取属性值
	this.getValByCode = function(code) {
        var attributeElm = null;
        var formatedData = this.getFormatedData();
        var attributeId  = null;

        for (var i = 0, length = formatedData.length; i < length; i++) {
            if (formatedData[i].info.code == code) {
            	attributeId = formatedData[i].info.id;
            	break;
            }
        }

        if (attributeId == null) {
            return null;
        }

        attributeElm = this.getElmObj(attributeId);

        return attributeElm.value;
	};
	// 获取属性代码
	this.getCodeById = function(attrId) {
		var formatedData = this.getFormatedData();
        for (var i = 0, length = formatedData.length; i < length; i++) {
        	if (formatedData[i].info.id == attrId) {
        		return formatedData[i].info.code;
        	}
        }

        return null;
	};
	// 获取属性Id
	this.getElmId = function(attrKey, type) {
        var elmId = 'attribute-' + this.getProductId() + '-';

        if (type == 'reload') {
            elmId += attrKey + '-reload';
        } else if (type == 'tip-container') {
            elmId += attrKey + '-tip-container';
        } else {
            elmId += attrKey;
        }

        return elmId;
	};
	// 获取属性Obj
	this.getElmObj = function(attrKey, type) {
        var elmId = this.getElmId(attrKey, type);
        elm = document.getElementById(elmId);

        return elm;
	};
	// 初始化数据
	this.create = function(attrKey, createOption, isForce) {
        var attributeData      = this.getFormatedData()[attrKey];
        var attributeContainer = this.getAttributeContainer();
        var optionContainer    = JSExt.$(this.tpl.get('optionContainer', attributeData.info)).get(0);
        var optionContainerId  = this.getElmId(attributeData.info.id, this.config.attributeContainerType);

        if (!isForce && document.getElementById(optionContainerId)) {
        	return ;
        }

        // 创建选项容器
        optionContainer.setAttribute('id',       optionContainerId);
        optionContainer.setAttribute('attrId',   attributeData.info.id);
        optionContainer.setAttribute('attrCode', attributeData.info.code);
        optionContainer.setAttribute('attrLv',   attrKey);
        optionContainer.setAttribute('isOptionContainer', 1);
        optionContainer.style.display = 'none';
        attributeContainer.appendChild(optionContainer);

        // 创建提示容器
        var tipContainer = null;
        if (this.config.showTipIn != null) {
            tipContainer = document.createElement('div');
            tipContainer.setAttribute('id', this.getElmId(attributeData.info.id, 'tip-container'));
        }

        if (tipContainer != null && this.config.showTipIn == 'before') {
            optionContainer.appendChild(tipContainer);
        }

        // 创建选项及绑定事件
        if (createOption == null || createOption == true) {
            var aoReKey = 0;
            for (var optKey in attributeData.options) {
            	if (isNaN(optKey)) {
            		continue;
            	}
            	var optionData = attributeData.options[optKey];
                if (!this.opt.inAttribute(attrKey, optKey)) {
                    continue;
                }

                var tempElmList         = [];
                var optionListContainer = null;
                // get optionContainer.children
                for (var i = 0, cnLength = optionContainer.childNodes.length; i < cnLength; i++) {
                    if (optionContainer.childNodes[i].nodeType == 1) {
                    	tempElmList.push(optionContainer.childNodes[i]);
                    }
                }
                if (tempElmList.length > 0) {
                	for (var i = 0, length = tempElmList.length; i < length; i++) {
                		if (tempElmList[i].getAttribute('containerType') && 
                			tempElmList[i].getAttribute('containerType') == 'optionList') {
                			optionListContainer = tempElmList[i];
                			break;
                		}
                	}
                }
                if (!optionListContainer) {
                	optionListContainer = optionContainer;
                }
                this.opt.create(optionListContainer, optionData, optionContainer.getAttribute('id'), attrKey, aoReKey++);
            }
        }

        if (tipContainer != null && this.config.showTipIn == 'after') {
            optionContainer.appendChild(tipContainer);
        }
	};
	// 显示属性选项
	this.show = function(attrKey) {
		JSExt.Product.Attr.Event.execute('pre', 'attributeShow', this, arguments);

        attrKey = (typeof attrKey == 'number' && attrKey > 0) ? attrKey : 0;

        var attributeContainer = this.getAttributeContainer();
        var attributeData = this.getFormatedData()[attrKey];
        if (attributeData == null) {
            return false;
        }

        // 去除所选属性的所有下级节点
        if (attributeContainer.hasChildNodes && attrKey > 0) {
            var removeList = [];
            JSExt.$.each(attributeContainer.childNodes, function(key, optionElm) {
                if (optionElm && (optionElm.getAttribute('attrLv') == null || parseInt(optionElm.getAttribute('attrLv')) >= attrKey)) {
                    removeList.push(optionElm);
                }
            });
			
            for (var i = 0; i < removeList.length; i++) {
                // 如果非默认显示全部，则去除未显示选项的选择提示
                if (this.config.showAllOption == false && removeList[i].getAttribute('attrId') != null) {
                    var attributeElm = this.getElmObj(removeList[i].getAttribute('attrId'));
                    if (attributeElm.disabled && attributeElm.options.length > 0) {
                        attributeElm.options[0].removeAttribute('value');
                    }
                }

                attributeContainer.removeChild(removeList[i]);
            }
			
        }

        // 创建并显示下级节点
        this.create(attrKey);
        var currentAttributeElm = document.getElementById(this.getElmId(attributeData.info.id, this.config.attributeContainerType));
        currentAttributeElm.style.display = 'block';

        JSExt.Product.Attr.Event.execute('post', 'attributeShow', this, arguments, {'currentAttributeElm': currentAttributeElm});
	};

	this.init(config);
};
JSExt.Product.Attr.Event = {
    preEvent:  {},
    postEvent: {},
    getParam: function(args) {
    	if (args.length > 0) {
    		return args[args.length - 1];
    	} else {
    		return {};
    	}
    },
    execute:   function(type, action, thisObj, args, param) {
        var events = this[type + 'Event'][action];
        var params = [];
        for (var i = 0, length = args.length; i < length; i++) {
        	params[i] = args[i];
        }
        params.push(param);

        for (var key in events) {
            events[key].apply(thisObj, params);
        }
    }
};


JSExt.Product.Attr.Option = function (attr) {
	this.attr = attr;
	this.inAttribute = function(attrKey, optKey) {
        var attributeData = this.attr.getFormatedData()[attrKey];
        var optionProducts = attributeData.options[optKey].products;

        if (attributeData == null) {
            return false;
        }

        // 取得选项商品，并回朔上级选项是否存在该商品
        for (var key = attrKey - 1; key >= 0; key--) {
            var tempArr   = [];
            var aProducts = this.getSelectedData(key).products;
            for (var i = 0, length = optionProducts.length; i < length; i++) {
                if (JSExt.$.inArray(optionProducts[i], aProducts) >= 0) {
                    tempArr.push(optionProducts[i]);
                }
            }

            optionProducts = tempArr;
            if (optionProducts.length < 1) {
                return false;
            }
        }

        return true;
	};
	this.getElmId = function(attrElmId, optKey, type) {
        var elmId = attrElmId + '-option-' + optKey + '-' + type;

        return elmId;
	};
	this.getElmByChild = function(childElm) {
		var elm = childElm;
        for (var i = 0; i < 20; i++) {
        	if (!elm || elm.getAttribute('isOption')) {
        		break;
        	} else {
        		elm = elm.parentNode;
        	}
        }

        return elm;
	};
	this.getContainer = function(optElm) {
		var container = optElm.parentNode;
        for (var i = 0; i < 20; i++) {
        	if (!container || container.getAttribute('isOptionContainer')) {
        		break;
        	} else {
        		container = container.parentNode;
        	}
        }

        return container;
	};
	this.getOptionElms = function(container) {
		var nodes = container.childNodes;
		var optionElmContainer = null;
        for (var i = 0, length = nodes.length; i < length; i++) {
        	if (nodes[i].nodeName != '#text' && nodes[i].getAttribute('containerType') && nodes[i].getAttribute('containerType') == 'optionList') {
        		optionElmContainer = nodes[i];
        		break;
        	}
        }
        if (!optionElmContainer) {
        	optionElmContainer = container;
        }

        return optionElmContainer.childNodes;
	};
	this.getTipContainers = function(container) {
		var nodes = container.childNodes;
		var elms  = [];

        for (var i = 0, length = nodes.length; i < length; i++) {
        	if (nodes[i].nodeName != '#text' && nodes[i].getAttribute('id') && nodes[i].getAttribute('id').indexOf('-' + this.attr.getElmId(container.getAttribute('attrId'), 'tip-container')) >= 0) {
        		elms.push(nodes[i]);
        	}
        }

        return elms;
	};
	this.getSelectedElm = function(attrKey) {
        var attributeData = this.attr.getFormatedData()[attrKey];
        var optionElm     = JSExt.$('#' + this.attr.getElmId(attributeData.info.id));

        for ( var i = 0, length = attributeData.options.length; i < length; i++ ) {
            if (attributeData.options[i].info.id == optionElm.val()) {
            	var elmId = this.getElmId(this.attr.getElmId(attributeData.info.id, this.attr.config.attributeContainerType), i, 'select');
                return document.getElementById(elmId);
            }
        }

        return null;
	};
	this.getSelectedData = function(attrKey) {
        var attributeData = this.attr.getFormatedData()[attrKey];
        var optionElm     = JSExt.$('#' + this.attr.getElmId(attributeData.info.id));

        for ( var i = 0, length = attributeData.options.length; i < length; i++ ) {
            if (attributeData.options[i].info.id == optionElm.val()) {
                return attributeData.options[i];
            }
        }

        return {};
	};
	this.create = function(optionContainer, optionData, attrElmId, attrKey, optKey) {
        // 创建默认状态
        var defaultOptionElm = JSExt.$(this.attr.tpl.get('optionNotSelect', optionData.info)).get(0);
        defaultOptionElm.cacheData = {};
        defaultOptionElm.setAttribute('id',     this.getElmId(attrElmId, optKey, 'default'));
        defaultOptionElm.setAttribute('attrLv', attrKey);
        defaultOptionElm.setAttribute('optLv',  optKey);
        defaultOptionElm.setAttribute('optId',  optionData.info.id);
        defaultOptionElm.setAttribute('title',  optionData.info.label);
        defaultOptionElm.setAttribute('isOption',    1);
		if(optionData.info.colorName){
			defaultOptionElm.setAttribute('colorname', optionData.info.colorName);
		}
        defaultOptionElm.setAttribute('optionType',  'default');
        defaultOptionElm.setAttribute('optionKey',   attrKey + '_' + optKey);
        defaultOptionElm.cacheData.displayMode = defaultOptionElm.style.display ? defaultOptionElm.style.display : '';

        optionContainer.appendChild(defaultOptionElm);
        defaultOptionElm.opt = this;
        JSExt.Event.bind(defaultOptionElm, 'click', this.Event.click);

        // 创建选中状态
        var selectOptionElm = JSExt.$(this.attr.tpl.get('optionIsSelect', optionData.info)).get(0);
        selectOptionElm.cacheData = {};
        selectOptionElm.setAttribute('id',     this.getElmId(attrElmId, optKey, 'select'));
        selectOptionElm.setAttribute('attrLv', attrKey);
        selectOptionElm.setAttribute('optLv',  optKey);
        selectOptionElm.setAttribute('optId',  optionData.info.id);
        selectOptionElm.setAttribute('title',  optionData.info.label);
		if(optionData.info.colorName){
			selectOptionElm.setAttribute('colorname', optionData.info.colorName);
		}
        selectOptionElm.setAttribute('isOption',    1);
        selectOptionElm.setAttribute('optionType',  'selected');
        selectOptionElm.setAttribute('optionKey',   attrKey + '_' + optKey);
        selectOptionElm.cacheData.displayMode = selectOptionElm.style.display ? selectOptionElm.style.display : '';
        selectOptionElm.style.display = 'none';

        optionContainer.appendChild(selectOptionElm);

        var param = {'defaultOptionElm': defaultOptionElm, 'selectOptionElm': selectOptionElm, 'optionData': optionData, 'attrKey': attrKey};
        JSExt.Product.Attr.Event.execute('post', 'optionCreate', this, arguments, param);
	};
	this.Event = {
		select: function() {
			var opt = this.opt ? this.opt : this;
        	var optionElm = opt.getElmByChild(this);
        	if (optionElm.getAttribute('notExeBasicEvent')) {
        		return false;
        	}

        	var optionContainer = opt.getContainer(optionElm);
            var selectElm       = opt.attr.getElmObj(optionContainer.getAttribute('attrId'));

            // 当选项不允许选择时
            if (selectElm.disabled) {
                return false;
            }

            selectElm.value = optionElm.getAttribute('optId');
            JSExt.Event.fire(selectElm, 'change');

            // 选择成功
            if (selectElm.value == optionElm.getAttribute('optId')) {
                var optionElmList = opt.getOptionElms(optionContainer);

                // 所有选项置为默认状态
                for (var i = 0, length = optionElmList.length; i < length; i++) {
                    if (optionElmList[i].nodeType == 1) {
                        if (optionElmList[i].getAttribute('optionType') == 'selected') {
                            optionElmList[i].style.display = 'none';
                        } else {
                            optionElmList[i].style.display = optionElmList[i].cacheData.displayMode;
                        }
                    }
                }
                var removeList = opt.getTipContainers(optionContainer);
                // 去除本选项提示信息
                for (var i = 0, length = removeList.length; i < length; i++) {
                	optionContainer.removeChild(removeList[i]);
                }

                // 改变选中选项样式
                var optionObj = JSExt.$(optionElm);
                optionObj.css('display', 'none');
                var optionOtherObj = optionObj.siblings('[optionKey=' + optionObj.attr('optionKey') + ']').get(0);
                optionOtherObj.style.display = optionOtherObj.cacheData.displayMode;

                // 显示下级菜单
                opt.attr.show(parseInt(optionContainer.getAttribute('attrLv')) + 1);
            } else {
                throw "Select failure, Options exception!";
            }
		}, 
		click: function() {
			var _this = JSExt.Event.getSrcElement(JSExt.Event.getEvent(this));
			JSExt.Product.Attr.Event.execute('pre',  'optionClick', _this, arguments);
			_this.opt.Event.select.apply(_this, arguments);
			JSExt.Product.Attr.Event.execute('post', 'optionClick', _this, arguments);
		}
	};
};



////////////////////////////////////// 商品事件

JSExt.Product.Event = {};

// 改变购买数
// @param $V.Product.Event.changeQty.maxQty
JSExt.Product.Event.changeQty = function(elm, operateType, qty) {
	if (operateType != 'add' && operateType != 'sub' && operateType != 'set') {
		return false;
	}

	var $          = JSExt.$;
	elm            = $(elm);
	var maxQty     = parseInt(JSExt.$V('Product.Event.changeQty.maxQty'));
	var productElm = $('[isOption=1][optionType=selected]:visible:last');
	var productQty = productElm.length > 0 ? parseInt(productElm.attr('productsQty')) : null;
	maxQty         = isNaN(maxQty) ? null : maxQty;
	productQty     = (productQty && !isNaN(productQty)) ? productQty : null;
	if (productQty && maxQty) {
		maxQty = maxQty > productQty ? productQty : maxQty;
	} else if (productQty) {
		maxQty = productQty;
	}

	var qtyElm     = elm.attr('elmId') ? elm : $('[elmId=' + elm.attr('callElm') + ']').eq(0);
	var currentQty = parseInt(qtyElm.val());
	currentQty     = (isNaN(currentQty) || currentQty < 1) ? 1 : currentQty;

	qty            = operateType == 'set' ? currentQty : parseInt(qty);
	qty            = (isNaN(qty) || qty < 1) ? 1 : qty;

	if (operateType == 'add' && ((maxQty && (currentQty + qty) <= maxQty) || !maxQty)) {
		currentQty += qty;
	} else if (operateType == 'sub') {
		if (currentQty > qty) {
			currentQty -= qty;
		}
	} else if (operateType == 'set') {
		currentQty  = qty;
	}

	if (maxQty && currentQty > maxQty) {
		currentQty = maxQty;
	}

	qtyElm.val(currentQty);
};


////////////////////////////////////// 商品属性事件
//currentAttributeElm
JSExt.Product.Attr.Event.preEvent.attributeShow = {};
//currentAttributeElm
JSExt.Product.Attr.Event.postEvent.attributeShow = {};

// 默认选择第一个选项
JSExt.Product.Attr.Event.postEvent.attributeShow.defaultSelect = function() {
	var attr = this;
	var opt  = this.opt;
	if (attr.config.defaultSelect != true) {
	   return false;
	}

	var param = JSExt.Product.Attr.Event.getParam(arguments);
	var currentAttributeElm = param.currentAttributeElm;
	if (currentAttributeElm != null) {
	   var optionId = opt.getElmId(currentAttributeElm.id, 0, 'default');
	   JSExt.Event.fire(document.getElementById(optionId), 'click');
	}
};

// 颜色尺寸规则事件
JSExt.Product.Attr.Event.postEvent.attributeShow.colorAndSizeRule = function() {
	var attr = this;
	var opt  = this.opt;
	var param = JSExt.Product.Attr.Event.getParam(arguments);
	var currentAttributeElm = param.currentAttributeElm;
    var attrCode = attr.getCodeById(currentAttributeElm.getAttribute('attrId'));
    var options  = JSExt.$(opt.getOptionElms(currentAttributeElm));
    if (options <= 0) {
    	return false;
    }
    if (attrCode == 'color') {
    	var colorData = attr.getColorData();
    	if (!colorData) {
    		return false;
    	}

    	// 自动选择颜色
	 var defaultOpt = null;
	 var selectedColorId=null;
	 var selectedColor=null;
	 var selectType=false;
	 /*selectedColor*/
	 if(this.selectColor.length>0){
		selectedColor = this.selectColor;
	 }else{
		selectedColorId=JSExt.Util.getUrlParam('ColorID');
	 }
    	// 获取所选颜色
		if (selectedColorId) {
			defaultOpt = options.filter('[optId=' + selectedColorId + ']');
			selectType=true;
		}  else if (selectedColor) {
			defaultOpt = options.filter('[colorname=' + selectedColor + ']');
			selectType=true;
		}
    	if ((!selectedColorId && !selectedColor) || !defaultOpt || defaultOpt.length <= 0) {
        	// 获取默认颜色
        	defaultOpt = options.filter('[optId=' + colorData.info.defaultColorId + ']');
    	}
    	if (defaultOpt.length > 0 && defaultOpt.attr('productsQty') <= 0) {
    		defaultOpt = options.filter('[productsQty!=0]');
    	}
    	if (defaultOpt.length > 0) {
    		JSExt.Event.fire(defaultOpt.get(0), 'click');
    	} else {
    		JSExt.Event.fire(options.get(0), 'click');
    	}

    	// 如果只有一个选项，隐藏属性框
    	if (options.length == 1) {
    		currentAttributeElm.style.display = 'none';
    	}
    } else if (attrCode.indexOf('size') == 0) {
    	// 如果只有一个选项，自动选择
    	if (options.length == 2) {
            JSExt.Event.fire(options.get(0), 'click');
    	}
    }
};

//默认显示所有选项
JSExt.Product.Attr.Event.postEvent.attributeShow.showAllOption = function() {
	var attr = this;
	var opt  = this.opt;
	if (attr.config.showAllOption != true) {
	   return false;
	}

	var currentAttributeElm = attr.getLastAttribute();
	if (currentAttributeElm != null) {
	   var attrKey         = parseInt(currentAttributeElm.getAttribute('attrLv'));
	   var formatedData    = attr.getFormatedData();
	   var attributeData   = formatedData[attrKey];
	   var attributeReload = null, attributeElm = null;

	   for (var i = attrKey + 1, length = formatedData.length; i < length; i++) {
	       // 显示选项
	   	   attr.create(i, false);
	       attributeReload = document.getElementById(attr.getElmId(formatedData[i].info.id, attr.config.attributeContainerType));
	       attributeReload.style.display = 'block';

	       // 启用未选择选项判断
	       attributeElm    = document.getElementById(attr.getElmId(formatedData[i].info.id));
	       if (attributeElm != null && attributeElm.disabled && attributeElm.options.length > 0) {
	           attributeElm.options[0].setAttribute('value', '');
	       }
	   }
	}
};


//////////////////////////////////////商品属性选项事件

//defaultOptionElm、selectOptionElm
JSExt.Product.Attr.Event.postEvent.optionCreate  = {};

JSExt.Product.Attr.Event.preEvent.optionClick = {};
JSExt.Product.Attr.Event.postEvent.optionClick   = {};

// 初始化库存信息
JSExt.Product.Attr.Event.postEvent.optionCreate.initQtyOption = function() {
	var attr  = this.attr;
	var opt   = this;
	var param = JSExt.Product.Attr.Event.getParam(arguments);

	var productCollection = [param.optionData.products];
	for (var i = 0; i < param.attrKey; i++) {
		productCollection.push(opt.getSelectedData(i).products);
	}

	// 筛选选项包含商品及库存
	var productIds = productCollection[0].slice();
	for (var i = 0, ilength = productIds.length; i < ilength; i++) {
		for (var j = 1, jlength = productCollection.length; j < jlength; j++) {
			if (JSExt.$.inArray(productIds[i], productCollection[j]) < 0) {
				productIds[i] = null;
			}
		}
	}
	var temp = [];
	var productsQty = 0;
	for (var i = 0, length = productIds.length; i < length; i++) {
		if (productIds[i] != null) {
			temp.push(productIds[i]);
			productsQty += parseInt(attr.getSourceData().qty[productIds[i]]);
		}
	}
	productIds = temp;

	var defOpt = JSExt.$(param.defaultOptionElm);
	var selOpt  = JSExt.$(param.selectOptionElm);
	if (productsQty <= 0) {
		defOpt.addClass('notQty');
		selOpt.addClass('notQty');
	}
	defOpt.attr('productIds', productIds);
	defOpt.attr('productsQty', productsQty);
	selOpt.attr('productIds', productIds);
	selOpt.attr('productsQty', productsQty);
};

// 绑定鼠标事件
JSExt.Product.Attr.Event.postEvent.optionCreate.bindMouseEvent = function() {
	var attr  = this.attr;
	var opt   = this;
	var args  = arguments;
	var param = JSExt.Product.Attr.Event.getParam(arguments);
	var defOpt = JSExt.$(param.defaultOptionElm);

	// 重载无库存选项点击事件
	if (parseInt(defOpt.attr('productsQty')) <= 0 && defOpt.attr('attrLv') >=attr.getFormatedData().length - 1) {
		JSExt.Event.unbind(param.defaultOptionElm, 'click',opt.Event.click);
		defOpt.click(function (e) {
			var mailWindow    = JSExt.$('#out_of_stock_send_mail_window');
			var offset=defOpt.offset();
			var emailInputElm = mailWindow.find('input[name=email]');
			mailWindow.css('display', 'block');
			mailWindow.css('top',(offset.top-100)+'px')
					  .css('left','785px');
			emailInputElm.css('display', '');
			mailWindow.attr('productId', defOpt.attr('productIds'));
			mailWindow.attr('colorId',attr.getValByCode('color'));
			mailWindow.attr('sizeId',  defOpt.attr('optId'));

			if (!mailWindow.attr('initEvent')) {
				var closeButton    = mailWindow.find('.close_window');
				var sendMailButton = mailWindow.find('.send-mail-button');
				closeButton.click(function(){
					mailWindow.css('display', 'none');
				});
				sendMailButton.click(function(){
					if (Validation.validate(emailInputElm.get(0))) {
						sendMailButton.attr('disabled', 'disabled');
						JSExt.$.ajax({
						    type: "POST",
						    dataType: "json",
						    url: mailWindow.attr('requestUrl'),
						    data: "product_id=" + mailWindow.attr('productId') + '&color_id=' + mailWindow.attr('colorId') + '&size_id=' + mailWindow.attr('sizeId') + '&email=' + emailInputElm.val(),
						    success: function(result){
							    if (result.success) {
							    	var inputContainer   = JSExt.$('#out_of_stock_send_mail_window_container > .send-mail-input');
							    	var messageContainer = JSExt.$('#out_of_stock_send_mail_window_container > .send-mail-message');
							    	inputContainer.css('display', 'none');
							    	messageContainer.html(result.notice);
							    	messageContainer.css('display', '');
							    	setTimeout(function(){
							    		closeButton.click();
							    		messageContainer.css('display', 'none');
							    		messageContainer.html('');
							    		inputContainer.css('display', '');
							    	}, 3000);
							    } else {
							    	alert(result.notice);
							    }
							    sendMailButton.removeAttr('disabled');
						    }
						});
					}
				});
				mailWindow.attr('initEvent', '1');
			}
		});
	} else {
		defOpt.click(function () {
			var qty       = JSExt.$('#qty');
			var qtyNumber = parseInt(qty.val());
			qtyNumber     = isNaN(qtyNumber) ? 1 : qtyNumber;
			var maxNumber = parseInt(defOpt.attr('productsQty'));
			if (!isNaN(maxNumber) && qtyNumber > maxNumber) {
				maxNumber = maxNumber > 0 ? maxNumber : 1;
				qty.val(maxNumber);
			}
			JSExt.$('#out_of_stock_send_mail_window > .close_window').click();
		});
	}

	// 设置鼠标经过事件
	defOpt.hover(
		function() {
			JSExt.Product.Attr.Event.preEvent.optionClick.showSelected.apply(this, args);
			JSExt.$(this).addClass('mouseOver');
		},
		function() {
			var params = [];
			for (var i = 0, length = arguments.length; i < length; i ++) {
				params[i] = arguments[i];
			}
			params.push({'defaultOptionElm': this.opt.getSelectedElm(param.attrKey)});
			JSExt.Product.Attr.Event.preEvent.optionClick.showSelected.apply(this, params);
			JSExt.$(this).removeClass('mouseOver');
		}
	);
};

/*显示选择*/
JSExt.Product.Attr.Event.preEvent.optionClick.showSelected = function() {
	var attr = this.opt.attr;
	var opt  = this.opt;
	var param   = JSExt.Product.Attr.Event.getParam(arguments);
	var content = JSExt.$(opt.getElmByChild(this));
	var notSelected = false;
	if (param) {
		if (param.defaultOptionElm == null) {
			notSelected = true;
		} else {
			content = JSExt.$(param.defaultOptionElm);
		}
	}
	var attributeContainer = content.parents('[isOptionContainer=1]');
	var contentContainer   = attributeContainer.find('.selected_option_label');
	if (contentContainer.length > 0) {
		var showInfo = null;
		if (notSelected) {
			showInfo = '';
		} else if (parseInt(content.attr('productsQty')) <= 0) {
			showInfo = content.attr('title') + ' / ' + Translator.translate('Out of Stock');
		} else {
			if (content.attr('attrLv') >= attr.getFormatedData().length - 1) {
				var maxQty = parseInt(JSExt.$V('Product.Event.changeQty.maxQty'));
				if (!isNaN(maxQty) && maxQty > parseInt(content.attr('productsQty'))) {
					showInfo = Translator.translate('%s - Over %s');
					showInfo = showInfo.replace('%s', content.attr('title')).replace('%s', content.attr('productsQty'));
				}
			}
			if (showInfo == null) {
				showInfo = content.attr('title');
			}
		}

		contentContainer.html(showInfo);
	}
};
/*
JSExt.Product.Attr.Event.postEvent.optionClick.showSelected = function() {
	var contentContainer = JSExt.$('#msg-select');
	if (contentContainer.length > 0) {
		var selectedOption   = JSExt.$('#attributeReloadContainer').find('[isOption=1][optionType=selected]:visible');
		contentContainer.empty();
		for (var i = 0, length = selectedOption.length; i < length; i++) {
			var tempObj = JSExt.$('<span></span>');
			tempObj.attr('class',  'is_' + selectedOption.eq(i).parents('[isOptionContainer=1]').attr('attrCode').split('_')[0]);
			tempObj.html('"' + selectedOption.eq(i).attr('title') + '"');
			contentContainer.append(tempObj);
		}
	}
};
*/


JSExt.ColorListPlus={};
JSExt.ColorListPlus.stock=function(select,stock_img_id){
	JSExt.$(select).each(function(){
		JSExt.$(this).click(function(){
			var qty=JSExt.$(this).attr('productsqty');
			if(qty<=0){
				JSExt.$(stock_img_id).show();
			}else{
				JSExt.$(stock_img_id).hide();
			}
		});
	});
};

JSExt.Addtocar= {};
JSExt.Addtocar.checkForm=function(elm){
		var is_select=productAddToCartForm.validator.validate();
		if(is_select){
			JSExt.$('#add-to-cart-hcon').removeClass("hide");
		}
};

JSExt.Addtocar.Tocar=function(elm){
			var is_select=productAddToCartForm.validator.validate();
			if(is_select){
				JSExt.$('#addtype').val(0);
				productAddToCartForm.form.submit();
			}
};
JSExt.Addtocar.continuebuy=function(elm){
			var is_select=productAddToCartForm.validator.validate();
			if(is_select){
				JSExt.$('#addtype').val(1);
				productAddToCartForm.form.submit();
			}
};

JSExt.Addtocar.close=function(elm){
	JSExt.$('#add-to-cart-hcon').addClass("hide");
};

JSExt.Addtocar.suitOneAdd=function(form,id){
	var suitOneForm=form+'_'+id;
	var suitAddToCartForm=new VarienForm(suitOneForm);
	if(suitAddToCartForm.validator.validate()){
		suitAddToCartForm.form.submit();
	}
};

JSExt.Addtocar.suitAdd=function(form, id) {
	if ( typeof(suitProductIds) === 'undefined' ) {
		alert(Translator.translate("data error!"));
		return this;	
	}
	
	var suitProductsInfo = [];
	for( var i=0;i<suitProductIds.length;i++ ) {
		var tmpProductForm = 	new VarienForm(form + '_' + suitProductIds[i]);
		if( !tmpProductForm.validator.validate() ){
			alert(Translator.translate("there are products which have not been selected"));
			return this;
		}
		suitProductsInfo.push(tmpProductForm.form.serialize());
	}
	
	if ( suitProductsInfo.length === 0 ) {
		alert(Translator.translate("there are products which have not been selected"));
		return this;	
	}
	
	var suitFormId = form + '_' + id;
	var suitAddtocarFrom = new VarienForm(suitFormId);
	suitAddtocarFrom.form.suit_products.value = suitProductsInfo;
	
	if(suitAddtocarFrom.validator.validate()){
		suitAddtocarFrom.form.submit();
		return this;
	}
};

JSExt.Checkout = {};
JSExt.Checkout.Cart = {};
JSExt.Checkout.Cart.add = function(formObj, type,id) {
	type = typeof type == 'string' ? type : '';
	if(id){
		var messagebox='div.add-to-messagebox-'+id;
		var addbutton='button.productadd';
		var loadingClass="div.add-to-cart-loading-"+id;
	}
	formObj.form.addtype.value = type;
	var isValidated = formObj.validator.validate();
	if (isValidated) {
		if (type == 'ajax') {
			JSExt.$(addbutton).attr('disabled','disabled');
			JSExt.$(loadingClass).show();
	        var request = new Ajax.Request(
	        	formObj.form.action,
	            {
	                method: 'post',
					/*onCreate:function(){
						request['timeoutId']=setTimeout(function(){
							if(!request.transport.readyState){
								alert('time out');
								JSExt.$(addbutton).removeAttr('disabled');
								JSExt.$(loadingClass).hide();
							}
						},1000);
					},*/
	                //onComplete: function() {},
	                onSuccess: function(transport) {
						clearTimeout(request['timeoutId']);
		                if (transport && transport.responseText){
		                    try{
		                        response = eval('(' + transport.responseText + ')');
		                    } catch (e) {
		                        response = {};
		                    }
		                }
		                if (response.error){
		                    if ((typeof response.message) == 'string') {
		                        alert(response.message);
								JSExt.$(addbutton).removeAttr('disabled');
								JSExt.$(loadingClass).hide();
		                    }
			            } else {
	                        if ((typeof response.update) == 'object') {
								
	                            if ((typeof response.update.cartLink) == 'string') {
									JSExt.$('.public_header').addClass('customerIsLogin');
	                                JSExt.$('#top-link-cart').html(JSExt.$(response.update.cartLink).html());
	                            }
	                            if ((typeof response.update.cartProductList) == 'string') {
	                     	        JSExt.$('.top_cart_list').html(response.update.cartProductList);
	                            }
								JSExt.$(loadingClass).hide();
								JSExt.$(messagebox).show();
								var messageboxTimeId=setTimeout(function(){JSExt.$(messagebox).hide();},3000);
								JSExt.$(addbutton).removeAttr('disabled');
	                        }
			            }
	     		    },
	                onFailure: function() {
	     		    	alert(Translator.translate('Can not add item to shopping cart'));
						JSExt.$(addbutton).removeAttr('disabled');
						JSExt.$(loadingClass).hide();
	     		    },
	                parameters: formObj.form.serialize()
	            }
	        );
		} else {
			formObj.form.submit();
		}
	}
};
JSExt.Checkout.Cart.close=function(id){
	var emlClass='div.add-to-messagebox-'+id;
	JSExt.$(emlClass).hide()
}
JSExt.Checkout.Cart.topcartShow=function(){
	 scroll(0,0);
	 JSExt.$('div.top_cart_list').show();
	 setTimeout(function(){JSExt.$('div.top_cart_list').hide();},3000);
}
JSExt.suitImage={}
JSExt.suitImage.show=function(divClass){
	var xOffset = 10;
	var yOffset = 30;
	divClass="."+divClass;
	JSExt.$(divClass).each(function(){
		JSExt.$(this).hover(
		function(e){
			var offset = JSExt.$(this).offset();
			JSExt.$("body").append("<p id='img_preview'><img src='"+ JSExt.$(this).attr('imgsrc') +"' alt='Image preview' /></p>");
			JSExt.$('#img_preview')
			.css("top",(offset.top) + "px")
			.css("left",(offset.left + 149) + "px")
			.css("z-index","2000")
			.fadeIn("fast");
		},function(e){
			JSExt.$("#img_preview").remove();
		
		});
	});
};
JSExt.Suit={};
JSExt.Suit.changeImg=function(eml){
	var suitImgEml=JSExt.$('#suitimage-container-inner #suit-img');
	var imgEml=JSExt.$(eml);
	imgEml.parent("li").hide().siblings().show();
	var baseimg=imgEml.attr('baseimg');
	suitImgEml.attr('src',baseimg);
};

JSExt.Color_list={};
JSExt.Color_list.show=function(elm){
	var  this_elm=JSExt.$(elm);
	this_elm.children('div.color_images').show();
};
JSExt.Color_list.hide=function(elm){
	var this_elm = JSExt.$(elm);
	this_elm.children('div.color_images').hide();
};

/********************************首页动画**************************************/
JSExt.CoverFlow = {};
JSExt.CoverFlow.init = function(container, coverFlowImgList, options) {
    var $         = JSExt.$;
    var list      = null;
    var imgHeight = options.imgHeight;
    var imgWidth  = options.imgWidth;

    container.height(imgHeight);
	
    var completeEvt = function() {
		$('#loading').css('display','none');
		$('#fk-load').css('display','none');
    	container.children('li').children('a').children('img').fadeIn();
        var moveLeft = function() {
            container.prepend(container.children('li:last'));
            JSExt.CoverFlow.core(container, options, true);
        };
        var moveRight = function() {
            container.append(container.children('li:first'));
            JSExt.CoverFlow.core(container, options, true);
        };

        var off = setInterval(moveRight, 5500);

        $('#pre').click(function() {
            moveLeft();
            clearInterval(off);
            off = setInterval(moveLeft, 5500);
        });
        $('#next').click(function() {
            moveRight();
            clearInterval(off);
            off = setInterval(moveRight, 5500);
        });
    };

    if (typeof coverFlowImgList != 'object') {
        return ;
    }
    for (var i = 0, loadedNum = coverFlowImgList.length, length = coverFlowImgList.length; i < length; i++) {
        var data   = coverFlowImgList[i];
        var liObj  = $('<li></li>');
        var aObj   = $('<a></a>');
        var imgObj = $('<img></img>');
        if (data.top) {
            imgObj.get(0).isTop = true;
        }

        aObj.attr('href', data.href);
		if(data.target){
			aObj.attr("target",data.target);
        }
        imgObj.hide();
        imgObj.load(function() {
            loadedNum--;
            if (loadedNum == 0) {
                completeEvt();
            }
        });
        imgObj.attr('src', data.img);

        aObj.append(imgObj);
        liObj.append(aObj);
        container.append(liObj);
    }
    list = container.children('li');
    list.height(imgHeight);

    JSExt.CoverFlow.core(container, options, false);
};

JSExt.CoverFlow.core = function(container, options, useAnimate){
    var showNumber = 3;
    var imgMaxHeight = options.imgHeight;
    var imgMinHeightPercent = options.imgMinHeightPercent;
	var ulWidth = options.ulWidth;

    var list = container.children('li');
    var sideNumber = showNumber - 1;
    var spacingWidth = ulWidth - options.imgWidth;
    var sideWidth = parseInt(spacingWidth / sideNumber);
    var centerNumber = parseInt(showNumber / 2) + 1;
    var imgMinHeight = (imgMaxHeight * imgMinHeightPercent / 100);
    var imgSidePartHeight = (imgMaxHeight - imgMinHeight) / centerNumber;
    list.each(function(key, elm) {
        var obj    = list.eq(key);
        var imgObj = obj.children('a').children('img');
        var imgElm = imgObj.get(0);

        if (!imgElm.orgHeight) {
            imgElm.orgHeight = options.imgHeight;
            imgElm.orgWidth  = options.imgWidth;
        }

        var zIdx = null;
        if (key + 1 > centerNumber) {
            zIdx = showNumber - key;
        } else {
            zIdx = key + 1;
        }

        var imgHeight = (imgSidePartHeight * zIdx + imgMinHeight);
        var imgWidth  = parseInt((imgHeight / imgElm.orgHeight) * imgElm.orgWidth);
        var liWidth = imgWidth + 32;
        var imgHeight = parseInt(imgHeight);

        var top  = ((imgMaxHeight - imgHeight) / 2) + 'px';
        var left = null;
        if (key + 1 > centerNumber) {
            left = (key * sideWidth + ((imgElm.orgWidth - imgWidth))) + 'px';
        } else {
            left = (key * sideWidth) +'px';
        }

        if (useAnimate) {
            obj.animate({'left': left, 'height': imgHeight + 'px', 'width': liWidth + 'px', 'top': top}, {queue: false, duration: 500});
            imgObj.animate({'height': imgHeight + 'px', 'width': imgWidth + 'px'}, {queue: false, duration: 500});
        } else {
            obj.css({'left': left, 'height': imgHeight + 'px', 'width': liWidth + 'px', 'top': top});
            imgObj.css({'height': imgHeight + 'px', 'width': imgWidth + 'px'});
        }
        obj.css('z-index', zIdx);
    });
};


