//var LimitBuyPrice;
//var CurrencySign;
$(document).ready(function() {	
//    LimitBuyPrice=LimitBuyPrice;
//    CurrencySign=CurrencySign;
    SetTab('#tabContainer .menuconainer li.menuitem','#tabContainer .itemcontainer div.tabitem');
	$(".related_img").bind("click",function(){
		$("#product_img").attr({
			"href" : $(this).attr("src")
		});
		$("#thumbnail_img").attr({
			"src" : $(this).attr("src")
		});
		$('#thumbnail_img').attr({
		    "src":$(this).attr("src"),
		    "jqimg":$(this).attr("src")
		});
	});
	$(".thumbnail_li").hover(function(){
		$(this).addClass("focus");
	},function(){
		$(this).removeClass("focus");
	});
	$(".thumbnail_li").bind("click",function(){
		$(".thumbnail_li").removeClass("active");
		$(this).addClass("active");
	});
	$("#thumbnail_bimg").mouseover(function(){
		$('#ddlCountry').hide();
		$('#shippingWay').hide();
	});
	$("#thumbnail_bimg").mouseout(function(){
		$('#ddlCountry').show();
		$('#shippingWay').show();
	});
	//点击放大隐藏右上角图标
	$('#product_img').click(function(){
	    $('.picture_div').fadeOut('slow');
	    setTimeout(function(){
	        $('div[@id^=highslide-wrapper-]').click(function(){
	            $('.picture_div').fadeIn('slow');
	        });
	    },500);
	});
	
	$("#viewbig").click(function(){
        var imgs = '';
        $('img.related_img').each(function(){
        //把 related_img 里的src 或 v 值 给imgs,商品在Goods表中有图时，会重新对related_img 中的src赋值，并加上v,否则只有src
            if(typeof($(this).attr('v'))!="undefined")
                imgs += $(this).attr('v') + '|';
            else
                imgs += $(this).attr('src') + '|';
        });
        if(imgs != ''){imgs = imgs.substring(0,imgs.length-1);};
        var form = $('#BigImgform');
        form.find('#hiddenimgs').val(imgs);
        form.submit();
	});
	
		//当ProductID与GoodsID存在一对多的时，显示最新限时促销的价格add by liwenhai	
	function ShowLimitBuyPrice(){
	    if(parseFloat(LimitBuyPrice)>0)
	    {
	        $('#limitbuy').empty().append("(为您再节省"+((Number($('#memberprice').text())-parseFloat(LimitBuyPrice))).toFix(2)+" 元)");
	    }
	};

//	function AutoSelectSpec(){
//	    var ASpec;
//	    if($.trim(SpecDesc) != '' && $.trim(Specs) != ''&&$.trim(Specs)!="{'Specs':[],'Contain':[]}"){
//            ASpec = eval('(' + Specs + ')');//将字符串转换成json		
//		    $.each(ASpec.Specs,function(i,n){
//		        alert(n.Contain[0]);
//		    })
//	    }
//	}
	

//	onsubmit="if(document.getElementById('GID').value == '0'){alert('商品信息不完整[GID:0]');return false;}"
	$('#btnBuy').click(function(){
    	var isChooseAllSpecs = true;//是否选择了所有规格
    	var notChoiceSpec = '';//记录未选择的规格名称
    	var choiceSpec = ''//记录已选择的规格名称,购买的时候要记录到数据库的
    	$('.spec_cotent').each(function(i,n){//遍历所有规格名称,如果下面没有选择值，则把该规格名压入未选择规格列
            if($(this).children('.selected_spec').length==0){
                isChooseAllSpecs = false;
                notChoiceSpec += $(this).attr('specname')+","
            }else{
				choiceSpec += $(this).attr('specname')+"："+$(this).children('.selected_spec').attr("val")+"<br/>"
            }
        });
        
	    if(!isChooseAllSpecs){
	        if(notChoiceSpec != ''){notChoiceSpec = notChoiceSpec.substring(0,notChoiceSpec.length-1);}
	        alert("请选择："+notChoiceSpec);
	        return false;
	    }
	    else
	    {
			choiceSpec = choiceSpec.substring(0,choiceSpec.length-5);//去掉最后一个<br/>
			$('#spectext').val(escape(choiceSpec));
	    }
	    return checkPStatus();
	});
	//显示规格参数
	ShowParas(productID);
	ShowSpec();
});

