
	
	//Global scope variable
	var globalScope = this;

	////
	//Structures to hold information on each product
	//percentageValue: % of the maxLoan value that this product represents
	//active: indicates if bar should be shown or not
	//loanValue: value of loan product
	//intRate: interest rate of product
	//fees: any product fees that apply
	////
	var bar1 = {percentageValue:0,active:false,loanVal:950000,productName:"",lenderName:"",intRate:8.25,loanTerm:360,appFees:60,appFeeFlag:false,ongoingFee:5};
	var bar2 = {percentageValue:0,active:false,loanVal:400000,productName:"",lenderName:"",intRate:7,loanTerm:360,appFees:60,appFeeFlag:false,ongoingFee:15};
	var bar3 = {percentageValue:0,active:false,loanVal:30000,productName:"",lenderName:"",intRate:6.25,loanTerm:360,appFees:60,appFeeFlag:false,ongoingFee:0};
	var bar4 = {percentageValue:0,active:false,loanVal:200000,productName:"",lenderName:"",intRate:5.67,loanTerm:360,appFees:60,appFeeFlag:false,ongoingFee:8};
	var bar5 = {percentageValue:0,active:false,loanVal:100000,productName:"",lenderName:"",intRate:10.5,loanTerm:360,appFees:60,appFeeFlag:false,ongoingFee:20};

	//Error counters for each of the tabs in loan pop-up up form
	//var tabErrors = {"income-tab-one":0,"income-tab-two":0,"expense-tab-one":0,"expense-tab-two":0};
	var tabElementErrors = {
			"RentalIncome1":false,
			"FamilyAllowance1":false,
			"CreditCard1":false,
			"CarLoan1":false,
			"OtherLoan1":false,
			"MortgagePayment1":false,
			"RentalExpense1":false,
			"RentalIncome2":false,
			"FamilyAllowance2":false,
			"CreditCard2":false,
			"CarLoan2":false,
			"OtherLoan2":false,
			"MortgagePayment2":false,
			"RentalExpense2":false
	};

	
	//The maximun loan value displayed on the y-axis
	var chartMax = 0;
	//The hight max loan value based on product selection
	var highestMaxLoanVal = 0;
	//Array of all products to be displayed in chart
	var products; //= [bar1,bar2,bar3,bar4,bar5];
	//Array to hold visibility state of each repayment box
	var repaymentsVisibility = [false,false,false,false,false];
		//[false,false,false,false,false];
	var barColors = ["#b5df71","#b5df71","#b5df71","#b5df71","#b5df71"];
		
	//Default family profile
	var familyProfile = "";
	//Default loan profile
	var loanProfile="";
	//Default employment profile
	var empProfile="";
	//Default state profile
	var stateProfile="";
	
	//Error messages for chart
	var errorAlert = "";
	
	//----------------------Applicant 1--------------------------------//
    
	
    //Incomes
    
    var investmentIncome1 =
    	 '<li><label  name="investment-income-one">Investment Income</label>'+ 
         '<div class="income-expense-item">'+
         '<input class="required number income-one" name="Investment1" value="0" type="text" id="Investment1"/>'+
         '<select class="required income-one" name="Investment1-Frequency">'+
         '<option value="monthly">Monthly</option>'+
         '<option value="fortnightly">Fortnightly</option>'+
         '<option value="weekly">Weekly</option>'+        
         '</select>'+
         '</div>'+
         '</li>';
    
	var rentalIncome1 = 
          '<li><label  name="rental-income-one">Rental Income</label>'+ 
          '<div class="income-expense-item">'+
          '<input class="required number income-one" name="NewRent1" value="0" type="text" id="NewRent1"/>'+
          '<select class="required income-one" name="NewRent1-Frequency">'+
          '<option value="monthly">Monthly</option>'+
          '<option value="fortnightly">Fortnightly</option>'+
          '<option value="weekly">Weekly</option>'+        
          '</select>'+
          '</div>'+
          '</li>';

    var familyAllowance1 =  
    '<li><label  name="family-allowance-one">Family Allowance</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number income-one" name="FamilyAllowance1" value="0" type="text" id="FamilyAllowance1" />'+
    '<select class="required income-one" name="FamilyAllowance1-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+      
    '</select>'+
    '</div>'+
    '</li>';
    
    //Expenses
    var carLoan1 =  
    '<li><label  name="car-loan-one">Car Loan Repayment</label>'+
    '<div class="income-expense-item">'+
    '<input class="required number expense-one" name="CarLoan1" value="0" type="text" id="CarLoan1" />'+
    '<select class="required expense-one" name="CarLoan1-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+         
    '</select>'+
    '</div>'+
    '</li>';

    var creditCard1 =  
    '<li><label  name="credit-card-one">Credit Card Limit(Annual)</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-one" name="CreditCard1" value="0" type="text" id="CreditCard1" />'+
    '<select class="required expense-one"  style="display:none" name="CreditCard1-Frequency">'+
    '<option value="annual" selected>Annual</option>'+  
    '</select>'+
    '</div>'+
    '</li>';

    var mortgageRepayment1 =  
    '<li><label  name="mortgage-repayment-one">Mortgage Repayment</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-one" name="MortgageRepayment1" value="0" type="text" id="MortgageRepayment1" />'+
    '<select class="required expense-one" name="MortgageRepayment1-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+        
    '</select>'+
    '</div>'+
    '</li>';

    var otherLoan1 = 
    '<li><label  name="other-loan-one">Other Loan Repayment</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-one" name="OtherLoan1" value="0" type="text" id="OtherLoan1" />'+
    '<select class="required expense-one" name="OtherLoan1-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+        
    '</select>'+
    '</div>'+
    '</li>';

    var rentalExpense1 = 
    '<li><label  name="rental-exp-one">Rent Paid</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-one" name="RentalExpense1" value="0" type="text" id="RentalExpense1" />'+
    '<select class="required expense-one" name="RentalExpense1-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+        
    '</select>'+
    '</div>'+
    '</li>';

    //----------------------Applicant 2--------------------------------//
    
    
  //Incomes
    
    var investmentIncome2 =
   	 '<li><label  name="investment-income-two">Investment Income</label>'+ 
        '<div class="income-expense-item">'+
        '<input class="required number income-two" name="Investment2" value="0" type="text" id="Investment2"/>'+
        '<select class="required income-two" name="Investment2-Frequency">'+
        '<option value="monthly">Monthly</option>'+
        '<option value="fortnightly">Fortnightly</option>'+
        '<option value="weekly">Weekly</option>'+        
        '</select>'+
        '</div>'+
        '</li>';
    
    
    var rentalIncome2 = 
          '<li><label  name="rental-income-two">Rental Income</label>'+ 
          '<div class="income-expense-item">'+
          '<input class="required number income-two" name="NewRent2" value="0" type="text" id="NewRent2"/>'+
          '<select class="required income-two" name="NewRent2-Frequency">'+
          '<option value="monthly">Monthly</option>'+
          '<option value="fortnightly">Fortnightly</option>'+
          '<option value="weekly">Weekly</option>'+        
          '</select>'+
          '</div>'+
          '</li>';

    var familyAllowance2 =  
    '<li><label  name="family-allowance-two">Family Allowance</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number income-two" name="FamilyAllowance2" value="0" type="text" id="FamilyAllowance2" />'+
    '<select class="required income-two" name="FamilyAllowance2-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+      
    '</select>'+
    '</div>'+
    '</li>';
    
    //Expenses
    var carLoan2 =  
    '<li><label  name="car-loan-two">Car Loan Repayment</label>'+
    '<div class="income-expense-item">'+
    '<input class="required number expense-two" name="CarLoan2" value="0" type="text" id="CarLoan2" />'+
    '<select class="required expense-two" name="CarLoan2-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+         
    '</select>'+
    '</div>'+
    '</li>';

    var creditCard2 =  
    '<li><label  name="credit-card-two">Credit Card Limit(Annual)</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-two" name="CreditCard2" value="0" type="text" id="CreditCard2" />'+
    '<select class="required expense-two"  style="display:none" name="CreditCard2-Frequency">'+
    '<option value="annual" selected>Annual</option>'+         
    '</select>'+
    '</div>'+
    '</li>';

    var mortgageRepayment2 =  
    '<li><label  name="mortgage-repayment-two">Mortgage Repayment</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-two" name="MortgageRepayment2" value="0" type="text" id="MortgageRepayment2" />'+
    '<select class="required expense-two" name="MortgageRepayment2-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+        
    '</select>'+
    '</div>'+
    '</li>';

    var otherLoan2 = 
    '<li><label  name="other-loan-two">Other Loan Repayment</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-two" name="OtherLoan2" value="0" type="text" id="OtherLoan2" />'+
    '<select class="required expense-two" name="OtherLoan2-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+        
    '</select>'+
    '</div>'+
    '</li>';

    var rentalExpense2 = 
    '<li><label  name="rental-exp-two">Rent Paid</label>'+ 
    '<div class="income-expense-item">'+
    '<input class="required number expense-two" name="RentalExpense2" value="0" type="text" id="RentalExpense2" />'+
    '<select class="required expense-two" name="RentalExpense2-Frequency">'+
    '<option value="monthly">Monthly</option>'+
    '<option value="fortnightly">Fortnightly</option>'+
    '<option value="weekly">Weekly</option>'+        
    '</select>'+
    '</div>'+
    '</li>';

    //-----------------Mapping for states and family profiles------------------------//
    var state = {"loan-option-wa":"wa","loan-option-nt":"nt","loan-option-qld":"qld",
                            "loan-option-sa":"sa","loan-option-nsw":"nsw","loan-option-vic":"vic",
                                  "loan-option-tas":"tas","loan-option-act":"act"};
    
    var family = {"single":1,"couple":2,"singlewkids":3,"couplewkids":4};

    var situationImgPath = "images/tools/myloanoptions/situation/";

    
    
    /*************Functions*************/
	

	////
	//This function sets the maximum loan value on the chart
	//as well as calculating and setting the increments on the chart
	////
	function setChartAxisValues(){

		var _increments = 0;
		var _maxFontSize = 0;
		//Force update of highest max loan value
		setHighestMaxLoanValue();	
		
		//Set increments based on the chartMax
		if(highestMaxLoanVal >10000 && highestMaxLoanVal<=200000){
			chartMax = 250000;
			_increments = 20; 
		}
		else if(highestMaxLoanVal >200000 && highestMaxLoanVal<=450000){
			chartMax = 500000;
			_increments = 10;
		}
		else if(highestMaxLoanVal >450000 && highestMaxLoanVal<=950000){
			chartMax = 1000000;
			_increments = 5;
		}
		else if(highestMaxLoanVal >950000 && highestMaxLoanVal<=1200000){
			chartMax = 1250000;
			_increments = 4;
		}
		else{
			if(highestMaxLoanVal < 10000 || highestMaxLoanVal > 1200000){
				
				errorAlert = "Thanks for the information you've supplied."+
					" We need just a few more details from you,"+
						" please contact us as soon as you can and we'll walk you through your loan options.";
			}
			return false;
		}

		//Add a 'tick' on the y-axis for every 50K
		var numPixels = 0;
		var offset = 50;
		var count = 1;


		//Empty the y-axis div
		$(".yaxis").empty();
		//Attach the y-scale div
		$(".yaxis").append("<div class=\"yscale\"><div>");
		

		while (numPixels<=500){

			//Add the 'tick'
			$(".yscale").append("<div class=\"tick"+count+"\"></div>");
			
			//Style the tick and set positioning
			$(".tick"+count).css("position","absolute");
			$(".tick"+count).css("height","1px");
			$(".tick"+count).css("width","6px");
			$(".tick"+count).css("top",(numPixels)+"px");
			$(".tick"+count).css("left","34px");
			$(".tick"+count).css("background-color","#8f8f8f");
			//$(".tick"+count).css("z-index","1");
			
			var tickValue = (chartMax-(50000*(count-1)))/1000;
			var suffix = "k";
			if(tickValue >= 1000){
				tickValue = (tickValue/1000).toFixed(2);
				suffix = "m";
			}
			
			//Add the value for each 'tick'
			$(".yaxis").append("<div class=\"grad"+count+"\"><span class=\"grad"+count+"text\">$"
					+tickValue+suffix+"</span></div>"); //Each step is worth 50K

			//Style the value div and set positioning
			$(".grad"+count).css("position","absolute");
			$(".grad"+count).css("height",0.5*(_increments*5)+"px");
			$(".grad"+count).css("width","50px");
			$(".grad"+count).css("left","10px");
			$(".grad"+count).css("top",(offset+numPixels-0.25*(_increments*5)));
			$(".grad"+count).css("text-align","center");
			//$(".grad"+count).css("border","1px solid #8f8f8f");
			//$(".grad"+count+"text").css("top","5%");
			
			//Move down another 50K on the scale.
			numPixels += _increments*5;
			count++;
		}
		
		//Set size of font in value <span> 
		for(i=1;i<count;i++){
			
			if(i==1){
				_maxFontSize = resizeFont(".grad"+(i)+"text",".grad"+(i));
			}
			else{
				$(".grad"+(i)+"text").css('font-size',_maxFontSize);
			}
			//After resizing font in span, position it to middle of label div
			var emptySpace = $(".grad"+i).height()- $(".grad"+i+"text").height();
			var topPadding = 0.5*emptySpace;
			$(".grad"+i+"text").css("top",topPadding);
			$(".grad"+i+"text").css("position","relative");
			
			
		}

		return true;
		
	}

	function prepareLoanBars(){


		var barIndex = 1;
		//remove all labels
		$(".labels").empty();
	
		for (i=0;i<5;i++){

			//Remove the bars before we set them up again
			$(".bar"+(i+1)).empty();
			//$(".bars").append("<div class=\"bar"+(i+1)+"\"></div>");
			
			if(products[i].active == true && products[i].loanVal > 0){

				var loanValRounded = products[i].loanVal.toNearest(10000);
				var ratio = loanValRounded/chartMax;
				var heightPX = (ratio*500);
				//alert("Product: "+barIndex+" has value of "+products[i].loanVal+", rounded to "+loanValRounded+
				//		" and a height in PX of "+heightPX);

				//Set up loan bar	
				$(".bar"+barIndex).append("<div id=\""+barIndex+"\" \" class=\"bar ui-widget-content\"></div>");
				$("#"+barIndex).css('height',heightPX-1);
				$("#"+barIndex).css('top',500-heightPX);
				$("#"+barIndex).css('background',barColors[i]);
				$("#"+barIndex).css('border','1px solid '+barColors[i]);
				$("#"+barIndex).css('border-bottom','0px');
				//alert("loan bar setup");

				//Set up loan bar label
				var lenderLogo = "";
				if (products[i].lenderLogo != "" || 
						products[i].lenderLogo != "" || 
						products[i].lenderLogo != undefined) {
					
					lenderLogo = "<img src='"+ products[i].lenderLogo +"' alt='"+ products[i].lenderName +"' />";
				}
				
				$(".labels").append("<div class=\"label"+(i+1)+"\"></div>");
				$(".label"+barIndex).html(lenderLogo);
				//alert("loan bar label setup");
				
				//Show the bar and it's associated label
				$(".label"+barIndex).show();
				//alert("bar and associated lable showing");
				
				//$(".label"+barIndex).show('slide',{},'slow',null);
				//13/9/2011 commented out $("#"+barIndex).show('puff',{},'slow',null);
				$("#"+barIndex).show();
				//alert("Show the bar and it's associated label");
			
				//Attach on-click listener to pop-up dialog box
				//$(".bar"+barIndex).live("click", function(event) {
					//loadMyDetailsDialog(event.target.id);
				//});
				
				barIndex++;
			}			
		}

	}

	////
	//This function calculates the highest max loan value from product panel
	////
	function setHighestMaxLoanValue(){

		var _highestMaxLoan = 0;
		
		for (i=0;i<5;i++){

			if(products[i].active == true){
				//alert("product["+i+"]:active "+products[i].active+" product:loanVal "+products[i].loanVal);
				if(products[i].loanVal > _highestMaxLoan) _highestMaxLoan=products[i].loanVal;
			}			
		}

		//Update global variable holding highest max loan value
		highestMaxLoanVal = _highestMaxLoan;
	} 

	
	////
	//This function calculates requisite loan amount based
	//on slider position
	//@param chartMax The maximum loan value as shown on the chart
	//@param sliderPos The position of the slider, in pixels
	//@return reqLoanAmount The amount that is being borrowed
	////
	function getLoanAmountFromSlider(chartMax,sliderPos){

		var sliderRatio = 0;
		var reqLoanAmount = 0;
		
		sliderRatio = (500-sliderPos)/500; //hard coded based on size of chart in px.
		reqLoanAmount = sliderRatio*chartMax;

		return parseFloat(reqLoanAmount.toFixed(0));
		 
	}

	////
	//This function computes repayments (if applicabale for each loan
	//product and updates the repayments divs.
	//@param sliderPos
	////
	function updateRepayments(sliderPos){

		
		var repayIndex = 1;
		//An array to hold the repayment amount for each product
		var repayValues = [];  //each element is an array [repayIndex,repayValue]
		
		for (i=0;i<5;i++){

			if(products[i].active == true && products[i].loanVal > 0){
				
				var loanValRounded = products[i].loanVal.toNearest(10000);
				var ratio = loanValRounded/chartMax;

				//Height of Bar in px from X Axis
				var barHeightXAxis = (ratio*500);
				//Height of Slider in px from X Axis
				var sliderHeightXAxis = 500-sliderPos;
				//Amount being borrowed
				var amountBorrowed = getLoanAmountFromSlider(chartMax,sliderPos);
				
				//If slider is intersecting with product bar
				//show repayments, else hide repayments
				if(sliderHeightXAxis <= barHeightXAxis){

					//calculate repayments
					var repaymentAmount = calculateRepayment(i,amountBorrowed);
					
					$("#repay"+repayIndex+"value").html("$"+repaymentAmount+"");
					//Update the stored value of this repayment so we can rank it.
					repayValues.push([repayIndex,repaymentAmount]);

					if(!repaymentsVisibility[repayIndex]){
						
						//13/9/2011 commented out
						//$("#repay"+repayIndex).show('puff',{},'slow',null);
						$("#repay"+repayIndex).show();
						repaymentsVisibility[repayIndex] = true;

					}
				}
				else{
					
					if(repaymentsVisibility[repayIndex]){
					
						//13/9/2011 commented out
						//$("#repay"+repayIndex).hide('puff',{},'slow',null);
						$("#repay"+repayIndex).hide();
						$("#repay"+repayIndex+"value").html();
						repaymentsVisibility[repayIndex] = false;
					}
				} //end else

				repayIndex++;
	
			} //end if			

		} //end for	

		updateRepaymentRankings(repayValues);
		
	}//end method

	////
	//Function updates rankings on the repayments
	//@param repaymentValues Array of repayment indicies/values
	////
	function updateRepaymentRankings(repaymentValues){

		//define a sorting function to use
		var sortingFunction = function(a,b) {
			if(a[1] <= b[1]){
				return -1;
			}
			else{
				return 1;
			}
		}

		//Sort the repayments
		repaymentValues.sort(sortingFunction);

		for (i=0;i<repaymentValues.length;i++){
			$("#repay"+repaymentValues[i][0]+"rank").html(i+1);
		}			
	}
	
	////
	//Function to calculate repayments for a given product
	//@param pid product id
	//@param loanAmount Amount being borrowed.
	////
	function calculateRepayment(pid,loanAmount){

		//alert("PID "+pid+" loanAmount"+loanAmount);
		var princ = 0;
		if(products[i].appFeeFlag){
			princ = loanAmount + products[i].appFees;
		}
		else{
			princ = loanAmount;
		}
		var term  = products[i].loanTerm;
		var intr   = products[i].intRate / 1200;
		//alert("princ "+princ+" term: "+term+"intr: "+intr+"ongoing fee "+products[i].ongoingFee);
		var monthlyPayment = princ * intr / (1 - (Math.pow(1/(1 + intr), term))) + (products[i].ongoingFee)/12;
		//alert("monthly pay "+monthlyPayment.toFixed(2));
		return monthlyPayment.toFixed(0);
		
		// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
	}
	
	////
	//Utility function to round to nearest 100 or 1000 for example.
	////
	Number.prototype.toNearest = function(num) { // num is an exponent of 10
         return Math.round(this/num)*num;
  	};

  	////
  	//Utility to resize a font to fit in div
  	////
  	function resizeFont(spanName,parentName,maxSize){

  		var spanWidth = $(spanName).width();
  		var targetWidth = $(parentName).width();

  		var spanHeight = $(spanName).height();
  		var targetHeight = $(parentName).height();
  		
  	    while(spanWidth > targetWidth || spanHeight > targetHeight){
  	       var currentFontSize = $(spanName).css('font-size');
  	       var currentFontSizeNum = parseFloat(currentFontSize, 10);
  	       var newFontSize = currentFontSizeNum*0.95;
  	       $(spanName).css('font-size', newFontSize);
  	       spanWidth = $(spanName).width();
  	       spanHeight = $(spanName).height();
  	    }

  		return newFontSize;		
  	 }

	 ////
	 //Utility to strip \r\n characters from a string
	 ////
	function removeLF(dataStr) {
        return dataStr.replace(/(\r\n|[\r\n])/g, "");
    }
	 

	////
	//Populate bar information from CAP
	////
	function populateBarInfo(data){

		//alert("data --> "+data);
		
		//reset all products to inactive
		for(i=0;i<5;i++){
			products[i].active = false;
		}	
		
		//Check for error message before beginning product extraction
		var errorAndProducts = data.split("~");
		//alert("errorAndProducts --> "+errorAndProducts);
		var error = errorAndProducts[0];
		//alert("error --> "+error);
		var productList = errorAndProducts[1];
		//alert("productList --> "+productList);
		
		var errorMessage = error.split(":")[1];
		//alert("error --> "+error);
		
		if(errorMessage != null && errorMessage != "" && errorMessage != undefined){
			
			errorAlert = errorMessage;
			return false;
		}
		
		//Each product
		var info = productList.split("|");
		//alert("info --> "+info);
		
		for(i=0;i<info.length;i++){

			if((info[i]).trim() != ""){
				//Activate Product
				//alert(products[0].active);
				products[i].active = true;
				
				//All the key:val pairs for product
				var keyValPairs = info[i].split(",");
	
				for(j=0;j<keyValPairs.length;j++){
	
					//Each Key, Val pair individually
					var singleKeyValPair = keyValPairs[j].split(":");
					var key = removeLF(singleKeyValPair[0]);
					var value = singleKeyValPair[1];
	
					if(key=='loanVal' || key == 'intRate' || key == 'appFees' || key =='ongoingFee' || key == 'loanTerm'){
						products[i][key] = parseFloat(value);
					}
					else{
						products[i][key] = value;
					}
					//alert("Setting product "+i+" key: "+key+" to value: "+value+"---->"+products[i][key]);
					
				}
			}
		}
		
		return true;	
	}
	////
	//Update slider
	////
	function updateSlider(){

		//Set slider position to amount that is required by customer
		var intendedLoan = stripNonNumericChars($('input#LoanAmount').val());
		//alert("intendedLoan: "+intendedLoan);
		//alert("chartMax: "+chartMax);
		//alert("intended Loan >= chartMax :"+(intendedLoan >= chartMax));
		
		//Otherwise, set the slider to rest on the top of highest loan bar
		if(intendedLoan >= chartMax){

			var offset = ((highestMaxLoanVal.toNearest(10000))/chartMax)*500;
			sliderPosition = 500 - offset;
			//sliderPosition = $("#slider").position().top;
		}
		else{
			var offset = (intendedLoan/chartMax)*500;
			//alert("offset: "+offset+" chartMax: "+chartMax);
			sliderPosition = 500 - offset;
			//alert("sliderPosition: "+sliderPosition);
		}
		
		updateRepayments(sliderPosition);	
		
		//////////////////Update draggable slider/////////////////////
		//Set it so slider can only be dragged along y-axis
		$("#slider").draggable({axis:'y'});
		//Restrict to chart area
		$("#slider").draggable({containment:'#containment-wrapper',scroll:false});
		//Set grid snapping. Only move in 10 pixel increments.
		var numGridSteps = chartMax/10000;
		var stepSize = (500/numGridSteps);
		//alert("stepsize: "+stepSize+" numGridSteps: "+numGridSteps);
		$("#slider").draggable({grid:[500,stepSize.toFixed(0)]});
		$("#slider").css('height',stepSize-2);
		$("#slider").css('top',sliderPosition/*0*/);

		$("#slider").draggable({
				stop: function(){
					//alert("Dragging");
					var sliderPosition = $(this).position().top;
					var loanAmount = getLoanAmountFromSlider(chartMax,sliderPosition);
					
					//Set loan amount to the amount in the slider
					$("input#LoanAmount").val(loanAmount);
					
					var suffix = "";
					if(loanAmount < 1000000){
						loanAmount = loanAmount/1000;
						suffix = "k";
					}
					else{
						loanAmount = (loanAmount/1000000).toFixed(2);
						suffix = "m";
					}
					$("#slider-value").html("$"+loanAmount+suffix);
					updateRepayments(sliderPosition);
					//updateChart(sliderPosition);
				}});

		$("#slider").draggable({
			drag: function(){
				//alert("Dragging");
				var sliderPosition = $(this).position().top;
				var loanAmount = getLoanAmountFromSlider(chartMax,sliderPosition);
				var suffix = "";
				if(loanAmount < 1000000){
					loanAmount = loanAmount/1000;
					suffix = "k";
				}
				else{
					loanAmount = (loanAmount/1000000).toFixed(2);
					suffix = "m";
				}
				$("#slider-value").html("$"+loanAmount+suffix);
				updateRepayments(sliderPosition);
				//updateChart(sliderPosition);
			}});

		//Update slider to reflect current value
		//var sliderPosition = $("#slider").position().top;;
		
		var loanAmount = getLoanAmountFromSlider(chartMax,sliderPosition);
		//alert("loanAmount: "+loanAmount);
		
		var suffix = "";
		if(loanAmount < 1000000){
			loanAmount = loanAmount/1000;
			suffix = "k";
		}
		else{
			loanAmount = (loanAmount/1000000).toFixed(2);
			suffix = "m";
		}
		$("#slider-value").html("$"+loanAmount+suffix);
		
		
	}
	
	function updateChart(data){
		
		//populate the product info 
		if(populateBarInfo(data)){
			
			//If this function returns successfully, then do nothing - carry on.
		
		}
		else{
			
			//If this function fails, return false and exit.
			$("#loan-option-results").hide();
			return false;
		
		}
		
		//Set up y-axis of chart -- if this goes smoothly, we can show the chart
		if(setChartAxisValues()){
				
			//Prepare the loan bars
			prepareLoanBars();
			
			//Set up the slider
			//Hide the repayments boxes
			for (i=1;i<6;i++){
				if($("#repay"+i+"value").html() == "")
					$("#repay"+i).hide();
			}	
			updateSlider();
			
			$("#loan-option-results").show();
			
			return true;
		}
		else{
			$("#loan-option-results").hide();
			return false;
		}
		//$("#chart").show('slide',{},'slow',null);
		//update repayments info
		//updateRepayments(0);
	}

	////
	//Function to toggle  status
	///
	function setProfile(type,setting){
		
		if(globalScope[setting] != type){
			//Set new profile
			$("#"+type).removeClass(type+"-deselected");
			$("#"+type).addClass(type+"-selected");
			//Hide error span
			$("#"+setting+"-error").hide();
			
			//if the self-employement proflie is set to no, hide the error
			if (setting == 'empProfile' && type == 'no') {
				
				$("#"+setting+"-error-self").hide();
				
			} 
			//if the loan profile is 're-finance' then we need to hide
			//the reminder message over the slider when they adjusts their loan amount
			if(setting == 'loanProfile' && type != 'refinance'){
				
				$("#loanAmount").removeClass('loanamount-alert');
			
			}
			else if(setting == 'loanProfile' && type == 'refinance'){
				
				$("#loanAmount").addClass('loanamount-alert');
			}
			else {
				
				//Hide error span
				$("#"+setting+"-error").hide();
				
			}
			//alert("added --> #"+type+" : "+$("#"+type).attr('class'));
			if(globalScope[setting] != "" && globalScope[setting] != null){
				//revert old image
				$("#"+globalScope[setting]).removeClass(globalScope[setting]+"-selected");
				$("#"+globalScope[setting]).addClass(globalScope[setting]+"-deselected");
				//alert("Removed --> #"+globalScope[setting]+" : "+$("#"+globalScope[setting]).attr('class'));
						
			}
			//update familyProfile to new type
			globalScope[setting] = type;
		}
		else{
			//Do nothing
		}
		
	}

	function remember( selector )
	{
		
		$(selector).each(
				
				function(){
					
						var name = $(this).attr('name');
						
						if( $.cookie( name ) ){
							$(this).val( $.cookie(name) );
							}
						
						$(this).change(function(){
							$.cookie(name, $(this).val(), { path: '/'});});
						}
		);
	}

	////
    //Function to customize the form displayed
    ////
    function customizeForm(){

    	  //Reset error checking variable on the loan pop up form
    	  tabElementErrors = {
    			"RentalIncome1":false,
    			"FamilyAllowance1":false,
    			"CreditCard1":false,
    			"CarLoan1":false,
    			"OtherLoan1":false,
    			"MortgagePayment1":false,
    			"RentalExpense1":false,
    			"RentalIncome2":false,
    			"FamilyAllowance2":false,
    			"CreditCard2":false,
    			"CarLoan2":false,
    			"OtherLoan2":false,
    			"MortgagePayment2":false,
    			"RentalExpense2":false
    	  };
    	
    	  //Remove applicant 1 dependents
		  $("#applicant1-dependents").empty();
    	
          //Remove 1st and 2nd applicant salary information
		  $("#applicant1-salary").empty();
		  $("#applicant1-overtime").empty();
          $("#applicant2-salary").empty();
          $("#applicant2-overtime").empty();

          //Empty both applicant incomes and expense tab content
          $(".first-tab-app-one-list").empty();
          $(".second-tab-app-one-list").empty();
          
          $(".first-tab-app-two-list").empty();
          $(".second-tab-app-two-list").empty();

          //Set the situation image
          var situationImage = situationImgPath+state[stateProfile]+"-"+family[familyProfile]+".png";
          $("#situation-image").attr("src",situationImage);
          
          //Set the state on the loan pop-up form
          $("#LoanState").val(state[stateProfile]);
          
          //Set the amount being borrowed
          
          //Check to see if 1 or 2 applicants are required
          if(familyProfile == "single" || familyProfile=="singlewkids"){

                //Hide second applicant
                $("#applicant2").hide();

                //Set up applicant one income and expenses
                
                if(familyProfile == "single"){
                	
                      setUpApplicant(1,false);
                }
                else if(familyProfile == "singlewkids"){

                      setUpApplicant(1,true);
                      
                }
                
          }
          else if(familyProfile == "couple" || familyProfile == "couplewkids"){

                      //Show second applicant
                      $("#applicant2").show();
                      
                      //Set up applicant one income and expenses
                      
                      if(familyProfile == "couple"){
                            
                            setUpApplicant(1,false);
                            setUpApplicant(2,false);
                            
                      }
                      else if(familyProfile == "couplewkids"){

                            setUpApplicant(1,true);
                            setUpApplicant(2,true);
                            
                      }

          }
         
        //Validating loan pop-up form
  		validateLoanPopupForm();
  		
    }//end of function
    
    
  //-----Set up single applicant---------//
    
    function setUpApplicant(applicantNumber,hasDependents){

          //Applicant 1
          if(applicantNumber == 1){

        	  $("#applicant1-salary").append(
                      '<input name="Salary1" value="" type="text" class="required number loan-large-field loan-large-field-dollar" />'+
                      '<select name="Salary1-Type" class="required">'+
                          '<option value="gross">Gross (Pre-Tax)</option>'+
                          '<option value="net">Net (Post-Tax)</option>'+
                      '</select>'+
                      '<select name="Salary1-Method" class="required">'+
			            '<option value="annual">Annual</option>'+
			            '<option value="monthly">Monthly</option>'+
			            '<option value="fortnightly">Fortnightly</option>'+
                      '</select>');
        	  
        	  remember('[name="Salary1"]');
        	  remember('[name="Salary1-Type"]');
        	  remember('[name="Salary1-Method"]');
        	  $("[name='Salary1']").DefaultValue("Salary");
        	  
        	  
        	  $("#applicant1-overtime").append( 
	        		'<input name="Overtime1" value="" type="text" class="required number loan-large-field loan-large-field-dollar" />'+
	                '<select name="Overtime1-Type" class="required">'+
	                    '<option value="gross">Gross (Pre-Tax)</option>'+
	                    '<option value="net">Net (Post-Tax)</option>'+
	                '</select>'+
	                '<select name="Overtime1-Method" class="required">'+
			            '<option value="annual">Annual</option>'+
			            '<option value="monthly">Monthly</option>'+
			            '<option value="fortnightly">Fortnightly</option>'+
	                '</select>');
        	  
        	  
        	  remember('[name="Overtime1"]');
        	  remember('[name="Overtime1-Type"]');
        	  remember('[name="Overtime1-Method"]');
        	  $("[name='Overtime1']").DefaultValue("Overtime");
        	  
        	  
                //Dependents
                if(hasDependents){

                      //----Dependents--------//
                      $("#applicant1-dependents").show();

                      //Add the required detail to capture dependants
                      $("#applicant1-dependents").append(
                            '<label class="loan-dependents">And the exact number dependents:</label>'+
                            '<div class="dependants-item">'+
							'<select name="Dependents1" class="required">'+
							'<option value="1">1</option>'+
							'<option value="2">2</option>'+
							'<option value="3">3</option>'+
							'<option value="4">4</option>'+
							'<option value="5">5</option>'+
							'<option value="6">6</option>'+    
							'<option value="7">7</option>'+
							'<option value="8">8</option>'+
							'<option value="9">9</option>'+                      
							'</select>'+
							'</div>');
                
                      remember('[name="Dependents1"]');
                      
                      //----Income------------//
                      $(".first-tab-app-one-list").empty();
                      
                      $(".first-tab-app-one-list").append(investmentIncome1);
                      
                      remember('[name="Investment1"]');
                      remember('[name="Investment1-Frequency"]');
                      
                      if(loanProfile == "fhb"){
                            //Family Allowance
                    	  $(".first-tab-app-one-list").append(familyAllowance1);
                    	  remember('[name="FamilyAllowance1"]');
                    	  remember('[name="FamilyAllowance1-Frequency"]');
                      }
                      else{
                            //Family A and Rental Income
                            $(".first-tab-app-one-list").append(familyAllowance1);
                            $(".first-tab-app-one-list").append(rentalIncome1);   
                            remember('[name="FamilyAllowance1"]');
                            remember('[name="FamilyAllowance1-Frequency"]');
                            remember('[name="NewRent1"]');
                            remember('[name="NewRent1-Frequency"]');
                      }
                     

                      //---------Expenses-----//
                      $(".second-tab-app-one-list").empty();
                      //Credit Card
                      $(".second-tab-app-one-list").append(creditCard1);
                      remember('[name="CreditCard1"]');
                      remember('[name="CreditCard1-Frequency"]');
                      //Car Loan
                      $(".second-tab-app-one-list").append(carLoan1);
                      remember('[name="CarLoan1"]');
                      remember('[name="CarLoan1-Frequency"]');
                      //Other Loan
                      $(".second-tab-app-one-list").append(otherLoan1);
                      remember('[name="OtherLoan1"]');
                      remember('[name="OtherLoan1-Frequency"]');
                      
                      //if(loanProfile == "fhb"){
                            //Rent
	                    $(".second-tab-app-one-list").append(rentalExpense1);
	                  remember('[name="RentalExpense1"]');
	                  remember('[name="RentalExpense1-Frequency"]');
                      //}
                      //else{
                            //Mortgage
                        $(".second-tab-app-one-list").append(mortgageRepayment1);
                      remember('[name="MortgageRepayment1"]');
                      remember('[name="MortgageRepayment1-Frequency"]');
                      //}
                            
                } //End applicant 1, with dependents
                
                //No Dependents
                else{

                      //-----Dependents---//
                      $("#applicant1-dependents").empty();
                      $("#applicant1-dependents").hide();
                      
                      //---Income---//
                      
                      $(".first-tab-app-one-list").empty();
                      
                      $(".first-tab-app-one-list").append(investmentIncome1);
                      remember('[name="Investment1"]');
                      remember('[name="Investment1-Frequency"]');
                      
                      //if(loanProfile != "fhb"){
                            //Rental Income
                      $(".first-tab-app-one-list").append(rentalIncome1);
                      remember('[name="NewRent1"]');
                      remember('[name="NewRent1-Frequency"]');
                     // }
                      
                            
                      //---Expenses--//
                      $(".second-tab-app-one-list").empty();
     
                      //Credit Card
                      $(".second-tab-app-one-list").append(creditCard1);
                      remember('[name="CreditCard1"]');
                      remember('[name="CreditCard1-Frequency"]');
                      //Car Loan
                      $(".second-tab-app-one-list").append(carLoan1);
                      remember('[name="CarLoan1"]');
                      remember('[name="CarLoan1-Frequency"]');
                      //Other Loan
                      $(".second-tab-app-one-list").append(otherLoan1);
                      remember('[name="OtherLoan1"]');
                      remember('[name="OtherLoan1-Frequency"]');
                      
                      //if(loanProfile == "fhb"){
                            //Rent
                      $(".second-tab-app-one-list").append(rentalExpense1);
                      remember('[name="RentalExpense1"]');
                      remember('[name="RentalExpense1-Frequency"]');
                      //}
                      //else{
                            //Mortgage
                            $(".second-tab-app-one-list").append(mortgageRepayment1);
                      remember('[name="MortgageRepayment1"]');
                      remember('[name="MortgageRepayment1-Frequency"]');
                     // } 

                } //End applicant 1, no dependents
                
          } // End applicant 1
          
          //Applicant 2
          else if(applicantNumber == 2){

                //Show the second applicant
                $("#applicant2").show();

                //Append applicant 2 income

                $("#applicant2-salary").append(
                        '<input name="Salary2" value="" type="text" class="required number loan-large-field loan-large-field-dollar" />'+
                        '<select name="Salary2-Type" class="required">'+
                            '<option value="gross">Gross (Pre-Tax)</option>'+
                            '<option value="net">Net (Post-Tax)</option>'+
                        '</select>'+
                        '<select name="Salary2-Method" class="required">'+
			            '<option value="annual">Annual</option>'+
			            '<option value="monthly">Monthly</option>'+
			            '<option value="fortnightly">Fortnightly</option>'+
                        '</select>');
                
                remember("[name='Salary2']");
                remember('[name="Salary2-Type"]');
          	  	remember('[name="Salary2-Method"]');
          	    $("[name='Salary2']").DefaultValue("Salary");
                
          	  $("#applicant2-overtime").append( 
  	        		'<input name="Overtime2" value="" type="text" class="required number loan-large-field loan-large-field-dollar" />'+
  	                '<select name="Overtime2-Type" class="required">'+
  	                    '<option value="gross">Gross (Pre-Tax)</option>'+
  	                    '<option value="net">Net (Post-Tax)</option>'+
  	                '</select>'+
  	                '<select name="Overtime2-Method" class="required">'+
  			            '<option value="annual">Annual</option>'+
  			            '<option value="monthly">Monthly</option>'+
  			            '<option value="fortnightly">Fortnightly</option>'+
  	                '</select>');
          	  
          	  remember("[name='Overtime2']");
          	  remember('[name="Overtime2-Type"]');
          	  remember('[name="Overtime2-Method"]');
          	 $("[name='Overtime2']").DefaultValue("Overtime");
                
                //Dependents
                if(hasDependents){

                      //----Dependents--------//
                      $("#applicant2-dependents").show();
                
                      
                      //----Income------------//
                      $(".first-tab-app-two-list").empty();
                      
                      $(".first-tab-app-two-list").append(investmentIncome2);
                      remember("[name='Investment2']");
                      remember("[name='Investment2-Frequency']");
                      
                      if(loanProfile == "fhb"){
                            //Family Allowance
                    	  	$(".first-tab-app-two-list").append(familyAllowance2);
                    	  	remember("[name='FamilyAllowance2']");
                    	  	remember("[name='FamilyAllowance2-Frequency']");
                      }
                      else{
                            
                            //Family A and Rental Income
                            $(".first-tab-app-two-list").append(familyAllowance2);
                            $(".first-tab-app-two-list").append(rentalIncome2);
                            remember("[name='FamilyAllowance2']");
                            remember("[name='FamilyAllowance2-Frequency']");
                            remember("[name='NewRent2']");
                            remember("[name='NewRent2-Frequency']");

                      }
                      //---------Expenses-----//
                      $(".second-tab-app-two-list").empty();
                      
                      //Credit Card
                      $(".second-tab-app-two-list").append(creditCard2);
                      remember("[name='CreditCard2']");
                      remember("[name='CreditCard2-Frequency']");
                      //Car Loan
                      $(".second-tab-app-two-list").append(carLoan2);
                      remember("[name='CarLoan2']");
                      remember("[name='CarLoan2-Frequency']");
                      //Other Loan
                      $(".second-tab-app-two-list").append(otherLoan2);
                      remember("[name='OtherLoan2']");
                      remember("[name='OtherLoan2-Frequency']");
                      
                      //if(loanProfile == "fhb"){
                            //Rent
                      $(".second-tab-app-two-list").append(rentalExpense2);
                      remember("[name='RentalExpense2']");
                      remember("[name='RentalExpense2-Frequency']");
                      //}
                      //else{
                            //Mortgage
                      $(".second-tab-app-two-list").append(mortgageRepayment2);
                      remember("[name='MortgageRepayment2']");
                      remember("[name='MortgageRepayment2-Frequency']");
                      //}
                }
                //No Dependents
                else{

                      //----Dependents---//
                      $("#applicant2-dependents").hide();
                      
                      //---Income---//
                      
                      $(".first-tab-app-two-list").empty();
                      
                      $(".first-tab-app-two-list").append(investmentIncome2);
                      remember("[name='Investment2']");
                      remember("[name='Investment2-Frequency']");
                      
                      //if(loanProfile != "fhb"){
                      //Rental Income
                      $(".first-tab-app-two-list").append(rentalIncome2);  
                      remember("[name='RentalIncome2']");
                      remember("[name='RentalIncome2-Frequency']");
                      //}
                            
                      //---Expenses--//
                      $(".second-tab-app-two-list").empty();
     
                      //Credit Card
                      $(".second-tab-app-two-list").append(creditCard2);
                      remember("[name='CreditCard2']");
                      remember("[name='CreditCard2-Frequency']");
                      //Car Loan
                      $(".second-tab-app-two-list").append(carLoan2);
                      remember("[name='CarLoan2']");
                      remember("[name='CarLoan2-Frequency']");
                      //Other Loan
                      $(".second-tab-app-two-list").append(otherLoan2);
                      remember("[name='OtherLoan2']");
                      remember("[name='OtherLoan2-Frequency']");
                      
                      //if(loanProfile == "fhb"){
                            //Rent
                      $(".second-tab-app-two-list").append(rentalExpense2);
                      remember("[name='RentalExpense2']");
                      remember("[name='RentalExpense2-Frequency']");
                      //}
                     //else{
                            //Mortgage
                      $(".second-tab-app-two-list").append(mortgageRepayment2);
                      remember("[name='MortgageRepayment2']");
                      remember("[name='MortgageRepayment2-Frequency']");
                      //}
                }
                
          }
    }//end of function


  //-----------------Function to format number nicely with commas----------------//
    function numberFormat(nStr){
          nStr += '';
          x = nStr.split('.');
          x1 = x[0];
          x2 = x.length > 1 ? '.' + x[1] : '';
          var rgx = /(\d+)(\d{3})/;
          while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
          return x1 + x2;
    }//end of function
    
    //------------Function to strip any non-numeric characters from a string------//
    function stripNonNumericChars(nStr){
    
    	nStr = nStr.replace(/\D+/, '');
    	nStr = nStr.replace(/\,/, '');

    	return nStr;
    	
    }//end function
    
    //------------Validate Loan Popup form----------------//
    
    function validateLoanPopupForm() {
    	
    	$("form#loan-popup-form").validate({
    		
	    		submitHandler: function(form){
	    		
	    			//show loading
	    			$('#loading-image').show();	
	    			$('#loan-option-results').hide();
    	
		    		//Grab form info and submit to server.
					var values = {};
					values = serializeFormData('#loan-popup-form');
		
					$.post("afgretail_server/execute-cap",values,function(data){
						
							//$("#wrapper").hide();
							if(updateChart(data)){		
								$('#loan-option-results').show();
							}
							else{
								alert(errorAlert);
							}
							
							$('#loading-image').hide();
						
						}
					);
					
	    		 	return false;
    		
    		},	
    		
    		
    		//Not displaying errors except for promotion_code
    		errorPlacement: function(error, element) { 


    			error.insertAfter(element.parent());
    	     	error.css("color", "#FF0000");
    	   },
    	   
    	   //Highlight/un-highlight the <th> tags 
    	   highlight: function(element, errorClass, validClass) {
    		   
    		   var elemName = element.name;
    		   $("#"+elemName).addClass("error-input");
    		   tabElementErrors[elemName] = true;
    		   
    		
				if( $("#"+elemName).hasClass("income-one")){
		    		   
						if(tabElementErrors["NewRent1"] 
						                    || tabElementErrors["FamilyAllowance1"]){
							
							$(".income-tab-one").addClass("error");
						}
					

				}
				
				else if( $("#"+elemName).hasClass("expense-one")) {
				
					if(tabElementErrors["CreditCard1"] 
					          ||tabElementErrors["CarLoan1"]
					                || tabElementErrors["OtherLoan1"]
					                     || tabElementErrors["MortgageRepayment2"]
					                         || tabElementErrors["RentalExpense1"]){
						
						$(".expense-tab-one").addClass("error");
					
					}
					
				}
				
				else if( $("#"+elemName).hasClass("income-two")){
				
					if(tabElementErrors["NewRent2"] 
					                    || tabElementErrors["FamilyAllowance2"]){
						
						$(".income-tab-two").addClass("error");
					}
				
				}
				
				else if( $("#"+elemName).hasClass("expense-two")) {
					
					if(tabElementErrors["CreditCard2"] 
								          ||tabElementErrors["CarLoan2"]
								                || tabElementErrors["OtherLoan2"]
								                     || tabElementErrors["MortgageRepayment2"]
								                         || tabElementErrors["RentalExpense2"]){
									
									$(".expense-tab-two").addClass("error");
								
								}
				}
    		    
    		   	
    		   	
    		  },
    	   unhighlight: function(element, errorClass, validClass) {
    			
    			  var elemName = element.name;
    			  $("#"+elemName).removeClass("error-input");
    	   		   tabElementErrors[elemName] = false;
        		   
        		   //alert("elemName: "+elemName);
        		   
    				if( $("#"+elemName).hasClass("income-one")){
    					
    						if(!tabElementErrors["NewRent1"] 
    						                    && !tabElementErrors["FamilyAllowance1"]){
    							
    							$(".income-tab-one").removeClass("error");
    						}
    					

    				}
    				
    				else if( $("#"+elemName).hasClass("expense-one")) {
    				
    					if(!tabElementErrors["CreditCard1"] 
    					          && !tabElementErrors["CarLoan1"]
    					                && !tabElementErrors["OtherLoan1"]
    					                     && !tabElementErrors["MortgageRepayment1"]
    					                         && !tabElementErrors["RentalExpense1"]){
    						
    						$(".expense-tab-one").removeClass("error");
    					
    					}
    					
    				}
    				
    				else if( $("#"+elemName).hasClass("income-two")){
    				
    					if(!tabElementErrors["NewRent2"] 
    					                    && !tabElementErrors["FamilyAllowance2"]){
    						
    						$(".income-tab-two").removeClass("error");
    					}
    				
    				}
    				
    				else if( $("#"+elemName).hasClass("expense-two")) {
    					
    					if(!tabElementErrors["CreditCard2"] 
    								          && !tabElementErrors["CarLoan2"]
    								                && !tabElementErrors["OtherLoan2"]
    								                     && !tabElementErrors["MortgageRepayment2"]
    								                         && !tabElementErrors["RentalExpense2"]){
    									
    									$(".expense-tab-two").removeClass("error");
    								
    					}
    				}
    			 
    		
    			 
    		  }
    	     
    	});
    	
    }//end of function
    
    //Function to serialize form(s)
    function serializeFormData(selector) {
    	var values = {};
		$.each($(selector).serializeArray(), 
				function(i, field) {
					values[field.name] = field.value;
				}
		);
		
		return values;
    }
    
    //This function takes an array and fills is with lender info
    //LenderName, LenderID, MaxLoanAmt and Repayment
    function getLenderinfo(values) {
    	
    	var lenderIndex = 1;
		//Get the lender info
		for(i=0;i<products.length;i++){
			values['Lender'+lenderIndex+'-MaxLoan'] = Math.round(products[i].loanVal);
			values['Lender'+lenderIndex+'-Id'] = products[i].lenderId;
			values['Lender'+lenderIndex+'-Name'] = products[i].lenderName;
			
			if ($("#LoanAmount").val() > Math.round(products[i].loanVal)) {
				values['Lender'+lenderIndex+'-Repayment'] = 0;
			}
			else {
				values['Lender'+lenderIndex+'-Repayment'] = $('#repay'+lenderIndex+'value').html();
			}
			 
			lenderIndex++;
		}
    	
		return values;
    	
    }
    
    //Serialize response returned from server
    function serializeResponse(data) {
    	
    	var response = data.split(":");
    	var outcome = response[0];
    	var message = response[1];
    	var errorsFormatted = "";
    	
    	if (outcome == 'success') {
    		//alert(message);
    		return message;
    	}
    	else {
    		
    		if (message.indexOf(",") != -1) {
    			
    			var errors = message.split(",");
    			
    			errorsFormatted += "<ul>"; 
    			for (i=0;i<errors.length;i++) {
    				errorsFormatted += "<li>" + errors[i] + "</li>";
    			}
    			errorsFormatted += "</ul>";
    			
    			//alert(errorsFormatted);
    			return errorsFormatted;
    			
    		}
    		else {
    			//alert(message);
    			return message;
    		}
    	}
    	
    }
    
    function setStateProfileFromCookie() {
    	if ($.cookie("stateProfile")) {
    		setProfile($.cookie("stateProfile"),"stateProfile");
    	}
    }
    
    function setFamilyProfileFromCookie() {
    	if ($.cookie("familyProfile")) {
    		setProfile($.cookie("familyProfile"),"familyProfile");
    	}
    }
    
    function getborrowingSliderValue() {
    	var sliderValue = 350000;
    	
		if ($.cookie("amount")) {
			sliderValue = stripNonNumericChars($.cookie("amount"));
		}
		
		return sliderValue;
    }
    
	//---------------------------JQUERY----------------------------------------------------------//
	$(function(){

		
		//Trim function
		if(typeof String.prototype.trim !== 'function') 
			{   
				String.prototype.trim = function() {     
					return this.replace(/^\s+|\s+$/g, '');    
				};
			} 
		
		products = [bar1,bar2,bar3,bar4,bar5];
		setChartAxisValues();
		//$("#chart").hide();
		
		$('#loading-image').hide();	

		$("#employmentDetails").buttonset();

		$("#fhb").button().click(function() {
			setProfile("fhb","loanProfile");
		});
		
		$("#newloan").button().click(function() {
			setProfile("newloan","loanProfile");
		});
		$("#refinance").button().click(function() {
			setProfile("refinance","loanProfile");
		});
		
		//Set family profile from cookie
		setFamilyProfileFromCookie();
		
		$("#single").button().click(function() {
			setProfile("single","familyProfile");
			$.cookie("familyProfile", "single");
		});
		$("#singlewkids").button().click(function() {
			setProfile("singlewkids","familyProfile");
			$.cookie("familyProfile", "singlewkids");
		});
		$("#couple").button().click(function() {
			setProfile("couple","familyProfile");
			$.cookie("familyProfile", "couple");
		});
		$("#couplewkids").button().click(function() {
			setProfile("couplewkids","familyProfile");
			$.cookie("familyProfile", "couplewkids");
		});
		$("#yes").button().click(function() {
			setProfile("yes","empProfile");
		});
		$("#no").button().click(function() {
			setProfile("no","empProfile");
		});

		//Set state profile from cookie
		setStateProfileFromCookie();
		
		$("#loan-option-wa").button().click(function() {
			setProfile("loan-option-wa","stateProfile");
			$.cookie("stateProfile", "loan-option-wa");
		});

		$("#loan-option-nt").button().click(function() {
			setProfile("loan-option-nt","stateProfile");
			$.cookie("stateProfile", "loan-option-nt");
		});

		$("#loan-option-qld").button().click(function() {
			setProfile("loan-option-qld","stateProfile");
			$.cookie("stateProfile", "loan-option-qld");
		});

		$("#loan-option-sa").button().click(function() {
			setProfile("loan-option-sa","stateProfile");
			$.cookie("stateProfile", "loan-option-sa");
		});

		$("#loan-option-nsw").button().click(function() {
			setProfile("loan-option-nsw","stateProfile");
			$.cookie("stateProfile", "loan-option-nsw");
		});

		$("#loan-option-vic").button().click(function() {
			setProfile("loan-option-vic","stateProfile");
			$.cookie("stateProfile", "loan-option-vic");
		});

		$("#loan-option-tas").button().click(function() {
			setProfile("loan-option-tas","stateProfile");
			$.cookie("stateProfile", "loan-option-tas");
		});

		$("#loan-option-act").button().click(function() {
			setProfile("loan-option-act","stateProfile");
			$.cookie("stateProfile", "loan-option-act");
		});
		
		//Loan slider
        $("#borrowingSlider").slider({	
              value:getborrowingSliderValue(),
              min: 10000,
              max: 1200000,
              step: 10000,
              slide: function(event, ui) {
                    $("#amount").val('$' + numberFormat(ui.value));
                    $.cookie("amount", $("#amount").val());
              },
              stop: function(event, ui) {
                    $("#LoanAmount").val('$' + numberFormat(ui.value));
              }
              
        });
        $("#amount").val('$' + numberFormat($("#borrowingSlider").slider("value")));
        $("#LoanAmount").val('$' + numberFormat($("#borrowingSlider").slider("value")));
		
		//Set up button to show user info form
		$('#loan-options-btn').live("click" , function() {
			
			if (familyProfile == ''  
						|| stateProfile == '') {
				
				if (familyProfile == '') {
					$("#familyProfile-error").show();
				}
				if (stateProfile == '') {
					$("#stateProfile-error").show();
				}
				
				$('#applicantDetails').hide();
				
				return false;
				
			}
			else {
				customizeForm();
				$('#applicantDetails').show();
				
				return false;
			}	
		});
		
		//loan options report button clicked form
		$('#loan-report-form-button').click(function() {
			
			$("#loan-report-form-container").show();
			$("#loan-report-error").html("");
			$("#loan-report-form-thankyou").hide();
			
		});
		
		//Submit request for Loan-options Report
		$('#loan-report-submit').click(function() {
			
			//Grab form info and submit to server.
			var loanReportFormValues = {};
			loanReportFormValues = serializeFormData('#form-loan-report, #loan-popup-form');
			
			//Getting lender information 					
			loanReportFormValues = getLenderinfo(loanReportFormValues);
			
			$.post("afgretail_server/loan-options-report",loanReportFormValues,function(data){
				
				data = serializeResponse(data);
				
				if (data == "success") {
					$("#loan-report-form-container").hide();
					$("#loan-report-form-thankyou").show();
				}
				else {
					$("#loan-report-error").show();
					$("#loan-report-error").html(data);
				}
			});
			
			return false;
			
		});
		
		//loan enquiry button clicked form
		$('#loan-enquiry-form-button').click(function() {
			
			$("#loan-enquiry-form-container").show();
			$("#loan-enquiry-error").html("");
			$("#loan-enquiry-form-thankyou").hide();
			
		});
		
		//Submit request for Loan-enquiry
		$('#loan-enquiry-submit').click(function() {
			
			//Grab form info and submit to server.
			var loanEnquiryFormValues = {};
			loanEnquiryFormValues = serializeFormData('#form-loan-enquiry, #loan-popup-form');
			
			//Getting lender information 					
			loanEnquiryFormValues = getLenderinfo(loanEnquiryFormValues);
			
			$.post("afgretail_server/loan-enquiry",loanEnquiryFormValues,function(data){
				
				data = serializeResponse(data);
				
				if (data == "success") {
					$("#loan-enquiry-form-container").hide();
					$("#loan-enquiry-form-thankyou").show();
				}
				else {
					$("#loan-enquiry-error").show();
					$("#loan-enquiry-error").html(data);
				}
			});
			
			return false;
			
		});
		
		//Close modal dialog boxes
		$('.close-modal').click(function() {
			$("#lean_overlay").hide();
			$(".modal-style").hide();
		});
		
	
		} // End of function

	);

		
	

