// For toggling input boxes
jQuery.fn.toggleVal=function(focusClass){this.each(function(){$(this).focus(function()
{if($(this).val()==this.defaultValue){$(this).val("")}if(focusClass)
{$(this).addClass(focusClass)}}).blur(function(){if($(this).val()=="")
{$(this).val(this.defaultValue)}if(focusClass){$(this).removeClass(focusClass)}})})}


//returns true if numeric
function numerics(event) {
	if(document.all) { // Internet Explorer
	  var tecla = event.keyCode;
	}
	else {
	  var tecla = (event.charCode)? event.charCode: event.which; // Firefox e afins
	}

	if(tecla == ''){
	  return true;
	}

	if((tecla > 47 && tecla < 58)) { // numbers of 0 to 9 and .
	  return true;
	}
	else {
	  if ( tecla != 8  ) { // backspace
	  return false;
	  }
	  else
	   {
		return true;
	  }
	}
}

// postcode suburb autocomplete
function selectItemSuburb(li) {
	if (li.extra) {
		$('#postcode').val(li.extra[0]);
		$('#state').val(li.extra[1]);
		$('#country_id').val(14);
		//updatePostageInformation();
	}
}
function selectItemPostcode(li) {
	if (li.extra) {
		$('#suburb').val(li.extra[0]);
		$('#state').val(li.extra[1]);
		$('#country_id').val(14);
		//updatePostageInformation();
	}
}
function selectItemOrderSuburb(li) {
	if (li.extra) {
		$('#order_postcode').val(li.extra[0]);
		$('#order_state').val(li.extra[1]);
		$('#order_country_id').val(14);
		lookupShippingOptions($('#order_postcode').val());
	}
}
function selectItemOrderPostcode(li) {
	if (li.extra) {
		$('#order_suburb').val(li.extra[0]);
		$('#order_state').val(li.extra[1]);
		$('#order_country_id').val(14);
		lookupShippingOptions($('#order_postcode').val());
	}
}

function formatItem(row) {
	return row[0] + ',' + row[1];
}
//end postcode suburb autocomplete

function checkStock(product_option_id, quantity) {
	$.getJSON('/product/check-stock/', {
		quantity: quantity,
		product_option_id: product_option_id
		}, function(data){
			if(quantity > data.current_stock){
				//not enough stock
				flashMessage(new Array(data.messages));
				messageBox.dialog('option',"buttons", {
					"Cancel": function() { $(this).dialog("close"); } 
					}
				);
				//check if there is any stock available
				if(data.current_stock>0){
					//give option to place back order and/or add available
					messageBox.dialog('option', 'button', {
						"Add Available to Cart": function() {},
						"Add Available to Cart and Place a Backorder": function(){}
						}
					)
				}
				
			} else {
				//product in stock		
				//add product to cart
				$.post('cart/add/', {
					product_id: product_id,
					product_option_id: product_id,
					quantity: qty
					},function(data) {
					// Display a modal box
					data = '<div style="width: 324px; height: 102px;"><p style="padding:10px;">You have successfully added this item to your cart. </p><div class="cart_confirm"><a href="javascript:;" id="fancy_close">Continue Shopping</a> or <span class="right"><a href="/cart/" class="button" title="View the items in your cart"><span>View your Cart</span></a></span></div></div>'
					updateCart(qty, price);

					$.fancybox(data,
						{
							'width' : '260px',
							'overlayShow'	: false,
							'hideOnContentClick' : true,
							'showCloseButton' : false,
							'padding' : '0'
						}
					);
				});
			}
		}
	);
}