var mainSpecCount = 0;//记录主规格的数量
var subSpecCount = 0;//记录次规格数量
var mainSpecName = '';//当前商品的主规格名称
var mainSpecValue = '';//当前商品的主规格值
function ShowSpec(){
    //Specs 和 SpecDesc 是在Show.aspx页面上定义的两个变量
    //有规格和无规格的情况不一样:有规格的情况Specs是一段json,无规格时Specs是{'Specs':[],'Contain':[]}.
    var goods = eval('(' + SpecDesc + ')').Goods;
    if($.trim(SpecDesc) != '' && $.trim(Specs) != ''&&$.trim(Specs)!="{'Specs':[],'Contain':[]}"){
        //有规格的情况
        Specs = eval('(' + Specs + ')');//将字符串转换成json		
		$('#marketprice').text(goods[0].MarketPrice);
		$('#memberprice').text(goods[0].MemberPrice);
	    $('#productno').text(goods[0].GoodsNo);
		$('#score').text(goods[0].Score);
		$('#weight').text(goods[0].Weight);
		var price=goods[0].MarketPrice-goods[0].MemberPrice;
		var str="(为您节省"+price.toFixed(2)+" 元)";
		$('#goodsprice').val(goods[0].MemberPrice);
		$('.pdt_tdspanp').empty().append(str);
		if(goods[0].Storage > 0){
                $('#ShowSorage').html('现货');
        }
        else{
                $('#ShowSorage').html("缺货<span id='stockreg_info' class='pdt_tdspan'>(到货通知)</span>");
                $('#stockreg_info').click(function(){
                showAddStockReg();//弹出框
          });
        };

//		if(goods[0].SPicture != '')//当货品在GOODS表中有图时，要重新绑定GOODS中的图
        if(goods[0].SPicture != ''& goods[0].SPicture!='nopic.gif')//当货品在GOODS表中有图时，要重新绑定GOODS中的图
		{
			$('.thumbnail_ul').empty();
			var spicture = goods[0].SPicture.split(',');
			var bpicture = goods[0].BPicture.split(',');
			for(var t = 0; t < spicture.length; t++)
			{
				$('<li class="thumbnail_li" style="overflow: hidden; float: left; width: 43px; height: 54px;"><img src="/upload/ProductImg/' + ppfolder + '/' + spicture[t] + '" class="related_img" v="/upload/ProductImg/' + ppfolder + '/' + bpicture[t] + '"></li>').appendTo($('.thumbnail_ul'));
				$(".related_img").bind("click",function(){
					$("#product_img").attr({
						"href" : $(this).attr("v")
					});
					$('#thumbnail_img').attr({
						"src":$(this).attr("v"),
						"jqimg":$(this).attr("v")
					});
				});
				$(".thumbnail_li").hover(function(){
					$(this).addClass("focus");
				},function(){
					$(this).removeClass("focus");
				});
				$(".thumbnail_li").bind("click",function(){
					$(".thumbnail_li").removeClass("active");
					$(this).addClass("active");
				});
			//20110121 add by liwenhai，当缩略图重新绑定到goods表中的图时，thumbnail_img要重新绑定goods表中bpicture的值
			$('#thumbnail_img').attr({
				"src":$(".related_img").eq(0).attr("v"),
				"jqimg":$(".related_img").eq(0).attr("v")
			});
			}
		}//end if
        var str_pro_links = '';
        var last_spec_row = $('#main_spec');
        var specChoice = $('<dl>请选择：</ul>');//显示在页面上的已选择的规格提示内容
        $('#ChoiceSpecTip').append('<dt>请选择：</dt>');
        var specEm = $('<dd></dd>').appendTo($('#ChoiceSpecTip'));
        $.each(Specs.Specs,function(i,n){
			subSpecCount += 1;//记录规格数量
            specEm.append('<em>'+n.SpecName+'</em>');
			var row = $('<tr></tr>');
			var th = $('<th>' + n.SpecName + '：</th>');
			var td = $('<td></td>');
			var ulcontent = $('<ul class="spec_cotent" specname=' + n.SpecName + '></ul>');
			$.each(n.Contain,function(j,m){//循环次规格的每一项
				var li = $('<li class="spec_item hand" title="' + m + '" val="' + m + '" >' + m + '<div></div></li>');
				li.bind('click',ChooseSpec).appendTo(ulcontent);//end li.click
			});//end n.Contain.each
			td.append(ulcontent);
			row.append(th).append(td).insertAfter(last_spec_row);
			last_spec_row = row;//重新指定last_spec_row,将下次生成的行添加到这行的
        });//end each Specs.Specs
    }else{
        //无规格的情况
        if($.trim(SpecDesc) != ''){
            $('#GID').val(goods[0].GID);
            $('#specdesc').val('');
             if(goods[0].Storage > 0){
                $('#ShowSorage').html('现货');
            }else{
                $('#ShowSorage').html("缺货<span id='stockreg_info' class='pdt_tdspan'>(到货通知)</span>");
                $('#stockreg_info').click(function(){
                    showAddStockReg();//弹出框
                });
            };
        };
    };//end else
	/*
    if(mainSpecCount > 0){
        $('#pro_link').html(str_pro_links);
        $('#spec_name').text(mainSpecName + '：');
        $('#main_spec').show();
    };
    
    //没有次规格或者没有规格
    if(subSpecCount == 0 || (subSpecCount + mainSpecCount)==0){
        if($.trim(SpecDesc) != ''){
            var goods = eval('(' + SpecDesc + ')').Goods;
            $('#GID').val(goods[0].GID);
            $('#specdesc').val('');
        };
        alert("ppp");
    };
    */
    
//    SelectSpecs();
};//end function

