$(document).ready(function() {
$('#loadingDiv').hide();
	jQuery(document).ajaxStart(function() {

			$('#loadingDiv').show();
		})
		.ajaxComplete(function() {

			$('#loadingDiv').hide();
		});

$('.wishlist_delete').click(function(){
	var product_id = $(this).attr('data-product_id');
	remove_from_wishlist(product_id);
	if($(this).hasClass('remove_on_delete')){
		$(this).parents('div.set').fadeOut(1000);//only for search results
	}else{
		$('#feedback').html('Removed from wishlist').show().fadeOut(2000);
	}
});

$('.wishlist_add').click(function(){					  
	var product_id = $(this).attr('data-product_id');
	add_to_wishlist(product_id);
});

$('.email_send').click(function(){
	var product_id = $(this).attr('data-product_id');

	$( "#emailto_dialog").dialog({
			autoOpen: true,
			height: 500,
			width: 575,
			modal: true,
			buttons: [{
				text: "Close",
				click: function() { $(this).dialog("close"); }
  			}],
			open: function(event, ui) {
				load_modal_form("emailto_dialog", "templates/"+window.template+"/mailto.php?product_id="+product_id, 'Email a Product');
				}
	});

});

/*$('#linkCTA').click(function(){
	var product_id = $('.email_send').attr('data-product_id');

	$( "#emailto_dialog").dialog({
			autoOpen: true,
			height: 500,
			width: 575,
			modal: true,
			buttons: [{
				text: "Close",
				click: function() { $(this).dialog("close"); }
  			}],
			open: function(event, ui) {
				load_modal_form("emailto_dialog", "templates/"+window.template+"/mailto.php?product_id="+product_id+"&emailTo=performance@genr8.net.au&messageTo="+product_id, 'Contact Us');
				}
	});

});*/

$('.print_pdf').click(function(){
	var product_id = $(this).attr('data-product_id');

	open_window(window.domain+"templates/"+window.template+"/print.php?product_id="+product_id, 'Print a Product');


});
});

function feedback(fb){
	switch(fb){
		case '1':
		return 'Your email has been sent!';
		break;
		case '2':
		return 'Sorry, there was an issue sending that email';
		break;
		case '3':
		return 'Error or Omission. Insufficient data was sent to the database.';
		break;
		case '24':
		return 'Request not processed. Other data relies on that record and so it cannot be changed / deleted.';
		break;
		default:
		return 'Unknown response received.';
		break;
	}
}
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
function load_modal_form(modal_id, load_page_url, modal_title){
		$.ajax({
	   type: "GET",
	   //dataType: 'script',
	   url: domain+load_page_url,
	   success: function(form){ 
		  $("#"+modal_id ).html(form).dialog("option", "title", modal_title );
	   }
	 });
	}
function open_window(href, name, attr){
	var winopen = window.open(href, name, attr+',titlebar=0,toolbar=0,statusbar=0');	
	//window.blur();
	winopen.focus();
}
function toggle_display(element){
	$(element).toggleClass('no_display');
}
function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))){
      return true;
 } else {
      return false;
 }
}
function add_to_wishlist(product_id){
	
	$.get(domain+"inc/ajax_ecat.php", { 
			request_type: 'add_to_wishlist', 'product_id': product_id},
		   function(data){
				   $('#feedback').html('Added to wishlist').show().fadeOut(2000);
					update_wishlist_status();
		});	
		return;	
}
function remove_from_wishlist(product_id){
	
	$.get(domain+"inc/ajax_ecat.php", { 
			request_type: 'remove_from_wishlist', 'product_id': product_id},
		   function(data){
				   $('#feedback').html('Removed from wishlist').show().fadeOut(2000);
					update_wishlist_status();
		});	
		return;	
}
function update_wishlist_status(){
	
	$.get(domain+"inc/ajax_ecat.php", { 
			request_type: 'update_wishlist_status'},
		   function(data){
				  $('.wishlist_count').html(data);
		});	
		return;	
}
// used by product-search module
function show_search(section){
	var display = $('#'+section).css('display');
	var f = $('#prod_list_container<? echo $module_id; ?>').find('.prod_list');

	for(var i=0; i<f.length; i++){
		$('#'+f[i].id).hide();
	}

	if(display == 'none'){
		$('#'+section).show('1000');
	}else{	
		$('#'+section).hide('slow');
	}

}
//used by product-display-ind module
function update_prod_image(image_url, update_id){
	$('#'+update_id).hide()
    .load(function () {
      $(this).fadeIn();
    })
    .attr('src', image_url)
}

