var cartShow = '';
$("document").ready(function(){
   $(".other_pic ul li,.list ul li div").mousemove(function(){
	   $(this).addClass("curr");
	}).mouseout(function(){$(this).removeClass("curr");});
	$("#no_keyword").keydown(function(event){
		if(event.keyCode == 13){
			$("#no").trigger('click');
		}
	})
	$("#head_keyword").keydown(function(event){
		if(event.keyCode == 13){
			$("#head").trigger('click');
		}
	})
	
	
	
	$(".sel").hover(function() {
		$.post('/index.php?module=default&controller=cart&action=ajax_get_cart', {}, function(msg){
			if (!msg) return;
			cartShow = msg;
			$("#cartInfoDiv").html(msg);
			$(".sel").find(".car").stop().fadeIn(0);
		});
	},function(){
		$(this).find(".car").stop().fadeOut(0);
	});
	
	
	//客服
	$(".service_01").mouseover(function(){
		$(this).removeClass("dispNone");
	}).mouseout(function(){
		$(this).addClass("dispNone");
	})
	$.fn.hoverForIE6=function(option){
			var s=$.extend({current:"hover",delay:10},option||{});
			$.each(this,function(){var timer1=null,timer2=null,flag=false;
			$(this).bind("mouseover",function(){
				if (flag)
				{
					clearTimeout(timer2);
				}
				else
				{
					var _this=$(this);
					timer1=setTimeout(function(){_this.addClass(s.current);flag=true;},s.delay);
				}
			}).bind("mouseout",function(){
				if (flag){ 
					var _this=$(this);timer2=setTimeout(function(){
						_this.removeClass(s.current);flag=false;
					},s.delay);
				}else{
					clearTimeout(timer1);
				}
			})
		})};
	$(".allsort").hoverForIE6({current:"firsthover",delay:50});
	$(".allsort .mc ul li").hoverForIE6({current:"threehover",delay:50});
	$(".plist_cont ul li .imgBorder").hoverForIE6({current:"plisthover",delay:50});
})


//返回顶部
$(function() {
    var $backToTopTxt = "", $backToTopEle = $('<div class="backToTop"></div>').appendTo($("body"))
        .text($backToTopTxt).attr("title", $backToTopTxt).click(function() {
            $("html, body").animate({ scrollTop: 0 }, 120);
    }), $backToTopFun = function() {
        var st = $(document).scrollTop();
		var winh = $(window).height();
        (st > (winh/2))? $backToTopEle.show(300): $backToTopEle.hide(300);
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);
        }
    };
    $(window).bind("scroll", $backToTopFun);
});
//TAB切换
function setTabAll(name,cursel,n){
	for(i=1;i<=n;i++){
	   if(cursel==i)
	   {
		  $("#"+name+"_"+i).removeClass("hidden");
		  $("#"+name+i).addClass("curr");
	   } 
	   else{
	   $("#"+name+"_"+i).addClass("hidden");
	   $("#"+name+i).removeClass("curr");}
	}
}

	

//添加到购物车
function addcart() {
	var productQuantity = Number($('input[name=quantity]').val());
	var purchaseQuantity = Number($('input[name=purchase_quantity]').val());
	var alertText = '';
	var tipDivId = '';
	$(".tips").hide();
	$('.buychoose-input').each(function(i) { 
		if ($(this).val() == '') {
			if (tipDivId == '') tipDivId = $(this).attr('title');
			alertText += "请先选择您要的"+$(this).attr('title')+"<br />";
		}
	});
	if (tipDivId) {
		$('.order_form_detail').addClass('detailCurr');
		$("#tip-"+tipDivId).show();
	}
	if (alertText) {
		$("#warning-text").html(alertText);
		$("#warning").show('500');
		setTimeout('$("#warning").hide()', 3000);
		return false;
	}
	if (!purchaseQuantity || purchaseQuantity < 0) { alert('请正确输入要的数量'); $('input[name=purchase_quantity]').focus(); return; }
	if (productQuantity == 0) { alert('此商品规格缺货'); return; }
	else if (productQuantity != -1 && purchaseQuantity > productQuantity) { alert('此商品缺货'); return; }
	$.post('/index.php?controller=cart&action=ajax_addcart', $("#buy-param").serialize(), function(result) {
		$('.cart-count').text(result); $("#cartOk").show('500');
    });
}

