function showNav()
{
	var dt = $('.menu dt');
	var x = dt.position().left;
	var y = dt.position().top + dt.outerHeight();
	$('.menu dt ul').css({left:x,top:y}).stop().slideDown();
}

function getCartCount()
{
	var carts = ali.util.cookie('Cart' + $('html').attr('lang'));
	if (carts == '')
		carts = [];
	else
		carts = JSON.parse(carts);
	return carts.length;
}

function showVisitedGoods(element)
{
	element = $(element)
	
	if (!element.length)
		return;

	var goods = ali.util.cookie('VisitedGoods' + $('html').attr('lang'));
	if (goods == '')
		goods = [];
	else
		goods = JSON.parse(goods);
	
	var html = '';
	for (var i = goods.length - 1; i >= 0; i--)
	{
		html += '<dl><dt><a href="' + goods[i].url + '"><img src="' + goods[i].thumbnail + '" alt="' + goods[i].name + '"></a></dt><dd><h2><a href="">' + goods[i].name + '</a></h2><span>' + goods[i].price +'</span>' +  _lang_yuan + '</dd></dl>';
	}
	element.html(html);
}

function collect()
{
	//如果没有登录，提示登录
	if (ali.util.cookie('UserID') == '' || ali.util.cookie('Namespace') == 'AliCMS.SystemModule')
	{
		ali.error(_lang_not_login, function(){window.location = _loginPath + '?Referer=' + window.location;});
		return false;
	}
	
	//#region 检查是否已经收藏
	var isExist = false;
	$.ajax(
	{
		url: _channelPath + 'ajax_is_collect.aspx?GoodsID=' + $(this).data('id'),
		type: 'GET',
		async: false,
		error: function()
		{
			ali.error(_lang_operation_fail);
		},
		success: function(data)
		{
			isExist = parseInt($.trim(data)) == 1 ? true : false;
		}
	});
	
	if (isExist)
	{
		ali.success(_lang_operation_success);
		return false;
	}
	//#endregion
	
	//准备数据
	var data = 'GoodsID=' + $(this).data('id');
	data += '&GoodsPageID=' + encodeURIComponent($(this).data('pageId'));
	data += '&GoodsName=' + encodeURIComponent($(this).data('name'));
	data += '&Thumbnail=' + encodeURIComponent($(this).data('thumbnail'));
	data += '&UserID=' + ali.util.cookie('UserID');
	data += '&UserName=' + encodeURIComponent(ali.util.cookie('UserName'));
	
	//提交数据
	$.ajax(
	{
		url: _webPath + 'alicms.aspx?Object=Collect&Operation=Add',
		data: data,
		type: 'POST',
		error: function()
		{
			ali.error(_lang_operation_fail);
		},
		success: function(guid)
		{
			ali.success(_lang_operation_success);
		}
	});
	
	return false;
}

function updatePromoteTime()
{
	if ($('.promotion .price').length || $('.promotion .price1').length)//正在促销或者即将开始
	{
		var allSecond = parseInt($('.promotion [data-second]').data('second')) - _elapse;
		if (allSecond == 0)
			window.location.reload();
			
		var text = '';
		var d = parseInt(allSecond / (60 * 60 * 24));
		if (d > 0)
			text += d + _lang_day;
		var secondOfDays = d * 60 * 60 * 24;
		var h = parseInt((allSecond - secondOfDays) / (60 * 60));
		if (d != 0 || h != 0)
			text += h + _lang_hour;
		var seondOfHour = h * 60 * 60;
		var m = parseInt((allSecond - secondOfDays - seondOfHour) / 60);
		if (d != 0 || h != 0 || m != 0)
			text += m + _lang_minute;
		var secondOfMinute = m * 60;
		var s = allSecond - secondOfDays - seondOfHour - secondOfMinute;
		text += s + _lang_second;
		
		$('.promotion [data-second]').text(text);
		_elapse++;

		setTimeout(updatePromoteTime, 1000);
		
	}
}

