/*
 * JS by Sofresh Inc.
 */
function redirect_url(params){
	//if(location.pathname.indexOf('cart.php')==-1) location.href = domain+'cart.php';//+(params?'?'+params:'');
	if(location.protocol=='http:'){location.href = domain.replace('http:','https:')+'cart.php?sid='+session_id; return false; }
	return true;
}

function switch_coupon(v){
	if(v) $('#show_coupon').show();
	else  $('#show_coupon').hide();
}

function getfree(){
	var $inputs = $('#checkout_step1 input, #checkout_step1 textarea, #checkout_step1 select');
	var k = 0;
	var values = {};
	$inputs.each(function(i, el) {
		values[el.name] = $(el).val();
		k=k+1;
	});
	
	$.post('checkout_submit.php?getfree=1',values,function(data){
		var dataObj = $.evalJSON(data);
		var str = '';
		if(dataObj['alert']['no'] == '1') str = 'You will get free product';
		$('.result_getfree').html(str);

		var result_coupon = '';
		for(var i in dataObj['redeem']){
			var amount = String(dataObj['redeem'][i].amount);
			result_coupon += '<span>'+dataObj['redeem'][i].name+'(- '+(str.substr(-1)=='%'?dataObj['redeem'][i].amount:currency_format(dataObj['redeem'][i].amount)+' '+dataObj['currency_code'])+')</span><br />';
		}
		$('#result_coupon').html(result_coupon);
		var txt_total = result_coupon?'<span class="green">'+currency_format(dataObj['total'])+'</span>':currency_format(dataObj['total']);
		//$('#total').html(txt_total+' '+dataObj['currency_code']);
		//$('#shipping').html(currency_format(dataObj['shipping']));

	});
}

function switch_code(val,selects,f){
	var maxlength = 6;
	var text = 'Postal Code';
	if(val == 'US'){
		maxlength = 5;
		text = 'Zip Code';
	}
	if(selects){
		$(selects).find('label').html(text);
		$(selects).find('input').attr({'maxlength':maxlength});
	}
	if(typeof(f) == 'function') f(val);
	
}
function copy_field(selects){
	var obj =  $(selects);
		$(obj).find('input[name="create_ship_firstname"]').val($(obj).find('input[name="create_bill_firstname"]').val());
		$(obj).find('input[name="create_ship_firstname"]').val($(obj).find('input[name="create_bill_firstname"]').val());
		$(obj).find('input[name="create_ship_lastname"]').val($(obj).find('input[name="create_bill_lastname"]').val());
		$(obj).find('input[name="create_ship_str_number"]').val($(obj).find('input[name="create_bill_str_number"]').val());
		$(obj).find('input[name="create_ship_str_name"]').val($(obj).find('input[name="create_bill_str_name"]').val());
		$(obj).find('input[name="create_ship_unit"]').val($(obj).find('input[name="create_bill_unit"]').val());
		$(obj).find('input[name="create_ship_postal"]').val($(obj).find('input[name="create_bill_postal"]').val());
		$(obj).find('input[name="create_ship_phone_code"]').val($(obj).find('input[name="create_bill_phone_code"]').val());
		$(obj).find('input[name="create_ship_phone_number"]').val($(obj).find('input[name="create_bill_phone_number"]').val());
		$(obj).find('input[name="create_ship_phone_number2"]').val($(obj).find('input[name="create_bill_phone_number2"]').val());
		$(obj).find('input[name="create_ship_city"]').val($(obj).find('input[name="create_bill_city"]').val());
		var bill_city = $(obj).find('select[name="create_bill_country"]').val();
		$(obj).find('select[name="create_ship_country"] option').each(function(){
			if ($(this).val() == $(obj).find('select[name="create_bill_country"]').val()){
				load_state('create_ship_state',$(this).val(),$(obj).find('select[name="create_bill_state"]').val());
				$(this).attr('selected','selected');
				
			}
		});
}
function isEmail(s){
	if(s=="") return false;
	if(s.indexOf(" ")>0) return false;
	if(s.indexOf("@")==-1)return false;
	var i=1; var sLength=s.length;
	if(s.indexOf(".")==-1) return false;
	if(s.indexOf("..")!=-1)return false;
	if(s.indexOf("@")!=s.lastIndexOf("@")) return false;
	if(s.lastIndexOf(".")==s.length-1)return false;
	var str="abcdefghikjlmnopqrstuvwxyz-@._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	for(var j=0;j<s.length;j++)
	if(str.indexOf(s.charAt(j))==-1)
	return false;return true;
}