function ChooseSpec(){
    var currSpec = $(this);
    var currSpecName = $(this).parent().attr("specname");//当前规格名
    var currSpecValue = $(this).attr("val");//当前规格值
    if($(this).hasClass('selected_spec')){
        $(this).removeClass('selected_spec');
        $('.spec_cotent[specname!='+currSpecName+']').children('.disable').removeClass("disable").addClass("hand").bind("click",ChooseSpec);
        $('em[title='+currSpecName+']').remove();
        if($('.selected_spec').length == 0){
            $('#ChoiceSpecTip').children('dt').text('请选择：');
            $.each(Specs.Specs,function(i,n){
                 $('#ChoiceSpecTip').children('dd').append('<em>'+n.SpecName+'</em>');
            });           
        }       
        return false;
    }else{
        $(this).addClass('selected_spec');
        $(this).siblings().removeClass('selected_spec');
        $('#ChoiceSpecTip').children('dt').text('已选择：');
        $('#ChoiceSpecTip').children('dd').empty();
    }
	var goods = eval('(' + SpecDesc + ')').Goods;
	var spec_select = '';
	$('.selected_spec').each(function(){//组合选中的规格值
		spec_select += (spec_select != '' ? ' ' : '') + $(this).attr("val");
		$('#ChoiceSpecTip').children('dd').append('<em title="'+$(this).parent().attr("specname")+'">'+$(this).attr("val")+'</em>');
	});
	if($('.selected_spec').length == $('.spec_cotent').length)//已选择了所有规格
	{
		$.each(goods,function(k,b){//根据组合的规格值匹配货品
			if(spec_select == b.Desc)//匹配到货品的情况
			{								
			    $('#marketprice').text(b.MarketPrice);
			    $('#memberprice').text(b.MemberPrice);
			    $('#productno').text(b.GoodsNo);
			    $('#score').text(b.Score);
			    $('#weight').text(b.Weight);
			    $('.sign').empty().html(CurrencySign);
			    //20101228 add by liwenhai
			    var price=b.MarketPrice-b.MemberPrice;
			    price=price.toFixed(2);
                str="(为您节省"+price+" 元)";
           	    $('#goodsprice').val(b.MemberPrice);
                $('.pdt_tdspanp').empty().append(str);
                //重新绑定促销价
                if(parseFloat(LimitBuyPrice)>0){
                    price=b.MemberPrice-parseFloat(LimitBuyPrice);
                    price=price.toFixed(2);
                    $('#limitbuy').empty().append("(为您再节省"+price+" 元)");
                }
                //20110103 add by liwenhai,重新对库存绑定值
                if(b.Storage > 0){
                   $('#ShowSorage').html('现货');
                }
                else{
                   $('#ShowSorage').html("缺货<span id='stockreg_info' class='pdt_tdspan'>(到货通知)</span>");
                   $('#stockreg_info').click(function(){
                   showAddStockReg();//弹出框
                   });
                };				
				if(b.SPicture != '')//有图片的话要更改多图
//                if(b.SPicture != ''& b.SPicture!='nopic.gif')//有图片的话要更改多图
				{

					$('.thumbnail_ul').empty();
					var spicture = b.SPicture.split(',');
					var bpicture = b.BPicture.split(',');
					for(var t = 0; t < spicture.length; t++)
					{
						$('<li class="thumbnail_li" style="overflow: hidden; float: left; width: 43px; height: 54px;"><img src="/upload/ProductImg/' + ppfolder + '/' + spicture[t] + '" class="related_img" v="/upload/ProductImg/' + ppfolder + '/' + bpicture[t] + '"></li>').appendTo($('.thumbnail_ul'));

						$(".related_img").bind("click",function(){
							$("#product_img").attr({
								"href" : $(this).attr("v")
							});
							$('#thumbnail_img').attr({
								"src":$(this).attr("v"),
								"jqimg":$(this).attr("v")
							});
						});
						$(".thumbnail_li").hover(function(){
							$(this).addClass("focus");
						},function(){
							$(this).removeClass("focus");
						});
						$(".thumbnail_li").bind("click",function(){
							$(".thumbnail_li").removeClass("active");
							$(this).addClass("active");
						});
					}
					// add by liwenhai 20110110 重新设定$('.thumbnail_ul')的宽度，默认情况下$('.thumbnail_ul')的宽度只等于第一个货品的所有LI的宽度+2，
					//因为每种货品的图片数量不一定相等。要把所有的LI在一行中显示，所以UL的宽度不能小于li宽度+2之和
					var liwidth=$('.thumbnail_li')[0].offsetWidth+parseInt($.css($('.thumbnail_li')[0],"marginRight"))+parseInt($.css($('.thumbnail_li')[0],"marginLeft"));;
					$('.thumbnail_ul').css("width",$('.thumbnail_li').size()*liwidth+2+"px");
				}
				else{//货品在GOODS表中没有图片时

				}
				//end if(b.SPicture != '')
				$('#GID').val(b.GID);
                $('#specdesc').val(escape(b.Desc));
                if(b.Storage > 0){
                    $('#ShowSorage').html('现货');
                }else{
                    $('#ShowSorage').html("缺货<span id='stockreg_info' class='pdt_tdspan'>(到货通知)</span>");
                    $('#stockreg_info').click(function(){
                        showAddStockReg();//弹出框
                    });
                };
			}//end if(spec_select == b.Desc)
		});//end goods.each
	}//end if
	
    //判断哪些规格没有组合的，要剔除掉
    $('.spec_cotent[specname!='+currSpecName+']').children('.spec_item').removeClass("hand").addClass("disable").unbind("click");
    $.each(goods,function(k,b){//根据组合的规格值匹配货品
		if((' '+b.Desc).indexOf(' '+currSpecValue) > -1){//匹配到规格
//		    alert(b.Desc);
            $.each(b.Desc.split(' '),function(p,q){
                $('.spec_cotent[specname!='+currSpecName+']').children('.spec_item[val='+q+']').removeClass("disable").addClass("hand").bind("click",ChooseSpec);
            });
		}
	});
	$(".related_img").eq(0).click();
	$(".thumbnail_li").eq(0).click();
}