function onSpecChange()
{
	//#region 规格联动处理
	var selects = $(this).closest('dl').find('select');
	
	//构造全部选项
	var allOptions = [];
	for (var i = 0; i < _specValues.length; i++)
	{
		allOptions.push(_specValues[i].optionIds.join());
	}
	
	//构造搜索值，并且更新后续的select的选项
	var query = '';
	var index = selects.index(this);
	if (index < selects.length - 1)
	{
		for (var i = 0; i <= index; i++)
		{
			if (query != '')
				query += ',';
			query += selects[i].value;
		}
		
		//构造需要重新生成的选项
		var foundOptions = [];
		for (var i = 0; i < allOptions.length; i++)
		{
			if (allOptions[i].indexOf(query) == 0)
			{
				foundOptions.push(allOptions[i].substr(query.length + 1));
			}
		}
		
		//更新后续的select选项
		for (var i = index + 1; i < selects.length; i++)
		{
			//准备选项数据
			var prepare = [];
			for (var j = 0; j < foundOptions.length; j++)
			{
				//获取选项ID
				var optionId = foundOptions[j].split(',')[i - index - 1];
				
				//判断是否重复
				var k = 0;
				for (; k < prepare.length; k++)
				{
					if (prepare[k].id == optionId)
						break;
				}
				if (k < prepare.length)
					continue;
				
				//获取名称
				var name = '';
				for (var k = 0; k < _specs.length; k++)
				{
					for (var g = 0; g < _specs[k].options.length; g++)
					{
						if (_specs[k].options[g].id == optionId)
						{
							name = _specs[k].options[g].name;
							break;
						}
					}
					
					if (name != '')
						break;
				}
				
				//添加
				prepare.push({id:optionId,name:name});
			}
			
			//构造选项的html代码
			var html = '';
			for (var j = 0; j < prepare.length; j++)
			{
				html += '<option value="' + prepare[j].id + '">' + prepare[j].name + '</option>';
			}
			selects.eq(i).html(html);
		}
	}
	//#endregion
	
	//#region 找出当前选择的组合
	var spec = null;
	var search = '';
	for (var i = 0; i < selects.length; i++)
	{
		if (search != '')
			search += ',';
		search += selects[i].value;
	}
	
	for (var i = 0; i < allOptions.length; i++)
	{
		if (allOptions[i] == search)
		{
			spec = _specValues[i];
			break;
		}	
	}
	
	_specIdForCart = null;
	_specNoForCart = null;
	if (spec == null)
		return;
	
	_specIdForCart = spec.id;
	_specNoForCart = spec.no;
	
	//#endregion
	
	//改变价格和节省
	$('#sale-price').text(parseFloat(spec.price).toFixed(2));
	$('#save-price').text((parseFloat($('#market-price').text()) - parseFloat(spec.price)).toFixed(2));
	
	//改变库存
	$('#stock').text(spec.stock);

	//改变货号
	$('#no').text(spec.no);

	//改变促销价 
	$('.promotion dt .price i').text(parseFloat(spec.promotePrice).toFixed(2))
	
	//准备购物车所需的规格信息
	_specForCart = '';
	for (var i = 0; i < _specs.length; i++)
	{
		for (var j = 0; j < _specs[i].options.length; j++)
		{
			for (var k = 0; k < spec.optionIds.length; k++)
			{
				if (_specs[i].options[j].id == spec.optionIds[k])
				{
					_specForCart += '<p>' + _specs[i].name + ':' + _specs[i].options[j].name + '</p>';
				}
			}
		}
	}
	
	//重新计算商品总价
	$('.spec :text').keyup();

}

function onAmountKeyUp()
{
	if (_page == 'goods')
	{
		var amount = parseInt($('.spec :text').val());
		if (isNaN(amount))
		{
			$('.spec :text').val(1);
			amount = 1;
		}
		
		var price = parseFloat($('#sale-price').text());
		if ($('.promotion .price').length) //如果正在促销
		{
			price = parseFloat($('.promotion .price i').text());
		}
		else if ($('#user-price').length && ali.util.cookie('UserID') != '' && ali.util.cookie('Namespace') != 'AliCMS.SystemModule') //如果是会员并且有匹配会员价，会员价是
		{
			$.get(_channelPath + 'ajax_my_roles.aspx', function(data)
			{
				data = $.trim(data);
				if (data != '')
				{
					var userPrices = $('#user-price b i');
					var myRoles = data.split('|');
					for (var i = 0; i < myRoles.length; i++)
					{
						for (var j = 0; j < userPrices.length; j++)
						{
							if (myRoles[i] == userPrices.eq(j).data('no'))
							{
								if (price > parseFloat(userPrices.eq(j).text()))
								{
									price = parseFloat(userPrices.eq(j).text()).toFixed(2); 
									$('.spec div span b').text((price * amount).toFixed(2));
								}
							}
						}
					}
				}
			});
		}
	
		$('.spec div span b').text((price * amount).toFixed(2));
	}
	else if (_page == 'cart')
	{
		var row = $(this).closest('tr');
		var amount = parseInt(this.value);
		
		//数量不能超过库存
		if (parseInt($(this).val()) > parseInt(row.data('stock')))
		{
			ali.error(_lang_amount_greater_than_stock, $.proxy(function(){this.value = 1;this.select();}, this));
			return;	
		}

		//如果输入的不合法，则改为1
		if (!$(this).val().match(/^[1-9]\d*$/))
		{
			amount = 1;
			this.value = amount;
		}
		
		//计算小计
		var price = parseFloat(row.data('salePrice'));
		var sum = amount * price;
		$(this).parent().next().text(sum + _lang_yuan);
		
		//购物车中找到当前的商品，并且修改数量
		var carts = JSON.parse(ali.util.cookie('Cart' + $('html').attr('lang')));
		var id = row.data('id');
		for (var i = 0; i < carts.length; i++)
		{
			if (carts[i].id == id)
			{
				carts[i].amount = amount;
				ali.util.cookie('Cart' + $('html').attr('lang'), JSON.stringify(carts), 365 * 24 * 60, '/');
	
				//更新小计
				calcSum();
			}
		}
	}
}