// Updates price and quantity of cart visually, without refreshing the page. Used for ajax add to cart
function updateCart(qty, price) {		
		current_qty = parseInt($('.num_items_top').text());
		cur_price = parseFloat($('.cur_price').text());

		total_qty = current_qty+parseInt(qty);
		total_price = cur_price+parseFloat(price);

		if ($('.cartNumSmall').is('.hidden')) {
			$('.cartNumSmall').removeClass('hidden');
		}

		$('.num_items_top,.num_items').text(total_qty).removeClass('hidden');
		$('.cur_price').text(total_price.toFixed(2));
		$('.slide_content').append('<li>&nbsp; '+qty+'x '+name+'&nbsp;  <strong><sup>$</sup>'+price+'</strong></li>')
}
	
	
$(function() {

$('#sameAsAbove').change(function(){
	if($(this).attr('checked')){
		$.each($('#customerFieldset').find(':input'), function(){
			$('[name="order_'+$(this).attr('name')+'"]').val($(this).val());
		});
	} else {
		$('#deliveryFieldset').find(':input').val('');
	}
	
	if ($('#order_country_id').val() === '14' && $('#order_postcode').val()){
		lookupShippingOptions($('#order_postcode').val());
	}
});

$('input').live('keypress', function(e) {

		var element = $(this);
		var clas_s = element.attr('class');
		
		if(clas_s=='qty'){
	
			return numerics(e);
	
		}
		
	});
	
	
	$('a[href*=#]').live("click", function(e){

	//prevent the "normal" behaviour which would be a "hard" jump
		e.preventDefault();
		//Get the target
		var target = $(this).attr("href").substr(1);
		//perform animated scrolling
		$('html,body').animate(
		{
		//get top-position of target-element and set it as scroll target
		scrollTop: $("a[name = '"+target+"']").offset().top
		//scrolldelay: 2 seconds
		},1000,function()
		{
		//attach the hash (#jumptarget) to the pageurl
		location.hash = '#'+target;
		});
	});

	// Toggle input box default text eg. Search this site...
	$(".toggle").toggleVal("active");

	// Fancybox Image Lightbox - for product photos
	$("a.fancybox").fancybox({
		'titleShow'		: false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic'
	});

	
	//Selects this on the page load
	$('.selected_first').focus();

			
	//Fix the #hash anchor problem with Zend
	$('a[href*=#]').live("click", function(e){

		//prevent the "normal" behaviour which would be a "hard" jump
		e.preventDefault();
		//Get the target
		var target = $(this).attr("href").substr(1);
		//perform animated scrolling
		$('html,body').animate(
		{
		//get top-position of target-element and set it as scroll target
		scrollTop: $("a[name = '"+target+"']").offset().top
		//scrolldelay: 2 seconds
		},1000,function()
		{
		//attach the hash (#jumptarget) to the pageurl
		location.hash = '#'+target;
		});
	});

	// Stripe table rows
	$("tbody>tr:odd").addClass('alt');

	//Initialise the slider by hiding all the child elements
	$('.slide_content').hide();

	//Toggle the divs
	$('.slide_header').toggle (function() {
		$(this).next().slideDown('fast');
	}, function() {
		$(this).next().slideUp('fast');
	});


	// Submit cart via AJAX
	$('#add_to_cart').click(function(e) {
		e.preventDefault();

		qty = $('#quantity').val();
		if (!qty) {qty=1;}

		product_id = $('#product_id').val();
		price = $('.prod_price').text();
		
		//look for product options
		if($('#product_option_id').length) {
			if ($('#product_option_id').is('select')){	
				var selectedProductOption = $('#product_option_id option:selected').val();
				//make sure one is selected
				if (selectedProductOption !== '') {
					var product_option_id = selectedProductOption;
				} else {
					//TODO: display error nicely
					alert("You must select a product option");
				}
			} else {
			//we just use the default
				var product_option_id = $('#product_option_id').val();
			}
		} else {
			//Epic Fail
			alert("The product needs a default option on the page.");
		}
		
		if(typeof(product_option_id) !== 'undefined'){
			//check stock levels (handles error message if it fails)
			checkStock(product_option_id, qty);
		}
		return false;
	});

	// Expands the form fields when clicked. Not crucial but nice effect
	$('textarea.expand').css({'height':'30px'});
	$('textarea.expand').click(function() {
		$(this).css({'height':'150px'});
	});

	$('textarea.expand').blur(function() {
		$(this).css({'height':'30px'});
	});


	$('#suburb').autocomplete('/index/get-suburbs-or-postcodes/', { minChars:3, mustMatch:false, selectFirst:true, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectItemSuburb, formatItem:formatItem });
	$('#postcode').autocomplete('/index/get-suburbs-or-postcodes/', { minChars:2, mustMatch:false, selectFirst:true, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectItemPostcode, formatItem:formatItem });
	
	$('#order_suburb').autocomplete('/index/get-suburbs-or-postcodes/', { minChars:3, mustMatch:false, selectFirst:true, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectItemOrderSuburb, formatItem:formatItem });
	$('#order_postcode').autocomplete('/index/get-suburbs-or-postcodes/', { minChars:2, mustMatch:false, selectFirst:true, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectItemOrderPostcode, formatItem:formatItem });

	$('.checkEmail').blur(function() {
		$.post('/order/check-email/', { email: $(this).val() }, function(d) {
			if (d=='emailIsTaken') {
				$('#emailIsTaken').slideDown(200);
				window.location = window.location.pathname + '#emailIsTaken';
				$('#checkout').attr('action', 'javascript:;');
				$('#purchaseButton').hide();
			}
			else {
				$('#emailIsTaken').slideUp(200);
				$('#checkout').attr('action', '/order/checkout/');
				$('#purchaseButton').show();
			}
		});
	});

	$('.payment_method').live('click', function(e) {
		var option = $(this);
		//console.log(option.val());
		if (option.val() == 'eway' || option.val() == 'camtech') {
			$('#cc_details').show();
		} else {
			$('#cc_details').hide();
		}
		if (option.val() == 'bank') {
			$('#bank_details').show();
		} else {
			$('#bank_details').hide();
		}
		if (option.val() == 'paypal') {
			$('#paypal_details').show();
		} else {
			$('#paypal_details').hide();
		}
	});
	
	$('#product_option_id').change(function(){
		//check if this option is in stock
		if ($('#product_option_id option:selected').attr('stock') > 0) {
			$('#in_stock').show();
			$('#out_stock').hide();
		} else {
			$('#in_stock').hide();
			$('#out_stock').show();
		}
		
		
		$('.prod_price').html($('#product_option_id option:selected').attr('price'));
		$('.old_price').html($('#product_option_id option:selected').attr('old_price'));

	});
	
	
	$('#deliveryModal').live('click', function(e) {
		e.preventDefault();
		if ($('#delivery').length == 0) {
			$('body').append('<div id="delivery"></div>');
		}
		
		$('#delivery').dialog({
			title: 'Freight',
			modal: true,
			autoOpen: false,
			height: 600,
			width: 940,
			resizable: false,
			closeText: 'hide',
			position: 'top',
			open: function() {
				// Here I load the content. This is the content of your link.
				$('#delivery').load('/page/delivery/', function() {
					
				});
			}
		}).dialog('open');
	});
	


	
	$(function() {
			$(".makeAwish").live( 'click',
				function(e) {
					var url = $(this).attr('href');
					var cmd = $(this).attr('cmd');
					var productId = $(this).attr('rel');
					var wishlink = $(this);
					e.preventDefault();
					$.ajax({
						url: url,
						success: function(data) {
							console.log(data);
							if( data == 'success' ) {
								if( cmd == 'rem' ) {
									wishlink.attr('href','/wishlist/ajax-add/product_id/'+productId);
									wishlink.attr('cmd','add');
									wishlink.text('Add to Wish List');
								} else {
									wishlink.attr('href','/wishlist/ajax-remove/product_id/'+productId);
									wishlink.attr('cmd','rem');
									wishlink.text('Remove from Wish List');
								}
								$(".num_wishes_top").load( '/wishlist/ajax-wish-count');
							}
						}
					});
				}
			);
	} );
	
	

});
