function dropMenu(obj){
	$(obj).each(function(){
		var theSpan = $(this);
		var theMenu = theSpan.find(".submenu");
		var tarHeight = theMenu.height();
		theMenu.css({height:0,opacity:0});
		theSpan.hover(
			function(){
				$(this).addClass("curr");
				theMenu.stop().show().animate({height:tarHeight,opacity:1},400);
			},
			function(){
				$(this).removeClass("curr");
				theMenu.stop().animate({height:0,opacity:0},400,function(){
					$(this).css({display:"none"});
				});
			}
		);
	});
}
var cartShow = '';
$("document").ready(function(){
	//回车search
	$("#head_keyword").keydown(function(event){
		if(event.keyCode == 13){
			$("#head").trigger('click');
		}
	})
	dropMenu(".drop-menu-effect");//nav
   $(".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: "20", 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: "20", opacity:1}, "fast").css("display","block");
			});
		}
	},function(){
		$(this).find(".car").stop().animate({top: "0", opacity: 0}, "fast").css("display","none");
	});
	$("#nav .cart").hover(function() {
		$(this).find(".car").stop().animate({top: "27", 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,.set_l textarea").focus(function(){
		 text_val=$(this).attr("placeholder");
		 $(this).addClass("textInput_curr");
		 if($(this).val()==text_val)
		 $(this).val("");
	  })
	  $(".textInput,.set_l textarea").blur(function(){
		  if(!$(this).val())
		  {
			$(this).removeClass("textInput_curr");
			$(this).val(text_val);
		  }    
	  })
	  //输入框提示和选中 end
})

//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 i").click( function(){
       if($(this).hasClass("curr"))
       {
         $(this).removeClass("curr");
         $("#on_line ul").hide();
         $("#on_line").css("width","26px");
       }
       else{
         $(this).addClass("curr");
         $("#on_line ul").show();
         $("#on_line").css("width","105px");
       }
   })
});


//导航
;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $([].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 100,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

//添加到购物车
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(){
   $(".searchBtn").click(function(){
	   var sType = $(this).attr('id');
		if (!$.trim($("#"+sType+"_keyword").val())) {
			alert('请输入您要查询的关键词！');
			return false;
		}
	   base = new Base64();
	   var keyword =  $("#"+sType+"_keyword").val();
	   //var keyword = keyword.replace('%2F', '_', keyword);
	   window.location.href='/mall/search.asp?tp=0&kw='+keyword;
	});
})
