// Execute this script once the page is fully loaded
$(document).ready(function() {
	
	var location = window.location.href.split("/");
	
	// Init jQuery Cycle plugin
	$('.slideshow').after('<div id="slideshow_nav">').cycle( { fx: 'fade', speed: 4000, pager: '#slideshow_nav' } );
	
	// Init prettyPhoto plugin
	$("a[rel^='prettyPhoto']").prettyPhoto( { theme: 'dark_rounded' } );
	
	// Init tabs support - (>$("#tabs").tabs( { selected: 0 } );<)
	if (location.inArray('shipyard') && location.inArray('page')){
		$("#tabs").tabs( { selected: 1 } );
	}	else {
		$("#tabs").tabs(); 
	}
	
	// init gallveryView plugin in line 147
	
	//Menu stuff
	$("#menu li").each(function(){
		$(this).mouseover(function(){ $(this).addClass("sfhover") });
		$(this).mouseout(function(){ $(this).removeClass("sfhover") });
	});
	
	// Populate the Basket shortlist 
	updateBasketShortList();
		
	//Display or hide the cart contents	
	$("#topBarBasket a").hover(
		//Display the cart contents
		function(){
			if ($("#topBarBasketShortlist").children().length > 0){
				$("#topBarBasketShortlistContainerContainer").fadeIn(150);
			}
		},
		
		//Hide the cart contents
		function(){
			if ($("#topBarBasketShortlist").children().length > 0){
				$("#topBarBasketShortlistContainerContainer").fadeOut(150);
			}
		}
	);
	
	
	/* If we're in the order confirmation screen */
	if (location.inArray('order') && location.inArray('confirmation')){
		orderConfirmationFunctions();
	}
	
		
	/* If we're on the homepage observe the newsletter subscribe form */
	if ($("#newsletter_subscribe_form").length > 0){
		
		//Handle if the form is submitted
		submitSubscribeForm = function(){		
			
			//Hide the old errors
			$("#newsletter_subscribe_form ul.errors").each(function(){
				$(this).remove();
			});
			
			//Send the ajax request
			$.ajax({
			  type: 'POST',
			  url: ajaxUrl +'newsletters/subscribe',
			  data: $("#newsletter_subscribe_form").serialize(),
			  dataType: 'json',
			  beforeSend: function(xhrObj){
			  	xhrObj.setRequestHeader("x-ajax-request", true);
			  },
			  success: function(jsonResponse){
					//If an error occured
					if (jsonResponse.result == "error"){ 
						//Loop through the errors and create them
						jQuery.each(jsonResponse.errors, function(key, value){
							//Create the error list
							var ul = $("<ul></ul>").addClass("errors");		
							
							//Stuff the error item in the list
							var li = $("<li></li>")
							li.css("display", "none");
							li.id = key +"_errors";
							li.text(value);
							
							//Put the error element on the screen
							ul.append(li);
							$("#" +key).parent().append(ul);
							
							//Display the error messages
							li.slideDown(300)
						});
					}
					
					//Otherwise if all went well
					else if (jsonResponse.result == "ok"){
						//Stop the observing
						$('#subscribe_submit_button').unbind('click');
						$('#newsletter_subscribe_form').unbind('submit');
						
						//Remove the form
						var parentDiv = $('#newsletter_subscribe_form').parent();
						parentDiv.children().each(function(){
							$(this).remove();
						});
						
						//Display the success message
						var div = $("<div></div>").text(jsonResponse.message);
						div.addClass("message");
						div.css({
							textAlign: "center",
							padding: "33px 0px"
						});
						
						parentDiv.append(div);
					}						
			  }
			});
		}
		
		//Make sure the submit button actually submits
		$("#subscribe_submit_button").click(function(event){ 
			submitSubscribeForm(); 
			return false;
		});
		
		//Observe if the subscribe form is being submitted
		$("#newsletter_subscribe_form").submit(function(event){ 
			//Make sure the form isn't submitted
			event.stopPropagation();
			
			//Submit the form
			submitSubscribeForm();
			return false;
		});		
	}			
	
	
	/* If we're in the faq screen */
	if (location.inArray('support') && location.inArray('faq')){		
		//Observe if the search form is being submitted
		$("#faq_search_form").submit(function(event){ 
			event.stopPropagation();
			window.location = ajaxUrl +'support/faq/keywords/' +urlencode($('#keywords').get(0).value);
			return false;
		});
	}		
	
	
	// init gallveryView plugin
	$('#gallery').galleryView( { } );
});


/* Retrieves a string from Zend_Translate and pushes this into a given object */
function getTranslation(keystring, object) {
	$(object).load(ajaxUrl +"service/gettranslation/keystring/"+keystring, 
	function(){
	});
}