function onAddCardClick()
{
	//运费模板指定的情况下，才可以购买或者加入购物车
	if (_freightTemplateId == '')
	{
		ali.error(_lang_freight_template_id_empty);
		return false;
	}
	
	var amount = $('.spec :text');
	
	//数量必须是数字，并且数量必须大于0
	if (!amount.val().match(/^[1-9]\d*$/) || parseInt(amount.val()) <= 0)
	{
		ali.error(_lang_amount_must_be_digit, $.proxy(function(){amount.select();}, this));
		return false;
	}

	//小于库存量
	if (parseInt(amount.val()) > parseInt($('#stock').text()))
	{
		ali.error(_lang_amount_greater_than_stock, $.proxy(function(){amount.select();}, this));
		return false;
	}
	
	//数据获取
	var name = $('#name').text();
	var thumbnail = $('#thumbnail').attr('src');
	var marketPrice = $('#market-price').text();
	var salePrice = $('#sale-price').text();
	var stock = $('#stock').text();

	var cart = {id:_specIdForCart == null ? _guid : _specIdForCart,goodsId:_guid,goodsNo:_no,specId:_specIdForCart,specNo:_specNoForCart,name:name,thumbnail:thumbnail,url:window.location.href,spec:_specForCart,marketPrice:marketPrice,salePrice:salePrice,amount:amount.val(),stock:stock,freightTemplateId:_freightTemplateId,method:_method,weight:_weight,volume:_volume,bear:_bear,express:_express,ems:_ems,post:_post};
	var result = addCart(cart);

	if ($(this).hasClass('buy'))
	{
		window.location = $('.header-right div a').attr('href');
	}
	else
	{
		if (result)
			ali.success(_lang_add_cart_success);
		else
			ali.error(_lang_cart_exist);
	
		//更新购物车数量
		$('#cart-count').text(getCartCount());
	}

	return false;
}

function addCart(cart)
{
	//读取购物车信息
	var carts = ali.util.cookie('Cart' + $('html').attr('lang'));
	if (carts == '')
		carts = [];
	else
		carts = JSON.parse(carts);
	
	//判断是否存在
	for (var i = 0; i < carts.length; i++)
	{
		if(carts[i].id == cart.id)
			return false;
	}
	
	//如果不存在，增加到购物车
	carts.push(cart);
	ali.util.cookie('Cart' + $('html').attr('lang'), JSON.stringify(carts), 365 * 24 * 60, '/');
	return true;
}

function showCart(element)
{
	element = $(element);
	
	//从cookie中获取商品,json格式
	var carts = ali.util.cookie('Cart' + $('html').attr('lang'));
	if (carts == '')
		carts = [];
	else
		carts = JSON.parse(carts);
	
	var html = '';
	for (var i = 0; i < carts.length; i++)
	{
		var pic = _page == 'order' ? '' : '<a href="' + carts[i].url + '"><img src="' + carts[i].thumbnail + '" alt="' + carts[i].name + '"></a>';
		var del = _page == 'order' ? '' : '<td><a href="">' + _lang_delete + '</a></td>';
		var amount =  _page == 'order' ? carts[i].amount : '<input value="' + carts[i].amount + '"></input>';
		
		//运送方式
		var deliver = '';
		if (_page == 'order')
		{
			var deliver = '<td>';
			if (carts[i].bear == 'Buyer')
				deliver += _lang_buyer;
			else if (carts[i].bear == 'Seller')
				deliver += _lang_seller;
			else
				deliver += '<select></select>';
			deliver += '</td>';
		}

		html += '<tr data-id="' + carts[i].id + '" data-market-price="' + carts[i].marketPrice + '" data-stock="' + carts[i].stock + '" data-sale-price="' + carts[i].salePrice + '"><th>' + pic + '<h2><a href="' + carts[i].url + '">' + carts[i].name + '</a></h2></th><td>' + carts[i].spec + '</td><td>' + carts[i].marketPrice + _lang_yuan + '</td><td>' + carts[i].salePrice + _lang_yuan + '</td><td>' + amount + '</td>' + deliver + '<td>' + (carts[i].salePrice * carts[i].amount) + _lang_yuan + '</td>' + del + '</tr>';
	}
	
	element.html(html);
	
	//生成运费
	onAddressClick();
}

function calcSum()
{
	//获取购物车所有商品
	var carts = ali.util.cookie('Cart' + $('html').attr('lang'));
	if (carts == '')
		carts = [];
	else
		carts = JSON.parse(carts);
	
	//计算总共销售价格和市场价格
	var salePriceSum = 0;
	var marketPriceSum = 0;
	var freightSum = 0;
	for (var i = 0; i < carts.length; i++)
	{
		salePriceSum += carts[i].salePrice * carts[i].amount;
		marketPriceSum += carts[i].marketPrice * carts[i].amount;

		var option = $('#goods tbody [data-id="' + carts[i].id + '"] :selected');
		if (option.length)
			freightSum += parseFloat(option.data('fee'));
	}
	
	salePriceSum = salePriceSum.toFixed(2);
	marketPriceSum = marketPriceSum.toFixed(2);
	freightSum = freightSum.toFixed(2);
	
	var save = parseFloat(marketPriceSum) - parseFloat(salePriceSum);
	var percent = parseFloat(marketPriceSum) == 0 ? 0 : save * 100 / parseFloat(marketPriceSum);
	
	$('#sale-price-sum').text(salePriceSum);
	$('#market-price-sum').text(marketPriceSum);
	$('#save').text(save.toFixed(2));
	$('#percent').text(percent.toFixed(2) + '%');
	
	//税点计算
	var tax = 0;
	if ($('[name=NeedInvoice]:checked').val() == 'true')
		tax = (parseFloat(salePriceSum) * parseFloat($('[name=TaxRate]').val()) / 100).toFixed(2);
	
	//订单总价计算
	var sum = parseFloat(salePriceSum) + parseFloat(freightSum) + parseFloat(tax);
	
	//订单页显示费用总计
	$('#price').text(salePriceSum);
	$('#freight').text(freightSum);
	$('#sum').text(sum.toFixed(2));
}

