//jquery-noconflict
jQuery.noConflict();
//iMycart
function iMycartBind(){
	var object_mycart = jQuery("#o-mycart-list");
	jQuery("#i-mycart").bind("mouseover",function(){
		object_mycart.show();        
	}).bind("mouseleave",function() {
		object_mycart.hide();       
	});
}
jQuery(function() {
	//show-mycart
	iMycartBind();
	//show-all-category
	var object_category = jQuery("#all_category_warp");
	jQuery("#all_category_menu").bind("mouseover",function() {
		object_category.show();
	}).bind("mouseleave",function() {
		object_category.hide();   
	});
	//del-mycart-items
	jQuery(".pane .del").click(function() {
		jQuery(this).parents(".pane").hide();
	});
});
//jauery-autocomplete
function suggest(inputString,event){
	if(event.keyCode == 27 || event.keyCode == 38 || event.keyCode == 40){return;}
	if(inputString.length == 0) {
		jQuery("#site_search_notice").hide();
		jQuery("#list-mode-select").css("visibility", "visible");
	} else {
		jQuery.post("/catalogsearch/result/notice/",{query_text: ""+inputString+""}, function(data){
			jQuery("#site_search_notice").show();			
			jQuery("#site_search_notice_list").html(data);
			jQuery("#site_search_notice_list li").mouseover(function(){jQuery(this).addClass('onfocus')}).mouseout(function(){jQuery(this).removeClass('onfocus')});
			jQuery(document).click(function(){jQuery('#site_search_notice').hide()});
			jQuery("#site_search_notice_list li").bind('click',function(){
				jQuery('#search').val(jQuery(this).children('span:first-child').html());
				jQuery('#search_mini_form').submit();
				jQuery('#site_search_notice').hide();
			});
			jQuery("#list-mode-select").css("visibility", "hidden");			
		});
	}
	}