function after_checkshipping(data){
	var dataObj = $.evalJSON(data);
	var _currency = Number(dataObj['currency_id']);
	var _currency_code = _currency==1?'CAD':'USD';
	$('#shipping_cost').html(dataObj['html']);
	//alert(dataObj['total']);
	$('#shipping').html((dataObj['free_shipping']!='0'?'<span style="text-decoration: line-through; color: red;">'+currency_format(dataObj['free_shipping'])+'</span>':currency_format(dataObj['shipping']))+ ' '+dataObj['currency_code']);
	$('#cost_shipping').val(dataObj['shipping_cnd']);
	$('#checksubmit').val('1');
	
	var str = '';
	for(var i in dataObj['getfree']) str = '<span style="color: green; text-transform: uppercase; font-size: 10px;">Free sampler included with your purchase</span>';
	$('.result_getfree').html(str);
	
	
	var tax_gst = dataObj['tax_gst'];
	var tax_pst = dataObj['tax_pst'];
	//alert(country+city);
	//alert(tax_pst);
	var _total = Number(dataObj['subtotal']+( (parseInt(dataObj['free_shipping'])>0)?0:dataObj['shipping']*1));
	var gst = _total*Number(tax_gst);
	var pst = _total*Number(tax_pst);
	var str = '';
	
	//alert(gst);
	if(pst) str += '<strong>Tax HST:</strong> <span id="shipping">'+currency_format(pst)+' '+dataObj['currency_code']+'</span>';
	if(gst) str += '<strong>Tax GST:</strong> <span id="shipping">'+currency_format(gst)+' '+dataObj['currency_code']+'</span>';
	
	//alert(str);
	$('#shipping_tax').html(str);
	
	
	var result_coupon = '';
	for(var i in dataObj['redeem']){
		var amount = String(dataObj['redeem'][i].amount);
		result_coupon += '<span>'+dataObj['redeem'][i].name+'(- '+(str.substr(-1)=='%'?dataObj['redeem'][i].amount:currency_format(dataObj['redeem'][i].amount)+' '+dataObj['currency_code'])+')</span><br />';
	}
	$('#result_coupon').html(result_coupon);
	$('input[name="coupon"]').val('');
	var txt_total = result_coupon?'<span class="green">'+currency_format(dataObj['total'])+'</span>':currency_format(dataObj['total']);
	$('#total').html(txt_total+' '+dataObj['currency_code']);
	//$('input[name="coupon"]').val('').focus();
}


function redeem(){
	var coupon = $('input[name="coupon"]');
	if(!coupon.val()){alert('Please enter a Coupon Code');coupon.focus();return false;}
	var $inputs = $('#checkout_step1 input, #checkout_step1 textarea, #checkout_step1 select');
	var k = 0;
	//alert($('.credit input:checked').val());
	var values = {};
	$inputs.each(function(i, el) {
		values[el.name] = $(el).val();
		k=k+1;
	});
	$.post(domain+'checkout_submit.php?redeem=1',values,function(data){
		var dataObj = $.evalJSON(data);
		$('#valid_coupon').html(dataObj['alert']['msg']).css({'visibility': 'visible'});
		after_checkshipping(data);
	});
}

$(document).ready(function(){
	
	if ($('.product_nav').html != null){
		$('.product_nav a').click(function(){
			var productNav = $(this).parent().attr('id');
			$('#'+productNav+' a').removeClass('active');
			$(this).addClass('active');
		});
	}
	
	if ($('.views').html != null){
		$('.views a').click(function(){
			$('.views .active').removeClass('active');
			$(this).addClass('active');
		});
	}
});


