/**
 * FILENAME: recommendations.js
 * AUTHOR: Ashley Barrett (ashley.barrett@group.co.uk)
 * CREATED: 04/05/2010
 * COMMENTS: The general javascript file for recommendations area of the Loanfinder website 
 * UPDATE: Ashley Barrett (08/08/2010) Added in js to allow for the count down timer to appear for first rec'ers
 */
$(function(){
	
	var staticPath = 'http://static.loanfinder.co.uk/images/recommendations/';
	
	/**
	 * Logic for check to see if a username exists when a customer wants to update.
	 * */
	if($("input[name=oldPass]").length > 0){
		/**
		 * Then the customer enters some text into the new username box check to see if it 
		 * exists and is of correct type.
		 * */
		$("input[name=username]").keyup(function(){
			$(this).checkUsername();
		});
		
		/**
		 * Check the entry into the new password input.
		 * */
		$("input[name=newPass]").keyup(function(){
			$(this).checkNewPassword();
		});
		
		/**
		 * Check the entry into the confirm new password input.
		 * */
		$("input[name=confirmNewPass]").keyup(function(){
			$(this).checkConfirmPass();
		});
	}
	
	$.fn.checkUsername = function(){
		/**
		 * Remove anything that may already be being displaied.
		 * */
		$(".noticeUsername").html('');
		
		var val = $("input[name=username]").val();
		var msg;
		var content

		if(val.length == 0){
			content = 'No spaces please';
		}
		else if(((val.length < 8) || (val.length > 15))&&(val.search('^[a-zA-Z0-9]+$') == -1)){
			msg = '8 to 15 characters with letters and numbers.';
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
			
		}
		else if((val.length < 8) || (val.length > 15)){
			msg = 'Must be between 8 and 15 characters long.';
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
			
		}
		else if(val.search('^[a-zA-Z0-9]+$') == -1){
			msg = 'Letters and numbers only please.';
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
		}
		else {
			/**
			 * We know that the username is in the correct format, now check to see if its free.
			 * */
			$.ajax({
				url : '/ajax/checkUsername/',
				data : 'username=' + val,
				dataType : 'json',
				type : 'post',
				success : function(result){
			
					$(".notice").html('');
				
					if(result){
						/**
						 * Has the custodmer just put their own username back in?
						 * */
						if(result.IsCustomer == 1){
							msg = "That's you!";
							content = '<img src="'+staticPath+'/tick-green.gif" alt="Good entry" height="15" width="15" />' + msg;
						}
						else if(result.Exist == 0){
							msg = "That's free!";
							content = '<img src="'+staticPath+'/tick-green.gif" alt="Good entry" height="15" width="15" />' + msg;
						}
						else{
							msg = "Sorry that's taken";
							content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
						}
					}
					
					$(".noticeUsername").append(content);
				}
				
			});
		}
		
		$(".noticeUsername").append(content);
	};
	
	$.fn.checkNewPassword = function(){
		/**
		 * Remove anything that may already be being displaied.
		 * */
		$(".noticeNewPass").html('');
		
		var val = $("input[name=newPass]").val();
		var msg;
		var content

		if(val.length == 0){
			content = 'No spaces please';
		}
		else if(((val.length < 8) || (val.length > 15))&&(val.search('^[a-zA-Z0-9]+$') == -1)){
			msg = '8 to 15 characters with letters and numbers.';
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
			
		}
		else if((val.length < 8) || (val.length > 15)){
			msg = 'Must be between 8 and 15 characters long.';
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
			
		}
		else if(val.search('^[a-zA-Z0-9]+$') == -1){
			msg = 'Letters and numbers only please.';
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
		}
		else{
			msg = "That's fine!";
			content = '<img src="'+staticPath+'/tick-green.gif" alt="Good entry" height="15" width="15" />' + msg;
		}
		
		$(".noticeNewPass").html('').append(content);
		
		if($("input[name=confirmNewPass]").val().length > 0){
			$(this).checkConfirmPass();
		}	
	}
	
	$.fn.checkConfirmPass = function(){
		var val = $("input[name=confirmNewPass]").val();
		var newPass = $("input[name=newPass]").val();
		var msg;
		var content;
		
		if(val.length == 0){
			content  = '';
		}
		else if(newPass.length == 0){
			msg = "Please enter your new password above.";
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
		}
		else if(newPass != val){
			msg = "Passwords do not match.";
			content = '<img src="'+staticPath+'/cross-red.gif" alt="Bad entry" height="15" width="15" />' + msg;
		}
		else{
			msg = "Passwords match.";
			content = '<img src="'+staticPath+'/tick-green.gif" alt="Good entry" height="15" width="15" />' + msg;
		}
		$(".noticeConNewPass").html('').append(content);
	};
	
	/**
	 * Just incase we have been directed back to this page.
	 * */	
	
	if($("input[name=oldPass]").length > 0){
		$(this).checkUsername();
		$(this).checkNewPassword();
		$(this).checkConfirmPass();
	}
	
	/**
	 * Code for the debtline pop.
	 * */
	if($("#debtLinePop").length > 0){
	
		var showDL = true;
		//don't show the popup for ie6
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
			showDL = false;
		}
				
		if (showDL) {
			$("#debtLinePop").jqm();
			$("#debtLinePop").jqmShow();
			$(".debtlineClose").click(function(){
				$("#debtLinePop").jqmHide();
				return false;
			});
		}
		
	}
	
	/**
	 * Code for the credit xtra pop.
	 * */
	if($("#cxPop").length > 0){
	
		var showCX = true;
		//don't show the popup for ie6
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
			showCX = false;
		}
		
		if (showCX) {
			$("#cxPop").jqm();
			$("#cxPop").jqmShow();						
			$(".cxClose").click(function(){
				$("#cxPop").jqmHide(); 
				return false;
			});
		}
		
	}
	
	/* Service Area */
	if($("form.service").length > 0){
		
		if($("#bankAccounts")){
			$("label.bankAccounts").text('Type in the box below and click on the names that appear to tell us which banks you have accounts with.');
		}
		
		if($("#lenders")){
			$("label.lenders").text("Type in the box below and click on the names that appear to tell us about who has refused you credit.");
		}
		
		if($("#creditors")){
			$("label.creditors").text("Type in the box below and click on the names that appear to tell us about who you have credit with.");
		}
		
		if($("input[name=selectPay]:radio:checked").val() == 0){
			$("form.service .cardPay").hide();
		}else{
			$("form.service .ddPay").hide();
		};
		
		$("input[name=selectPay]").click(function(){
			if($(this).val() == 1){
				$("form.service div.ddPay").slideUp("slow",function(){
					$("form.service div.cardPay").slideDown("slow");
					
					$("form.service .ddPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
						//$(this).parent().css("background-color","#fff");
						//$(this).parent().css("border","none");
						$(this).parent().find("span.err").text('');
					});
				});
			}else{
				$("form.service div.cardPay").slideUp("slow",function(){
					$("form.service div.ddPay").slideDown("slow");
					
					$("form.service .cardPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
					});

					$("form.service div.cardPay select[name=ValidFromMonth], form.service div.cardPay select[name=ValidFromYear], form.service div.cardPay select[name=ExpiryMonth], form.service div.cardPay select[name=ExpiryYear]").val('-1');
				
				});
			}	
		});
		
		// Show details for currently selected form of payment.
		$('input[name=selectPay][checked]').click();
		
		/* Validation class highlights. */
		$("form.service .formSection .formElementSeperator").each(function(i,val) {

			var objLabel = $(this).find('label');

			if (objLabel != null && objLabel.hasClass('err'))
			{
				$(this).find('input, select').each(function(intIndex, objElement) {
					
					if (objElement.tagName == 'INPUT')
					{					
						var strElementType = $(objElement).attr('type');
						
						switch (strElementType)
						{
							case 'text':
							case 'password':	
								$(objElement).removeClass('formTextArea').addClass('formTextAreaError');
							break;	
							
							case 'select':
								$(objElement).removeClass('formDropDown').addClass('formDropDownError');
							break;	
				
							case 'radio':
								$(objElement).parent().find('i').removeClass('yesNoBlue').addClass('yesNoRed');
							break;	
						}
					}
					else
					{
						if ($(objElement).hasClass('formDropDownSmall')) 
						{
							$(objElement).removeClass('formDropDownSmall').addClass('formDropDownSmallError');
						}
						else 
						{
							$(objElement).removeClass('formDropDown').addClass('formDropDownError');
						}
					}
				});
			}
		});
		
		$('#EmploymentStatus').change(function() {
			
			if ($(this).val() in {'2':'', '6':'', '7':'', '12':''})
			{
				$('#WorkOver16Hours').parent().hide();
				$('#WorkOver16Hours[value=1]').attr('checked', true);
			}
			else
			{
				$('#WorkOver16Hours').parent().show();
				$('#WorkOver16Hours').attr('checked', false);
			}
			
			if ($(this).val() in {'6':'', '7':'', '12':''})
			{
				$('#Occupation').parent().hide();
				$('#OccupationStartDateYear').parent().hide();
			}
			else
			{
				$('#Occupation').parent().show();
				$('#OccupationStartDateYear').parent().show();	
			}
		});
		
		$('#EmploymentStatus').change();
	}
	
	$('#buttonUnsecuredLoanApplyNow').click(function() {
		
		var blnResult = true;
		
		$('#frmUnsecuredLoanApply INPUT:checkbox').each(function(intIndex) {
			if ($(this).attr('checked') == false) {
				blnResult = false;
				
				var strPrefix = (($(this).attr('class') == 'UnsecuredLoanCheckMustHave') ? 'You must' : "You can't have");
				var strCheckText = $('#checkListItem' + intIndex).find('DIV').text();
				
				$('#checkListItemError' + intIndex).html(strPrefix + ' ' + strCheckText + '.');
			}
			else {
				$('#checkListItemError' + intIndex).html('');
			}
		});
		
		if (blnResult) {
			
			$('#divUnsecuredLoanCheckWarning').html('');
			
			var strApplyURL = $('#frmApplyNow').attr('action');
			window.open(strApplyURL);
		}
		
		// Important: We must stop the form from submitting.
		return false;
	});
	
	$.fn.countdownFirstRec = function(countdown){	
		if(countdown != 0){
			if(countdown == 5){
				$("#countDownTimer #countDownDisplay p").html("<strong>Almost there...</strong>");
			}
			
			countdown = countdown - 1;
			t = setTimeout("$('html').countdownFirstRec("+countdown+");",1000);
		}else{
			$("#countDownTimer").jqmHide();
			var url = 'https://secure.loanfinder.co.uk/recommendations/?noPop=1#unsecured';
			window.location = url;
		}	
	}
	
	/** 
	 * If this div exists then we know that this customer is on there first rec. 
	 * Display the modal pop for 70 seconds (1 min 10 secs) as this will give us enough time to
	 * rec the customer behind the secens. 
	 * */
	if($("#countDownTimer").length > 0){
		/* Enable the pop. */
		/*$("#countDownTimer").jqm({'modal' : true});*/
		/*$("#countDownTimer").jqmShow();*/
		
		/* The number of secs to display the pop for */
		/*var countdown = 70;*/
		/*$("html").countdownFirstRec(countdown);*/
	}
	
	// Open up sponsored result links in a new window (if possible).
	$('form.frmSponsoredResult').submit(function() {
		window.open($(this).attr('action'));
		return false;
	});
	
	$(".sponsored .leftPane a").click(function(){
		window.open($(this).attr("href"));
		return false;
	});
});
