// JavaScript Document
$(document).ready(function(){
	var UserPage = document.location;
	$.ajax({
		url: "product_assets/select_product.php",
		type: 'POST',
		data: "UserPage="+UserPage,
		async: false,
		success: function(msg)
		{ 
			$('#LoadProduct').html(msg);
		}
	});
 }); 

/*//Load Sample product on Home page
// JavaScript Document
$(document).ready(function(){
	var UserPage = document.location;
	var type = '';
	if($('#LoadSampleImageH').html() != null)
	{
		type = 1;//Horizointal
		
	}
	if($('#LoadSampleImageV').html() != null)
	{
		type = 2;//Vertical
	}
	$.ajax({
		url: "product_assets/sample_product_image.php",
		type: 'POST',
		data: "UserPage="+UserPage+"&type="+type,
		async: false,
		success: function(msg)
		{ 
			if(type == 1)
			{
				$('#LoadSampleImageH').html(msg);
			}
			if(type == 2)
			{
				$('#LoadSampleImageV').html(msg);
			}
			
		}
	});
 }); */





//Cart functions
function ShowAddCart()
{
	$("#CartAddTr").show();
}
function OrderShowHide()
{
	$('#OrderTr').show();	
}

function ShowPrice(baseprice,id)
{
	var qty = $("#quantity"+id).val();
	if(qty == '' || qty == 0 || isNaN(qty))
	{
		alert("Please enter valid Quantity !");
		$("#quantity"+id).val(1);
		
		var total = parseInt(1) * parseFloat(baseprice);
		var num = roundNumber2(total,2);
		$("#price_area"+id).html(num);

		return false;
	}
	else
	{
		var total = parseInt(qty) * parseFloat(baseprice);
		var num = roundNumber2(total,2);
		$("#price_area"+id).html(num);
	}
}

function ShowCartPrice(item_row_id,baseprice)
{
	var qty = $("#quantity"+item_row_id).val();
	if(qty == '' || qty == 0 || isNaN(qty))
	{
		alert("Please enter valid Quantity !");
		$("#quantity"+item_row_id).val(1);
		$('#price_area'+item_row_id).html('$'+baseprice);
		return false;
	}
	else
	{
		$("#price_area"+item_row_id).html("<img src='images/loader.gif'>");
		$("#TotalPrice").html("<img src='images/loader.gif'>");
		var total = parseInt(qty) * parseFloat(baseprice);
		var num = roundNumber2(total,2);

		$.ajax({
			url: "product_assets/cart_handler.php",
			type: 'POST',
			data: "action=CalPrice&row_id="+item_row_id+"&qty="+qty,
			async: false,
			success: function(msg)
			{ 
				var t = parseFloat(msg);
				t = roundNumber2(t,2);
				$('#price_area'+item_row_id).html('$'+num);
				$('#TotalPrice').html('$'+t);

			}
		});

	}
}


function AddToCart(item_id, redirect_path,id)
{
	var unit_price = $("#unit_price"+id).val();
	var item_title = $("#item_title").val();
	var desc = $("#item_desc").val();
	var image = $("#item_image").val();
	var qty = $("#quantity"+id).val();
	var item_name = $("#item_name"+id).val();

	$.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } }); 

	$.ajax({
		url: "product_assets/add_to_cart.php",
		type: 'POST',
		data: "item_id="+item_id+"&qty="+qty+"&item_title="+item_title+"&price="+unit_price+"&desc="+desc+"&image="+image+"&item_name="+item_name,
		async: false,
		success: function(msg)
		{ 
			if(msg !='error')
			{
				$("#CartAddTr").hide('slow');
				$("#showMassege").show();
				$("#showMassege").html("<div class='OKmessegeBody'>Item id "+item_id+" successfully added into your cart</div>");
			}
			else
			{
				$("#showMassege").show();
				$("#showMassege").html("<div class='ErrormessegeBody'>We are unable to add items into your cart.Please try another time.</div>");

			}
			setTimeout("ClearMessage('"+redirect_path+"')",2000);
		}
	});
}



function ClearMessage(redirect_path)
{
	$("#showMassege").hide();
	//setTimeout($.unblockUI, 6000); 
	var url = "shoppingcart.php?"+redirect_path
	window.location.href= url;
}

