var JSExt = {};

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;
	}
};

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;
    },
    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);
    },
    getUrlParam: function(paramName) {
        return this.getUrlParams()[paramName];
    }
};

// 事件处理
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 (document.all) {
            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.config.colorListData = configData.colorData.list;
		if (configData.bindLoadGallery) {
			JSExt.Product.Attr.Event.postEvent.optionClick.loadCurrentGalleryImage = JSExt.Product.Image.loadCurrentGallery;
		}
		this.isInit = true;
	}, 
	// 选择图片
	select: function(elm) {
	    try {
	    	if (!JSExt.Product.Image.isInit) {
	    		throw 'Please initialize object first!';
	    	}
	        var elm     = $j(elm);
	        var colorId = elm.attr('imgColorId');

	        // 如果找不到属性，则加载
	        if (!elm.attr('bigImg')) {
	            var galleryImagesData = JSExt.Product.Image.config.colorListData[colorId].galleryImages;
	            for (var i = 0, length = galleryImagesData.length; i < length; i++) {
	                if (galleryImagesData[i].info.id == elm.attr('imgId')) {
	                	elm.attr('baseImg',  galleryImagesData[i].image.base);
	                	elm.attr('bigImg',   galleryImagesData[i].image.big);
	                    elm.attr('fileType', galleryImagesData[i].info.fileType);
	                    break;
	                }
	            }
	        }

	        // 读取数据
	        if (elm.attr('fileType') && elm.attr('fileType') != 'swf') {
	            $j('#gallery-image').attr('alt',   elm.attr('alt'));
	            $j('#gallery-image').attr('title', elm.attr('title'));
	            $j('#gallery-image').attr('src',   elm.attr('baseImg'));
	            $j('#gallery-image').attr('jqImg', elm.attr('bigImg'));
	            $j('#flash-container-inner').css('display', 'none');
	            $j('#image-container-inner').css('display', 'block');
	        } else {
	            $j('#gallery-flash > param[name=movie]').val(elm.attr('baseImg'));
	            $j('#gallery-flash > embed:first').attr('src', elm.attr('baseImg'));
	            $j('#image-container-inner').css('display', 'none');
	            $j('#flash-container-inner').css('display', 'block');
	        }
	    } catch (e) { throw e; }
	}, 
	//列表页切换
	turnSecondImg:function(elm){
		var elm=$j(elm);
		var elm_img_url=elm.attr('src');
		var second_url=elm.attr('second_img');
		elm.attr('src',second_url);
		elm.attr('second_img',elm_img_url);
	},
	/**选择默认颜色**/
	defaultColorSelect:function(ColorId){
		var eml='.select_color[optid='+ColorId+']';
		var index=$j('.select_color:visible').index($j(eml));
		var currentAttributeElm = JSExt.Product.Attr.getLastAttribute();
		if (currentAttributeElm != null) {
			var optionId = JSExt.Product.Attr.Opt.getElmId(currentAttributeElm.id, index, 'default');
			JSExt.Event.fire(document.getElementById(optionId), 'click');
		}
	},
	// 加载当前列表
	loadCurrentGallery: function() {
	    try {
	    	if (!JSExt.Product.Image.isInit) {
	    		throw 'Please initialize object first!';
	    	}
	        var colorId  = JSExt.Product.Attr.getValByCode('color');
	        var moreView = JSExt.$('#more-views > ul');
	        if (moreView.attr('colorId') == colorId) {
	        	return ;
	        }

	        var template = JSExt.$('#more-views > ul > li:first').html();
	        if (colorId > 0 && template != null && template.length > 0) {
	            var templateElm = JSExt.$(template);
	            moreView.html('');
	            var galleryImagesData = JSExt.Product.Image.config.colorListData[colorId].galleryImages;
	            for (var i = 0, length = galleryImagesData.length; i < length; i++) {
	            	templateElm.attr('alt',        galleryImagesData[i].info.label);
	                templateElm.attr('title',      galleryImagesData[i].info.label);
	                templateElm.attr('fileType',   galleryImagesData[i].info.fileType);
	                templateElm.attr('src',        galleryImagesData[i].image.thumbnail);
	                templateElm.attr('baseImg',    galleryImagesData[i].image.base);
	                templateElm.attr('bigImg',     galleryImagesData[i].image.big);
	                templateElm.attr('imgId',      galleryImagesData[i].image.id);
	                templateElm.attr('imgColorId', galleryImagesData[i].image.colorId);
	                var tempElm = JSExt.$('<li></li>').append(JSExt.$('<li></li>').append(templateElm));

	                moreView.append(tempElm.eq(0).html());
	            }
	        }
	        moreView.attr('colorId', colorId);
	        JSExt.$('#more-views > ul > li:first > img').click();
	    } catch (e) { throw e; }
	}
};