function checkout_switch_ship(val,selects){
	switch_code(val,selects,function(){
		if (val == 'US') $('#chose_shipping').html('<option value="1">Ground</option>');
		else $('#chose_shipping').html('<option value="1">Ground</option><option value="5">Select Parcel (2 business days)</option>');
	});
}

function input_data(key,id,title){
	cdata[key] = [id,title];
	show_alias();
	view_product(view);
}

function show_alias(){
	if(typeof cdata != 'undefined'){
			//alert(typeof cdata);
		var str = cdata['cat'][1];
		//if(cdata['filter1'][0]) str += ' '+ cdata['filter1'][1];
		//else str += ' ';
		// if(cdata['filter2'][0]) str += ', '+ cdata['filter2'][1];
		$('#show_alias').html(str);	
	}
	$('.sIFR-replaced').removeClass('sIFR-replaced');
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({sSelector:"#show_alias", sFlashSrc:"futurastd.swf", sColor:"#737373", sLinkColor:"#737373", sBgColor:"#fefdf9", sHoverColor:"#737373", nPaddingTop:0, nPaddingBottom:0, sFlashVars:""}));
	};
		
}

function view_product(tview){
	view = tview;
	if (typeof cdata != "undefined"){
		$.post(domain+'product_data.php?cat='+cdata['cat'][0]+'&f1='+cdata['filter1'][0]+'&f2='+cdata['filter2'][0]+'&view='+tview,{},function(data){
			$('#product_view').html(data);
			var url = tmp = window.location.toString();
			if(tmp.indexOf('#')==-1) url += '#';
			$('.back2top').attr({'href':url});
		});	
	}
}


// Compare Page
function compare(show,id){
	$.post(domain+'compare_data.php?id='+id,{},function(data){
		$('#'+show).html(data);
	});
}

function loadproduct(cat){
	$.post(domain+'product_data.php?cat='+cat+'&view=2',{},function(data){
		$('.load_product').html(data);
	});
}

var blinkRepeatNum = 6;

function update_html_cart(id,data){
	var o = $('#viewcart .checkout_product_'+id);
	
	if(o.length){
		var cval = $('#viewcart .checkout_qty_'+id).val();
		$('#viewcart .checkout_qty_'+id).val(parseInt(cval)+1);
		$('#cartNum').html(Math.abs(Number(data)));
	}else{
		var dataObj = $.evalJSON(data);
		$('#cartNum').html(Math.abs(Number(dataObj.numcart)));
		$('.checkout_empty_text').html('');
var append = '<li class="product_'+dataObj.css+' checkout_product_'+id+'_'+dataObj.product_in_box+'">\
<div>\
<img alt="" src="images/products/checkout_03.gif" class="product_img" />\
<label>'+dataObj.name+'</label>\
<select name="price['+id+']" onchange="checkout_page();">';
for(var j in dataObj.prices){
if(dataObj.product_in_box == j) append +='<option value="'+id+'-'+j+'">'+(parseInt(j)>1?'Box of '+j:'1 single')+' - '+currency_format(dataObj.prices[j][dataObj.currencyid])+' '+(dataObj.currencyid==2?'USD':'CAD')+' </option>';
}
append += '</select>\
<p>#</p>\
<input name="qty['+id+']" onblur="checkout_page('+id+',this);" value="1" class="qty checkout_qty_'+id+'_'+dataObj.product_in_box+'" />\
<input style="display:none;" name="product_in_box" value="'+dataObj.product_in_box+'" />\
<a href="/'+id+'.php#" name="'+id+'_'+dataObj.product_in_box+'" class="remove">Remove</a>\
</div></li>';
		$('#viewcart').append(append);
	}
	
}
function add2cart(obj,id,buy){
	$('#checkout_step1 .checkout_list').show();
	var product_in_box = $(obj).parent().find('select').val();//$('#btn_tag'+id).val();
	//alert(product_in_box);
	$.post(domain+'cart_data.php?id='+id,{'product_in_box': product_in_box},function(data){
		if(data=='error') alert('Invalid Id');
		else if(buy){ // mua
			
			//if(location.host !='localhost' && location.protocol=='http:'){location.href = domain.replace('http:','https:')+'cart.php'; return false; }
			//if(location.host =='localhost' && domain.indexOf('cart.php')!=-1) location.href = './cart.php';
			if(!redirect_url()) return false;
/*			update_html_cart(id,data);
			$('.checkout_form').css({'display':'none'});
			caobox.show('checkout', 'b4b5a6', '80', '', '', '33', 'showCheckoutForm');		
		$('ul.credit input').click(function(){
			//$(this).find('input').attr('checked','checked');
			if($('.credit input:checked').val()== 'amex'){
				alert(amex_alert);
			}
			if($('#ship_country').val()!='0' && $('#ship_state').val()!='0') check_shipping();
		});
*/			
		}else if(parseInt(data)<0){
			var cval = $('.checkout_qty_'+id+'_'+product_in_box).val();
			$('.checkout_qty_'+id+'_'+product_in_box).val(parseInt(cval)+1);
			$('#cartBlink').html('<span class="cartNum" id="cartNum">'+Math.abs(data)+'</span>Items in your <strong>Shopping Bag</strong>').hide().fadeIn('slow', 
				function(){
					$('#cartBlink').hide().fadeIn('slow', 
						function(){
							$('#cartBlink').hide().fadeIn('slow');
						});
				});
			//$('#cartNum').html(data);
/*			$('#cartText').html('Items in your <strong>Shopping Bag</strong>').hide().fadeIn('slow', 
				function(){
					$('#cartText').hide().fadeIn('slow', 
						function(){
							$('#cartText').hide().fadeIn('slow');
						});
				});
*/		
			checkout_page();
		}else{ // chua co 
			
			update_html_cart(id,data);
			
			$('.checkout_form').css({'display':'none'});
			checkout_page();
			caobox.show('checkout', 'b4b5a6', '80', '', '', '33', 'checkout_removeItem');
			/*addCartNum(data);*/
			
			
		}
		
		
		
		/*function addCartNum(data){	
			blinkRepeatNum = blinkRepeatNum - 1;
			$('#cartNum').html(Math.abs(data)).hide().fadeIn(200);
			//if (blinkRepeatNum > 0){
				setTimeout("addCartNum("+data+");",1000);
			//}
			alert(blinkRepeatNum);
		};*/
	});
}




