//debugger;

$(document).ready(function() {
	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(){
            imgs += $(this).attr('src') + '|';
        });
        if(imgs != ''){imgs = imgs.substring(0,imgs.length-1);};
        var form = $('#BigImgform');
        form.find('#hiddenimgs').val(imgs);
        form.submit();
	});
	//显示规格参数
	ShowParas(productID);
	ShowSpec();
});

var mainSpecCount = 0;//记录主规格的数量
var subSpecCount = 0;//记录次规格数量
var mainSpecName = '';//当前商品的主规格名称
var mainSpecValue = '';//当前商品的主规格值
function ShowSpec(){
    //Specs 和 SpecDesc 是在Show.aspx页面上定义的两个变量
    //有规格和无规格的情况不一样:有规格的情况Specs是一段json,无规格时Specs是空字符串.
    if($.trim(SpecDesc) != '' && $.trim(Specs) != ''){
        //有规格的情况
        Specs = eval('(' + Specs + ')');//将字符串转换成json
		var goods = eval('(' + SpecDesc + ')').Goods;
		$('#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);
		
		if(goods[0].SPicture != '')
		{
			$('.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");
				});
			}
		}
        
        var str_pro_links = '';
        var last_spec_row = $('#main_spec');
        $.each(Specs.Specs,function(i,n){
			subSpecCount += 1;//记录次规格数量
			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" title="' + m + '" val="' + m + '" >' + m + '<div></div></li>');
				li.click(function(){
					//处理样式
					
					$(this).addClass('selected_spec').siblings().removeClass('selected_spec');
					//处理数据
					SelectSpecs();
					if($('.selected_spec').length == $('.spec_cotent').length)
					{
						var spec_select = '';
						$('.selected_spec').each(function(){//构造当前选中的规格项组合
							spec_select += (spec_select != '' ? ' ' : '') + $(this).text();
						});
						$.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);
								if(b.SPicture != '')
								{
									$('.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");
										});
									}
								}
							}//end if b.Desc
						});//end each goods
					}
					$(".related_img").eq(0).click();
					$(".thumbnail_li").eq(0).click();
				});
				
				$.each(goods[0].Desc.split(' '),function(q,w){
					if(w == li.text())
					{
						li.click();
					}
				});
				ulcontent.append(li);
			});
			td.append(ulcontent);
			row.append(th).append(td).insertAfter(last_spec_row);
			last_spec_row = row;//重新指定last_spec_row,将下次生成的行添加到这行的
			
        });//end each
    }else{
        //无规格的情况
        if($.trim(SpecDesc) != ''){
            var goods = eval('(' + SpecDesc + ')').Goods;
            $('#GID').val(goods[0].GID);
            $('#specdesc').val('');
        };
    };//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('');
        };
    };
    
    SelectSpecs();
};//end function

function SelectSpecs(){
    var selected_values = '';//记录选择的尺寸,用来匹配对应的GoodsID
    var html_spec_result = '<ul>';//显示在页面上的html内容
    var text_spec_result = '';//存入数据库的文本内容
    if(mainSpecCount > 0){
        html_spec_result += '<li><span class="spec_name">' + mainSpecName + '</span>：<span class="spec_value">' + mainSpecValue + '</span></li>';
        text_spec_result += mainSpecName + '：' + mainSpecValue + '<br/>';
    };
    $('li.selected_spec').each(function(){
        selected_values += $(this).attr('val') + ' ';
        html_spec_result += '<li><span class="spec_name">' + $(this).parent().attr('specname') + '：</span><span class="spec_value">' + $(this).attr('val') + '</span></li>';
        text_spec_result += $(this).parent().attr('specname') + '：' + $(this).attr('val') + '<br/>';
    });
    html_spec_result += '</ul>';
    
    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);
    };
    $('#SpecResult').html(html_spec_result);
        
    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 PPFolder(cid){
    return (cid.length > 4 ? cid.substring(0,4) : cid);
}