function SelectSpecs(){
    var selected_values = '';//记录选择的尺寸,用来匹配对应的GoodsID
    var text_spec_result = '';//记录要存入数据库的已选择的规格
    
    if(selected_values != ''){
        selected_values = selected_values.substring(0,selected_values.length-1);
        text_spec_result = text_spec_result.substring(0,text_spec_result.length-5);
    };
        
    var goods = eval('(' + SpecDesc + ')').Goods;
    $.each(goods,function(i,n){
        if(selected_values == n.Desc){
            $('#GID').val(n.GID);
            $('#specdesc').val(escape(n.Desc));
            if(n.Storage > 0){
                $('#ShowSorage').html('现货');
            }else{
                $('#ShowSorage').html("缺货<span id='stockreg_info' class='pdt_tdspan'>(到货通知)</span>");
                $('#stockreg_info').click(function(){
                    showAddStockReg();//弹出框
                });
            };
            return false;
        }else{
            $('#GID').val('0');
            $('#specdesc').val('');
        };
    });
    $('#spectext').val(escape(text_spec_result));
    
};//end function

function ShowParas(arg){
	$.ajax({
        type:"get",
        dataType:"json",
        url:shopFolder + "show.aspx?NoCopyRight=1",
        data:"type=ajax&Action=GetPara&pid="+arg,
        cache:false,
        success:function(msg){
			var paras=msg.paras;
			$.each(paras,function(i,n){
				var tempItem=$("<tr><th class='tdTitle'>"+n.group+"</th><th>&nbsp;</th></tr>").appendTo($("#paras"));					
					$.each(n.options,function(j,m){
						var tempRow=$("<tr></tr>").appendTo($("#paras"));
						var tempCell1=$("<td class='tdTitle'>"+m.name+"</td>").appendTo(tempRow);
						var tempCell2=$("<td>"+m.value+"</td>").appendTo(tempRow);
					});
			});
        },//end seccess
        error:function(XMLHttpRequest,textStatus){if(textStatus=='parsererror'){alert('Get Para error')}else{alert('error_GetPara')};}
    });//end ajax
}

function checkPStatus(){
    var pass = false;
    $.ajax({
        url:baseUrl + 'ajax.aspx?NoCopyRight=1&type=GetProductStatusByID&GID=' + $('#GID').val(),
        cache:false,
        async:false,
        success:function(data){
            switch(data){
                case 'NotExist':
                    alert(NotExist);    //商品不存在
                    pass = false;
                    break;
                case 'NotForSale':
                    alert(NotForSale);  //暂停销售
                    pass = false;
                    break;
                case 'NotStorage':
                    alert(NotStorage);  //库存不足
                    pass = false;
                    //弹出层
                    showAddStockReg();
                    break;
                case 'OK':
                    pass = true;
                    break;        
            };
        },
        error:function(){alert('error');}
    });
    return pass;
};

function PPFolder(cid){
    return (cid.length > 4 ? cid.substring(0,4) : cid);
}