function calculate_cart_value(form_id){
	/*
		get the cart subtotal
		get the freight option selected and it's value from the array
		check if vouchers used
	*/
	var form_data = $('#'+form_id).serialize();
	var cart_subtotal = parseFloat($('#'+form_id+' #order-subtotal').val());
	var order_subtotal_gst = parseFloat($('#'+form_id+' #order-subtotal_gst').val());

	$.get(domain+"inc/ajax_ecat.php", { 
			  request_type: "calculate_freight", 'form_data':form_data},
		   		function(freight_cost){
					freight_cost = parseFloat(freight_cost);
					
					var order_total = cart_subtotal + freight_cost;
					var new_order_gst = order_subtotal_gst + (freight_cost*0.1);
					
			  		$('#'+form_id+' #delivery_fee_show').html('$'+freight_cost.toFixed(2));
					$('#'+form_id+' #order-delivery_fee').val(freight_cost);
					
					$('#'+form_id+' #total_show').html('$'+order_total.toFixed(2));
					$('#'+form_id+' #order-total').val(order_total.toFixed(2));
					
					$('#'+form_id+' #gst_show').html('$'+new_order_gst.toFixed(2));
					$('#'+form_id+' #order-gst').val(new_order_gst.toFixed(2));
				});	
	//change freight, total, gst
	
}

function add_cart_item(product_id, price, qty, option_id_arr, soh_qty, is_short_order){
//2. check soh
   if(!is_short_order && (parseFloat(soh_qty)-qty) < 1){//not enough SOH
	 //advise
	 alert('Sorry, insufficient stock available!');
	 return false;
   }

	//3. add the item to the cart
		$.get(domain+"inc/ajax_ecat.php", { 
			  request_type: 'update_cart', product_id: product_id,  'option_id_arr[]':option_id_arr, 'price':price, 'qty':qty},
		   function(data){

			  // if(data == 'true'){
				   
				   //4. confirm the update
				   $('.widget_product_display_ind .cart_confirm').show();
				   $('.widget_product_display_ind .cart_confirm').fadeOut(2000);
				   
				   var orig_color = $('.widget_cart_status .cart_status_content').css("color");
				   
				   //$('.widget_cart_status .cart_status_content').animate({color:'#E4E4E4'}, 1000);
				   // $('.widget_cart_status .cart_status_content').animate({color:orig_color}, 1000);
				   //update the cart
				   $.get(domain+"inc/ajax_ecat.php", { 
					  request_type: 'cart_status'},
				   function(data){
					   
					$('.cart_status_content').html(data);
				});		
				   
			   //}else{//the update failed
				   
			  // }
		});	
		return;
}

function update_cart_values(cart_key, product_id, option_id_arr, price, qty){
	
	$.get(domain+"inc/ajax_ecat.php", { 
			  request_type: 'update_cart', 'product_id': product_id,  'option_id_arr[]':option_id_arr, 'price':price, 'qty':qty, 'cart_key':cart_key},
		   function(data){

			   if(data == 'true'){
				   //4. confirm the update
				   $('#cart_confirm').show();
				   $('#cart_confirm').fadeOut(2000);
				   
				   //update the cart
				   $.get(domain+"inc/ajax_ecat.php", { 
					  request_type: 'cart_status'},
				   function(data){
						$('#cart_status_content').html(data);
				});		
				   
			   }else{//the update failed
				   
			   }
		});	
		return;	
}

