var picEditor = new Class({
    Implements: [Events, Options],
    options: {},
    initialize: $empty,
    del: function(id, obj) {
        if (confirm("确认删除本图片吗?")) {
            obj = $(obj);
            var op = obj.getParent(".gpic-box");
            try {
                if (id) { (function() {
                        op.remove();
                        if ($E("#all-pics .gpic-box .current")) {
                            return
                        }
                        if ($$("#all-pics .gpic-box").length && $$("#all-pics .gpic-box").length > 0) {
                            $("x-main-pic").empty().set("html", '<div class="notice" style="margin:0 auto">请重新选择默认商品图片.</div>')
                        } else {
                            $("x-main-pic").empty().set("html", '<div class="notice" style="margin:0 auto">您还未上传商品图片.</div>')
                        }
                    })();
                }
            } catch(e) {
                op.remove()
            }
        }
    },
    setDefault: function(id, key) {
        if (isNaN(id)) {
            return
        }
        if ($("x-main-pic").retrieve("cururl") == key) {
            return
        }
        $("x-main-pic").store("cururl", "loading");
        var el = this.getDefault();
        if (el) {
            el = $E("#all-pics img[sn=_img_" + el + "]");
            if (el) {
                el.getParent("span").removeClass("current");
            }
        }
        if ($E("#x-main-pic input[name=image_default]") && $E("#x-main-pic input[name=image_default_src]")) {
            $E("#x-main-pic input[name=image_default]").set("value", id);
            $E("#x-main-pic input[name=image_default_src]").set("value", key);
        }        
        else {
            $("x-main-pic").empty();
            new Element("input", {
                type: "hidden",
                name: "image_default"
            }).set("value", id).inject("x-main-pic");
            
            new Element("input", {
                type: "hidden",
                name: "image_default_src"
            }).set("value", key).inject("x-main-pic");
        }        
        if (_temimg = $("x-main-pic").getElements("img")) {
            if (_temimg.length) {
                _temimg.remove()
            }
        }
        $("x-main-pic").addClass("x-main-pic-loading");
        var src = key;

        //远程地址处理 for V8.21 Package
        if(key.indexOf("http://") == -1)
            src = "../" + key;
            
        new Asset.image(src, {
            onload: function(el) {
                var e = $(el.zoomImg(290, 220));
                e.inject($("x-main-pic"));
                e.setStyle("margin-top", Math.abs((220 - e.height.toInt()) / 2));
                $("x-main-pic").removeClass("x-main-pic-loading");
                $("x-main-pic").store("cururl", key)
            },
            onerror: function() {
                $("x-main-pic").removeClass("x-main-pic-loading");
                $("x-main-pic").store("cururl", "")
            }
        });
        $E("#all-pics img[sn=_img_" + id + "]").getParent("span").addClass("current")
    },
    getDefault: function() {
        var el = $E("#x-main-pic input[name=image_default]");
        if (el) {
            return el.value
        } else {
            return false
        }
    },
    viewSource: function(obj) {
        //这里必须使用标准dom的setAttribute方法，在mootools中value是预定义的property
        //在调用时候会直接取this[attribute]
        $("sourceSrc").setAttribute("value",obj.source);
        $("smallSrc").setAttribute("value",obj.small);
        return new parent.Dialog({}, {
            title: "查看图片信息",
            singlon: false,
            width: 650,
            height: 180,
            modal:true,
            html:$("viewPicInfo").get("html")
        })
    }
});