var current_li = -1;
var last_li = -1;
jQuery(function(){
jQuery('#search').keydown(function(event){
	if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 27){return true;}
	var li_length = jQuery('#site_search_notice_list li').length;
	if(li_length > 0){
		if(jQuery('#site_search_notice').css('display') != 'none'){
			last_li = current_li;
			if(event.keyCode == 40){
				current_li += 1;
				if(current_li >= li_length){current_li = 0;}
			}
			if(event.keyCode == 38){
				current_li -= 1;
				if(current_li < 0){current_li = li_length - 1;}
			}
			if(last_li != -1){
				jQuery('#site_search_notice_list li').eq(last_li).removeClass('onfocus');
			}
			jQuery('#site_search_notice_list li').eq(current_li).addClass('onfocus');
			jQuery('#search').val(jQuery('#site_search_notice_list li').eq(current_li).children('span:first-child').html());
			if(event.keyCode == 27){
				jQuery('#site_search_notice').hide();
			}
			return false;
		}
	}
	else{
		
	}
});
});
//clearReview
function clearReview(url){
	var reviewDiv = jQuery('#re-viewed-div');
	reviewDiv.html('<dl><span style="color:#BABABA">暂无记录！</span></dl>');
	jQuery.get(url);
}
//addToCart
function clearNotice(id){
	jQuery(id).hide();
	jQuery(id).html('');
}
function addToCart(url){
	url = url.replace('checkout','ajaxcheckout/index/addfromcart');
	jQuery.ajax({
		type: "POST",
		url: url,
		dataType: 'json',
		success: function(data, textStatus){
			if(data.result){
				jQuery('#shopping_cart_form_div').html(data.cart);
				jQuery('#top_cart').html(data.topcart);
				iMycartBind();
			}
			jQuery('#shopping_cart_form_message').html(data.message);
			jQuery('#shopping_cart_form_message').show();
			window.setTimeout('clearNotice("#shopping_cart_form_message")',5000);
		},
		error:function(){
			alert('添加到购物车失败，请稍候再试!');
		}
	});
}
function setLocation(url){
    window.location.href = url;
}
function delProductFromTop(productId,updateUrl){
	delProduct(productId,updateUrl);
}
function delProductFromShopping(productId,updateUrl){
    if (confirm('确定不购买该商品？')) {
        delProduct(productId,updateUrl);
    }
}
//j2tCart
var changeObj = null;
function delProduct(productId,updateUrl) {
	var reAddUrl = updateUrl.replace('update','addfromcart');
	var delTr = '<tr id="delrow'+productId+'">';
	delTr = delTr + '<td>'+jQuery('#row'+productId+' td').eq(0).html()+'</td>';
	delTr = delTr + '<td>'+jQuery('#row'+productId+' td').eq(1).html()+'</td>';
	delTr = delTr + '<td>'+jQuery('#row'+productId+' td').eq(2).html()+'</td>';
	delTr = delTr + '<td>'+jQuery('#row'+productId+' td').eq(3).html()+'</td>';
	delTr = delTr + '<td>'+jQuery('#row'+productId+' td input').val()+'</td>';
	jQuery.ajax({
		type: "POST",
		url: updateUrl,
		dataType: 'json',
		data: 'cart['+productId+'][qty]=0',
		success: function(data, textStatus){
			if(data.result){
				jQuery('#shopping_cart_form_div').html(data.cart);
				jQuery('#top_cart').html(data.topcart);
				iMycartBind();
			}
			jQuery('#shopping_cart_form_message').html(data.message);
			jQuery('#shopping_cart_form_message').show();
			window.setTimeout('clearNotice("#shopping_cart_form_message")',5000);
			jQuery('#deleteProduct').show();
			jQuery('#deleteProductList').show();
			delTr = delTr + '<td><a href="#nogo" onclick="reAdd(\''+reAddUrl+'\','+data.productId+',this);">重新购买</a></td></tr>';
			jQuery('#deleteProductListTable tbody').append(delTr);
		},
		error:function(){
			alert('更新购物车失败，请稍候再试!');
		}
	});
};
function reAdd(url,productId,obj){
	var qty = jQuery(obj).parent().parent().children().eq(4).html();
	url = url+'product/'+productId+'/qty/'+qty;
	jQuery.ajax({
		type: "POST",
		url: url,
		dataType: 'json',
		success: function(data, textStatus){
			if(data.result){
				jQuery('#shopping_cart_form_div').html(data.cart);
				jQuery('#top_cart').html(data.topcart);
				iMycartBind();
			}
			jQuery('#shopping_cart_form_message').html(data.message);
			jQuery('#shopping_cart_form_message').show();
			window.setTimeout('clearNotice("#shopping_cart_form_message")',5000);
			jQuery('#deleteProduct').hide();
			jQuery('#deleteProductList').hide();
			jQuery(obj).parent().parent().remove();
		},
		error:function(){
			alert('添加到购物车失败，请稍候再试!');
		}
	});
}
function changeQty(itemId,url){
	changeObj = jQuery('#'+itemId);
	if(changeObj.val() == jQuery('#hidChange'+itemId).val()){
		return true;
	}
	if(!checkInt(changeObj.val())){
		alert('您输入的数量不正确!');
		changeObj.val(jQuery('#hidChange'+itemId).val());
	}
	else if(changeObj.val() == 0){
		delProductFromShopping(itemId,url);
	}
	else{
		jQuery.ajax({
			type: "POST",
			url: url,
			data: 'cart['+itemId+'][qty]='+changeObj.val(),
			dataType: 'json',
			success: function(data, textStatus){
				if(data.result){
					jQuery('#shopping_cart_form_div').html(data.cart);
					jQuery('#top_cart').html(data.topcart);
					iMycartBind();
					changeObj = jQuery('#'+itemId);
					changeObj.val(jQuery('#hidChange'+itemId).val());
					jQuery('#hidChange'+itemId).val(changeObj.val());
					sChangeMessage(itemId);
				}
				else{
					alert(data.message);
					changeObj.val(jQuery('#hidChange'+itemId).val());
				}
			},
			error:function(){
				alert('发送修改请求时出错!');
			}
		});
	}
};
function getPos(obj) {
    var pos = {};
    pos.Left = 0;
    pos.Top = 0;
    pos.Height = obj[0].offsetHeight;
    pos.Width = obj[0].offsetWidth;
    while (obj.prop('tagName').toLowerCase() != "body" && obj.prop('tagName').toLowerCase() != "html") {
        pos.Left += obj.offset().left;
        pos.Top += obj.offset().top;
        obj = obj.offsetParent();
    }
    return pos;
}
function closeMessage(){
	if(jQuery('#mesDiv') != null){
		jQuery('#mesDiv').remove();
	}
}
function sChangeMessage(itemId){
	closeMessage();
    var message = "<div id='changeSucTip'><div id='tipContent'><div id='tipTitle'>商品数量修改成功！<br />商品金额为：<span id='priceSpan'>"
        + jQuery('#price_' + itemId + ' span').html() + "</span>元<br /><a href='javascript:closeMessage()'>关闭</a></div></div></div>";
    pos = getPos(changeObj);
    pos.Top = pos.Top - 84;
    pos.Left = pos.Left - (204 - pos.Width) / 2;
    showMessageDiv(message, pos, 204);
    var mWin = jQuery('#mesWindow');
    mWin.css('opacity',0.9);
    setTimeout(function(){closeMessage()},4000);
};
function showMessageDiv(content, pos, wWidth)
{
	closeMessage();
    var bWidth = parseInt(document.documentElement.scrollWidth);
    var bHeight = parseInt(document.documentElement.scrollHeight);
    var mesDiv = document.createElement("div");
    mesDiv.id = "mesDiv";
    mesDiv.innerHTML = content;
    if (bWidth - pos.Left < wWidth)
    {
        styleStr = "left:" + (pos.Left - wWidth) + "px;";
    }
    else
    {
        styleStr = "left:" + (pos.Left) + "px;";
    }
    styleStr += "top:" + pos.Top + "px;position:absolute;width:" + wWidth + "px;";
    mesDiv.style.cssText = styleStr;
    document.body.appendChild(mesDiv);
};
function checkInt(string){
	if(trimTxt(string) == ""){
		return false;
	}
	var letters="1234567890";
	var i;
	var c;
	for(i=0;i<string.length;i++){
		c = string.charAt(i);
		if(letters.indexOf(c)==-1){
			return false;
		}
	}
	return true;
}
function addQty(itemId,url){
	changeObj = jQuery('#'+itemId);
	changeObj.val(parseInt(changeObj.val())+1);
	jQuery.ajax({
		type: "POST",
		url: url,
		data: 'cart['+itemId+'][qty]='+changeObj.val(),
		dataType: 'json',
		success: function(data, textStatus){
			if(data.result){
				jQuery('#shopping_cart_form_div').html(data.cart);
				jQuery('#top_cart').html(data.topcart);
				iMycartBind();
				changeObj = jQuery('#'+itemId);
				changeObj.val(jQuery('#hidChange'+itemId).val());
				jQuery('#hidChange'+itemId).val(changeObj.val());
				sChangeMessage(itemId);
			}
			else{
				alert(data.message);
				changeObj.val(jQuery('#hidChange'+itemId).val());
			}
		},
		error:function(){
			alert('发送修改请求时出错!');
		}
	});
}
function reduceQty(itemId,url){
	changeObj = jQuery('#'+itemId);
	changeObj.val(changeObj.val() - 1);
	if(changeObj.val() == 0){
		delProductFromShopping(itemId,url);
	}
	else{
		jQuery.ajax({
			type: "POST",
			url: url,
			data: 'cart['+itemId+'][qty]='+changeObj.val(),
			dataType: 'json',
			success: function(data, textStatus){
				if(data.result){
					jQuery('#shopping_cart_form_div').html(data.cart);
					jQuery('#top_cart').html(data.topcart);
					iMycartBind();
					changeObj = jQuery('#'+itemId);
					changeObj.val(jQuery('#hidChange'+itemId).val());
					jQuery('#hidChange'+itemId).val(changeObj.val());
					sChangeMessage(itemId);
				}
				else{
					alert(data.message);
					changeObj.val(jQuery('#hidChange'+itemId).val());
				}
			},
			error:function(){
				alert('发送修改请求时出错!');
			}
		});
	}
}
function removeAllProductOnShoppingCart(url){
	if(confirm('确定清空所有商品？')){
		jQuery.ajax({
			type: "POST",
			url: url,
			data: 'allFlag=1',
			dataType: 'json',
			success: function(data, textStatus){
				if(data.result){
					jQuery('#shopping_cart_form_div').html(data.cart);
					jQuery('#top_cart').html(data.topcart);
					iMycartBind();
					changeObj = jQuery('#'+itemId);
					changeObj.val(jQuery('#hidChange'+itemId).val());
					jQuery('#hidChange'+itemId).val(changeObj.val());
					sChangeMessage(itemId);
				}
				else{
					alert(data.message);
					changeObj.val(jQuery('#hidChange'+itemId).val());
				}
			},
			error:function(){
				alert('发送修改请求时出错!');
			}
		});
	}
}
//loadCitys
var citys = new Array();
var countys = new Array();
function loadCitys(regionId,url,cityElement,countyElement,customerCity){
	if(regionId != 0){
		if(citys[regionId]){
			loadSelectFromJson(citys[regionId],cityElement,customerCity);
			return true;
		}
		else{
			jQuery.getJSON(url+'parent/'+regionId,function(json){
				citys[regionId] = json;
				loadSelectFromJson(json,cityElement,customerCity);
				return true;
			})
		}
	}
	jQuery(cityElement).html('<option value="0">--请先选择省--</option>');
	jQuery(countyElement).html('<option value="0">--请先选择市--</option>');
}
function loadCountys(cityId,url,countyElement,customerCounty){
	if(cityId != 0){
		if(countys[cityId]){
			loadSelectFromJson(countys[cityId],countyElement,customerCounty);
			return true;
		}
		else{
			jQuery.getJSON(url+'parent/'+cityId,function(json){
				countys[cityId] = json;
				loadSelectFromJson(json,countyElement,customerCounty);
				return true;
			})
		}
	}
	jQuery(countyElement).html('<option value="0">--请先选择市--</option>');
}
function loadSelectFromJson(json,ele,val){
	var html = '';
	for(var i=0;i<json.length;i++){
		if(json[i].value == val){
			html = html + '<option value="'+json[i].value+'" selected>'+json[i].label+'</option>';
		}
		else{
			html = html + '<option value="'+json[i].value+'">'+json[i].label+'</option>';
		}
	}
	jQuery(ele).html(html);
};
/**
 * Placeholder (Version 1.0)
 * This snippet is written for the purpose of supporting the 
 * HTML5 placeholder attribute on most non-HTML5-compliant browsers.
 * on Jquery
 */
