// 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;
	  }
	}
}

function lookupShippingOptions(postcode, country_id) {
	$('#deliveryInformation').load('/order/get-shipping-options', {postcode: postcode, country_id: country_id});
}

function formatItem(row) {
	return row[0] + ',' + row[1];
}

// 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() {

$('.postcode_suburb_autocomplete').autocomplete({
	source: '/index/get-suburbs-or-postcodes/',
	minLength: 2,
	select: function(event, ui) {
		// set the other values in the nearest fieldset
		$(this).parents('fieldset').find('.suburb').val(ui.item.suburb);
		$(this).parents('fieldset').find('.state').val(ui.item.state);
		$(this).parents('fieldset').find('.postcode').val(ui.item.postcode).change();
		$(this).parents('fieldset').find('.country').val(14);
		
	}
});

$('#order_postcode').keyup(function(e) {
	$(this).change();
});

$('#order_postcode, #order_country_id, #order_suburb').change(function(e) {
	var postcode = $('#order_postcode').val();
	// there are 3 digit postcodes in Australia
	if (postcode.length > 2) {
		lookupShippingOptions($('#order_postcode').val(), $('#order_country_id').val());
	}
});

$('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;
   });
});

$('#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('');
	}
	
	lookupShippingOptions($('#order_postcode').val(), $('#order_country_id').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');
	});

	// 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'});
	});
	
	$('.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'));

	});

	$(".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');
					}
				}
			});
		}
	);

});