function delete_cart_item(key, cart_status_id, form_id){
		$.get(domain+"inc/ajax_ecat.php", { 
			  'request_type': 'delete_cart_item', 'cart_key':key},
		   function(data){
			   
			   if(data == 1){
					$("#row"+key).fadeOut(500, function(){
						$("#row"+key).remove();
					});
					
					$.get(domain+"inc/ajax_ecat.php", { 
			  			request_type: "calculate_cart_subtotal"},
						function(data){
							
							$('#'+form_id+' #subtotal_show').html('$'+parseFloat(data).toFixed(2));
							$('#'+form_id+' #order-subtotal').val(data);
							$('#'+form_id+' #order-subtotal_gst').val(parseFloat(data)*0.1);
							calculate_cart_value(form_id);
						});	
					
			   }else if(data == 0){
				 $('#'+form_id).html('<p>Your shopping trolley is currently empty.</p>');
			   }
			   
			});	
		update_cart_status(cart_status_id);
}

function update_cart_item(cart_key, form_id){
	
	/*
	1. get the form values
	2. are there any options?
		if options exist, get amended price/soh_qty
	3. check soh_qty
	4. update SESSION data
	5. update price, if needed, cart total
	6. update cart status
	7. confirm changes
	
	*/
	var new_qty = parseFloat($('#row'+cart_key+'-qty').val());
	//make sur the qty is p[ositive and an integer
	if(new_qty < 1){alert('Please correct quantity ordered first');return false;}
	if(!is_int(new_qty)){alert('Order quantity needs to be a whole number');return false;}
	
	var product_id = $('#row'+cart_key+'-product_id').val();
	var is_short_order = $('#row'+cart_key+'-is_short_order').val();
	//are there any options?
	var option_arr = $('.select'+cart_key); 
	option_id_arr = new Array();//declare the array
	
	if(option_arr.length > 0){//check for new price/soh
		
		//build the option arr
		for(i=0; i<option_arr.length;i++){
			option_id_arr[i] = $(option_arr[i]).val();
			if(option_id_arr[i] == ''){//make sure we have received data
				alert('You need to make a selection for each option.');
				return;
			}
		}
	}//options exist
	else{
		option_id_arr[0] = '';//declare the empty aray value
	}
		$.get(domain+"inc/ajax_ecat.php", { 
			  request_type: "get_product_price_soh", product_id: product_id,  'option_id_array[]':option_id_arr},
		   function(data){

			   data_arr = data.split('-');
			   new_price = parseFloat(data_arr[0].replace(',', ''));
			   new_soh = parseFloat(data_arr[1]);
			 
			   if(new_soh < new_qty && is_short_order == '0'){//not enought stock, and we can't short order it
			   	alert('Sorry, we don\'t currently have '+new_qty+' of those in stock.');
					return false;   
			   }
			   
			   if(option_id_arr.length == 0) option_id_arr[0] = '';
			   update_cart_values(cart_key, product_id, option_id_arr, new_price, new_qty);

			  //update price and row subtotal
			  $('#row'+cart_key+'-price').html('$'+new_price);
			  $('#row'+cart_key+'-line_total').val(new_price*new_qty);
			   $('#row'+cart_key+'-line_total_show').html('$'+(new_price*new_qty).toFixed(2));
			   
			   $('#row'+cart_key+'-cart_update_confirm').show();
				$('#row'+cart_key+'-cart_update_confirm').fadeOut(2000);
				
				$.get(domain+"inc/ajax_ecat.php", { 
			  		request_type: "calculate_cart_subtotal"},
						function(data){
							
							$('#'+form_id+' #subtotal_show').html('$'+parseFloat(data).toFixed(2));
							$('#'+form_id+' #order-subtotal').val(data);
							$('#'+form_id+' #order-subtotal_gst').val(parseFloat(data)*0.1);
							calculate_cart_value(form_id);
						});	
				
				
			});	


}




function update_cart_status(update_id){	
	$.get(domain+"inc/ajax_ecat.php", { 
			  request_type: 'cart_status'},
		   function(data){
			$('.'+update_id).html(data);
		});						   
}

function show_hide_option_prices(){
	var display = $('#option_price_list').css('display');

	if(display == 'none'){
		$('#option_price_list').show('1000');
		$('#view_option_price_link').html('Hide Price Variations');
	}else{	
		$('#option_price_list').hide('slow');
		$('#view_option_price_link').html('<strong>*</strong>View Price Variations');
	}
}