// 产品属性
JSExt.Product.Attr = {
	tpl: null,
	isInit: false,
	// 初始化数据
	init: function(config) {
		this.tpl = config.tpl ? config.tpl : null;
		if (config.attributeData) {
			if (config.attributeDataIndex) {
				JSExt.Product.Attr.getFormatedData(config.attributeData, config.attributeDataIndex);
			} else {
				JSExt.Product.Attr.getFormatedData(config.attributeData);
			}
		} else {
			throw 'attribute data source not found!';
		}
		if (config.colorData) {
			JSExt.Product.Attr.setColorData(colorData);
			var mergeColorData = JSExt.Product.Attr.mergeColorData4AttrData(JSExt.Product.Attr.getFormatedData(), colorData);
			JSExt.Product.Attr.setFormatedData(mergeColorData);
		}
		if (config.defaultShow) {
			JSExt.Product.Attr.show();
		}
		this.isInit = true;
	},
	config: {
		showTipIn: 'after', // before, after, null
		showAllOption: false,
		defaultSelect: false
	},
	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;
	},
	setColorData: function (data) {
		JSExt.$V('product.colorData', data);
		return true;
	},
	getColorData: function () {
		return JSExt.$V('product.colorData');
	},
	setFormatedData: function (data) {
		JSExt.$V('product.formatedData', data);
		return true;
	},
	getFormatedData: function (sourceData, attributeConfigIndex) {
		if (sourceData) {
			JSExt.$V('product.sourceData', sourceData);
			JSExt.$V('product.formatedData', JSExt.Product.Attr.formatData(sourceData, attributeConfigIndex));
		} else if (!JSExt.$V('product.formatedData')) {
			throw 'format data is not found!';
		}

		return JSExt.$V('product.formatedData');
	},
	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];
                    }
                }

                break;
            }
        }

        return attrData;
    },
    getLastAttribute: function() {
        var attributeReloadContainer = document.getElementById('attributeReloadContainer');
        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;
    },
	// 获取属性值
	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 = document.getElementById(this.getElmId(attributeId));

        return attributeElm.value;
	},
	// 获取属性代码
	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
	getElmId: function(attrKey, type) {
        var elmId = 'attribute';

        if (type == 'reload') {
            elmId += attrKey + '-reload';
        } else if (type == 'tip-container') {
            elmId += attrKey + '-tip-container';
        } else {
            elmId += attrKey;
        }

        return elmId;
	},
	// 初始化数据
	create: function(attrKey, createOption) {
        var attributeData      = this.getFormatedData()[attrKey];
        var attributeContainer = document.getElementById('attributeReloadContainer');
        var optionContainer    = JSExt.$(JSExt.Product.Attr.tpl.get('optionContainer', attributeData.info)).get(0);
        // 创建选项容器
        optionContainer.setAttribute('id',       this.getElmId(attributeData.info.id, 'reload'));
        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;
            JSExt.$.each(attributeData.options, function(optKey, optionData) {
                if (!JSExt.Product.Attr.Opt.inAttribute(attrKey, optKey)) {
                    return null;
                }

                var tempElmList         = optionContainer.children; 
                var optionListContainer = null;
                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;
                }
                JSExt.Product.Attr.Opt.create(optionListContainer, optionData, optionContainer.getAttribute('id'), attrKey, aoReKey++);
            });
        }

        if (tipContainer != null && this.config.showTipIn == 'after') {
            optionContainer.appendChild(tipContainer);
        }
	},
	// 显示属性选项
	show: function(attrKey) {
        this.Event.execute('pre', 'attributeShow', this, arguments);

        attrKey = (typeof attrKey == 'number' && attrKey > 0) ? attrKey : 0;

        var attributeContainer = document.getElementById('attributeReloadContainer');
        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 = document.getElementById(this.getElmId(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, 'reload'));
        currentAttributeElm.style.display = 'block';

        this.Event.execute('post', 'attributeShow', this, arguments);
	},
	Opt: { 
		getElmId: function(attrId, optKey, type) {
	        var elmId = attrId + '-option-' + optKey + '-' + type;
	
	        return elmId;
		},
		inAttribute: function(attrKey, optKey) {
	        var attributeData = JSExt.Product.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;
		},
		getSelectedData: function(attrKey) {
	        var attributeData = JSExt.Product.Attr.getFormatedData()[attrKey];
	        var optionElm     = JSExt.$('#' + JSExt.Product.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 {};
		},
		create: function(optionContainer, optionData, attrElmId, attrKey, optKey) {
	        // 创建默认状态
	        var optionElm = JSExt.$(JSExt.Product.Attr.tpl.get('optionNotSelect', optionData.info)).get(0);
	        optionElm.setAttribute('id',     this.getElmId(attrElmId, optKey, 'default'));
	        optionElm.setAttribute('attrLv', attrKey);
	        optionElm.setAttribute('optLv',  optKey);
	        optionElm.setAttribute('optId',  optionData.info.id);
	        optionElm.setAttribute('title',  optionData.info.label);
	        optionElm.setAttribute('isOption',   1);
	        optionElm.setAttribute('optionType', 'default');
	        optionElm.setAttribute('optionKey',  attrKey + '_' + optKey);

	        optionContainer.appendChild(optionElm);
	        JSExt.Event.bind(optionElm, 'click', this.Event.click);

	        // 创建选中状态
	        var optionElm = JSExt.$(JSExt.Product.Attr.tpl.get('optionIsSelect', optionData.info)).get(0);
	        optionElm.setAttribute('id',     this.getElmId(attrElmId, optKey, 'select'));
	        optionElm.setAttribute('attrLv', attrKey);
	        optionElm.setAttribute('optLv',  optKey);
	        optionElm.setAttribute('optId',  optionData.info.id);
	        optionElm.setAttribute('title',  optionData.info.label);
	        optionElm.setAttribute('isOption',   1);
	        optionElm.setAttribute('optionType', 'selected');
	        optionElm.setAttribute('optionKey',  attrKey + '_' + optKey);
	        optionElm.style.display = 'none';

	        optionContainer.appendChild(optionElm);
	        JSExt.Event.bind(optionElm, 'click', this.Event.click);
		},
		Event: {
			select: function() {
            	var optionElm       = JSExt.Event.getSrcElement(JSExt.Event.getEvent(this));
                var optionContainer = optionElm.parentNode.getAttribute('isoptioncontainer') ? optionElm.parentNode : optionElm.parentNode.parentNode;
                var selectElm       = document.getElementById(JSExt.Product.Attr.getElmId(optionContainer.getAttribute('attrId')));

                // 当选项不变时
                if (selectElm.value == optionElm.getAttribute('optId')) {
                    return true;
                }
                // 当选项不允许选择时
                else if (selectElm.disabled) {
                    return false;
                }

                selectElm.value = optionElm.getAttribute('optId');
                JSExt.Event.fire(selectElm, 'change');

                // 选择成功
                if (selectElm.value == optionElm.getAttribute('optId')) {
                    var optionElmList = optionContainer.childNodes;

                    // 所有选项置为默认状态
                    var removeList = [];
                    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 = '';
                            }

                            // 由于“tip-container”机制，特殊处理本选项提示信息去除
                            if (optionElmList[i].getAttribute('id') != null && 
                                optionElmList[i].getAttribute('id').indexOf('-' + JSExt.Product.Attr.getElmId(optionContainer.getAttribute('attrId'), 'tip-container')) >= 0) {
                                removeList.push(optionElmList[i]);
                            }
                        }
                    }
                    // 去除本选项提示信息
                    for (var i = 0, length = removeList.length; i < length; i++) {
                    	optionContainer.removeChild(removeList[i]);
                    }

                    // 改变选中选项样式
                    preOptElm = JSExt.$(optionElm).siblings('[isOption=1][optionType=selected]:visible');
                    JSExt.$(optionElm).siblings('[isOption=1][optionKey=' + preOptElm.attr('optionKey') + ']').css('display', '');
                    preOptElm.css('display', 'none');
                    JSExt.$(optionElm).siblings('[isOption=1][optionKey=' + JSExt.$(optionElm).attr('optionKey') + ']').css('display', '');
                    JSExt.$(optionElm).css('display', 'none');

                    // 显示下级菜单
                    JSExt.Product.Attr.show(parseInt(optionContainer.getAttribute('attrLv')) + 1);
                } else {
                    throw "Select failure, Options exception!";
                }
			}, 
			click: function() {
			    JSExt.Product.Attr.Event.execute('pre',  'optionClick', this, arguments);
			    JSExt.Product.Attr.Opt.Event.select.apply(this, arguments);
			    JSExt.Product.Attr.Event.execute('post', 'optionClick', this, arguments);
			}
		}
	},
	Event: {
	    preEvent:  {},
	    postEvent: {},
	    execute:   function(type, action, thisObj, args) {
	        var events = this[type + 'Event'][action];
	        for (var key in events) {
	            events[key].apply(thisObj, args);
	        }
	    }
	}
};

