var cartShow = '';
$("document").ready(function(){
	
	$(".imageMenu ul li .imgBorder,.layout_pic1 ul li,.layout_pic2 ul li,.layout_pic5 ul li").mousemove(function(){
	   $(this).addClass("curr");
	}).mouseout(function(){$(this).removeClass("curr");})
	$(".purchase,.a_btn2").hover(function(){$(".category").css({height:"30px"});},function(){$(".category").css({height:"auto"});});
		
	
   $(".list ul li .imgBorder").mousemove(function(){
	   $(this).addClass("curr");
	}).mouseout(function(){$(this).removeClass("curr");});
	$(".tabbtn li").click(function(){
		$(".tabbtn li").removeClass('current');
		$(".tabcon").hide();
		var tab = $(this).attr('id');
		$(this).addClass('current');
		$("#"+tab.replace('tab-', 'item-')).show();
	});
	$(".sel").hover(function() {
		if (cartShow) {
			$("#cartInfoDiv").html(cartShow);
			$(".sel").find(".car").stop().animate({top: "35", opacity:1}, "fast").css("display","block");
		}
		else {
			$.post('/index.php?module=default&controller=cart&action=ajax_get_cart', {}, function(msg){
				cartShow = msg;
				$("#cartInfoDiv").html(msg);
				$(".sel").find(".car").stop().animate({top: "35", opacity:1}, "fast").css("display","block");
			});
		}
	},function(){
		$(this).find(".car").stop().animate({top: "0", opacity: 0}, "fast").css("display","none");
	});
	
	$(".sidebar_right ul li").mousemove(function(){
	   for(i=0;i<$(this).parents("ul").find("li").length;i++)
	   {$(this).parents("ul").find("li").eq(i).removeClass("curr");}	
	   $(this).addClass("curr");
	})
	  //输入框提示和选中
	  var text_val;
	  $(".textInput").focus(function(){
		 text_val=$(this).attr("placeholder");
		 $(this).addClass("textInput_curr");
		 if($(this).val()==text_val)
		 $(this).val("");
	  })
	  $(".textInput").blur(function(){
		  if(!$(this).val())
		  {
			$(this).removeClass("textInput_curr");
			$(this).val(text_val);
		  }    
	  })
	  //输入框提示和选中 end
	  
	  $(".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});
})

//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(){
$("#on_line dl dt").click( function(){
       if($(this).hasClass("curr"))
       {
         $(this).removeClass("curr");
         $("#on_line dd").hide();
         $("#on_line").css("width","26px");
       }
       else{
         $(this).addClass("curr");
         $("#on_line dd").show();
         $("#on_line").css("width","105px");
       }
   })
});
//返回顶部
$(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(), winh = $(window).height();
        (st > 0)? $backToTopEle.show(): $backToTopEle.hide();
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);
        }
    };
    $(window).bind("scroll", $backToTopFun);
});

// 修复 IE 下 PNG 图片不能透明显示的问题
function fixPNG(myImage) {
var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
if ((version >= 5.5) && (version < 7) && (document.body.filters)){
     var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
     var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
     var imgTitle = (myImage.title) ? "title='" + myImage.title   + "' " : "title='" + myImage.alt + "' ";
     var imgStyle = "display:inline-block;" + myImage.style.cssText;
     var strNewHTML = "<span " + imgID + imgClass + imgTitle

   + " style=\"" + "width:" + myImage.width

   + "px; height:" + myImage.height

   + "px;" + imgStyle + ";"

   + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"

   + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
     myImage.outerHTML = strNewHTML;
} }


//添加到购物车
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 gbk 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 gbk 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(){
	$("#no_keyword,#head_keyword,#checkcode").keydown(function(e){
		var e = e ? e :(window.event ? window.event : null);
		if(e.keyCode==13) {
			var id = $(this).attr('id').replace('_keyword', '');
			$("#"+id).trigger('click');
			$(".inputbtn1").trigger("click");
		}
	});
	
	$(".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';
	});
	
	var obj=$(".sort_mid");
	//$(".sort_mid dl").first().addClass("curr");
	$(".sort_mid dl").each(function(){		
		if ($(this).hasClass("curr")){
			obj=$(this);
		}
		$(this).click(function(){
			obj.removeClass("curr");
			$(this).addClass("curr");
			obj=$(this);
		})
	});
});