// JavaScript Document
function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function setFooter() {
	//if (document.getElementById) {
	var windowHeight = getWindowHeight();
	if (windowHeight > 0) {
		var contentHeight = document.getElementById('wrap').offsetHeight;
		var footerElement = document.getElementById('bottom');
		var footerHeight  = footerElement.offsetHeight;
		if (windowHeight - (contentHeight + footerHeight) >= 0) {
			footerElement.style.position = 'relative';
			footerElement.style.top = (windowHeight - (contentHeight + footerHeight)) + 'px';
		}
		else {
			footerElement.style.position = 'static';
		}
	}
	//}
}

function add_to_cart(){
	$.post('cart/addToCart', $('#frmAddToCart').serialize(), function(result) {
		var obj = null; var obj = jQuery.parseJSON( result );
		if( obj.status == true ){			
			var citem_content = '';			
			for(var m=0; m<obj.added_item.length; m++){
				var thumbImg = obj.added_item[m].prod_thumb;
				var point = thumbImg.lastIndexOf(".");
				if(point!=-1){
					thumbImg = thumbImg.substr(0,point) + "_50." + thumbImg.substr(point+1);
				} else {
					thumbImg = thumbImg+"_50";
				}
			
				citem_content += '<div class="cart_per_item"><div id="product_pic"><a href="prods/' + obj.added_item[m].prod_id + '" title=""><img src="' + thumbImg +'" alt="' + obj.added_item[m].prod_name + '" /></a></div><div id="product_infor"><span class="gray">' + obj.added_item[m].prod_name + '</span><br />';
				if(obj.added_item[m].prod_attr != ''){
					citem_content += '<span class="black">' + obj.added_item[m].prod_attr + '</span><br />'; 
				}
				citem_content += _ge('cart_item_price') + ' <span class="orange">' + obj.added_item[m].prod_price + '</span><br />' + _ge('cart_item_qty') + ' <span class="black">' + obj.added_item[m].prod_qty + '</span>' + '</div></div>';				
			}

			if( citem_content == ''){
				$('#cart_content').html('<div id="product_infor">' + _ge('cart_no_item') + '</div>');
			}					
			else{
				$('#cart_content').html(citem_content);
				$('#total_price').html(obj.amt); 
			}
			
			$("#citems").html(obj.total_count);
			$("#total_count").html(obj.total_count);
			show_cart();
		}		 
		else{
			showMsg('', obj.msg);
		}
	});			   
}

function getMax(prod){
	var max_qty = 0;	
	$.ajaxSetup({ async: false });
	$.ajax({ type: "GET", url: 'ajaxfun/getMaxBuyQty/'+prod, success: function(data) { if(data.length > 0) max_qty = data; $.ajaxSetup({ async: true }); } });
	return max_qty;
}