function onDeleteCart()
{
	//客户端删除
	var row = $(this).closest('tr');
	var id = row.data('id');
	row.remove();	
	
	//获取所有商品
	var carts = JSON.parse(ali.util.cookie('Cart' + $('html').attr('lang')));
	
	//cookie中删除，并且保存cookie
	for (var i = 0; i < carts.length; i++)
	{
		if (carts[i].id == id)
		{
			carts.splice(i, 1);
			ali.util.cookie('Cart' + $('html').attr('lang'), JSON.stringify(carts), 365 * 24 * 60, '/');
		}
	}
	
	//更新小计
	calcSum();
	
	return false;
}

function clearCart()
{
	//清空列表
	$('.block6 tbody').empty();
	
	//清空cookie
	ali.util.cookie('Cart' + $('html').attr('lang'), '', 365 * 24 * 60, '/');
	
	//更新小计
	calcSum();
	
	return false;
}

function order()
{
	//是否有收货地址
	var addresses = $('#addresses tbody tr');
	if (addresses.length == 0 || addresses.find('[name=IsDefault]:checked').length == 0)
	{
		ali.error(_lang_no_address);
		return false;
	}
	var address = addresses.filter(':has([name=IsDefault]:checked)');
	
	//发票
	var needInvoice = $('[name=NeedInvoice]:checked').val();
	var invoiceRise = $('[name=InvoiceRise]');
	if (needInvoice == 'true' && invoiceRise.val() == '')
	{
		ali.error(_lang_invoice_rise_empty, $.proxy(function(){invoiceRise[0].select();}, this));
		return false;
	}
	
	//#region 准备商品
	var products = [];
	var title = '';
	var carts = ali.util.cookie('Cart' + $('html').attr('lang'));
	if (carts == '')
	{
		ali.error(_lang_no_goods);
		return false;
	}
	
	carts = JSON.parse(carts);
	for (var i = 0; i < carts.length; i++)
	{
		//获取运送方式和运费
		var freight = 0;
		var deliver = '';
		var option = $('#goods tbody [data-id="' + carts[i].id + '"] :selected');
		if (option.length)
		{
			deliver = option.val();
			freight = parseFloat(option.data('fee'));
		}
		
		//
		products.push({id:carts[i].goodsId,no:carts[i].goodsNo,specId:carts[i].specId,specNo:carts[i].specNo,spec:carts[i].spec,name:carts[i].name,thumbnail:carts[i].thumbnail,price:carts[i].salePrice,amount:carts[i].amount,freightTemplateId:carts[i].freightTemplateId,bear:carts[i].bear,deliver:deliver,freight:freight});
		title += carts[i].name;
	}
	//#endregion
	
	//准备电话
	var phone = address.data('phone');
	if (phone != '' && address.data('mobile') != '')
		phone += ' , ' + address.data('mobile');
	else if (address.data('mobile') != '')
		phone = address.data('mobile');
	
	//准备数据
	var data = 'Title=' + encodeURIComponent(title);
	data += '&UserName=' + encodeURIComponent(ali.util.cookie('UserName'));
	data += '&UserID=' + encodeURIComponent(ali.util.cookie('UserID'));
	data += '&ReceiverName=' + encodeURIComponent(address.data('name'));
	data += '&ReceiverPhone=' + encodeURIComponent(phone);
	data += '&ReceiverAddress=' + encodeURIComponent(address.data('address'));
	data += '&ReceiverZip=' + encodeURIComponent(address.data('zip'));
	data += '&UserMemo=' + encodeURIComponent($('[name=UserMemo]').val());
	data += '&Freight=' + encodeURIComponent($('#freight').text());
	data += '&NeedInvoice=' + needInvoice;
	data += '&InvoiceRise=' + encodeURIComponent(invoiceRise.val());
	data += '&TaxRate=' + encodeURIComponent($('[name=TaxRate]').val());
	data += '&Price=' + encodeURIComponent($('#price').text());
	data += '&Sum=' + encodeURIComponent($('#sum').text());
	
	ali.working(_lang_working);
	
	$.ajax(
	{
		url: _webPath + 'alicms.aspx?Object=Order&Operation=Add',
		data: data,
		type: 'POST',
		error: function()
		{
			ali.error(_lang_operation_fail);
			ali.working();
		},
		success: function(guid)
		{
			addDetail(guid, 0, products);
		}
	});
	
	return false;
}