JSExt.Product.Attr.Event.postEvent.attributeShow = {};
JSExt.Product.Attr.Event.postEvent.optionClick   = {};

/*显示选择*/
JSExt.Product.Attr.Event.postEvent.optionClick.showSelect = function(){
	var selectedOption   = JSExt.$('#attributeReloadContainer').find('[isOption=1][optionType=selected]:visible');
	var contentContainer = JSExt.$('#msg-select');
	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.Product.Attr.Event.postEvent.attributeShow.defaultSelect = function() {
    if (JSExt.Product.Attr.config.defaultSelect != true) {
        return false;
    }

    var currentAttributeElm = JSExt.Product.Attr.getLastAttribute();
    if (currentAttributeElm != null) {
    	/*
        setTimeout(function(){
            var optionId = JSExt.Product.Attr.Opt.getElmId(currentAttributeElm.id, 0, 'default');
            JSExt.Event.fire(document.getElementById(optionId), 'click');
        }, 0);
        */
        var optionId = JSExt.Product.Attr.Opt.getElmId(currentAttributeElm.id, 0, 'default');
        JSExt.Event.fire(document.getElementById(optionId), 'click');
    }
};

JSExt.Product.Attr.Event.postEvent.attributeShow.colorAndSizeRule = function() {
    var currentAttributeElm = JSExt.Product.Attr.getLastAttribute();
    var attrCode = JSExt.Product.Attr.getCodeById(currentAttributeElm.getAttribute('attrId'));
    var options  = JSExt.$(currentAttributeElm).find('[isOption=1]:visible');
    if (options <= 0) {
    	return false;
    }
    if (attrCode == 'color') {
    	var colorData = JSExt.Product.Attr.getColorData();
    	if (!colorData) {
    		return false;
    	}

    	// 自动选择颜色
    	var defaultOpt      = null;
    	var selectedColorId = JSExt.Util.getUrlParam('colorid');
    	if (selectedColorId) {
    		selectedColorId = selectedColorId.replace('{', '').replace('}', '');
    	}
    	// 获取所选颜色
    	defaultOpt = options.filter('[optId=' + selectedColorId + ']');
    	if (defaultOpt.length <= 0) {
        	// 获取默认颜色
        	defaultOpt = options.filter('[optId=' + colorData.info.defaultColorId + ']');
    	}

    	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 == 1) {
            JSExt.Event.fire(options.get(0), 'click');
    	}
    }
};

// 默认显示所有选项
JSExt.Product.Attr.Event.postEvent.attributeShow.showAllOption = function() {
    if (JSExt.Product.Attr.config.showAllOption != true) {
        return false;
    }

    var currentAttributeElm = JSExt.Product.Attr.getLastAttribute();
    if (currentAttributeElm != null) {
        var attrKey         = parseInt(currentAttributeElm.getAttribute('attrLv'));
        var formatedData    = JSExt.Product.Attr.getFormatedData();
        var attributeData   = formatedData[attrKey];
        var attributeReload = null, attributeElm = null;

        for (var i = attrKey + 1, length = formatedData.length; i < length; i++) {
            // 显示选项
        	JSExt.Product.Attr.create(i, false);
            attributeReload = document.getElementById(JSExt.Product.Attr.getElmId(formatedData[i].info.id, 'reload'));
            attributeReload.style.display = 'block';

            // 启用未选择选项判断
            attributeElm    = document.getElementById(JSExt.Product.Attr.getElmId(formatedData[i].info.id));
            if (attributeElm != null && attributeElm.disabled && attributeElm.options.length > 0) {
                attributeElm.options[0].setAttribute('value', '');
            }
        }
    }
};
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");
};