/*** 
	*	Shopping cart specific functions 
	*	
	*	Add product to cart
	*	- animate basket
	*	- populate/update basket shortlist
	*	
	*	Update Cart
	*	
	***/

// Add product to shopping cart
$(".productAdd").click(function() {
	
	// Retrieve product ID
	var productID = this;
	var productIDValSplitter = (this.id).split("_");
	var product = productIDValSplitter[1];
	
	// Execute add-to-cart function
	$.post(ajaxUrl +"cart/add",
		{ product: product }, 
		function(data){
			if (data == 0) 
				// No or empty result from addAction in the CartController, perhaps the product does not exist anymore?
				alert('Error: Could not retrieve Shopping Cart object or the object is empty.');
			else {	
				var added_text = $(productID).after("<div style='margin-left:-50px;width:200px;clear:left;display:block;'>1 Item added to the Shopping Cart</div>");	
				updateBasket(data);
				updateBasketShortList();		
				 $(productID).next().delay(3000).fadeOut("slow",function() {} );
			}			
		}, "json");
});

// Updates the cart total items in the top header
function updateBasket(data) {
	// Update basket "# item(s)"
	$('#topBarBasketCartCount').text(data);
	
	// Show basket animation effect on clone object
	var basketClone = $('#topBarBasketHeader').clone().prependTo('#topBarBasket').get(0);
	$(basketClone).css( {'fontWeight':'bold', 'position': 'absolute', 'background': 'none', 'color': 'white', 'text-align': 'center'} );
	$(basketClone).fadeOut(1500,function() { $(this).remove(); });
}

// Updates the cart item shortlist in the top header
function updateBasketShortList() {
	$.getJSON(ajaxUrl +"cart/shortlist",
		function(data){
			if (data == "") {
				// No or empty result from shortlistAction in the CartController
				//alert('Error: Could not retrieve Shopping Cart object or the object is empty.'); 
			}
			else {	
				//alert(data);			
				var cartRows = data.split(";");
				var output = "";
				
				for ( var j in cartRows ) {
					if (j != "inArray") {
						cartValue = cartRows[j].split(",");
						output += "<div class='amount'>" + cartValue[1] + "x</div><div class='product'>" + cartValue[2] + "</div><div class='clear'></div>";
					} 
				}
				$('#topBarBasketShortlist').html(output);
			}			
		});
}


function orderConfirmationFunctions() {
	if (!$('#PM-CreditCard') || $('#PM-CreditCard').attr('checked') != true) {
		$('.CC').parent().hide();
	}
		
	if (!$('#PM-iDeal') || $('#PM-iDeal').attr('checked') != true) {
		$('.iDeal').parent().hide();
	}
	$('#agree').click(function(event){
		if ($('#agree').attr('checked') == true) {
			$('#agree_validator').val("1");	
		} else {
			$('#agree_validator').val("");
		}
	});
	
	//Show or hide the language fields on click
	$('input[type="radio"]').click(function(event){
		if ($('#PM-CreditCard').attr('checked') == true) {
			$('#BRAND').val("VISA");
			$('.CC').parent().show();
		} else {
			$('.CC').parent().hide();
		}
		
		if ($('#PM-iDeal').attr('checked') == true) {
			$('#BRAND').val("iDeal");
			$('.iDeal').parent().show();
		} else {
			$('.iDeal').parent().hide();
		}
		
		if ($('#PM-PayPal').attr('checked') == true) {	
			$('#BRAND').val("PayPal");			
		}		
	});

	$('#CARDNAME').click(function(event){
		$('#BRAND').val($('#CARDNAME').val());
	});
		
	$('#CVC').keydown(function() {
		$('#Ecom_Payment_Card_Verification').val($('#CVC').val());
	});
}
	
function confirmPayment() {
	
	// First we save the payment attempt to the database
	$('input').each(function(){  });
	if ($('#agree').attr('checked') == true &&
			(($('#PM-iDeal') && $('#PM-iDeal').attr('checked') == true) ||
			($('#PM-PayPal') && $('#PM-PayPal').attr('checked') == true))) {
		
		// Retrieve URL to connect to payment system
		$.get(ajaxUrl +"order/geturl", function(response){
			
			$("#secure_payment_form").attr('action', response);		
			$("#secure_payment_form").attr('enctype', 'application/x-www-form-urlencoded');	
			
			// Perform order confirmation / pre-payment checks
			$.ajax({
		  	type: 'POST',
		  	url: ajaxUrl +'order/preprocess', 
		  	data: $("#secure_payment_form").serialize(),
		  	complete: function(response) {				
					$("#secure_payment_form").submit();	
		  	}
			});
				
		});		
		
		
		
	} else {
		$("#secure_payment_form").submit();
	}	
			
}