function addDetail(orderId, index, products)
{
	if (index >= products.length)
	{
		ali.working();
		clearCart();
		ali.success(_lang_operation_success, {onClose:function(){window.location = _payPath.replace('{ID}', orderId);}});
		return;
	}
	
	var data = 'OrderID=' + orderId;
	data += '&GoodsID=' + products[index].id;
	data += '&GoodsNo=' + products[index].no;
	data += '&GoodsSpecID=' + products[index].specId;
	data += '&GoodsSpecNo=' + products[index].specNo;
	data += '&GoodsSpec=' + encodeURIComponent(products[index].spec);
	data += '&Name=' + encodeURIComponent(products[index].name);
	data += '&Thumbnail=' + encodeURIComponent(products[index].thumbnail);
	data += '&Price=' + products[index].price;
	data += '&Amount=' + products[index].amount;
	data += '&FreightTemplateID=' + products[index].freightTemplateId;
	data += '&Bear=' + products[index].bear;
	data += '&Deliver=' + products[index].deliver;
	data += '&Freight=' + products[index].freight;
	
	index++;
	
	$.ajax(
	{
		url: _webPath + 'alicms.aspx?Object=Order.Detail&Operation=Add',
		data: data,
		type: 'POST',
		error: function()
		{
			ali.error(_lang_operation_fail);
			ali.working();
		},
		success: function(guid)
		{
			addDetail(orderId, index, products);
		}
	});
}

function addAddress()
{
	//检查地区
	var region = $('select:first', this);
	if (region.val() == '')
	{
		ali.error(_lang_region_empty);
		return false;	
	}
	
	//检查收货地址
	if (this.SubAddress.value == '')
	{
		ali.error(_lang_sub_address_empty, $.proxy(function(){this.SubAddress.select();}, this));
		return false;
	}
	
	//检查邮政编码
	if (this.Zip.value == '')
	{
		ali.error(_lang_zip_empty, $.proxy(function(){this.Zip.select();}, this));
		return false;
	}
	
	//检查收货人名称
	if (this.Name.value == '')
	{
		ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
		return false;
	}
	
	//检查收货人手机
	if (!this.Mobile.value.match(/^\d{11}$/))
	{
		ali.error(_lang_mobile_incorrect, $.proxy(function(){this.Mobile.select();}, this));
		return false;
	}
	
	//准备数据
	var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&RegionID=' + region.val();
		data += '&SubAddress=' + encodeURIComponent(this.SubAddress.value);
		data += '&Zip=' + this.Zip.value;
		data += '&Mobile=' + this.Mobile.value;
		data += '&Phone=' + this.Phone.value;
		data += '&IsDefault=' + this.IsDefault.checked;
		data += '&UserID=' + ali.util.cookie('UserID');
		data += '&UserName=' + encodeURIComponent(ali.util.cookie('UserName'));
	
	//提交数据
	var form = this;
	$.ajax(
	{
		url: _webPath + 'alicms.aspx?Object=Address&Operation=Add',
		data: data,
		type: 'POST',
		error: function()
		{
			ali.error(_lang_operation_fail);
		},
		success: function(guid)
		{
			ali.success(_lang_operation_success);
			
			//增加到列表中	
			var tbody = $('.block3 tbody');
			if (tbody.length == 0)
			{
				$('.block3 thead').after('<tbody>');
				tbody = $('.block3 tbody');
			}
			
			var tr = '<tr data-name="' + form.Name.value + '" data-region-id="' + region.val() + '" data-phone="' + form.Phone.value + '" data-mobile="' + form.Mobile.value + '" data-address="' + $(form.SubAddress).prev().text() + form.SubAddress.value + '" data-zip="' + form.Zip.value + '">';
			tr += '<td><input type="radio" name="IsDefault" checked></td>';
			tr += '<td>' + form.Name.value + '</td>';
			tr += '<td>' + $(form.SubAddress).prev().text() + '</td>';
			tr += '<td>' + form.SubAddress.value + '</td>';
			tr += '<td>' + form.Zip.value + '</td>';
			tr += '<td>' + form.Mobile.value + '</td>';
			tr += '<td>' + form.Phone.value + '</td>';
			tr += '</tr>';
			tbody.append(tr);
		}
	});
	
	return false;
}

function addBook()
{
	
	if (this.Subject.value == '')
	{
		ali.error(_lang_subject_empty, $.proxy(function(){this.Subject.select();}, this));
		return false;
	}
	if (this.Content.value == '')
	{
		ali.error(_lang_content_empty, $.proxy(function(){this.Content.select();}, this));
		return false;	
	}
	if (this.QQ.value == '')
	{
		ali.error(_lang_qq_empty, $.proxy(function(){this.QQ.select();}, this));	
		return false;
	}
	
	ali.working(_lang_working);
	
	var data = 'Subject=' + encodeURIComponent(this.Subject.value);
	data += '&Content=' + encodeURIComponent(this.Content.value);
	data += '&QQ=' + encodeURIComponent(this.QQ.value);
	
	$.ajax(
	{
		url: _webPath + 'alicms.aspx?Mark=GuestBook&Object=GuestBook&Operation=Add',
		data: data,
		type: 'POST',
		error: function()
		{
			ali.error(_lang_operation_fail);
			ali.working();
		},
		success: function()
		{
			ali.success(_lang_operation_success);
			ali.working();
			
			$('.frame6-main form')[0].reset();
		}
	});
	
	return false;
}