var hs = $H();
var Product = {
    imgLoader: function(call) {
        var el = $(call);
        var _src = el.get('lsrc');
        
        //远程地址处理 for V8.21 Package
        if(el.get('lsrc').indexOf("http://") == -1)
            _src = "../" + el.get('lsrc');
            
        var _sn = el.get('sn');
        var _span = el.getParent('span');
        new Asset.image(_src, {
            onload: function(img) {
                if (!img || !img.width) return;
                var _img = img.zoomImg(50, 50);
                _span.empty().adopt(_img.set('sn', _sn));
                _img.setStyles({
                    'margin-top': Math.abs((51 - _img.height.toInt()) / 2)
                });
            },
            onerror: function() {
                _span.empty();
            }
        });
    },
    mainImgLoader: function(call){
        var el = $(call);
        var _src = el.get('lsrc');
        
        //远程地址处理 for V8.21 Package
        if(el.get('lsrc').indexOf("http://") == -1)
            _src = "../" + el.get('lsrc');
            
        var _div = el.getParent('div');    
        new Asset.image(_src,{
            onload: function(img){
                if (!img || !img.width) return;
                var _img = img.zoomImg(290, 220);
                el.dispose();
                _div.grab(_img);
                _img.setStyles({
                    'margin-top': Math.abs((220 - _img.height.toInt()) / 2)
                });                    
            }
        })
    },
    openSpec: function(){
        new parent.Dialog("Product_Operate_Ajax.aspx?act=getSpecList&date="+Date(),{
            title:"规格列表",
            modal:true,
            width:756,
            height:386
        });
    },
    closeSpec: function(){
        var el = $("specBtn"); el.value="开启规格";
        
        //还原虚拟商品设置
        $("openspec-notice").hide();
        $("trMemberPrice").show();
        if(!$("cbAutoComputerMemPrice").checked) $("trAutoComputerMemPrice").show();
        $("trStock").show();
        $("trWeight").show();
        
        el.removeEvents().addEvent("click",Product.openSpec);
        //清空规格
        el.getParent("tr").getAllNext().each(function(v){
           v.dispose(); 
        });
        $("spec-table").empty();
    },
    addSpec: function (arr){
        if(arr.length){
            var el = $("specBtn"); el.value="重新设置规格";
            
            //开启规格则隐藏部分虚拟商品设置
            $("openspec-notice").show();
            $ES("#trMemberPrice,#trAutoComputerMemPrice","table13").hide();
            if($("txtStorage")) if($("txtStorage").value=="") $("txtStorage").value="0";
            $("trStock").hide();
            if($("txtProductWeight").value=="") $("txtProductWeight").value="0";
            $("trWeight").hide();
            
            this.bindCloseEvent();
            
            //遍历生成规格选择区域
            arr.each(function(v,i){
                var sid, name;
                var s = v.replace(/\{specid:([^,]*),name:([^\}]*)\}/g, function(){
                    sid = arguments[1];
                    name = arguments[2];
                    return "";
                });

                //这里必须使用此方法setHTML，在ff中将<td></td>自动转换为合法标记
                var td = new Element("td", {
                    "align": "right"
                }).setStyles({width:"20%",height:"26px","padding-top":"6px","vertical-align":"top"}).set("html",name+"：&nbsp;");
                var td1 = new Element("td", {
                    "align": "left"
                }).setStyles({"background-color":"#FFFFFF"}).set("html",s);
                
                var el = new Element("tr", {
                    "class": "spec-menu",
                    "specid": sid,
                    "name": name
                }).adopt(td,td1).inject($("specBtn").getParent("tr"),"after");
            });
            
            this.bindToggleEvent();
            
            this.bindItemEvent();
        }
    },
    bindCloseEvent: function(){
        var el = $("specBtn");
        el.removeEvents().addEvent("click",function(e){
            if(confirm("关闭规格将会导致重新设置规格数据，是否确认关闭？")) {
                Product.closeSpec();
            }else e.stop();
        });        
    },
    bindToggleEvent: function(){
        //bind events for setImgBtn
        $ES(".show-tbeImg-Btn","table13").removeEvents().addEvent("click", function(e){
            e.stop();
            var id = $(this).get("tbeImgId");
            if($(id)) $(id).toggleDisplay();
        });    
    },
    bindItemEvent: function(){
        //bind events
        $ES(".spec-item","table13").removeEvents().addEvent("click", function(e){
            //spec-img-table
            var spec_id = $(this).getParent("tr").get("specid");
            var _hidImg = "<input type='hidden' name='txtSpec' value='"+this.value+"' /><input type='hidden' name='txtSpecImgs-"+this.value+"' value='' />";
            var tbeImg = "<table cellspacing='0' cellpadding='0' border='0' class='tb-img tb-color' id='tbe-img-"+spec_id+"'>";
            tbeImg += "<thead>";
            tbeImg += "<tr><th>规格值关联多图<br><span style='color:#999'>前台点击该规格值时将显示设置的图片</span></th></tr>";
            tbeImg += "</thead>";
            tbeImg += "<tbody>";
            tbeImg += "<tr id='tbe-img-item-"+this.value+"'>";
            tbeImg += "<td class='td-img'>";
            var _img = "";
            if($(this).get("src"))
                _img = "<img src='"+$(this).get("src")+"' width='16' height='16' alt='"+$(this).get("dsc")+"' />";
            else
                _img = $(this).get("dsc");
            var _img_s = "<span>"+_img+"</span>&nbsp;"+_hidImg+"<button class='sel-img-btn'>选择</button>";
            
            tbeImg += _img_s;
            tbeImg += "</td>";
            tbeImg += "</tr>";
            tbeImg += "</tbody>";
            tbeImg += "</table>";
            
            var el_tbe = $("tbe-img-"+spec_id), el_tbe_item = $("tbe-img-item-"+this.value);
            //首先判断有没有生成规格多图的table
            if(el_tbe){
                //判断该规格值项多图是否存在
                if(el_tbe_item){
                    if(!this.checked) el_tbe_item.empty().dispose();
                }else{
                    var _e = new Element("tr", {id:"tbe-img-item-"+this.value}).grab(
                        new Element("td", {
                            "class": "td-img"
                        }).set("html",_img_s)
                    );
                    el_tbe.getLast().grab(_e);
                }
            }else
                new Element("div").set("html",tbeImg).inject($(this).getParent("ul").getNext(),"after");
            
            //spec-table
            var arr_menu = $ES(".spec-menu","table13");
            var menu_list="";
            //第一次循环获得所有规格值列表，以$和|分割，输出1|2$3|5格式数据
            //组合算法即是一种乘法算法，直接使用嵌套for循环即可实现。但是这是一种正推法，即知道组合数目。
            //这里采用的是逆推组合算法，即先取2项进行组合。其它的再乘以组合之后结果，即对其它项再次for。剩下的项以此类推即可。
            arr_menu.each(function(v){
	            var _chk_arr = $(v).getElements("input:checked");
	            var _val = "";
	            _chk_arr.each(function(v){
		            _val = _val == "" ? $(v).value : _val + "|" + $(v).value;
	            });
	            if(_val != "|" && _val != "")
		            menu_list = menu_list=="" ? _val : menu_list + "$"+ _val;
            });
            var spec_list = (function step(){
                //分析生成好的数据
                //还原出组合
	            var _arr_menu = menu_list.split("$");
	            var arr2,arr3;
	            var tmp="",tmp1="",_spec="";
	            for(i=0;i<_arr_menu.length;i++){
	                //如果只有1种规格项，则不需要组合
		            if(_arr_menu.length==1){
			            _spec=menu_list;
		            }else{
		                //对于最后一项，不进行操作。组合时已取最后一项进行了组合。
			            if(!(i+2>_arr_menu.length)){
				            tmp1="";
				            if(_spec == "")
					            arr2=_arr_menu[i].split("|"); //第一个组合项
				            else
					            arr2=_spec.split("|"); //取得之后的组合项，即2个数组合之后再产生一个数组
				            for(k=0;k<arr2.length;k++){
					            arr3=_arr_menu[i+1].split("|"); //第二个组合项
					            for(m=0;m<arr3.length;m++){ //开始组合
						            tmp=arr2[k]+","+arr3[m];
						            tmp1= tmp1=="" ? tmp : tmp1+"|"+tmp
					            }
				            }
				            _spec=tmp1;
			            }
		            }
	            }
	            return _spec;
            })();
            
            var str= (function(){
	            //存储页面上所有控件值
	            $$("#spec-table .tb-color input").each(function(v){
	                if(v.value) hs.set(v.id,v.value);
	            });
	            //hs.each(function(v,i){alert(i+":"+v);});
	            
	            if(spec_list=="") return "";
	            var _arr_spec = spec_list.split("|");
	            var tbeSpec = "<table cellspacing='0' cellpadding='0' border='0' class='tb-color'>";
	            for(i=0;i<_arr_spec.length;i++){
		            //第一次循环输出表头
		            if(i==0){
		                tbeSpec += "<thead>"
			            tbeSpec += "<tr>";
			            var _arr_first = _arr_spec[0].split(",");
			            _arr_first.each(function(v){
				            var name = $("item-"+v).getParent("tr").get("name");
				            //alert($E("input[value='"+v+"']",$("spec")).getParent("tr").tagName);
				            tbeSpec += "<th>"+name+"</th>";
			            });
			            tbeSpec += "<th><i>*</i>货号 <img src='images/key_down.gif' alt='同步货号' class='syn-bar-btn'></th>";
			            tbeSpec += "<th><i>*</i>库存 <img src='images/key_down.gif' alt='同步库存' class='syn-st-btn'></th>";
			            tbeSpec += "<th><i>*</i>销售价 <img src='images/key_down.gif' alt='同步销售价' class='syn-p-btn'></th>";
			            tbeSpec += "<th>成本价</th>";
			            tbeSpec += "<th><i>*</i>市场价 <img src='images/key_down.gif' alt='同步市场价' class='syn-mp-btn'></th>";
			            tbeSpec += "<th><i>*</i>重量 <img src='images/key_down.gif' alt='同步重量' class='syn-w-btn'></th>";
			            tbeSpec += "<th>货位</th>";
			            tbeSpec += "<th>移除</th>";
			            tbeSpec += "</tr>";
			            tbeSpec += "</thead>";
		            }
		            tbeSpec += "<tr>";
		            var _arr = _arr_spec[i].split(",");
		            var _specs = "";
		            _arr.each(function(v){
		                var _id, _value_id, _dsc, _str;
		                var el = $("item-"+v);
		                _id = el.getParent("tr").get("specid");
		                _value_id = v;
		                _dsc = el.get("dsc");
		                _str = el.get("src")?"<img src='"+el.get("src")+"' width='16' height='16' alt='"+_dsc+"' />":_dsc;
		                _specs += "{specid:"+_id+";specvalueid:"+_value_id+";specvalue:"+_dsc+"}|";
			            tbeSpec += "<td>" + _str + "</td>";
		            });
		            
		            //规格项隐藏表单
		            _specs = _specs.substring(0,_specs.length-1);
		            tbeSpec += "<input type='hidden' value='" + _specs + "' name='txtSpecs' />";
		            var id = _arr_spec[i].replace(/\,/g,"-");
		            var bid="-bar-"+id, sid="-store-"+id, pid="-price-"+id, cpid="-cost-"+id, mpid="-marketprice-"+id, wid="-weight-"+id, spid="-storeplace-"+id
    				tbeSpec += "<td><input name='txtBarcode' type='text' size='14' id='"+bid+"' value='"+getHsValue(bid)+"'/></td>";
		            tbeSpec += "<td><input name='txtStore' type='text' size='6' id='"+sid+"' value='"+getHsValue(sid)+"'/></td>";
		            //会员价隐藏表单
		            var _mbpid = "-member-price-"+id;
		            var _hidmp = "<input type='hidden' name='txtmPrice' id='"+_mbpid+"' value='"+getHsValue(_mbpid)+"'/>";
		            tbeSpec += "<td><input name='txtPrice' type='text' size='5' id='"+pid+"' value='"+getHsValue(pid)+"'/>&nbsp;"+_hidmp+"<button class='sel-p-btn' mbpid='"+_mbpid+"'>会员价</button></td>";
		            tbeSpec += "<td><input name='txtCost' type='text' size='6' id='"+cpid+"' value='"+ (getHsValue(cpid).length==0?0:getHsValue(cpid)) +"'/></td>";
		            tbeSpec += "<td><input name='txtMarketPrice' type='text' size='6' id='"+mpid+"' value='"+getHsValue(mpid)+"'/></td>";
		            tbeSpec += "<td><input name='txtWeight' type='text' size='6' id='"+wid+"' value='"+getHsValue(wid)+"'/></td>";
		            tbeSpec += "<td><input name='txtStorePlace' type='text' size='10' id='"+spid+"' value='"+getHsValue(spid)+"'/></td>";
		            tbeSpec += "<td><img src='images/product/icon_delete.gif' onclick='Product.delSpecItem(this)'></td>";
		            tbeSpec += "</tr>";	
	            }
	            tbeSpec += "</table>";
	            return tbeSpec;
            })();
            
            function getHsValue(id){
	            return hs.get(id)==null ? "" : hs.get(id);
            }
            
            $("spec-table").empty().set("html",str);
            //end spec
            
            //bind dialog for all selimgbtn
            Product.bindDialogEvent();
            
            //bind syn event
            Product.bindSynEvent();

        })
        //end bind        
    },
    bindDialogEvent: function(){
        //bind events for selImgBtn
        $ES(".sel-img-btn","table13").removeEvents().addEvent("click", function(e){
            e.stop();
            var el = $(this).getPrevious();
            var pics = "";
            $ES("input", "all-pics").each(function(v){
                pics += v.value+",";
            });
            pics = pics.substring(0,pics.length-1);
            new parent.Dialog("Product_Operate_Ajax.aspx?act=getPicList&pics=" + pics + "&ids="+el.value+"&d="+Date(), {
                title: "设置商品规格多图",
                modal:true,
                width:756,
                height:410,
                //这里其实是将一个function对象作为参数传递给父对象，同时该function对象中含有对子对象成员el的引用
                callback: function(ids, srcs){
                    el.value=ids.substring(0,ids.length-1);
                    el.getAllPrevious("img").dispose();
                    srcs.split(",").each(function(v){                                
                        if(v.length){
                            new Element("img",{
                                src:v,
                                border:0
                            }).setStyles({width:"22px",height:"22px"}).inject(el,"before");
                        }
                    });
                }
            });
        });
        
        //bind events for selImgBtn
        $ES(".sel-p-btn","spec-table").removeEvents().addEvent("click", function(e){
            e.stop();
            var el = $( $(this).get("mbpid") );
            var value = el.getPrevious().value;
            new parent.Dialog("Product_Operate_Ajax.aspx?act=getPriceList&value="+value+"&values="+el.value+"&d="+Date(), {
                title: "设置会员组价格",
                modal:true,
                width:560,
                height:300,
                callback: function(values){
                    el.value=values.substring(0,values.length-1);
                }
            });
        });        
    },
    bindSynEvent: function(){
        if(!$E(".syn-bar-btn")) return;
    
        //barcode
        $E(".syn-bar-btn").removeEvents().addEvent("click", function(e){
            var number = $("txtNumber").value;
            if(number.length==0) { MessageBox.error("请先输入商品编号"); return; }
            
            $ES("input[name='txtBarcode']","spec-table").each(function(v,i){
                if(v.value.length == 0)
                    v.value=number+"-"+(i+1);
            });                
        });
        
        //store
        $E(".syn-st-btn").removeEvents().addEvent("click", function(e){
            if( $("txtStorage") && $("txtStorage").value.length == 0 ) { MessageBox.error("请先输入商品库存"); return; }

            $ES("input[name='txtStore']").each(function(v,i){
                if(v.value.length == 0)
                    v.value = ($("lblStorageCount") && $("lblStorageCount").get("text")) || $("txtStorage").value;
            });                
        });
   
                
        //其它按钮放到hash表中方便操作
        var hs = new Hash({
            "syn-p-btn": {"e":"txtPrice","g":"txtMemberPrice","s":"请先输入商品商城价格"}, 
            "syn-mp-btn": {"e":"txtMarketPrice","g":"txtProductMarketPrice","s":"请先输入商品市场价格"},
            "syn-w-btn": {"e":"txtWeight","g":"txtProductWeight","s":"请先输入商品重量"}
            
        });
        hs.each(function(val,key){
            $E("."+key).removeEvents().addEvent("click", function(e){
                if( $(val.g).value.length == 0 ) { MessageBox.error(val.s); return; }

                $ES("input[name='"+val.e+"']").each(function(v,i){
                    if(v.value.length == 0)
                        v.value=$(val.g).value;
                });                
            });
        });                 
        
    },
    delSpecItem: function(o){
        $(o).getParent("tr").empty().dispose();
    },
    checkUnique: function(e){
        var old = new Array();
        var n = new Array();
        $ES("input[name='txtBarcode']","spec-table").each(function(v,idx){
            if(v.value.length>0){
                old.push(v.value);
                n.include(v.value);
            }
        });
        if(old.length != n.length){
            MessageBox.error("货号不允许重复，请检查后重新输入。",{width:260});
            e.stop();
        }
    }
}