$(document).ready(function(){

	$('#query').focus(function(){
		$(this).val('');
	}).blur(function(){
		if ($(this).val() == '') $(this).val('Search Parts');
	});

});

function updateShipping() {
$.post("/checkout/ajax/cart.php", { action: "calcshipping", stateprov: $('#stateprov').val(), session: sessionid },
	function(data){
		$('#shipcost').text(data);
		updateTaxandTotal(data);
	});
}

function updateTaxandTotal(shippingcost) {
$.post("/checkout/ajax/cart.php", { action: "calctaxandtotal", stateprov: $('#stateprov').val(), shipping: shippingcost, session: sessionid },
	function(data){
		$('#taxandtotal').html(data);
	});
}

function is_int(value){
   for (i = 0 ; i < value.length ; i++) { 
	  if ((value.charAt(i) < '0') || (value.charAt(i) > '9')) return false 
   } 
   return true; 
}

function updateCartSubTotal() {
	$.post("/checkout/ajax/cart.php", { action: "calcsubtotal", session: sessionid },
	  function(data){
		$('#bottomsubtotal').text(data);
	  });
}

function removeProduct(link, id) {
	$.post("/checkout/ajax/cart.php", { action: "updateqty", session: "<?php echo session_id(); ?>", qty: '0', product: id, session: sessionid },
	
	function(data) {
		updateCartSubTotal();
		updateCount('<?php echo session_id(); ?>');
	});
	
	$(link).parent().parent().remove();
}

function removeRental(link, id) {
	$.post("/checkout/ajax/cart.php", { action: "removalrental", session: "<?php echo session_id(); ?>", qty: '0', rental: id, session: sessionid },
	
	function(data) {
		updateBottomTotal();
		updateCount('<?php echo session_id(); ?>');
	});
	
	$(link).parent().parent().remove();
}

function updateQty(qty, product, unitprice) {
	
	if(is_int(qty) == false) {
		 $('.product'+product+' > .qty').val(1);
		 return false;
	}
	
	$.post("/checkout/ajax/cart.php", { action: "updateqty", session: "<?php echo session_id(); ?>", qty: qty, product: product, unitprice: unitprice, session: sessionid },
  function(data){
	$('.product'+product+' > .subtotal').text(data);
	
		updateCartSubTotal();
		
  });
  
}

function updateCartCount(sess) {
	
	$.post("/products/ajax/cart.php", { action: "getcountnotice", session: sess }, function(data) {
		$('#cart').html(data);
	});
	
}

function addToCart(product, sess) {

	//run ajax call
	$.post("/products/ajax/cart.php", { action: "addtocart", session: sess, product: product }, function(data) {
		//update cart count in upper corner
		updateCartCount(sess);
	});
	
	//show confirmation window
	$.fn.colorbox({href:"/products/ajax/cartadded.php?product="+product, scrolling: false});

}

function updateRentalLength() {
	
	//construct list of days, up to 30
	var returnstring = '<select id="term" style="width: 90px;" onchange="setBookingPrices();"><option value="">- Select -</option>';
	
	if($('#book_rate').val() == "day") {
				
		for (x=1;x<=30;x=x+1) {
			if(x == 1) {
				plural = '';
			} else {
				plural = 's';
			}
			returnstring = returnstring+'<option value="'+x+'">'+x+' day'+plural+'</option>';
		}
		
	} else if($('#book_rate').val() == "week") {
	
		for (x=1;x<=6;x=x+1) {
			if(x == 1) {
				plural = '';
			} else {
				plural = 's';
			}
			returnstring = returnstring+'<option value="'+x+'">'+x+' week'+plural+'</option>';
		}

	} else if($('#book_rate').val() == "month") {
	
		for (x=1;x<=12;x=x+1) {
			if(x == 1) {
				plural = '';
			} else {
				plural = 's';
			}
			returnstring = returnstring+'<option value="'+x+'">'+x+' month'+plural+'</option>';
		}
	
	}
	
	returnstring = returnstring+"<select>";
	
	$('#rentallengthcontainer').html(returnstring);
	
	resetBookingRates();
	
}

function resetBookingRates() {
	$('#gstvalue').html('0.00');
	$('#pstvalue').html('0.00');
	$('#totalvalue').html('0.00');
}

function setBookingPrices() {
	subtotal = $('#rate_'+$('#book_rate').val()).val()*$('#term').val();
	gst = subtotal*0.05;
	pst = subtotal*0.05;
	total = subtotal+gst+pst;
	
	$('#subtotalvalue').html(subtotal.toFixed(2));
	$('#gstvalue').html(gst.toFixed(2));
	$('#pstvalue').html(pst.toFixed(2));
	$('#totalvalue').html(total.toFixed(2));
	
}

function showImage(hash) {
	$('#imagebay').html('<img src="/files/'+hash+'_r.jpg">');
}

function checkRentalDates() {

	if($('#dp1').val() == '') {
		alert('Please enter pickup and return dates for this rental.');
		return false;
	}
	
	if($('#dp2').val() == '') {
		alert('Please enter pickup and return dates for this rental.');
		return false;
	}
	
}

function estimatePayment() {
	
    // Get the user's input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in years
    // to the number of monthly payments.
    
    initialhtml = $('#pmtcontent').html();
    
    var principal = $('#amount').val();
    var interest = $('#interest').val() / 100 / 12;
    var payments = $('#term').val();

    // Now compute the monthly payment figure, using esoteric math.
    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);

    // Check that the result is a finite number. If so, display the results
    if (!isNaN(monthly) && 
        (monthly != Number.POSITIVE_INFINITY) &&
        (monthly != Number.NEGATIVE_INFINITY)) {

        monthlypmt = round(monthly);
        
        $('#pmtcontent').html('<div style="font-size: 16px; font-weight: bold; text-align: center; padding: 20px 15px;">Your monthly payment would be $'+monthlypmt+'</div><div style="padding-bottom: 15px; text-align: center; font-weight: bold;"><a href="#">Apply for Financing</a></div><div style="padding-bottom: 15px; text-align: center;"><a href="#" onclick="resetPmt();">Reset Calculator</a></div>');
        
    }
	
}

function round(x) {
  return Math.round(x*100)/100;
}

function resetPmt() {
	$('#pmtcontent').html(initialhtml);
}

function clearEmailField() {
	if($('#newslettersubscribefield').val() == "E-mail Address") {
		$('#newslettersubscribefield').val('');
		$('#newslettersubscribefield').css('color', '#000000');
	}
}

function newsletterSubscribe() {
	
	$.post("/checkout/ajax/newsletter.php", { action: "subscribe", email: $('#newslettersubscribefield').val() },
	function(data){
		$('#newsletter > div').fadeOut('fast', function() {
		$('#newsletter').html('<div style="display: none;">Thank you for subscribing!</div>');
		$('#newsletter > div').fadeIn('fast');
	});
	});
	
}

function loadBrand(elm) {
	window.location.href='/products/brand/'+$(elm).val();
}

function loadCat(elm) {
	window.location.href='/products/cat/'+$(elm).val();
}