function onAddressClick()
{
	var defaultAddress = $('#addresses :radio:checked');
	if (!defaultAddress.length)
	{
		calcSum();
		return;
	}
	
	//从cookie中获取商品,json格式
	var carts = ali.util.cookie('Cart' + $('html').attr('lang'));
	if (carts == '')
		carts = [];
	else
		carts = JSON.parse(carts);

	//获取收货地区ID（查找城市）
	var regionId = defaultAddress.closest('tr').data('regionId');
	$.ajax(
	{
		url: _city_path + '?RegionID=' + regionId,
		type: 'GET',
		async: false,
		success: function(data)
		{
			regionId = $.trim(data);
		}
	});

	for (var i = 0; i < carts.length; i++)
	{
		row = $('#goods tbody [data-id="' + carts[i].id + '"]');

		if (carts[i].bear != 'BuyerCustom')
			continue;
		
		var option = '';
		for (var d = 0; d < 3; d++)
		{
			var value = null;
			var defaultValue = null;
			var regions = {};
			if (d == 0)
			{
				defaultValue = carts[i].express.defaultValue;
				regions = carts[i].express.regions;
			}
			else if (d == 1)
			{
				defaultValue = carts[i].ems.defaultValue;
				regions = carts[i].ems.regions;
			}
			else
			{
				defaultValue = carts[i].post.defaultValue;
				regions = carts[i].post.regions;
			}
			
			//查找是否指定地区
			for (var j = 0; j < regions.length; j++)
			{
				for (var k = 0; k < regions[j].ids.length; k++)
				{
					if (regionId == regions[j].ids[k])
					{
						value = regions[j];
						break;
					}
				}
				
				if (value != null)
					break;
			}
			
			//如果没有指定地区，则取默认值
			if (value == null)
				value = defaultValue;
			
			//计算运费
			var fee = 0;
			if (carts[i].method == 'Number')
			{
				fee += value.startFee;
				fee += Math.ceil((carts[i].amount - value.start) / value.plus) * value.plusFee;
			}
			else if (carts[i].method == 'Weight')
			{
				fee += value.startFee;
				fee += Math.ceil((carts[i].weight - value.start) / value.plus) * value.plusFee;
			}
			else// if (carts[i].method == 'Volume')
			{
				fee += value.startFee;
				fee += Math.ceil((carts[i].volume - value.start) / value.plus) * value.plusFee;
			}
			
			//形成option
			if (d == 0)
				option += '<option value="Express" data-fee="' + fee + '">' + _lang_express + ' ' + fee + _lang_yuan + '</option>';
			else if (d == 1)
				option += '<option value="EMS" data-fee="' + fee + '">' + _lang_ems + ' ' + fee + _lang_yuan + '</option>';
			else// if (d == 2)
				option += '<option value="Post" data-fee="' + fee + '">' + _lang_post + ' ' + fee + _lang_yuan + '</option>';
		}
		
		$('select', row).html(option);
	}
	
	//更新小计
	calcSum();
}