//立即购买
function buynow() {	
	var productQuantity = Number($('input[name=quantity]').val());
	var purchaseQuantity = Number($('input[name=purchase_quantity]').val());
	var alertText = '';
	var tipDivId = '';
	$(".tips").hide();
	$('.buychoose-input').each(function(i) { 
		if ($(this).val() == '') {
			if (tipDivId == '') tipDivId = $(this).attr('title');
			alertText += "请先选择您要的"+$(this).attr('title')+"<br />";
		}
	});
	if (tipDivId) {
		$('.order_form_detail').addClass('detailCurr');
		$("#tip-"+tipDivId).show();
	}
	if (alertText) {
		$("#warning-text").html(alertText);
		$("#warning").show('500');
		setTimeout('$("#warning").hide()', 3000);
		return false;
	}	
	if (!purchaseQuantity || purchaseQuantity < 0) { alert('请正确输入要的数量'); $('input[name=purchase_quantity]').focus(); return; }
	if (productQuantity == 0) { alert('此商品规格缺货'); return; }
	else if (productQuantity != -1 && purchaseQuantity > productQuantity) { alert('此商品缺货'); return; }
	$.post('/index.php?controller=cart&action=ajax_buynow', $("#buy-param").serialize(), function(result) {
		window.location = '/?controller=cart&action=confirm&marks='+result;
    });
}

function butbuynow(obj) {
	var productQuantity = Number($(obj).attr('productQuantity'));
	var productId = Number($(obj).attr('productId'));
	
	if (productQuantity && productId) {
		$.post('/index.php?controller=cart&action=ajax_buynow', {'id':productId, 'purchase_quantity':productQuantity}, function(result) {
			window.location = '/?controller=cart&action=confirm&marks='+result;
		});
	}
}

//用户选购
function buychoose(t, key) {
	var promotionPrice = Number($('input[name=promotion_price]').val());
	var sellingPrice = Number($('input[name=selling_price]').val());
	var marketPrice = Number($('input[name=market_price]').val());
	
	$('.order_form_detail').removeClass('detailCurr');

	$('#buychoose-'+key).val('['+key+':'+$(t).text()+']');
	$('#show-buychoose-'+key).text($(t).text());
	$('#options-'+key+' span').removeClass('curr');
	$(t).addClass('curr');
	$("#tip-"+key).hide();
	$(".col").show();
	$.post('/index.php?controller=product&action=ajax_buychoose', $("#buy-param").serialize(), function(json) {
		//$('.notice').empty();
		if (json) {
			if (json.adjustment_price) {
				$('.promotion-price').html((Number(json.adjustment_price) + Number(promotionPrice)).toFixed(2)); 
				$('.selling-price').html((Number(json.adjustment_price) + Number(sellingPrice)).toFixed(2)); 
				$('.market-price').html((Number(json.adjustment_price) + Number(marketPrice)).toFixed(2));
			}
			if (json.quantity != -1) {
				if (json.quantity <= 0) {
					$('.notice_').text('(缺货)');
				}
				else {
					$('.notice_').html('(库存<b class="ff00">'+json.quantity+'</b>件)');
				}
			}
			else {
				$('.notice_').html('<span class="f666">库存充足，下单后可立即发货</span>');
			}
			$('input[name=quantity]').val(json.quantity);
		}
    }, 'json');
}

function fav(id) {
	$.post('/index.php?controller=product&action=ajax_fav', {id:id}, function(result) {
		alert(result);
    });
}

function AddFavorite(title,url) { 
	if (window.sidebar) { 
		window.sidebar.addPanel(title,url,""); 
	}
	else if( document.all ) { 
		window.external.AddFavorite(url,title); 
	}
	else { 
		alert("您的浏览器暂不支持，请使用Ctrl+D进行添加！");
	} 
}

// base64 类库
function Base64() {
	// private property
	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	// public method for encoding
	this.encode = function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = _utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
			_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
			_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	}
 
	// public method for decoding
	this.decode = function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = _utf8_decode(output);
		return output;
	}
 
	// private method for UTF-8 encoding
	_utf8_encode = function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
		return utftext;
	}
 
	// private method for UTF-8 decoding
	_utf8_decode = function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}
$(function(){
		   $(".tabbtn li").click(function(){
		$(".tabbtn li").removeClass('current');
		$(".tabcon").hide();
		var tab = $(this).attr('id');
		$(this).addClass('current');
		$("#"+tab.replace('tab-', 'item-')).show();
	});
   $(".searchBtn").click(function(){
	   var sType = $(this).attr('id');
		var tips = sType == 'no' ? '按产品名称搜索' : '按产品名称搜索';
		if (!$.trim($("#"+sType+"_keyword").val()) || $.trim($("#"+sType+"_keyword").val()) == tips) {
			alert('请输入您要查询的关键词！');
			$("#"+sType+"_keyword").focus();
			return false;
		}
	   base = new Base64();
	   var keyword =  base.encode(encodeURI($("#"+sType+"_keyword").val()));
	   //var keyword = keyword.replace('%2F', '_', keyword);
	   window.location.href='/search/'+keyword+'.html';
	});
})