function ContinueShop(cat_id)
{
	var url = 'search.php?category='+cat_id;
	window.location.href = url;
}
//Deleting item from Cart
function DelFromCart(item_id)
{
	if(confirm('Are you sure?'))
	{
		//update total price after user delete item from cart
		var del_item_price = $('#price_area'+item_id).text(); 
		var total_price = $('#TotalPrice').text(); 
		del_item_price = del_item_price.substr(1,del_item_price.length);
		total_price = total_price.substr(1,total_price.length);

		var final_total = parseFloat(total_price) - parseFloat(del_item_price);
		var num = roundNumber2(final_total,2);
		
		$.ajax({
			url: "product_assets/cart_handler.php",
			type: 'POST',
			data: "action=delete&item_id="+item_id,
			async: false,
			success: function(msg)
			{
				$('#TotalPrice').text('$'+num);
				$('#C_row'+item_id).hide();
				var spath = window.location.href;
				$.blockUI({ css: { 
						border: 'none', 
						padding: '15px', 
						backgroundColor: '#000', 
						'-webkit-border-radius': '10px', 
						'-moz-border-radius': '10px', 
						opacity: .5, 
						color: '#fff' 
					} }); 
				
				window.location.href = spath;
				setTimeout($.unblockUI, 10000); 
			}
		});

	}

}










//round the number upto specified decimal place
function roundNumber2(number,decimals) {
	var newString;// The new rounded number
	decimals = Number(decimals);
	if (decimals < 1) {
		newString = (Math.round(number)).toString();
	} else {
		var numString = number.toString();
		if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
			numString += ".";// give it one at the end
		}
		var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
		var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
		var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
		if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
			if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
				while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
					if (d1 != ".") {
						cutoff -= 1;
						d1 = Number(numString.substring(cutoff,cutoff+1));
					} else {
						cutoff -= 1;
					}
				}
			}
			d1 += 1;
			//newString = numString.substring(0,cutoff) + d1.toString();
		} //else {
			//newString = numString.substring(0,cutoff) + d1.toString();// Just the string up to cutoff point
			if (d1 == 10) {
           		numString = numString.substring(0, numString.lastIndexOf("."));
           		var roundedNum = Number(numString) + 1;
           		newString = roundedNum.toString() + '.';
      	 	} else {
           		newString = numString.substring(0,cutoff) + d1.toString();
       		}
		//}
	}
	if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
		newString += ".";
	}
	var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
	for(var i=0;i<decimals-decs;i++) newString += "0";
	return newString;
	//var newNumber = Number(newString);// make it a number if you like
	//document.roundform2.roundedfield.value = newString; // Output the result to the form field (change for your purposes)
	
}

//CHECK ORDER FORM
function CheckOrder()
{
	var email = jQuery.trim($('#email').val());
	var first_name = jQuery.trim($('#first_name').val());
	var last_name = jQuery.trim($('#last_name').val());
	var street_address = jQuery.trim($('#street_address').val());
	var city = jQuery.trim($('#city').val());
	var state = jQuery.trim($('#state').val());
	var postal_code = jQuery.trim($('#postal_code').val());
	var country = jQuery.trim($('#country').val());
	/*Validate Data here*/
	if(email =='')
	{
		alert("Plese provide your email address !");
		$('#email').focus();
		return false;
	}
	if(!email.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-Z0-9]{2,4}$/))
	{
		alert("Please enter proper email address.");
		$('#email').focus();
		return false;
	}
	
	if(first_name =='')
	{
		alert("Plese provide your first name !");
		$('#first_name').focus();
		return false;
	}
	if(last_name =='')
	{
		alert("Plese provide your last name !");
		$('#last_name').focus();
		return false;
	}
	if(street_address =='')
	{
		alert("Plese provide your street address !");
		$('#street_address').focus();
		return false;
	}
	if(city =='')
	{
		alert("Plese provide your city !");
		$('#city').focus();
		return false;
	}
	if(state =='')
	{
		alert("Plese select your state !");
		$('#state').focus();
		return false;
	}
	if(postal_code =='')
	{
		alert("Plese provide your postal code !");
		$('#postal_code').focus();
		return false;
	}

	$.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } });

}