//delete item
function del_item_cart(i, p, a, n, mp){
	$.blockUI({ message: $('img#displayBox'), css: { border: 'none', margin:0, pdding:0, top:  ($(window).height() - 31) /2 + 'px', left: ($(window).width() - 31) /2 + 'px', width: 31, height: 31 }});
	
	var opt = '#'+a;		
	$.post('cart/delItem', { 'prod': p, 'attr_opt': $(opt).val(), 'ajax': $('#ajax').val(), 'next': n, 'main_prod': mp }, function(result) {
		var obj = null; var obj = jQuery.parseJSON( result );		
		if(obj.success==true){
			if(obj.next_buy == true){
				self.location.href = dm+'cust_buylist/wishlist';
			}
			else{
				var cart_amt = parseInt(obj.amt.replace(',', ''));
				//reload mini cart
				reload_cart();
				
				var tmp_i = 0;			
				$('#cart_item_'+i).remove();			
				$(".shopping_cart_l_list").each(function(){ if($(this).attr('rel') == 'p_'+obj.pid){ tmp_i++; }	});					
				if(tmp_i == 0){
					$(".shopping_cart_l_list").each(function(){ if($(this).attr('rel')=='p_m'+obj.pid){ $(this).remove(); } });
				}				
				if(cart_amt > 0){
					showResult(obj);
					if(obj.has_cash_items == "N"){ if($('input[name="rdoCash"]').length > 0){ $('.price_select').remove(); $('input[name="rdoCash"]').remove(); $('#shopping_cart_l').removeClass('hasCash'); if($('#msg_cash_payment').length > 0){ $('#msg_cash_payment').hide(); $('.price').css('color', ''); $('.cash_price').hide().css('color', '#978F89'); } } }				
					if(obj.has_layaway_items == "N"){ $('.layaway').hide(); $('.isLayaway').hide(); $('.item').addClass('long');  } else { $('.layaway').css('display', 'block'); $('.isLayaway').css('display', 'block'); }
					if(obj.has_layaway_items == "N" && obj.has_cash_items == "N"){ $('.item').addClass('longer'); }
				}
				else{
					if($('.price_select').length > 0) $('.price_select').remove();
					$('#shopping_cart_l').removeClass('hasCash');
					var emptyCartHeader = obj.cart_header;
					var emptyCartHtml = '<li class="shopping_cart_l_list item_list"><div class="item">'+_ge('empty_cart')+'</div></li>';
					$('.cart_button').html('&nbsp;');
					$(".shopping_cart_l_list:first").html(emptyCartHeader).after(emptyCartHtml);			
				}
								
				if(obj.msg != '') showMsg('', obj.msg);
				$('#main').height($(".main_border").height());
				setFooter();
				setTimeout($.unblockUI, 100);
			}
		}
		else{
			showMsg('', obj.msg); return false;
			setTimeout($.unblockUI, 100);
		}		
	});
}
function update_qty(i, prod, opt, mp, qty){	
	$.blockUI({ message: $('img#displayBox'), css: { border: 'none', margin:0, pdding:0, top:  ($(window).height() - 31) /2 + 'px', left: ($(window).width() - 31) /2 + 'px', width: 31, height: 31 }});

	var prod_arr = new Array(prod);	 var opt_arr = new Array(opt); var main_prod_arr = new Array(mp); var qty_arr = new Array(qty);		
	$.ajax({ type: 'POST', url: 'cart/updateToCart', data: ({ 'prods[]': prod_arr, 'attr_opt[]': opt_arr, 'main_prods[]': main_prod_arr, 'qty[]': qty_arr, 'ajax': $('#ajax').val() }), dataType: "json", success: function(result){
		if(result.success==true){
			var cart_amt = parseInt(result.amt.replace(',', ''));
			//reload mini cart
			reload_cart();
			//update promotion message(Prod)
			$.each(result.single_discount, function(k, v){ $(k).html(v); });				
			
			if(cart_amt > 0){					
				$('#amt_'+i).html("<span class='align_box'>$"+result.item_amt+"</span>");
				showResult(result);
			}
			else{ $('.cart_button').html('&nbsp;'); setTimeout($.unblockUI, 100); }
		}
		else{
			$('#qty_'+i).val(result.qty); showMsg('', result.msg);
			setTimeout($.unblockUI, 100);
		}		
	}		
	});
}

function showCartMsg(msg){ showMsg('',msg);	}
function applyCouponCode(){	
	if($('#coupon_code').val() != ""){ $('#discountCodeForm').submit(); }
}

function settingPaymentTerms(term){	
	$.blockUI({ message: $('img#displayBox'), css: { border: 'none', margin:0, pdding:0, top:  ($(window).height() - 31) /2 + 'px', left: ($(window).width() - 31) /2 + 'px', width: 31, height: 31 }});
	$.post("cart/settingCashPayment", { cash: term } , function(response){																
		if(term == 'N'){ $('div.price:gt(0)').css('color', ''); $('div.cash_price:gt(0)').css('color', '#978F89') } else { $('div.price:gt(0)').css('color', '#978F89'); $('div.cash_price:gt(0)').css('color', ''); }
		$.ajaxSetup({ cache: false });
		$.getJSON('cart/recalculateCartAmount/'+response, function(result) {
			$.ajaxSetup({ cache: true }); var priStr = "";
			$.each(result.item_amount, function(i, item){
				priStr = '$'+item; itemObj = '#amt_'+i; $(itemObj).html(priStr);
			});
			showResult(result);	
		});			
	});		
}

