/**
 * FILENAME: lenders.js
 * AUTHOR: Ashley Barrett (ashley.barrett@group.co.uk)
 * CREATED: 23/08/2010
 * COMMENTS: The B side for the lenders AB test.
 * UPDATE: Ashley Barrett (14/09/2010) New ajax panel to make ajax calls to see if we have lenders for each panel to show
 * UPDATE: Crandy (07/10/2010) New function to get the journey popup for lender page visitors
 */
$(function(){
	
	$("a#DLRedirA").click(function(){
		window.open($("input#DLRedirURL").val(), "_blank", "width=1100, height=900, scrollbars=1, top=25, left=110");
		$("a.PBLCrossSaleModalClose").click();
		return false;
	});
	
	if($(".PBLCrossSaleModal").length){
		setTimeout (function (){$(".PBLCrossSaleModal").css("background", "#fff");}, 5000);
	}
	
	$(".lendersCrossSaleSubmit").submit(function(){
		if($("input."+$(this).attr('lender')).val() == ''){
			$("input."+$(this).attr('lender')).css('background-color', '#FFC0CB');
			return false;
		}
	});
	
	$(".PBLEligibilityUpdate").hide();
	
	$("a.PBLCrossSaleModalClose").click(function(){
		$(".PBLCrossSaleModalPage").hide();
	});
	
	if($("#FLMQModalFlag").length){
		$("#FLMQModalPage").show();
	}
	
	if($("#DLModalFlag").length){
		$("#DLModalPage").show();
	}

	if($("#closeContainer").length){
		window.parent.location = "https://secure.loanfinder.co.uk/lenders";
	}
	
	$("a.PBLApplyLink").click(function(){
		sponsor = $(this).attr('lender');

		if($("input#"+sponsor+"Eligibility").val() == 'Eligible_Need_More_Data'){
			$("a#"+sponsor+"Link").slideUp("slow");
			$("."+sponsor+"EligibilityUpdate").slideDown("slow");
		}else{
			$("#"+sponsor+"ModalPage").show();
		}

		return false;
	});
	
	
	var lendersSearched = new Array();
	
	/**
	 * A function to get the content for a given panel. It will make a ajax call every 'n' number of seconds.
	 */
	$.fn.getPanelContent = function(panelName){
		/* Every 'n' seconds we should try. */
		var runEvery = 10000;
		/* Make the ajax call to try and get the panel content. */
		$.ajax({
			type:           'GET',
			url:            '/ajax/lenders/getPanelContent.php',
			data:			'panelName='+panelName,
			cache:          false,
			dataType: 		'html',
			success:        function(panelContent){

								/* OK? */
								if((panelContent != 'FAIL')&&(panelContent != 'NONE')){
									
									$('#'+panelName)
									.find('.content')
									.fadeOut('slow', function(){
										/* Remove the existing content. */
										$(this)
										.children()
										.remove();
										
										/* Fade in the new content. */
										$('#'+panelName)
										.find(".content")
										.append(panelContent)
										.fadeIn('slow');
										
										/* Reset the H2 value. */
										$('#'+panelName)
										.find('.top .heading h2')
										.fadeOut('slow',function(){
											$(this)
											.html(lendersSearched[panelName])
											.fadeIn('slow')
										});
										
										/* Bind the new click event. */
										$('#'+panelName)
										.find(".content .rightPane .interaction .popInit")
										.click(function(){
											
											var selector = $('#'+panelName)
														   .find('.content');
													
											$(selector)
											.find(".lenderResponse")
											.jqm({'modal' : true});
											
											$(selector)
											.find(".lenderResponse")
											.jqmShow();
											
											$(selector)
											.find(".responseWindow")
											.click(function(){
												$(this).jqmHide();
											});
										
											return false;
										});
										
									});
									
									$(this).showJourneyPopup();
									
								}else if(panelContent == 'NONE'){
									setTimeout('$(this).getPanelContent(\''+ panelName +'\');',runEvery);
								}else{
									/* If there is an error with the request. */
									var errorContent = '<div class="noRecs">' + 
														'<p>Sorry an unexpected error has occurred.</p>' + 
														'<p class="lenderRefresh"><a href="/lenders/">Refresh page</a></p>'+
														'</div>'
									
									$('#'+panelName)
									.find('.content')
									.fadeOut('slow', function(){
										/* Remove the existing content. */
										$(this)
										.children()
										.remove();
										
										$('#'+panelName)
										.find(".content")
										.append(errorContent)
										.fadeIn('slow');
									});					
								}
							}
		});
	}
	
	$.fn.showJourneyPopup = function(){
		
		var showCX = true;
		//don't show the popup for ie6
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
			showCX = false;
		}
		
		if (showCX) {
			if(($("#journeyPop").length > 0) && ($("#journeyPop .awaiting").length > 0)){
			
				$.ajax({
					type:           'GET',
					url:            '/ajax/lenders/getJourneyPopup.php',
					data:			'',
					cache:          false,
					dataType: 		'html',
					success:        function(journeyContent){
						
						//populate content
						$("#journeyPop").html(journeyContent);
						
						//show popup
						$("#journeyPop").jqm();
						$("#journeyPop").jqmShow();					
						$("#journeyClose").click(function(){
							$("#journeyPop").jqmHide();
							return false;
						});
						
						//remove focus from the button
						$("#journeyClose").blur();
						
						//scroll the page to the top
						$("html").scrollTop(0);
					}
					
				});
				
			}
		}
	}
	
	var showPops = true;
	
	if ($.browser.msie && $.browser.version < 7) {
		showPops = false;
	}	
	
	if(showPops){
		/*$("#unsecuredPopInit").click(function(){
			$("#unsecured").jqm({'modal' : true});
			$("#unsecured").jqmShow();
			return false;
		});*/

		/*$("#paydayPopInit").click(function(){
			$("#payday").jqm({'modal' : true});
			$("#payday").jqmShow();
			return false;
		});

		$("#lendersClosePayday").click(function(){
			$("#payday").jqmHide(); 
			return false;
		});*/
		
		$(".popInit").click(function(){
			
			var selector = $(this).parent().parent().parent().parent();
			
			/*var id = $($(selector).attr("id"));*/
			
			$(selector).find(".lenderResponse:first").jqm({'modal' : true});
			$(selector).find(".lenderResponse:first").jqmShow();
			
			
			$(".responseWindow, .popClose, .lendersClose").click(function(){
				$(this).jqmHide();
				//$(".lenderResponse").jqmHide();
			});
			


			return false;
		});
		
		$(".popInitLendersPage").click(function(){

			$(".lenderResponse").jqm({'modal' : true});
			$(".lenderResponse").jqmShow();
			
			$(".popClose").click(function(){
				$(".lenderResponse").jqmHide();
				return false;
			});		
			
			return false;
		});
		
		//JavaScript to initilise LightBox on Lender Review Pages
		$("#applyingImages a").lightBox();
		$("#repayingImages a").lightBox();
	}
	
	$('#buttonApplyNow').click(function() {
			
		var strApplyURL = $('#frmApplyNow').attr('action');
		window.open(strApplyURL);
		// Important: We must stop the form from submitting.
		return false;
		
	});

	
	$('#buttonApplyNowNoWindow').click(function() {
		
		var strApplyURL = $('#frmApplyNow').attr('action');
		window.location(strApplyURL);
		// Important: We must stop the form from submitting.
		return false;
		
	});
	
	//is there a rec?
	if($(".lenderSection").length > 0){
		var recs = true;
		$(".lenderSection").each(function(){
			var id = $(this).attr("id");
			if((id.length > 0)&&($(this).find('.content .searchable').length > 0)){
				recs = false;
			}
		});
		if (recs == true){
			$(this).showJourneyPopup();
		}
	}
	
	/* Lets find all of the panels that have no lenders currently. */
	if($(".lenderSection").length > 0){
		$(".lenderSection").each(function(){
			var id = $(this).attr("id");
	
			if((id.length > 0)&&($(this).find('.content .searchable').length > 0)){
	
				var noRecs = $(this)
							 .find(".content .noRecs");	
	
				/* Remove the refresh link. */
				$(noRecs)
				.find(".lenderRefresh")
				.remove()
									 
				/* Take a copy of the rest of the inner content. */
				var orginalContent = $(noRecs)
									 .html();					 
					
				/* Get the value of h2 and change it. */					 
				var searching = $(this).find('.top .heading h2').html();
				
				/* Save to be used later. */
				lendersSearched[id] = searching
				
				searching = searching.replace('searched','');
				$(this).find('.top .heading h2').html('Please wait....');
				
				/* Remove the rest of the old content. */
				$(noRecs)
				.remove();
				
				/* Create the new content and append the old message into the right pane. */
				var newContent = "<div class=\"leftPane\">" +
									"<img src=\"/images/recommendations/ajax-loading-lenders.gif\" />" +
									"<div class=\"smallSpace\">&nbsp;</div>" + 
								"</div>" + 
								"<div class=\"rightPane\">" +
									"<h2>Searching "+ $.trim(searching) +"</h2>" +
									orginalContent +
								"</div>";
				
				/* If IE6... */
				if ($.browser.msie && $.browser.version.substr(0,1) == 6) {
					newContent += "<div class=\"spaceSmall\">&nbsp;</div>";
				}
				
				$(this)
				.find(".content")
				.html(newContent);
				
				/* Get the panel content. */
				$(this).getPanelContent(id);
			}
		});
		
	}
});