function load_state(id,code,selected,load_shipping,f){
	//$.post(domain+'state_data.php?code='+code+'&selected='+selected,{},function(data){
		var data = '<option value="0">-- please select --</option>';
		for(var i in js_languages[code]){
			data += '<option value="'+js_languages[code][i][1]+'" '+(js_languages[code][i][1] ==selected?'selected':'' )+'  >'+js_languages[code][i][2]+'</option>';	
		}
		$('#'+id).html(data);
		//if(load_shipping) check_shipping(0,0,selected);
		if(typeof(f)=='function') f();
	//});
}
function load_city(id,code,selected){
	$.post(domain+'city_data.php?code='+code+'&selected='+selected,{},function(data){
		$('#'+id).html(data);
	});
}

function loadshipping(weight,country,city,postal){
	$('#shipping_cost').html('Loading...');
	$('#checksubmit').val(0);
	var _type = 1;
	if(country=='US') _type = 2;
	if(country == 'CA') _type = $('#chose_shipping').val();
	//if(country=='US' && $('.credit input:checked').val()!= 'amex') {_currency = 2; _currency_code = 'USD';}
	//if(country=='CA' || $('.credit input:checked').val() == 'amex') {_currency = 1; _currency_code = 'CAD'; }
	var $inputs = $('#checkout_step1 input, #checkout_step1 textarea, #checkout_step1 select');
	var k = 0;
	//alert($('.credit input:checked').val());
	var values = {};
	$inputs.each(function(i, el) {
		values[el.name] = $(el).val();
		k=k+1;
	});
	values['weight'] = weight;
	values['credit'] = $('.credit input:checked').val();
	values['country'] = country;
	
	values['city'] = city;
	values['postal'] = postal;
	values['type'] =  _type;
	values['ship_country'] = country;
	values['ship_city'] = city;
	values['ship_postal'] = postal;
	//alert(values['country']);
	$.post(domain+'checkout_submit.php?shipping=1',values,function(data){
		after_checkshipping(data);
	});
}