$(document).ready(function(){
	$("#ConfirmOrder").bind("click",function(){
	var spath = "http://"+location.hostname+""+location.pathname;
	$.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } });
		
		$.ajax({
			url: "product_assets/cart_handler.php",
			type: 'POST',
			data: "action=ConfirmOrder&spath="+spath,
			async: false,
			success: function(msg)
			{ 
				$.unblockUI();
				$("#OrderContent").html("<div class='OKmessegeBody'>"+msg+"</div>");
				//setTimeout(function(){window.location.href= 'fund_order.php';}, 4000);
			}
		});
	});

}); 


/*Fund page coading*/
function ShowOptions(id)
{
	if(id==1)
	{
		$("#PaymentAccountId").show();
		$("#NewPaymentInfo").hide();
	}
	
	if(id==2)
	{
		$("#PaymentAccountId").hide();
		$("#NewPaymentInfo").show();
	}
	
}

$(document).ready(function(){
	$("#fund_submit").bind("click",function(){
	/*Validate Form*/
	var pay_method = $("#pay_method").val();
	if(pay_method == '')
	{
		alert("Please select payment method !");
		$("#pay_method").focus();
		return false; 
	}
	
	if(pay_method == 1)
	{
		
		if(jQuery.trim($("#doba_ac_id").val()) == '')
		{
			alert("Please enter your doba payment account id !");
			$("#doba_ac_id").focus();
			return false;
		}
	}
	if(pay_method == 2)
	{
		var first_name = jQuery.trim($("#first_name").val());
		var last_name = jQuery.trim($("#last_name").val());
		var street_address = jQuery.trim($("#street_address").val());
		var city = jQuery.trim($("#city").val());
		var state = jQuery.trim($("#state").val());
		var postal_code = jQuery.trim($("#postal_code").val());
		var country = jQuery.trim($("#country").val());
		var cc_number = jQuery.trim($("#cc_number").val());
		var exp_month = jQuery.trim($("#exp_month").val());
		var exp_year = jQuery.trim($("#exp_year").val());
		var cvv2_code1 = jQuery.trim($("#cvv2_code1").val());
		
		if(first_name == '')
		{
			alert("Please enter your first name !");
			$("#first_name").focus();
			return false;
		}
		if(last_name == '')
		{
			alert("Please enter your last name !");
			$("#last_name").focus();
			return false;
		}
		if(street_address == '')
		{
			alert("Please enter your street address !");
			$("#street_address").focus();
			return false;
		}
		if(city == '')
		{
			alert("Please enter your city !");
			$("#city").focus();
			return false;
		}
		if(state == '')
		{
			alert("Please enter your state !");
			$("#state").focus();
			return false;
		}
		if(postal_code == '')
		{
			alert("Please enter your postal code !");
			$("#postal_code").focus();
			return false;
		}
		if(country == '')
		{
			alert("Please select your country !");
			$("#country").focus();
			return false;
		}
		if(cc_number == '')
		{
			alert("Please enter your credit card number !");
			$("#cc_number").focus();
			return false;
		}
		if(exp_month == '')
		{
			alert("Please select your credit card expiry month !");
			$("#exp_month").focus();
			return false;
		}
		if(exp_year == '')
		{
			alert("Please select your credit card expiry year !");
			$("#exp_year").focus();
			return false;
		}
		if(cvv2_code1 == '')
		{
			alert("Please enter your credit card CVV2 code !");
			$("#cvv2_code").focus();
			return false;
		}
	}
	
	var spath = "http://"+location.hostname+""+location.pathname;
	$.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } });
		
		$("#FundTr").hide();
	});

}); 


//Track Order page js

$(document).ready(function(){
	$("#track_order").bind("click",function(){
	/*Validate Form*/
	var email = jQuery.trim($('#email').val());
	var order_id = jQuery.trim($('#order_id').val());
	if(email == '')
	{
		alert("Please enter your email address!");
		$('#email').focus();
		return false;	
	}
	if(!email.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-Z0-9]{2,4}$/))
	{
		alert("Please enter proper email address.");
		$('#email').focus();
		return false;
	}
	if(order_id == '')
	{
		alert("Please enter order ID!");
		$('#order_id').focus();
		return false;	
	}
	
	$.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } });
	
		return true;
	
	});
});	