(function()
{
	//搜索
	$('.header form').submit(function()
	{
		var q = $('[name=q]', this);
		if (q.val() == '')
		{
			ali.error(_lang_keyword_empty, $.proxy(function(){q[0].select();}, this));
			return false;
		}
		
		window.open($(this).attr('action').replace('{q}', q.val()));
		
		return false;
	});
	
	//显示浏览过的商品
	if ($('.history div').length)
	{
		showVisitedGoods('.history div');
	}

	//侧栏二级导航
	$('.menu dt ul>li').mouseenter(function()
	{
		var me = $('>a', this);
		me.addClass('hover');
		var x = me.outerWidth();
		var y = me.position().top;
		if ($('html').attr('lang') == 'UYG')
			$('div', this).css({right:x,top:y}).show();
		else
			$('div', this).css({left:x,top:y}).show();
	}).mouseleave(function()
	{
		var me = $('>a', this);
		me.removeClass('hover');
		$('div', this).hide();
	});
	
	//index之外，并且有菜单的页面
	if ($('.menu ul').length && (typeof(_page) == 'undefined' || _page != 'index'))
	{
		$('.menu dt').mouseenter(showNav).mouseleave(function(){$('.menu ul').stop().slideUp();});
	}
	
	//设置购物车数量
	$('#cart-count').text(getCartCount());
	
	if (typeof(_page) == 'undefined')
		return;

	if (_page == 'index')
	{
		//侧栏导航
		$(window).resize(showNav);
		showNav();
		
		//tabmenu：热门商品，推荐商品，人气商品，促销商品
		$('.tab-menu1 h1 a,.tab-menu2 h1 a').mouseover(function()
		{
		   var me = $(this);
		   if (!me.hasClass('active'))
		   {
				me.siblings('a').removeClass('active');
				me.addClass('active');
				
				var index = me.parent().children('a').index(this);
				var panels = me.parent().siblings();
				panels.hide();
				panels.eq(index).show();
		   }			
		});
	}
	else if (_page == 'goods_category')
	{
		//加入购物车
		$('.cart').click(addCart);
		
		//排序下拉选择框处理
		$('.col4 select').change(function(){window.location = this.value;})[0].selectedIndex = _order;
		
		//上面的页数设置
		$('.col1 span').append($('.pagination').data('pageCount'));
		
		//上面的“上页”和“下页”处理
		$('.pagination .prev').clone().appendTo('.col1');
		$('.pagination .next').clone().appendTo('.col1');	
		
		//收藏
		$('.list14 tbody tr td:nth-child(4) a,.list16 dd p .collect').click(collect);
	}
	else if (_page == 'goods')
	{
		//启动促销时间程序
		updatePromoteTime();
		
		// 商品描述，商品属性 商品标签之间的切换//
		$('#goods-tabmenu a').click(function()
		{
			if ($(this).hasClass('active'))
				return false;
			
			$(this).addClass('active');
			$(this).siblings().removeClass('active');
			
			var index = $(this).parent().children().index(this);
			var contents = $(this).parent().next().children();
			contents.hide();
			contents.eq(index).show();
			
			return false;
		});
		
		//放大镜
		var jqzoom = $('.jqzoom').jqzoom({zoomType:'standard',lens:true,preloadImages:false,alwaysOn:false,zoomWidth:400,zoomHeight:300});

		//查看原图
		$('#view-orgin-picture').click(function()
		{
			window.open($('.jqzoom').attr('href'));
			return false;
		});	
		
		//更多图片滚动
		var ul = $('#more-picture ul');
		ul.css('width', ul.children().width() * ul.children().length);
		if (ul.children().length <= 4)
			$('#more-picture .prev').css('visibility', 'hidden');

		//更多图片左箭头
		var mpPage = 1;
		var mpPageCount = Math.ceil(ul.children().length / 4);
		var mpStep = ul.children().outerWidth() * 4;
		$('#more-picture .prev').click(function()
		{
			mpPage++;

			ul.stop();
			if ($('html').attr('lang') == 'UYG')
				ul.animate({right:-(mpPage - 1) * mpStep});
			else
				ul.animate({left:-(mpPage - 1) * mpStep});
			
			if (mpPage == mpPageCount)
				$(this).css('visibility', 'hidden');
			
			if (mpPage > 1)
				$('#more-picture .next').css('visibility', 'visible');
		});
		
		//更多图片右箭头
		$('#more-picture .next').click(function()
		{
			mpPage--;

			ul.stop();
			if ($('html').attr('lang') == 'UYG')
				ul.animate({right:-(mpPage - 1) * mpStep});
			else
				ul.animate({left:-(mpPage -1) * mpStep});
			
			if (mpPage == 1)
				$(this).css('visibility', 'hidden');
			
			if (mpPage < mpPageCount)
				$('#more-picture .prev').css('visibility', 'visible');
		});
		
		//获取用户评价
		$('.comment').on('click', '.pagenation a', function()
		{
			$('.comment>div').load(_channelPath + 'ajax_comment.aspx?GoodsID=' + _guid + '&Page=' + $(this).data('page'));
			return false;
		});

		//购买数量处理
		$('.up,.down').click(function()
		{
			var amount = $('[name=Amount]').val();
			if (!amount.match(/^\d+$/))
			{
				amount = 1;
				$('[name=Amount]').val(amount);
				return false;
			}
			
			if ($(this).hasClass('up'))
				amount++;
			else
				amount--;
			
			if (amount < 1)
				return false;
			
			$('[name=Amount]').val(amount).keyup();
				
			return false;
		});
		
		//处理数量改变事件
		$('.spec :text').keyup(onAmountKeyUp);
		
		//#region 处理规格
		if (_specValues.length > 0)
		{
			//筛选规格
			for (var i = 0; i < _specs.length; i++)
			{
				for (var j = 0; j < _specs[i].options.length; j++)
				{
					var exist = false;
					
					for (var k = 0; k < _specValues.length; k++)
					{
						for (var g = 0; g < _specValues[k].optionIds.length; g++)
						{
							if (_specs[i].options[j].id == _specValues[k].optionIds[g])
							{
								exist = true;
								break;
							}
						}
						
						if (exist)
							break;
					}
					
					if (!exist)
					{
						_specs[i].options.splice(j, 1);
						j--;
					}
				}
				
				if (_specs[i].options.length == 0)
				{
					_specs.splice(i, 1);
					i--;
				}
			}
			
			// 构造规格
			var specs = '';
			for (var i = 0; i < _specs.length; i++)
			{
				if (i == 0)
					specs += '<dl>';
				
				specs += '<dt>' + _specs[i].name + ' : </dt><dd><select>';
				for (var j = 0; j < _specs[i].options.length; j++)
				{
					specs += '<option value="' + _specs[i].options[j].id + '">' + _specs[i].options[j].name + '</option>';
				}
				specs += '</select></dd>';
				
				if (i == _specs.length - 1)
					specs += '</dl>';
			}
			$('.spec').prepend(specs);
			
			//规格选项变化事件处理
			var selects = $('.spec dl select');
			selects.change(onSpecChange).eq(0).change();
		}
		//#endregion 处理规格	
		
		//#region 构造属性
		var props = '<tr>';
		for (var i = 0; i < _props.length; i++)
		{
			props += '<th>' + _props[i].name + '</th>';
			var td = '';
			for (var j = 0; j < _propValues.length; j++)
			{
				if (_props[i].id == _propValues[j].id)
				{
					if (_propValues[j].optionIds.length > 0)
					{
						var value = '';
						for (var k = 0; k < _propValues[j].optionIds.length; k++)
						{
							for (var g = 0; g < _props[i].options.length; g++)
							{
								if (_propValues[j].optionIds[k] == _props[i].options[g].id)
								{
									if (value != '')
										value += ' , ';
									value += _props[i].options[g].name;
								}
							}
						}

						td = '<td>' + value + '</td>';
					}
					else
					{
						td = '<td>' + _propValues[j].value + '</td>';
					}
				}
			}
			
			if (td == '')
				td = '<td></td>';
			props += td;
		}
		props += '</tr>';
		$('.property tbody').html(props);
		//#endregion 构造属性
		
		// 立即购买和加入购物车
		$('.spec .buy,.spec .cart').click(onAddCardClick);
		
		//收藏
		$('.spec .collect').click(collect);

	}
	else if (_page == 'cart')
	{
		//显示购物车的商品列表
		showCart('.block6 tbody');
		
		//删除商品
		$('.block6 tbody tr td a').click(onDeleteCart);
		
		//清空购物车
		$('.block6 tfoot .clear').click(clearCart);
				
		//订单数量的改变
		$('.block6 tbody tr input').keyup(onAmountKeyUp);
		
	}
	else if (_page == 'order')
	{
		//显示订单商品的列表
		showCart('#goods tbody');
		
		//处理“新增收货人地址”
		$('#addresses tfoot :checkbox').click(function(){$('#new-address').toggle();});
		
		//地址改变时，重新计算运费
		$('#addresses tbody :radio').click(onAddressClick);
		
		//如果没有任何收货地址，默认显示新增收货地址表单
		if ($('#addresses tbody').length == 0)
			$('#addresses tfoot :checkbox').click();
			
		//处理地区变化
		$('#new-address').on('change', 'select', onRegionChange);
		
		//处理新增收货人地址表单
		$('#new-address').submit(addAddress);
		
		//运送方式变化时，重新计算订单总价
		$('#goods').on('change', 'select', calcSum);
		
		//“是否需要发票”点击事件
		$('[name=NeedInvoice]').click(function()
		{
			$('[name=InvoiceRise]').prop('disabled', this.value == 'false');
			calcSum();
		});
		
		//提交订单
		$('#order').click(order);
	}
	else if (_page == 'pay')
	{
		$('#pay').submit(function()
		{
			var sum = parseFloat($('thead td em', this).text());
			var firstPayment = $('[name=Payment]:first', this);
			if (firstPayment.prop('checked'))
			{
				var balance = parseFloat(firstPayment.val());
				if (balance < sum)
				{
					ali.error(_lang_balance_not_enough);
					return false;
				}
				
				ali.working(_lang_working);
				
				$.ajax(
				{
					url: _webPath + 'alicms.aspx?Object=Order&Operation=Pay&ID=' + _id,
					data: 'Amount=' + sum,
					type: 'POST',
					error: function()
					{
						ali.error(_lang_operation_fail);
						ali.working();
					},
					success: function()
					{
						ali.success(_lang_operation_success, function(){window.location = _orderListPath});
						ali.working();
					}
				});
			}
			else
			{
				var payment = $('[name=Payment]:checked', this);
				
				var data = 'Title=' +  encodeURIComponent(_lang_title);
				data += '&Amount=' + sum;
				data += '&PaymentID=' + payment.val();
				data += '&ReturnUrl=' + encodeURIComponent('http://' + document.location.host + _returnPath);
				
				ali.working(_lang_working);
				
				$.ajax(
				{
					url: _webPath + 'alicms.aspx?Mark=User&Object=User.Money&Operation=OnlineRecharge',
					data: data,
					type: 'POST',
					error: function(request)
					{
						ali.error(_lang_operation_fail);
						ali.working();
					},
					success: function(data)
					{
						$('body').append('<div style="display:none">' + data + '</div>').find('form:last').submit();
					}
				});
			}
			
			return false;
		});			
	}
	else if (_page == 'pay_return_url')
	{
		ali.working(_lang_working);
		
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=Order&Operation=Pay&ID=' + _id,
			data: 'Amount=' + _sum,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_operation_fail);
				ali.working();
			},
			success: function()
			{
				ali.success(_lang_operation_success, function(){window.location = _orderListPath});
				ali.working();
			}
		});
	}
	else if (_page == 'brand')
	{
		//收藏
		$('.list16 dl dd p a:last').click(collect);
	}
	else if (_page == 'book')
	{
		$('.frame6-main form').submit(addBook);
		$('.frame6-main form:reset').click(function(){this.form.reset();});
	}
})();