function shopping_bag(f,nocb){
	$('#checkout_step1 .checkout_list').show();
	$('#checkout_result').html('');
	$('#checkout_step1').show();
	checkout_page();
	$.post(domain+'cart_data.php',{},function(data){
		$('.checkout_form').css({'display':'none'}); 
		if(nocb){
			checkout_removeItem();
		}else{
			if(data=='0' ) caobox.show(domain+'checkout_empty.php', 'b4b5a6', '80', '', '', '33'); //&& location.protocol != 'https:'
			else caobox.show('checkout', 'b4b5a6', '80', '', '', '33','checkout_removeItem');
		}
		
		if(typeof(f) == 'function') f();
	});	
}

function number_format(n){
	if(isNaN(n)) return 0;
	nStr = Number(n);
	nStr = nStr.toFixed(2);
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;

}
function currency_format(number){
	return symbol_left+''+ number_format(number);
}

function isPostCode(s,type) {
	if (type == 'CA')
	{
		if (s.search(/^([A-Za-z][0-9][A-Za-z][0-9][A-Za-z][0-9])$/) != -1)
			return true ;
		return false ;
	}
	else if (type == 'US')
	{
		if (s.search(/^([0-9][0-9][0-9][0-9][0-9])$/) != -1)
			return true ;
		return false ;
	}
	else
	{
		if (trim(s) != "")
			return true;
		return false;
	}
}
function trim(str) {

	return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
var subtotal = new Array();

function checkout_page(proid,obj,f){
	if(proid && obj.value){
		//alert( proid+ ' '+ obj.value);
		//var product_in_box = $('input[name="product_in_box_'+proid+'"]').val();
		var product_in_box =  $(obj).parent().parent().find('input[name="product_in_box"]').val();
		//alert(product_in_box);
		//var product_in_box =  $('.checkout_qty_'+proid+'_'+product_in_box).find('input[name="product_in_box_'+proid+'"]').val();
		if(obj.value*1<=0){alert('Please enter a qty is numberic > 0'); obj.value = obj.defaultValue;  };
		$.post(domain+'cart_data.php?act=update&id='+proid+'&qty='+obj.value,{'product_in_box':product_in_box},function(data){
			$('#cartNum').html(data);
			
			$('.checkout_qty_'+proid+'_'+product_in_box).val(obj.value);//val(obj.value);
			//$('.checkout_qty_'+proid).attr('value',obj.value);
			//alert($('.checkout_qty_'+proid).val());//val(obj.value);
			
			//alert($(this).val());
			//var tmp = obj.value;
			
			
			//alert('.checkout_qty_'+proid);
			if(typeof(f)=='function') f();
		});	
		//$('.checkout_qty_'+proid).attr('value',7);
		
	}
	
	var step2 = 1;
	subtotal[1] = 0;
	subtotal[2] = 0;
	var subtotal_cnd = 0;
	var w = 0;
	var currency_code = currency_id==1?'CAD':'USD';
	
	//alert(currency_id);
	
	$.each($('#viewcart li'),function(i,obj){
		var t1 = obj.getElementsByTagName('select')[0].value;//product id + qty
		var t2 = Number(obj.getElementsByTagName('input')[0].value); // qty
		var tmp = t1.split('-');
		var _id = Number(tmp[0]);
		var _qty = (tmp.length==3)?-1*Number(tmp[2]):Number(tmp[1]);
		var t = Number(aPro[_id][_qty][currency_id])*t2;
		if(t==0) step2  = 0;
		subtotal[1] += Number(aPro[_id][_qty][1])*t2;
		subtotal[2] += Number(aPro[_id][_qty][2])*t2;
		//subtotal_cnd += Number(tmp[0])*t2;
		w += (t2>=1 && t2<=$max_weight)?aW[t2]:aW[$max_weight]+ (t2-$max_weight)*0.438;
	});
	
	//alert(subtotal[1]);
	
	if(step2){ // 
	//alert('dde');
	//alert(subtotal[currency_id]);
		$('#subtotal').html('Sub Total: '+currency_format(subtotal[currency_id])+ ' '+ currency_code);// /rate
		$('#ship_weight').val(w);
		$('#cost_subtotal').val(subtotal[currency_id]);
		//$('#cost_subtotal_cnd').val(subtotal_cnd);
		$('#numsubtotal').html(currency_format(subtotal[currency_id])+ ' '+ currency_code); // /rate
		var total = subtotal[currency_id] + $('#cost_shipping').val()*1; // 
		$('#total').html(currency_format(total)+ ' '+ currency_code); // /rate
		if(w) check_shipping(w);
	}else{
		$('.checkout_form').css({'display':'none'});
		$('#ship_weight').val('0');
		$('#subtotal').html('Please select a size  for highlighted item(s) to proceed');
	}
}

function check_shipping(w,co,ci){
	//alert(co + ' - '+ ci);
	$('#checksubmit').val('0');
	var country_ship = $('#ship_country').val();
	var city_ship = $('#ship_state').val();

	if(country_ship == 'US'){
		//if(dataObj['credit'] == 'amex'){ alert(amex_alert); $('#credit_amex').attr({'checked': false}); }
		$('#credit_amex').attr({'checked': false});
		$('.clear_amex').hide();	
	}else{
		$('.clear_amex').show();
	}

	var postal_ship = $('#ship_postal').val();
	var weight_ship = $('#ship_weight').val();
	var _currency = currency_id;
	var _currency_code = currency_id==1?'CAD':'USD';
	$('#shipping_tax').html('');
	//if($('.credit input:checked').val() == 'amex') alert(amex_alert);
	if(country_ship=='US' ) {_currency = 2; _currency_code = 'USD';}
	if(country_ship=='CA' ) { _currency = 1; _currency_code = 'CAD';}
	$('#subtotal').html('Sub Total: '+currency_format(subtotal[_currency])+' '+_currency_code);
	$('#numsubtotal').html(currency_format(subtotal[_currency])+' '+_currency_code);
	$('#total').html(currency_format(subtotal[_currency])+' '+_currency_code);
	if(weight_ship&&country_ship && city_ship && postal_ship) loadshipping(w?w:weight_ship,co?co:country_ship,ci?ci:city_ship,postal_ship);
}


function shopping_submit(obj_click){
	//Validate Billing information
	//if($('#checksubmit').val()=='-1'){alert('Please wait to load shipping ');$('#bill_firstname').focus();return false;}
	if($('.checkout_form input[name="coupon"]').val()){
		redeem();
		return false;
	}
	if($('#bill_firstname').val()==''){alert('Please enter billing information: First Name');$('#bill_firstname').focus();return false;}
	if($('#bill_lastname').val()==''){alert('Please enter billing information: Last name');$('#bill_lastname').focus();return false;}
	if($('#bill_str_number').val()==''){alert('Please enter billing information: Street Number');$('#bill_str_number').focus();return false;}
	if($('#bill_str_name').val()==''){alert('Please enter billing information: Street Name');$('#bill_str_name').focus();return false;}
	if($('#bill_country').val()=='0'){alert('Please enter billing information: Country');$('#bill_country').focus();return false;}
	if($('#bill_state').val()=='0'){alert('Please enter billing information: State/Provine');$('#bill_state').focus();return false;}
	if(!isPostCode($('#bill_postal').val(),$('#bill_country').val())){alert('Please input a valid billing information: Postal code');$('#bill_postal').focus();return false;}
	if($('#bill_phone_code').val()==''){alert('Please enter billing information: Phone Code');$('#bill_phone_code').focus();return false;}
	//if($('#bill_phone_number').val()=='' || $('#bill_phone_number2').val()==''){alert('Please enter billing information: Phone number');$('#bill_phone_number').focus();return false;}
	
	if(!isEmail($('#bill_email').val())){alert('Please enter billing information: Email Address');$('#bill_email').focus();return false;}
	var credit = $('input[name=credit]:checked').val();
	if(typeof credit == 'undefined'){alert('Please select a credit card type');$('#credit').focus();return false;}
	
	//alert(credit);
	if(!isValidCreditCard(credit,$('#card_number').val())){alert('Please enter a  valid '+credit.toUpperCase()+' number');$('#card_number').focus();return false;}
	if($('#card_cvv').val()==''){alert('Please enter the Security Code');$('#card_cvv').focus();return false;}
	
	
// for shipping
	if($('#ship_firstname').val()==''){alert('Please enter shipping information: First Name');$('#ship_firstname').focus();return false;}
	if($('#ship_lastname').val()==''){alert('Please enter shipping information: Last name');$('#ship_lastname').focus();return false;}
	if($('#ship_str_number').val()==''){alert('Please enter shipping information: Street Number');$('#ship_str_number').focus();return false;}
	if($('#ship_str_name').val()==''){alert('Please enter shipping information: Street Name');$('#ship_str_name').focus();return false;}
	//if($('#ship_unit').val()==''){alert('Please enter shipping information: Unit');$('#ship_unit').focus();return false;}
	if($('#ship_country').val()=='0'){alert('Please enter shipping information: Country');$('#ship_country').focus();return false;}
	if($('#ship_state').val()=='0'){alert('Please enter shipping information: State/Provine');$('#ship_state').focus();return false;}
	if(!isPostCode($('#ship_postal').val(),$('#ship_country').val())){alert('Please enter a valid shipping information: Postal code');$('#ship_postal').focus();return false;}
	if($('#ship_phone_code').val()==''){alert('Please enter shipping information: Phone Code');$('#ship_phone_code').focus();return false;}
	//if($('#ship_phone_number').val()=='' || $('#ship_phone_number2').val()==''){alert('Please enter shipping information: Phone number');$('#ship_phone_number').focus();return false;}
	
	var expdate = ($('select[name="exp_year"]').val()*1+2000)*100 +  $('select[name="exp_month"]').val()*1;
	var now = new Date();
	var nowdate = now.getFullYear() *100 + now.getMonth()*1;
	
	if(expdate  < nowdate){alert('Invalid expiration date');return false;}
	
//	if(=='0'){alert('Please enter billing information: State/Provine');$('#bill_state').focus();return false;}
	
	if(credit == 'amex' && $('#ship_country').val() == 'US'){alert('We cannot process a purchase shipping to United State by AMEX');return false;}
	if($('#checksubmit').val()=='0'){alert('You can only place your order after you caculate your shipping cost');return false;}

	var $inputs = $('#checkout_step1 input, #checkout_step1 textarea, #checkout_step1 select');
	var k = 0;
	var values = {};
	$inputs.each(function(i, el) {
		values[el.name] = $(el).val();
		k=k+1;
	});
	//alert(values);
	//alert(domain+'checkout_submit.php');
	values['credit'] = credit;
	$('#checkout_submit').html('Loading...');
	$(obj_click).hide();
	$.post(domain+'checkout_submit.php',values,function(data){
		var dataObj = $.evalJSON(data);
		//alert(data);
		if(dataObj['type']!='fail'){
			$('#cartNum').html(dataObj['numcart']?dataObj['numcart']:'0');
			$('#checkout_result').html(dataObj['html']);
			if(dataObj['type']=='success'){ $('ul#viewcart li').remove();} 
			$('#checkout_step1').css({'display':'none'});
		}else{
			//alert(dataObj['html']);
			$('#checkout_result').html('<ul>'+dataObj['html']+'</ul>');
			$('#checkout_step1').css({'display':'none'});
			//$('#errorMessage').html('<ul>'+dataObj['html']+'</ul>');
			
		}
	});	
}


function checkout_back1(){
	$('#checkout_result').html('');
	$('#errorMessage').html('');
	$('#checkout_step1').css({'display':''});
	$('#checkout_submit').html('');
	$('.btn_placeOrder').show();
}

function isValidCreditCard(type, ccnum) {
   if (type == "visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "master") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "amex") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }else{
	  return false;   
   }
   if (!re.test(ccnum)) return false;
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}



// show checkout form
function showCheckoutForm(){
	$('.checkout_form').show();
	checkout_removeItem();
}

function changeProductImg(obj,box_img,sachet_img){
	var img = '';
	if(obj.value == '-1') img = sachet_img;
	else img = box_img;
	//alert('Img: '+img);
	$(obj).parent().find('img.mainImg').attr({src: 'upload/'+img});
}