jQuery(function(){
	// -- Constants --
	var PLACE_HOLDER_COLOR = "rgb(169,169,169)"; // "darkGrey" does not work in IE6
	var PLACE_HOLDER_DATA_NAME = "original-font-color";
	
	// -- Util Methods --	
	var getContent = function(element){
		return jQuery(element).val();		
	}

	var setContent = function(element, content){
		jQuery(element).val(content);		
	}
	
	var getPlaceholder = function(element){
		return jQuery(element).attr("placeholder");
	}
	
	var isContentEmpty = function(element){
		var content = getContent(element);
		return (content.length === 0) || content == getPlaceholder(element);
	}
		
	var setPlaceholderStyle = function(element){
		jQuery(element).data(PLACE_HOLDER_DATA_NAME, jQuery(element).css("color"));
		jQuery(element).css("color", PLACE_HOLDER_COLOR);		
	}
	
	var clearPlaceholderStyle = function(element){
		jQuery(element).css("color", jQuery(element).data(PLACE_HOLDER_DATA_NAME));		
		jQuery(element).removeData(PLACE_HOLDER_DATA_NAME);
	}
	
	var showPlaceholder = function(element){
		setContent(element, getPlaceholder(element));
		setPlaceholderStyle(element);	
	}
	
	var hidePlaceholder = function(element){
		if(jQuery(element).data(PLACE_HOLDER_DATA_NAME)){
			setContent(element, "");
			clearPlaceholderStyle(element);
		}
	}
	
	// -- Event Handlers --
	var inputFocused = function(){
		if(isContentEmpty(this)){
			hidePlaceholder(this);		
		}
	}
	
	var inputBlurred = function(){
		if(isContentEmpty(this)){
			showPlaceholder(this);
		}
	}
	
	var parentFormSubmitted = function(){
		if(isContentEmpty(this)){
			hidePlaceholder(this);		
		}	
	}
	
	// -- Bind event to components --
	jQuery("textarea, input[type='text']").each(function(index, element){
		if(jQuery(element).attr("placeholder")){
			jQuery(element).focus(inputFocused);
			jQuery(element).blur(inputBlurred);			
			jQuery(element).bind("parentformsubmitted", parentFormSubmitted);
			
			// triggers show place holder on page load
			jQuery(element).trigger("blur");
			// triggers form submitted event on parent form submit
			jQuery(element).parents("form").submit(function(){
				jQuery(element).trigger("parentformsubmitted");
			});
		}
	});
});