function showResult(result){	
	if(result.shipping > 0){ $('#shipping_label').css('display', 'block'); $('#shipping_val').css('display', 'block'); $('#shipping_fee_note').css('display', 'block'); } else { $('#shipping_label').hide(); $('#shipping_val').hide(); $('#shipping_fee_note').hide(); }
	$('#shipping_val').html('$'+result.shipping);
	
	if(result.discount > 0){
		$('#cart_discount').find('span').html('-$'+result.discount); $('#cart_discount').css('display', 'block'); $('#cart_discount_title').css('display', 'block');
	} else { $('#cart_discount').hide(); $('#cart_discount_title').hide(); }
	$('#subtotal').html("$"+result.subtotal);
	$('#cart_amt').html("$"+result.amt);
	//update promotion message(Cart)
	if(result.promo_msg !== ""){ $('#promo_msg').html(result.promo_msg).css('display', 'block'); } else { $('#promo_msg').hide().html(''); }
	
	setTimeout($.unblockUI, 100);
}


$(function(){
	if($('input[name="rdoCash"]').length > 0){	
		$('input[name="rdoCash"]').click(function(){
			settingPaymentTerms($(this).val());
		});
		if(byCash == 'Y'){ $('div.price:gt(0)').css('color', '#978F89'); $('div.cash_price:gt(0)').css('color', ''); } else { $('div.price:gt(0)').css('color', ''); $('div.cash_price:gt(0)').css('color', '#978F89'); }
	}
	
	if($('a[name="remove_code"]').length > 0){
		$('a[name="remove_code"]').live('click', function(){ $(this).closest('form').submit(); });
	}
		   
	if($('input.btnAddBundle').length > 0){
		$('input.btnAddBundle').click(function(){								
			var formContent = $('#frmAddToCart').serialize();
			formContent += '&addwithOutMainProds=1';
			
			$.ajaxSetup({ async: true });
			$.post('cart/addToCart', formContent, function(result) {
				var obj = null;
				var obj = jQuery.parseJSON( result );				
				if( obj.status == true || ( obj.added_item!=undefined && obj.added_item.length != 0) ){
					var citem_content = '';			
					for(var m=0; m<obj.added_item.length; m++){
						var thumbImg = obj.added_item[m].prod_thumb;
						var point = thumbImg.lastIndexOf(".");
						if(point!=-1){
							thumbImg = thumbImg.substr(0,point) + "_50." + thumbImg.substr(point+1);
						}
						else{
							thumbImg = thumbImg+"_50";
						}
					
						citem_content += '<div class="cart_per_item"><div id="product_pic"><a href="prods/' + obj.added_item[m].prod_id + '" title=""><img src="' + thumbImg +'" alt="' + obj.added_item[m].prod_name + '" /></a></div><div id="product_infor"><span class="gray">' + obj.added_item[m].prod_name + '</span><br />';
						if(obj.added_item[m].prod_attr != ''){
							citem_content += '<span class="black">' + obj.added_item[m].prod_attr + '</span><br />'; 
						}
						citem_content += _ge('cart_item_price') + ' <span class="orange">' + obj.added_item[m].prod_price + '</span><br />' + _ge('cart_item_qty') + ' <span class="black">' + obj.added_item[m].prod_qty + '</span>' + '</div></div>';				
						
						if(obj.added_item.length != 1 && m!=obj.added_item.length-1){
							citem_content += "<hr />";
						}
					}
	
					if( citem_content == ''){
						$('#cart_content').html('<div id="product_infor">' + _ge('cart_no_item') + '</div>');
					}					
					else{
						$('#cart_content').html(citem_content);
						$('#total_price').html(obj.amt); 
					}
					
					$("#citems").html(obj.total_count);	//�w���ʦh�ְӫ~
					$("#total_count").html(obj.total_count);
					show_cart();
				}		 
				
				if( obj.msg != "" ){ alert( obj.msg ); }
			});			
		});
	}
	
	$("select[name='qty[]']").change(function(){											  
		var index = $(this).attr('id').replace('qty_', '');
		var prod = $('#prod_'+index).val();
		var opt = $('#opt_'+index).val();
		var mp = $('#main_prods_'+index).val();
		update_qty(index, prod, opt, mp, $(this).val());
	});		
});

function dialog_cash_payment_note(){
	showMsg(aa, bb);	
}
