/*******************************************************************************
 * 
 * 							V4 Wizard - JDAY.  4/13/09
 *
 *******************************************************************************/



var app = {

	/*******************************************************************************
	 * 
	 * Define Application-Specific Variables
	 *
	 *******************************************************************************/

	inactiveSchools : [],
	rightColDelay : false,
	rightColOrig : "",
	skin : "default",
	path : "",
	main_url : "",
	phase : 1,
	school_id : 0,
	school_name : "",
	small_logo : "",
	ajaxUrl : "",
	ajaxSpinnerImg : "",
	progressBarImg : "",
	progressBarBoxImg : "",
	modalOn : false,
	test : "",
	formReady : false,
	percentComplete : 0,
	answer : "",
	currentPage : 1,
	currentPrequalPage : 0,
	currentPrequalPageHistory : "0",
	exitPrequal : false,
	madeCompatible : false,
	areaOfStudyPopulated : false,
	degreeTypePopulated : false,
	degreeInfoPopulated : false,
	degreeCatAndConcs : {},
	degreeTypes : {},
	numPages : 0,
	numActiveAjaxRequests : 0,
	navLinks : "<div class='nav_prev'>prev</div> <div class='nav_next'>next</div>",
	disableBeforeUnloadEvent : false,
	unloadAttempt : 0,
	unloadMsg : "All your information will be lost!",
	errAjax : "There was an error processing your request, please try again.",
	errAgeNotSelected : "Please Select Your Age.",
	errCountryNotSelected : "Please Select Your Country.",
	errCatNotSelected : "Please Select Your Area of Study.",
	errTypeNotSelected : "Please Select The Degree Type You're Interested In.",
	errInvalidEmailAddress : "Your Email Address Appears to be Invalid.",
	errInvalidZipcode : "Your Zip/Postal Code Appears to be Invalid.",
	errProgramNotSelected : "Please select the program you are interested in.",
	errWhenBeginNotSelected : "Please select when you would like to begin classes.",
	errEmployedNotSelected : "Please select if you are employed.",
	errEmployerReimbursementNotSelected : "Please select if your employer offers education reimbursement.",
	errStudentLoansNotSelected : "Please select if you plan to take out student loans.",
	errTimeCommitmentNotSelected : "Please select if you have 8-16 hours a week to devote to earning your degree.",
	errPreviouslyAttendedNotSelected : "Please select if you have already earned college credits at another school.",
	errPreviouslyRequestedNotSelected : "Please select if you have requested information from an online university in the last 6 months.",
	errFinancialCommitmentNotSelected : "Please select if you are currently able to pay without student loans.",
	errContactAdvisorNotSelected : "Please select if you would like to receive a phone call from an enrollment advisor.",
	waldenSpecializationNotSelected : "Please specify the specialization for this program",
	imagesToPreload : ["progressbar.gif","progressbg_green.gif","ftr-bkgrd.gif","number-bkgrd.gif","txt-bg.gif","watermark.gif","ajax.gif","ajax2.gif","previous.gif","previous_off.gif","1.gif","2.gif","3.gif","4.gif","5.gif","6.gif","7.gif","8.gif","9.gif","10.gif"],
	nextTopFirstLoad : 0,
	nextTopAjaxSpinnerImg : "<img id='nextTopAjaxSpinnerImg' src='http://www.earnmydegree.com/images/ajax_loading.gif'/>",
	
	//Define the names of each V4 fieldname
	v4fields : {
		age : "v4_age",
		cat_id : "v4_cat_id",
		conc_id : "v4_conc_id",
		type_id : "v4_type_id",
		country : "df_country",
		zip : "df_zip",
		email : "df_email",
		first_name : "df_first_name",
		last_name : "df_last_name",
		address : "df_address",
		day_phone_area : "df_day_phone_area",
		day_phone_prefix : "df_day_phone_prefix",
		day_phone_suffix : "df_day_phone_suffix",
		night_phone_area : "df_night_phone_area",
		night_phone_prefix : "df_night_phone_prefix",
		night_phone_suffix : "df_night_phone_suffix",
		mobile_phone_area : "df_mobile_phone_area",
		mobile_phone_prefix : "df_mobile_phone_prefix",
		mobile_phone_suffix : "df_mobile_phone_suffix",
		samephone : "sameV4phone"
	},
	
	//Define the names of each V4 fieldname
	v4prequalfields : {
		when_begin : "v4_when_begin",
		employed : "v4_employed",
		employer_reimbursement : "v4_employer_reimbursement",
		student_loans : "v4_student_loans",
		time_commitment : "v4_time_commitment",
		previously_attended : "v4_previously_attended",
		previously_requested : "v4_previously_requested",
		financial_commitment : "v4_financial_commitment",
		contact_advisor: "v4_contact_advisor"
	},


	/*******************************************************************************
	 * 
	 * init() - Fire it up, Chief
	 * 
	 *******************************************************************************/
	
	init : function (args){
		//Do NOT Fire init for JPOP iframe
		if (args.location.search.indexOf("invalidateme") > -1) {
			return;
		}

		this.debug("Initializing...");

		//Setting path info
		this.debug("Setting path info to "+this.path + "...");
		this.setPaths();

		//Count the number of Pages
		numPages = $(".page").size();
		this.debug("Set number of pages to "+numPages + "...");

		//If On School (PHASE2), set page to 8
		if (this.phase == 2 || this.phase == 4) this.currentPage = 8;
	
		//Capture Unload Event for the Main Window (DISABLED BECAUSE OF MULTIPLE IFRAMES, BUGS IN beforeunload JQUERY)
		//window.onbeforeunload = alert(this.unloadMsg);
	
		//Initialize JQuery Event Handlers for Form Elements
		this.debug("Initializing Event Handlers...");
		this.initEventHandlers();

		//Render Page One
		this.debug("Loading page " + this.currentPage + "...");
		
		//Check for Prequal to enter Prequal Wiz
		if (this.phase == 1 && $("input[name='prequal']").val() == 1) {
			this.beginPrequalWizard();
		} else {
			this.gotoPage(this.currentPage);
		}
	
		//Preload Images
		if (this.phase == 1) {
			this.debug("PreLoading Images...");
			this.preloadImages();

			/*
			//Prepop Compatibility
			if (prepop.age != "") {
				$("select[name='"+this.v4fields.age+"']").val(prepop.age);
				this.gotoPage(2);
			}
			*/

		//If phase 2, Run the V3 version's init function
		}else if (this.phase == 2 || this.phase == 4){
			this.debug("Running V3 TemplateInit()...");
			this.nextTopFirstLoad = 1;
			TemplateInit();
		}

		//Display the transfer process
		if (this.phase == 4 ){
			this.debug("Rendering Transfer Process...");
			$("#slider").easySlider();
			this.tooltip();
		}

		this.debug("Initialized!");
	},

	/*******************************************************************************
	 * 
	 * tooltip() - Associate all <a> tags with a "tooltip" class with this tooltip function
	 * 
	 *******************************************************************************/
	
	tooltip : function(){	
		var xOffset = 10;
		var yOffset = 20;		
		$("a.tooltip").hover(function(e){											  
			this.t = this.title;
			this.title = "";									  
			$("body").append("<div id='tooltip'>"+ this.t +"</div>");
			$("#tooltip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("normal");		
	    },
		function(){
			this.title = this.t;		
			$("#tooltip").remove();
	    });	
		$("a.tooltip").mousemove(function(e){
			$("#tooltip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px");
		});			
	},


	/*******************************************************************************
	 * 
	 * setPaths() - set paths to images based on this.path
	 *
	 *******************************************************************************/
	
	setPaths : function () {
		this.ajaxUrl = this.path + "/services/ajax.cfm";
		this.ajaxSpinnerImg = this.path + "/skins/" + this.skin + "/images/ajax.gif";
		this.progressBarImg = this.path + "/skins/" + this.skin + "/images/progressbg_green.gif";
		this.progressBarBoxImg = this.path + "/skins/" + this.skin + "/images/progressbar.gif";
	},

	/*******************************************************************************
	 * 
	 * gotoPage() - performs validation, hides the "currentPage" div, fades-in the 
	 * 				"page" div, renders the navigation bar, and fires "getSchoo
	 * 
	 * arguments - "page": the name of the div to display 
	 * dependencies - jquery1.3.2
	 *
	 *******************************************************************************/
	
	gotoPage : function (page) {

	    //Perform Validation
	    if (!this.isPageValid(page)) { return false; }
	    
		//"Colorize" the previous button
		$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous.gif"});
		$("#nav_prev").attr({"style":"cursor:pointer"});
	
		//If Page1 Selected OR on Page Init
		if (page==1) {
			//Grey out the previous button
			$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous_off.gif"});
			$("#nav_prev").attr({"style":"cursor:default"});	
		}
		
		//If Page2 Selected
		else if (page==2) {
			//Don't update the right column if required by the skin
			if (!this.rightColDelay) {
				//Show the DegreeCount
		        this.getDegreeCount();
				//Display the watermark
				$(".mid-container").css({"background-image":"url('"+this.path+"/skins/"+this.skin+"/images/watermark.gif')","background-repeat":"no-repeat","background-position":"bottom right"});
			}
		}
	

		//If Page3 Selected (zip, email)
		else if (page==3) {
			//Don't update the right column if required by the skin
			if (!this.rightColDelay) {
				//Show the DegreeCount
		        this.getDegreeCount();
			}
		}

		//If Page4 Selected and user hasn't selected the area of study yet
		else if (page==4 && !this.areaOfStudyPopulated) {
			//Check for Duplicates
			this.checkDupStatus();
		}
	
		//If Page5 Selected
		else if (page==5 && !this.degreeTypePopulated) {
			//Fire ajax and populate degree level
			this.getActiveTypes();
			//Set flag
			this.degreeTypePopulated = true;
		}
	
		//If Page6 Selected
		else if (page==6) {
			//Show the DegreeCount
	        this.getDegreeCount();
		}
	
		//If Page7 Selected
		else if (page==7) {
			//Get the best-matched degree and Perform Redirect into actual school
			this.getBestDegreeMatch();

			//Unbind the click events for the nav buttons (about to redirect)
			//NAV - previous
		    $("#nav_prev").unbind();
		
			//NAV - next
		    $("#nav_next").unbind();
		}
	
		//If Page8 Selected (PHASE 2) and the degree info has NOT been populated/cached yet
		else if (page==8) {
			//Get the degree type and degree information from the best-matched degree
			this.getDegreeInfo();
	
			//Set Flag
			this.degreeInfoPopulated = true;
	
			//Perform any Compatibility functions (like select boxes being too big, things being wrong color, etc)
			this.V3V4Compatibility(page,"view")
		}
	
		//If Page9 Selected (PHASE 2)
		else if (page==9) {
			//"Colorize" the previous button
			$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous.gif"});
			$("#nav_prev").attr({"style":"cursor:pointer"});
	
			//Hide the Next Button (submit button is present)
			$("#nav_next").attr({"style":"display:none"});
	
			//Show the submit Button
			$("#submitButton").fadeIn("slow");
	
			//Allow them to submit the form
			this.formReady = true;
	
			//Perform any Compatibility functions (like select boxes being too big, things being wrong color, etc)
			this.V3V4Compatibility(page,"view");
		}
	
		//If Page8 Selected (PHASE 2) and the degree info HAS been populated/cached
		if (page==8) {
			//Grey out the previous button
			$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous_off.gif"});
			$("#nav_prev").attr({"style":"cursor:default"});
	
			//Show the Next Button
			$("#nav_next").attr({"style":"display:inline"});
	
			//Hide the submit Button
			$("#submitButton").hide();
		}
	
	    //Hide Currently Displayed Page and Show the Requested Page
	    $("#page" + this.currentPage).hide();
	    $("#page" + page).fadeIn("normal");
	
		//Hide the page number
		$("#pageNum").hide();
	    //Update the page number graphic
		$("#pageNum").attr({"src":this.path+"/skins/"+this.skin+"/images/"+page+".gif"});
		//Fade in the page number
		$("#pageNum").fadeIn("normal");	
	
		//Set global variable "currentPage" to the latest requested page
	    this.currentPage = page;
	
	    //Update the ProgressBar
	    this.renderProgressBar();

		//TrackView
		if (page != 1 && page != 8) {
			this.trackView("P"+page);
		}
	},
	
	/*******************************************************************************
	 * 
	 * gotoPreviousPrequalPage() - hides the "currentPage" div, fades-in the 
	 * 				"page" div, renders the navigation bar, and fires "getSchoo
	 * 
	 * dependencies - jquery1.3.2
	 *
	 *******************************************************************************/
	
	gotoPreviousPrequalPage : function () {
		var pagetohide = this.currentPrequalPage;
		this.currentPrequalPage = this.currentPrequalPageHistory.substring(this.currentPrequalPageHistory.lastIndexOf(",")+1);
		this.currentPrequalPageHistory = this.currentPrequalPageHistory.substring(0,this.currentPrequalPageHistory.lastIndexOf(","));

		//If Page1 Selected
		if (this.currentPrequalPage==1) {
			//Grey out the previous button
			$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous_off.gif"});
			$("#nav_prev").attr({"style":"cursor:default"});	
		}
		
		$("#prequalpage" + pagetohide).hide();
		$("#prequalpage" + this.currentPrequalPage).fadeIn("normal");
		
		//Display correct right column for the current page
		//var rightmsg = '<img id="logosImg" src="<cfoutput>'+this.path+'/images/'+this.currentPrequalPage+'.gif</cfoutput>" usemap="#logos" border="0" />';
		$("#rightcol_default").hide();
		$("#rightcol_default").html('<img id="logosImg" src="'+this.path+'/images/pqsidebar'+this.currentPrequalPage+'.jpg" border="0" />');
		$("#rightcol_default").fadeIn("slow");

		//TrackView
		this.trackView("Q"+this.currentPrequalPage);
		
	},
	
	/*******************************************************************************
	 * 
	 * gotoNextPrequalPage() - performs validation, hides the old "currentPrequalPage" div, fades-in the 
	 * 				new "currentPrequalPage" div, renders the navigation bar, updates currentPrequalPageHistory
	 * 
	 * dependencies - jquery1.3.2
	 *
	 *******************************************************************************/
	
	gotoNextPrequalPage : function () {
		
		var pagetohide = this.currentPrequalPage;
		
		//Perform Validation
		if (!this.isPrequalPageValid(this.currentPrequalPage)) { return false; }
	    
		if (app.exitPrequal == true) {
			this.endPrequalWizard(pagetohide);
		} else {
						
			//"Colorize" the previous button
			$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous.gif"});
			$("#nav_prev").attr({"style":"cursor:pointer"});
		
			//If Page1 Selected OR on Page Init
			if (this.currentPrequalPage==1) {
				//Grey out the previous button
				$("#nav_prev").attr({"src":this.path+"/skins/"+this.skin+"/images/previous_off.gif"});
				$("#nav_prev").attr({"style":"cursor:default"});
				
				//Hide the page number and progressbar label
				$("#pageNum").hide();
				$("#progressbarLabel").hide();
			}
		
			//Hide Currently Displayed Page and Show the Requested Page
			if (pagetohide != 0 ){
				this.currentPrequalPageHistory = this.currentPrequalPageHistory + "," + pagetohide;
				$("#prequalpage" + pagetohide).hide();
			}
			$("#prequalpage" + this.currentPrequalPage).fadeIn("normal");
			
			//Display correct right column for the current page
			//var rightmsg = '<img id="logosImg" src="<cfoutput>'+this.path+'/images/'+this.currentPrequalPage+'.gif</cfoutput>" usemap="#logos" border="0" />';
			$("#rightcol_default").hide();
			$("#rightcol_default").html('<img id="logosImg" src="'+this.path+'/images/pqsidebar'+this.currentPrequalPage+'.jpg" border="0" />');
			$("#rightcol_default").fadeIn("slow");
		
			//TrackView
			if (this.answer == ""){
				this.trackView("Q"+this.currentPrequalPage);
			} else {

				this.trackView(this.answer+",Q"+this.currentPrequalPage);
			}
			this.answer = "";
		}
	},


	/*******************************************************************************
	 * 
	 * beginPrequalWizard() - Begin the Prequal Wizard Process
	 * 
	 *******************************************************************************/
	
	beginPrequalWizard : function() {

		//NAV - previous
		$("#nav_prev").unbind();
		$("#nav_prev").click(function() {
			if (app.currentPrequalPage != 1) {
				app.gotoPreviousPrequalPage();			
			}
		});
	
		//NAV - next
		$("#nav_next").unbind();
		$("#nav_next").click(function() {
			app.gotoNextPrequalPage();
		});
		app.rightColOrig = $("#rightcol_default").html();
		this.gotoNextPrequalPage();
		
	},
	
	/*******************************************************************************
	 * 
	 * endPrequalWizard() - End the Prequal Wizard Process
	 * 
	 *******************************************************************************/
	
	endPrequalWizard : function(prequalPagetohide) {

		//reset NAV - previous
		$("#nav_prev").unbind();
		$("#nav_prev").click(function() {
			if (app.currentPage != 1 && app.currentPage != 8) {
				app.gotoPage(app.currentPage - 1);			
			}
		});
	
		//reset NAV - next
		$("#nav_next").unbind();
		$("#nav_next").click(function() {
			app.gotoPage(app.currentPage + 1);
		});
		
		$("#progressbarLabel").fadeIn("normal");
		this.trackView("PQPASS");
		
		$("#prequalpage" + prequalPagetohide).hide();
		//Display correct right column for the current page
		//var rightmsg = '<img id="logosImg" src="<cfoutput>'+this.path+'/images/pqsidebar'+this.currentPrequalPage+'.jpg</cfoutput>" border="0" />';
		$("#rightcol_default").hide();
		$("#rightcol_default").html(app.rightColOrig);
		$("#rightcol_default").fadeIn("slow");
		this.gotoPage(this.currentPage);
		
	},

	/*******************************************************************************
	 * 
	 * checkDupStatus() - See if this email address is a duplicate internally or externally
	 * 
	 *******************************************************************************/
	
	checkDupStatus : function() {
		
		//Hide the Concentration DIV
		$("#div_conc_id").hide();

		//Clear the cat_id dropdown options
		this.clearEntireDropdown(this.v4fields.cat_id);
		
		//Populate the cat_id dropdown with "Please Wait..." and disable it until ajax is finished
		$("#"+this.v4fields.cat_id).append("<option value=''>Please Wait...</option>").attr({"disabled":"true"});


		//Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "checkDupStatus";
	    data.email = $("input[name='"+this.v4fields.email+"']").val();
		data.inactiveSchools = this.inactiveSchools;
	    var ajaxdata = $.toJSON(data);

	    //Create Ajax Object For Parameters
	    var a = {};
		a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("handleDupStatus",response)};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {};
	
	    //Make Ajax Request
	    this.ajax(a);
	
	},

	/*******************************************************************************
	 * 
	 * handleDupStatus() - If DUP, Exclude UOP.  If not, add UOP's types/cats/concs to the mix
	 * 
	 *******************************************************************************/
	
	handleDupStatus : function(response) {
		//Add each school_id to inactiveSchools
		$.each(response, function(name,val){
			if (val != "") {
				app.inactiveSchools.push(val);
			}
		});
		
		this.debug("<BR>DUPLICATES: inactiveSchools set to " + this.inactiveSchools.slice());

		//Fire ajax and populate area of study
		this.getActiveCatsAndConcs();

	},

	/*******************************************************************************
	 * 
	 * trackView() - Track this page view for better performance
	 * 
	 *******************************************************************************/
	
	trackView : function(newFid) {

	    if (!newFid) newFid = "";
		
		//Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "track";
	    data.sid = $("input[name='sid']").val();
	    data.fid = $("input[name='fid']").val();
	    data.newFid = newFid;
	    var ajaxdata = $.toJSON(data);
	
	    //Create Ajax Object For Parameters
	    var a = {};
	    a.doTrack = true;
		a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("doTrack",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {};
	
	    //Make Ajax Request
	    this.ajax(a);
	},

	/*******************************************************************************
	 * 
	 * doTrack() - callback for trackView(), display degree info
	 * 
	 *******************************************************************************/
	
	doTrack : function(response) {
		//Update FID
	    $("input[name='fid']").val(response.FID);
	},

	/*******************************************************************************
	 * 
	 * V3V4Compatibility() - Perform any Compatibility functions (like select boxes being too big, things being wrong color, etc)
	 * 
	 *******************************************************************************/
	
	V3V4Compatibility : function(page,viewOrPost) {
		//If viewing a page, perform certain "hacks"
		if (viewOrPost=="view") {
			if (page == 8 && !this.madeCompatible) {
				
				this.madeCompatible = true;
				
				//Move Program / Area of Study from Page 9 to Page 8
				$("#f_program").appendTo("#f_program2");
		
				//Move Zipcode Into the basic_info div
				$("#f_zip").prependTo("#basic_info");
				$("#f_zip").after("<BR><BR><BR clear='all'>");
		
				//Walden Specific
				if (this.school_id==6){
					$("select[name='program']").attr({"style":"width:300px"});
					$("select[name='specialization']").attr({"style":"width:300px"});
				}
			}
		
			else if (page == 9) {
				//Hide Fields
				var hideArray = ["country"];
				for (var i in hideArray) {
					$("."+hideArray[i]).hide();
				}
	
				//Kaplan Specific
				if (this.school_id==4) {
					//The disclaimer is currently hardcoded to color:white... set to black.
					$(".question_inner table tr td span").css({"color":"black"});
				}

				//LACollege Specific
				if (this.school_id==131) {
					//"Best Time To Be Contacted" label font is too large, wraps
					$("#div_best_time").css({"font-size":"8pt"});
				}
				
				//WGU Specific
				if (this.school_id==32) {
					//Dropdown is hardcoded and too big
					$("select[name='learner_rating']").css({"width":"315px"})
				}
			}
		}

		//If posting/validating a page, ensure that any school-specific validation is handled.
		else if (viewOrPost=="post") {
			if (page == 8) {
				//Walden Specific
				if (this.school_id==6){
					if ($("select[name='specialization']").val() == "") {
						alert(this.waldenSpecializationNotSelected);
						return false;
					}
				}
			}
		
			else if (page == 9) {
	
			}
	
			return true;
		}
	
	},

	/*******************************************************************************
	 * 
	 * getBestDegreeMatch() - takes the selected form elements and makes an ajax call
	 * 						  to determine the best-matched drop_id
	 * 
	 * arguments - n/a 
	 * dependencies - jquery1.3.2
	 * 				  jquery.json-1.3.min.js (http://code.google.com/p/jquery-json/)
	 * 
	 *******************************************************************************/
	
	getBestDegreeMatch : function() {

		//Turn off the ajax spinner (already exists on page7)
		this.ajaxSpinner(0);

	    //Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "getDegrees";
		data.inactiveSchools = this.inactiveSchools;
		data.getCount = false;
	    data.country = this.getRadioVal(this.v4fields.country);
	    data.type_id = this.getSelectVal(this.v4fields.type_id);
	    data.cat_id = this.getSelectVal(this.v4fields.cat_id);
	    data.conc_id = this.getSelectVal(this.v4fields.conc_id);
	    data.zip = $("input[name='"+this.v4fields.zip+"']").val();
	    var ajaxdata = $.toJSON(data);
	
	    //Create Ajax Object For Parameters
	    var a = {};
	    a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("redirect",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {app.handleAjaxError(XMLHttpRequest,textStatus,errorThrown);};
	
	    //Make Ajax Request
	    this.ajax(a);

	},
	
	/*******************************************************************************
	 * 
	 * getOtherDegreeMatches() - takes the selected form elements and makes an ajax call
	 * 						  to determine the best-matched drop_ids
	 * 
	 * arguments - n/a 
	 * dependencies - jquery1.3.2
	 * 				  jquery.json-1.3.min.js (http://code.google.com/p/jquery-json/)
	 * 
	 *******************************************************************************/
	
	getOtherDegreeMatches : function(dropid) {
		//Turn on the ajax spinner 
		if (this.nextTopFirstLoad == 0)
		{
		$("#info_otherSchools").html(this.nextTopAjaxSpinnerImg);
		}
		
		var trk_formname = $("input[name='trk_formname']").val();
		var drop_text = $('#s1 :selected').text();
		if(drop_text == "")
		{
			drop_text = $('#program :selected').text();
		}
		var current_info = this.school_name+' - '+drop_text
		$("#info_currentSchool").html(current_info);


	    //Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "getOtherPrograms";
		data.inactiveSchools = this.inactiveSchools;
		data.trk_formname = trk_formname;
	    data.country = prepop.country;
		data.state = $('#s2').val();
		data.drop_id = dropid;
	    data.zip = prepop.zip;
		data.email = prepop.email;
	    var ajaxdata = $.toJSON(data);

	    //Create Ajax Object For Parameters
	    var a = {};
	    a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("renderOtherDegreeInfo",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {app.handleAjaxError(XMLHttpRequest,textStatus,errorThrown);};
	
	    //Make Ajax Request
		if (this.nextTopFirstLoad == 1)
		{
			this.nextTopFirstLoad = 0;
		}
		else
		{
			this.ajax(a);
		}
	    

	},
	
	/*******************************************************************************
	 * 
	 * renderOtherDegreeInfo() - callback for getOtherDegreeMatches(), display other degree info
	 * 
	 *******************************************************************************/
	
	renderOtherDegreeInfo : function(response) {
		
		var template = "V4";
		var qs = "";

		//Create object to store each element used in the redirect
		var u = {};
		u.key = $("input[name='key']").val();
		u.sid = $("input[name='sid']").val();
		u.fid = $("input[name='fid']").val();
		u.v4_type_id = prepop.type_id;
		u.zip = prepop.zip;
		u.df_fname = prepop.first_name;
		u.df_lname = prepop.last_name;
		u.df_address = prepop.address;
		u.df_day_phone_area = prepop.day_phone_area;
		u.df_day_phone_prefix = prepop.day_phone_prefix;
		u.df_day_phone_suffix = prepop.day_phone_suffix;
		u.df_work_phone_area = prepop.night_phone_area;
		u.df_work_phone_prefix = prepop.night_phone_prefix;
		u.df_work_phone_suffix = prepop.night_phone_suffix;
		u.mobile_phone_area = prepop.mobile_phone_area;
		u.mobile_phone_prefix = prepop.mobile_phone_prefix;
		u.mobile_phone_suffix = prepop.mobile_phone_suffix;
		u.df_email = prepop.email;
		u.country = prepop.country;
		u.inactiveSchools = this.inactiveSchools;
		u.skin = this.skin;

		$.each(u, function(i, val) {
			if (i!=0) {qs+="&";}
			qs += i + "=" + val;
		});
		
		$("#info_otherSchools").html("");
		var count = response.recordcount;

		if (count > 0) {
			$("#otherSchoolsMain").css("display","block");
		}else{
			$("#otherSchoolsMain").css("display","none");
		}

		if(count > 3){var limit = 3;}else{var limit = count;}
	   	for (i = 0;i < limit; i++)
		{
			var url = this.main_url + "/" + response.data.trk_formname[i];
			var strLink = '<a href="'+url+'/?t='+template+'&drop_id='+response.data.drop_id[i]+qs+'">'+response.data.school_name[i]+' - '+response.data.short_title[i]+'</a><br clear="all">';
			
			$("#info_otherSchools").append(strLink);
		}
			
	},
	
	/*******************************************************************************
	 * 
	 * getDegreeInfo() - Get the degree type and degree information from the best-matched degree
	 * 
	 *******************************************************************************/
	
	getDegreeInfo : function() {
	    //Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "getDegreeInfo";
	    //data.school_id = $("input[name='trk_emdschool_id']").val();
	    data.school_id = this.school_id;
	    data.sid = $("input[name='sid']").val();
	    data.drop_id = prepop.drop_id;
	    data.type_id = prepop.type_id;
	    var ajaxdata = $.toJSON(data);
	
	    //Create Ajax Object For Parameters
	    var a = {};
	    a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("renderDegreeInfo",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {app.handleAjaxError(XMLHttpRequest,textStatus,errorThrown);};
	
	    //Make Ajax Request
	    this.ajax(a);
	},
	
	/*******************************************************************************
	 * 
	 * renderDegreeInfo() - callback for getDegreeInfo(), display degree info
	 * 
	 *******************************************************************************/
	
	renderDegreeInfo : function(response) {
		var drop_id = prepop.drop_id;
		var drop_title = response.DROP_TITLE;
		var degree_title = response.DEGREE_TITLE;
		var long_desc = response.LONG_DESC;
		var type = response.TYPE;
	
		//Set program information
		prepop.drop_title = drop_title;
	
		//Left Column
		$("#info_degree").hide();
		$("#info_school_name").html(this.school_name);
		$("#info_degree_level").html(type);
		$("#info_degree_name").html(degree_title);
	    $("#info_degree").fadeIn("normal");
	
		//Hide Right Column (to be handled by school code, degree_details, school_details, etc)
		$("#rightcol").hide();
	
		var strImg = '<div style="text-align:center"><img id="logo" src="http://www.earnmydegree.com/images/'+this.small_logo+'" alt="'+this.school_name+'" /></div>';
	    $("#school_logo").hide();
	    $("#school_logo").html(strImg);
	    $("#school_logo").fadeIn("slow");
	},
	
	/*******************************************************************************
	 * 
	 * redirect() - redirect user to prepopped school
	 * 
	 * arguments - n/a 
	 * dependencies - jquery1.3.2
	 * 				  jquery.json-1.3.min.js (http://code.google.com/p/jquery-json/)
	 * 
	 *******************************************************************************/
	
	redirect : function(response) {
		//var url = response.FORM_URL;
		var trk_formname = response.TRK_FORMNAME;
		var url = this.main_url + "/" + trk_formname;
		var drop_id = response.DROP_ID;
		var template = "V4";
		var qsCurrent = window.location.search
		//alert(qsCurrent);
		var qs = "?";
		var urlVars = this.getUrlVars(qsCurrent);
		
		$.each(urlVars, function(i, val) {
			if (i!=0) {qs+="&";}
			
			//Pull out Key
			if (i == "key") {
				//Do nothing	
			}
			else if (i == "c") {
				//Do nothing	
			}else{
				qs += i + "=" + val;			
			}
		});
		
		if (qs.indexOf("?") > -1) {
			qs += "&";
		}else{
			qs += "?";
		}
		//alert(qs);
		//Create object to store each element used in the redirect
		var u = {};
		u.t = template;
		u.drop_id = drop_id;
		u.sid = $("input[name='sid']").val();
		u.fid = $("input[name='fid']").val();
		u.key = $("input[name='key']").val();
		u.c = $("input[name='c']").val();
		u.v4_type_id = this.getSelectVal(this.v4fields.type_id);
		u.zip = $("#"+this.v4fields.zip).val();
		u.df_fname = $("#"+this.v4fields.first_name).val();
		u.df_lname = $("#"+this.v4fields.last_name).val();
		u.df_address = $("#"+this.v4fields.address).val();
		u.df_day_phone_area = $("#"+this.v4fields.day_phone_area).val();
		u.df_day_phone_prefix = $("#"+this.v4fields.day_phone_prefix).val();
		u.df_day_phone_suffix = $("#"+this.v4fields.day_phone_suffix).val();
		u.df_work_phone_area = $("#"+this.v4fields.night_phone_area).val();
		u.df_work_phone_prefix = $("#"+this.v4fields.night_phone_prefix).val();
		u.df_work_phone_suffix = $("#"+this.v4fields.night_phone_suffix).val();
		u.mobile_phone_area = $("#"+this.v4fields.mobile_phone_area).val();
		u.mobile_phone_prefix = $("#"+this.v4fields.mobile_phone_prefix).val();
		u.mobile_phone_suffix = $("#"+this.v4fields.mobile_phone_suffix).val();
		u.df_email = $("#"+this.v4fields.email).val();
		u.country = this.getRadioVal(this.v4fields.country);
		u.inactiveSchools = this.inactiveSchools;
		$.each(u, function(i, val) {
			if (i!=0) {qs+="&";}
			
			//If SID is already in the URL, don't append again
			if (i == "sid" && (qs.indexOf("sid=") > -1 || qs.indexOf("SID=") > -1)) {
				//Do nothing	
			}else{
				qs += i + "=" + val;			
			}
		});

		loc = url + qs;
		//alert(loc);
		this.debug("Redirecting to " + loc);
		
		this.setBool();
		setBool();
		window.location = loc;
	},

	/*******************************************************************************
	 * 
	 * isPageValid() - performs validation on a given page
	 * 
	 * arguments - string "page": the div that contains the elements to validate
	 * 
	 *******************************************************************************/
	
	isPageValid : function(page) {
	    var page = page - 1;
	
	    if (page == 1) {
	        //Ensure Age is Selected
	        if (this.getSelectVal(this.v4fields.age) == "") {
				this.throwError(this.errAgeNotSelected);
	            return false;
	        }
			else if (this.getSelectVal(this.v4fields.age) == "17 and Under") {
				this.invalidate("under_18");
				return false;
			}
	    } 
		
		else if (page == 2) {
	        //Ensure Country is Selected
			if (this.getRadioVal(this.v4fields.country) == "") {
	            this.throwError(this.errCountryNotSelected);
	            return false;
	        }
			else if (this.getRadioVal(this.v4fields.country) == "Other") {
				this.invalidate("foreign");
				return false;
			}
	
	    }
		
		else if (page == 3) {

			var country = this.getRadioVal(this.v4fields.country);
			var zip = $("#"+this.v4fields.zip);

	        //Ensure Zip/Postal Code is valid
			switch (country)
			{
				case 'US':
					//make sure it is all digits
					if (!this.isNumeric(zip.val()))
					{
						alert(this.errInvalidZipcode);
						zip.focus();
						return false;
					}
					
					//make sure it is 5 digits
					if (zip.val().length != 5)
					{
						alert(this.errInvalidZipcode);
						zip.focus();
						return false;
					}
					break;
				case 'CA':
					//make sure it is 6 long
					//remove all spaces inside the string
					var can_zip='';;
					for (i=0; i<zip.val().length; i++)
					{
						if (zip.val().charAt(i) != ' ')
						{
							can_zip += zip.val().charAt(i);
						}
					}
					if (can_zip.length != 6)
					{
						alert(this.errInvalidZipcode);
						zip.focus();
						return false;
					}
					break;
				default:
					//do no validation
					break;
			}

	        //Ensure Email Address is valid
	        if (!this.isValidEmail($("#"+this.v4fields.email).val())) {
	            this.throwError(this.errInvalidEmailAddress);
	            return false;
	        }
	    }

		else if (page == 4) {
	        //Ensure Cat is Selected
	        if (this.getSelectVal(this.v4fields.cat_id) == "") {
	            this.throwError(this.errCatNotSelected);
	            return false;
	        }
	    }
		
		else if (page == 5) {
	        //Ensure Type is Selected
	        if (this.getSelectVal(this.v4fields.type_id) == "") {
	            this.throwError(this.errTypeNotSelected);
	            return false;
	        }
	    }
		

		
		else if (page == 6) {
	
	
	    }
		
		else if (page == 7) {
	
	
	    }
		
		else if (page == 8) {
	        //Ensure the program is selected
	        if ($("select[name='program']").val() == "") {
	            this.throwError(this.errProgramNotSelected);
	            return false;
	        }
	
	    }
		
		else if (page == 9) {

	    }
	
		//Run any extra validation - usually school specific (like having to select Walden's specialization)
		if (!this.V3V4Compatibility(page,"post")) {return false;}
	
	    return true;
	},
	
	/*******************************************************************************
	 * 
	 * isPrequalPageValid() - performs validation on a given page
	 * 
	 * arguments - string "page": the div that contains the elements to validate
	 * 
	 *******************************************************************************/
	
	isPrequalPageValid : function(page) {
		
		if (page == 0) {
			this.currentPrequalPage = 1;
		}
	    else if (page == 1) {
	        //Ensure when_begin is Selected
	        if (this.getSelectVal(this.v4prequalfields.when_begin) == "") {
				this.throwError(this.errWhenBeginNotSelected);
	            return false;
	        }
			else if (this.getSelectVal(this.v4prequalfields.when_begin) == "1-3 Months") {
				this.answer = "1";
				app.exitPrequal = true;
			}
			else if (this.getSelectVal(this.v4prequalfields.when_begin) == "3-6 Months") {
				this.answer = "3";
				this.currentPrequalPage = 2;
			}
			else if (this.getSelectVal(this.v4prequalfields.when_begin) == "6-12 Months") {
				this.answer = "6";
				this.currentPrequalPage = 2;
			}
	    } 

		else if (page == 2) {
	        //Ensure employed is Selected
	        if (this.getSelectVal(this.v4prequalfields.employed) == "") {
				this.throwError(this.errEmployedNotSelected);
	            return false;
	        }
			else if (this.getSelectVal(this.v4prequalfields.employed) == "Yes") {
				this.answer = "Y";
				this.currentPrequalPage = 3;
			}
			else if (this.getSelectVal(this.v4prequalfields.employed) == "No") {
				this.answer = "N";
				if (this.getSelectVal(this.v4prequalfields.when_begin) == "3-6 Months") {
					this.currentPrequalPage = 4;
				}
				else if (this.getSelectVal(this.v4prequalfields.when_begin) == "6-12 Months") {
					this.currentPrequalPage = 5;
				}
			}
	    }
		
		else if (page == 3) {
			//Ensure employer_reimbursement is Selected
	        if (this.getSelectVal(this.v4prequalfields.employer_reimbursement) == "") {
				this.throwError(this.errEmployerReimbursementNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.when_begin) == "3-6 Months") {
				if (this.getSelectVal(this.v4prequalfields.employer_reimbursement) == "Yes") {
					this.answer = "Y";
				}
				else if (this.getSelectVal(this.v4prequalfields.employer_reimbursement) == "No") {
					this.answer = "N";
				}
				app.exitPrequal = true;
			}
			else { 
				if (this.getSelectVal(this.v4prequalfields.employer_reimbursement) == "Yes") {
					this.answer = "Y";
					app.exitPrequal = true;
				}
				else if (this.getSelectVal(this.v4prequalfields.employer_reimbursement) == "No") {
					this.answer = "N";
					this.currentPrequalPage = 4;
				}
			}
		}
		
		else if (page == 4) {
			//Ensure student_loans is Selected
	        if (this.getSelectVal(this.v4prequalfields.student_loans) == "") {
				this.throwError(this.errStudentLoansNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.when_begin) == "3-6 Months") {
				if (this.getSelectVal(this.v4prequalfields.student_loans) == "Yes") {
					this.answer = "Y";
					app.exitPrequal = true;
				}
				else if (this.getSelectVal(this.v4prequalfields.student_loans) == "No") {
					this.answer = "N";
					this.currentPrequalPage = 6;
				}
			}
			else if (this.getSelectVal(this.v4prequalfields.when_begin) == "6-12 Months") {
				if (this.getSelectVal(this.v4prequalfields.student_loans) == "Yes") {
					this.answer = "Y";
					this.currentPrequalPage = 7;
				}
				else if (this.getSelectVal(this.v4prequalfields.student_loans) == "No") {
					this.answer = "N";
					this.currentPrequalPage = 8;
				}
			}
		}
		
		else if (page == 5) {
			//Ensure time_commitment is Selected
	        if (this.getSelectVal(this.v4prequalfields.time_commitment) == "") {
				this.throwError(this.errTimeCommitmentNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.time_commitment) == "Yes") {
				this.answer = "Y";
				this.currentPrequalPage = 7;
			}
			else if (this.getSelectVal(this.v4prequalfields.time_commitment) == "No") {
				this.answer = "N";
				this.currentPrequalPage = 4;
			}
		}
		
		else if (page == 6) {
			//Ensure previously_attended is Selected
	        if (this.getSelectVal(this.v4prequalfields.previously_attended) == "") {
				this.throwError(this.errPreviouslyAttendedNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.previously_attended) == "Yes") {
				this.answer = "Y";
				app.exitPrequal = true;
			}
			else if (this.getSelectVal(this.v4prequalfields.previously_attended) == "No") {
				this.answer = "N";
				this.currentPrequalPage = 7;
			}
		}
		
		else if (page == 7) {
			//Ensure previously_requested is Selected
	        if (this.getSelectVal(this.v4prequalfields.previously_requested) == "") {
				this.throwError(this.errPreviouslyRequestedNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.previously_requested) == "Yes") {
				this.answer = "Y";
				this.currentPrequalPage = 9;
			}
			else if (this.getSelectVal(this.v4prequalfields.previously_requested) == "No") {
				this.answer = "N";
				app.exitPrequal = true;
			}
		}
		
		else if (page == 8) {
			//Ensure financial_commitment is Selected
	        if (this.getSelectVal(this.v4prequalfields.financial_commitment) == "") {
				this.throwError(this.errFinancialCommitmentNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.financial_commitment) == "Yes") {
				app.exitPrequal = true;
				this.answer = "Y";
			}
			else if (this.getSelectVal(this.v4prequalfields.financial_commitment) == "No") {
				this.answer = "N";
				this.currentPrequalPage = 9;
			}
		}
		
		else if (page == 9) {
			//Ensure contact_advisor is Selected
	        if (this.getSelectVal(this.v4prequalfields.contact_advisor) == "") {
				this.throwError(this.errContactAdvisorNotSelected);
	            return false;
	        }
			if (this.getSelectVal(this.v4prequalfields.contact_advisor) == "Yes") {
				this.answer = "Y";
				app.exitPrequal = true;
			}
			else if (this.getSelectVal(this.v4prequalfields.contact_advisor) == "No") {
				this.answer = "N";
				this.invalidate("invalid_prequal");
				return false;
			}
		}
	
		//Run any extra validation - usually school specific (like having to select Walden's specialization)
		//if (!this.V3V4Compatibility(page,"post")) {return false;}
		
	    return true;
	},
	
	/*******************************************************************************
	 * 
	 * invalidate() - Invalidate a lead given certain information
	 * 
	 *******************************************************************************/
	
	invalidate : function(reason) {
		var msg = "";
		var loc = "";
		var qs = window.location.search;
		var autoRedirect = true;
		
		window.onbeforeunload = null;
		this.setBool();
		setBool();
		
		//Ensure KEY, SID, AND FID are added in the query_string (if we dont already have them)
		if (qs.indexOf("sid=") == -1 && qs.indexOf("SID=") == -1) {
			qs += "&sid=" + $("input[name='sid']").val();
		}
		if (qs.indexOf("&fid=") == -1 && qs.indexOf("&FID=") == -1) {
			qs += "&fid=" + $("input[name='fid']").val();
		}		

		$("#numSchoolsContent").hide();
	

		if (reason == "under_18") {
			loc = "http://military.zinch.com/?source=Eddy&utm_source=Eddy&utm_medium=Affiliate&utm_campaign=MilitaryScholarships";
			//msg += "<a target='_new' href='"+loc+qs+"'>www.EarnMyHighschoolDiploma.com</a>";
			msg += "<a target='_new' href='"+loc+qs+"'><img src='images/zinch-military.jpg' border='0'></a>";
			autoRedirect = false;
		}
		if (reason == "invalid_prequal") {
			loc = "http://EarnMyDegree.com";
			msg += '<br/>Thank you for your interest in online education.  Unfortunately, we don\'t have any opportunities that meet your needs at this time.<BR/><BR/>We\'re happy to present you the following from one of our trusted partners:<BR/><BR/>';
			msg += '<IFRAME SRC="http://ad.doubleclick.net/adi/N5177.EarnMyDegree.com/B4050170.3;sz=740x300;ord=[timestamp]?" WIDTH=740 HEIGHT=300 MARGINWIDTH=0 MARGINHEIGHT=0 HSPACE=0 VSPACE=0 FRAMEBORDER=0 SCROLLING=no BORDERCOLOR=\'#000000\' style="margin-left:-15px;">';
			msg += '<SCRIPT language=\'JavaScript1.1\' SRC="http://ad.doubleclick.net/adj/N5177.EarnMyDegree.com/B4050170.3;abr=!ie;sz=740x300;ord=[timestamp]?">';
			msg += '</SCRIPT><NOSCRIPT>';
			msg += '<A HREF="http://ad.doubleclick.net/jump/N5177.EarnMyDegree.com/B4050170.3;abr=!ie4;abr=!ie5;sz=740x300;ord=[timestamp]?">';
			msg += '<IMG SRC="http://ad.doubleclick.net/ad/N5177.EarnMyDegree.com/B4050170.3;abr=!ie4;abr=!ie5;sz=740x300;ord=[timestamp]?" BORDER=0 WIDTH=740 HEIGHT=300 ALT="Click Here"></A>';
			msg += '</NOSCRIPT></IFRAME>';
			
			autoRedirect = false;
		}
		if (reason == "foreign") {
			loc = "http://earnmydegreeabroad.com";
			a = "<a target='_new' href='"+loc+qs+"'>www.EarnMyDegreeAbroad.com</a>";
			msg += "<BR><BR><BR>Looking for schools and degrees for international students?<BR><BR>Check out "+a+" to find a school that's right for you!";
			msg += "<BR><BR><BR>(you will be automatically redirected in 10 seconds)";
		}
	
	
		//Remove Top-Left Text (Please answer the questionnaire below...)
	    $(".top-left-content").hide();
	
	  	//Remove Questions
	    $(".pageNumBG").hide();
	    $("#pageNum").hide();
	    $("#page" + this.currentPage).hide();
	
		//Remove Navigation
	    $("#nav_prev").hide();
	    $("#nav_next").hide();
	
		//Animate - Fade out the left column
		$(".left-content").fadeOut("normal", function() {
			//Make the right column about 100% width/height of container
			$("#rightcol").css({"width":"750px"}).css({"height":"350px"});
			//Show disqualifying message
			$("#rightcol_default").html(msg);
			$("#rightcol_default").fadeIn("slow");
		});
	
		//Track the invalidation
		this.trackView(reason);
		
		loc += qs;
		this.setBool();
		
		if (autoRedirect) {
			setTimeout("window.location='"+loc+"'",10000);
		}
	},
	
	/*******************************************************************************
	 * 
	 * initEventHandlers() - Handle each user interaction with a form element
	 * 
	 *******************************************************************************/
	
	initEventHandlers : function() {
		
		//When_Begin Handler
		$("#"+this.v4prequalfields.when_begin).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Employed Handler
		$("#"+this.v4prequalfields.employed).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Employer_Reimbursement Handler
		$("#"+this.v4prequalfields.employer_reimbursement).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Time_Commitment Handler
		$("#"+this.v4prequalfields.time_commitment).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Student_Loans Handler
		$("#"+this.v4prequalfields.student_loans).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Previously_Attended Handler
		$("#"+this.v4prequalfields.previously_attended).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Previously_Requested Handler
		$("#"+this.v4prequalfields.previously_requested).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Financial_Commitment Handler
		$("#"+this.v4prequalfields.financial_commitment).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Contact_Advisor Handler
		$("#"+this.v4prequalfields.contact_advisor).change(
			function(){
				app.gotoNextPrequalPage();
			}
		);
		
		//Age Handler
		$("#"+this.v4fields.age).change(
			function(){
				app.gotoPage(2);
			}
		);

		//Country Handler
		$("input[name='"+this.v4fields.country+"']").click(
			function(){
				//Clear Caching of dropdown items
				app.areaOfStudyPopulated = false;
				app.degreeTypePopulated = false;

				//Clear the type, cat, and conc_id dropdown options
				app.clearDropdown(app.v4fields.type_id);
				app.clearDropdown(app.v4fields.cat_id);
				app.clearDropdown(app.v4fields.conc_id);

				app.debug("Type/Cat/Concs Reset");
				
				app.gotoPage(3);
			}
		);

		//Zip Handler
		$("input[name='"+this.v4fields.zip+"']").blur(function(){
				app.resetTypeCatConc();
		});

		//Email Handler
		$("input[name='"+this.v4fields.email+"']").blur(function(){
				app.resetTypeCatConc();
		});
		$("input[name='"+this.v4fields.email+"']").keydown(function(e){
			if (e.keyCode == 13) {
				$("input[name='"+app.v4fields.email+"']").blur();
				app.gotoPage(app.currentPage + 1);
			}
		});


		//cat_id Handler (either displays div_conc_id or fires gotoPage(4))
		$("#"+this.v4fields.cat_id).change(
			function(){
				//Clear the type, cat, and conc_id dropdown options
				app.clearDropdown(app.v4fields.type_id);

				//reset degreeTypePopulated so it will be cleared and re-populated
				app.degreeTypePopulated = false;
				app.populateConcentrationDropDown(app.getSelectVal(app.v4fields.cat_id))
			}
		);

		//conc_id Handler
		$("#"+this.v4fields.conc_id).change(
			function(){
				//reset degreeTypePopulated so it will be cleared and re-populated
				app.clearDropdown(app.v4fields.type_id);
				app.degreeTypePopulated = false;
				app.gotoPage(5);
			}
		);
		//type_id Handler
		$("#"+this.v4fields.type_id).change(
			function(){
				app.gotoPage(6);
			}
		);
	
		//NAV - previous
	    $("#nav_prev").click(function() {
	        if (app.currentPage != 1 && app.currentPage != 8) {
				app.gotoPage(app.currentPage - 1);			
	        }
	    });
	
		//NAV - next
	    $("#nav_next").click(function() {
	       	app.gotoPage(app.currentPage + 1);
	    });
	
		//MODAL - close button
	    $("#modalClose").click(function() {
	       	app.toggleModal();
	    });
	
		//submit button Handler
		$("#button").click(
			function(){
				app.setBool();
			}
		);
	
		//FORM "Entry" submit
		$("#Entry").submit(function() {
			if (!app.formReady) return false;
			app.setBool();
			return checkForm();
		});
	
	},
	
	/*******************************************************************************
	 * 
	 * resetTypeCatConc() - require a re-rendering of category, concentration, and type dropdowns
	 * 
	 *******************************************************************************/
	resetTypeCatConc : function() {
		//Clear Caching of dropdown items
		this.areaOfStudyPopulated = false;
		this.degreeTypePopulated = false;

		//Clear the type, cat, and conc_id dropdown options
		this.clearDropdown(this.v4fields.type_id);
		this.clearDropdown(this.v4fields.cat_id);
		this.clearDropdown(this.v4fields.conc_id);

		//Reset School List
		this.inactiveSchools = [];

		this.debug("Type/Cat/Concs Reset");
		this.debug("inactiveSchools reset to empty array: [ "+this.inactiveSchools+" ]");
	},

	/*******************************************************************************
	 * 
	 * getDegreeCount() - takes any selected type_id, cat_id, and conc_id, constructs
	 * 					  a JSON string, and passes it over to "url" to determine how
	 * 					  many degrees are available with these parameters.
	 * 
	 * arguments - n/a 
	 * dependencies - jquery1.3.2
	 * 				  jquery.json-1.3.min.js (http://code.google.com/p/jquery-json/)
	 * 
	 *******************************************************************************/
	
	getDegreeCount : function() {
	
	    //Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "getDegrees";
		data.inactiveSchools = this.inactiveSchools;
		data.getCount = true;
	    data.country = this.getRadioVal(this.v4fields.country);
	    data.type_id = this.getSelectVal(this.v4fields.type_id);
	    data.cat_id = this.getSelectVal(this.v4fields.cat_id);
	    data.conc_id = this.getSelectVal(this.v4fields.conc_id);
	    data.zip = $("input[name='"+this.v4fields.zip+"']").val();
	    var ajaxdata = $.toJSON(data);
	
	    //Create Ajax Object For Parameters
	    var a = {};
	    a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("showDegreeCount",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {app.handleAjaxError(XMLHttpRequest,textStatus,errorThrown);};
	
	    //Make Ajax Request
	    this.ajax(a);
	},
	
	/*******************************************************************************
	 * 
	 * showDegreeCount() - hides "rightcolContent", sets the number of degrees found, 
	 * 					  and fades-in "numSchools".
	 * 
	 * arguments - int "response" - the response from an ajax call
	 * 
	 *******************************************************************************/
	
	showDegreeCount : function(response) {
		var numschools = response.NUMDEGREES;
	    var degreeTxt = (numschools==1) ? " Program<br /><br /> That Matches Your Interests" : " Programs<br /><br /> That Match Your Interests";
	
		//Turn off the Ajax GIF
		this.ajaxSpinner(0);

	    $("#rightcol_default").hide();
		$("#numSchools").attr({ "innerHTML": numschools + degreeTxt });
	    $("#numSchoolsContent").fadeIn("normal");
	},
	
	/*******************************************************************************
	 * 
	 * getActiveTypes() - returns a JSON string of types
	 * 
	 * arguments - int cat_id
	 * dependencies - jquery1.3.2
	 * 				  jquery.json-1.3.min.js (http://code.google.com/p/jquery-json/)
	 * 
	 *******************************************************************************/
	
	getActiveTypes : function() {

		//Clear the type_id dropdown options
		this.clearEntireDropdown(this.v4fields.type_id);
		
		//Populate the type_id dropdown with "Please Wait..." and disable it until ajax is finished
		$("#"+this.v4fields.type_id).append("<option value=''>Please Wait...</option>").attr({"disabled":"true"});

	    //Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "getActiveTypes";
		data.inactiveSchools = this.inactiveSchools;
		data.cat_id = this.getSelectVal(this.v4fields.cat_id);
		data.conc_id = this.getSelectVal(this.v4fields.conc_id);
		data.country = this.getRadioVal(this.v4fields.country);
	    data.zip = $("input[name='"+this.v4fields.zip+"']").val();
	    var ajaxdata = $.toJSON(data);
		
	    //Create Ajax Object For Parameters
	    var a = {};
	    a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("populateTypeDropDown",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {app.handleAjaxError(XMLHttpRequest,textStatus,errorThrown);};
	
	    //Make Ajax Request
	    this.ajax(a);
	},
	
	/*******************************************************************************
	 * 
	 * populateTypeDropDown() - populates the area of study dropdown from ajax call
	 * 
	 * arguments - string "response" - a selectbox from an ajax call
	 * 
	 *******************************************************************************/
	
	populateTypeDropDown : function(response) {
		//Set global variable for later use
		this.degreeTypes = response;
	
		//Clear the type_id dropdown options
		this.clearEntireDropdown(this.v4fields.type_id);
	
		//Populate the cat_id dropdown with "Please Wait..." and disable it until ajax is finished
		$("#"+this.v4fields.type_id).append("<option value=''>Choose Degree Type</option>").attr({"disabled":""});
	
		//Populate type_id dropdown
		$.each(response, function(i,types){
			$("#"+app.v4fields.type_id).append("<option value='"+types.TYPE_ID+"'>"+types.TYPE+"</option>");
		});

		//Set flag
		this.degreeTypePopulated = true;

		//Show the DegreeCount
        this.getDegreeCount();
	},
	
	/*******************************************************************************
	 * 
	 * getActiveCatsAndConcs() - returns a JSON string of cats[concs]
	 * 
	 * arguments - n/a 
	 * dependencies - jquery1.3.2
	 * 				  jquery.json-1.3.min.js (http://code.google.com/p/jquery-json/)
	 * 
	 *******************************************************************************/
	
	getActiveCatsAndConcs : function() {

		//Don't update the right column if required by the skin
		if (!this.rightColDelay) {
			//Show the DegreeCount
	        this.getDegreeCount();
		}

	    //Store Ajax Request Variables In An Object and convert them to JSON
	    var data = {};
	    data.action = "getActiveCatsAndConcs";
		data.inactiveSchools = this.inactiveSchools;
		data.country = this.getRadioVal(this.v4fields.country);
	    data.zip = $("input[name='"+this.v4fields.zip+"']").val();
	    var ajaxdata = $.toJSON(data);
		
	    //Create Ajax Object For Parameters
	    var a = {};
	    a.type = "POST";
	    a.url = this.ajaxUrl;
	    a.data = {data:ajaxdata};
	    a.dataType = "json";//"xml", "html", "script", "json", "jsonp", or "text";
	    a.success = function(response) {app.handleAjaxSuccess("populateAreaOfStudyDropDown",response);};
	    a.error = function(XMLHttpRequest, textStatus, errorThrown) {app.handleAjaxError(XMLHttpRequest,textStatus,errorThrown);};
	
	    //Make Ajax Request
	    this.ajax(a);

	},
	
	/*******************************************************************************
	 * 
	 * populateAreaOfStudyDropDown() - populates the area of study dropdown from ajax call
	 * 
	 * arguments - string "response" - a selectbox from an ajax call
	 * 
	 *******************************************************************************/
	
	populateAreaOfStudyDropDown : function(response) {
		var strSelected = "";
		
		//Set global variable for later use
		this.degreeCatAndConcs = response;
	
		//Clear the cat_id dropdown options
		this.clearEntireDropdown(this.v4fields.cat_id);
	
		//Populate the cat_id dropdown with "Please Wait..." and disable it until ajax is finished
		$("#"+this.v4fields.cat_id).append("<option value=''>Choose an area of study</option>").attr({"disabled":""});

		//Populate cat_id dropdown
		$.each(response, function(i,cats){
			strSelected = (prepop.cat_id == cats.CAT_ID) ? "selected" : "";
			$("#"+app.v4fields.cat_id).append("<option value='"+cats.CAT_ID+"' "+strSelected+">"+cats.CATNAME+"</option>");
			if (prepop.cat_id == cats.CAT_ID) {app.populateConcentrationDropDown(cats.CAT_ID)};
		});

		//Set flag
		this.areaOfStudyPopulated = true;

	},
	
	/*******************************************************************************
	 * 
	 * populateConcentrationDropDown() - populates the concentration dropdown from ajax call
	 * 
	 * arguments - int "cat_id" - the cat_id to fetch concentrations for
	 * 
	 *******************************************************************************/
	
	populateConcentrationDropDown : function(cat_id) {
		var strSelected = "";
		var hasConcs = false;
		var prepoppedConc = false;
	
		//Hide the Concentration DIV
		$("#div_conc_id").hide();
	
		//Clear the conc_id dropdown options
		this.clearDropdown(this.v4fields.conc_id);
	
		//Loop through cached degreeCatAndConcs and get our concentrations for the cat_id
		$.each(this.degreeCatAndConcs, function(i,cats){
			if (cats.CAT_ID == cat_id) {
				$.each(cats.CONCENTRATIONS, function(j,concs){
					if (prepop.conc_id == concs.CONCENTRATION_ID) {strSelected = "selected";prepoppedConc = true;}else{strSelected = "";}
					$("#"+app.v4fields.conc_id).append("<option value='"+concs.CONCENTRATION_ID+"' "+strSelected+">"+concs.CONCENTRATION_NAME+"</option>");
					hasConcs=true;
				});
			}
		});
	
		//If we have concentrations, display the Concentration DIV
		if (hasConcs) {
			$("#div_conc_id").fadeIn("normal");
			if (prepoppedConc){
				this.gotoPage(5);
			}
		}else{
			this.gotoPage(5);
		}
	},
	
	/*******************************************************************************
	 * 
	 * updateCityStateV4() - set hidden fields for city/state
	 * 
	 * arguments - obj "response": the JSON'd city and state
	 *
	 *******************************************************************************/
	
	updateCityStateV4 : function(response) {
		$("#"+this.v4fields.city).val(response.CITY);
		$("#"+this.v4fields.state).val(response.STATE);
	
		this.debug("City set to: " + $("#"+this.v4fields.city).val() + "<BR>" + "State set to: " + $("#"+this.v4fields.state).val());
	},




	/*******************************************************************************
	 *	AJAX FUNCTIONS
	 *******************************************************************************/
	
	debug : function(str) {
		this.test = str + "<BR><BR>" + this.test;
		$("#debug").attr({"innerHTML":this.test})
	},
	
	/*******************************************************************************
	 * 
	 * ajax() - make an ajax request
	 * 
	 * arguments - object a
	 * 
	 *******************************************************************************/
	
	ajax : function(a) {
	
		//DEBUG
		var ajaxUrl = this.ajaxUrl + "?debug=true&data=" + escape(a.data.data);
		var ajaxA = "<a target='_new' href='" + ajaxUrl + "'>" + ajaxUrl + "</a>";
		var rightColDelay = false;
		this.debug(ajaxA);

		//Make Ajax Request
	    $.ajax(a);

		///If RightColDelay, don't update the right column until page 5
		if (this.rightColDelay && (this.currentPage == 3 || this.currentPage == 4)) {
			rightColDelay=true;
		}

		if(!a.doTrack && !rightColDelay) {
			//Turn on the Ajax GIF
		    this.ajaxSpinner(1);
	
			//Increment number of active ajax requests
			this.numActiveAjaxRequests++;

			this.debug("number of active ajax requests: " + this.numActiveAjaxRequests);
	    }

	},
	
	/*******************************************************************************
	 * 
	 * handleAjaxSuccess() - make an ajax request
	 * 
	 * arguments - string callback, object response
	 * 
	 *******************************************************************************/
	
	handleAjaxSuccess : function(callback, response) {
	    if (callback != "doTrack") {

			//Decrement number of active ajax requests
			this.numActiveAjaxRequests--;
			this.debug("decrementing number of active ajax requests for "+callback+" to " + this.numActiveAjaxRequests);

			//Turn off the Ajax GIF
			if (this.numActiveAjaxRequests <= 0) {
				this.ajaxSpinner(0);
			}
		}

		if (callback=="showDegreeCount") {
			this.showDegreeCount(response);
		}else if (callback=="populateAreaOfStudyDropDown") {
			this.populateAreaOfStudyDropDown(response);
		}else if (callback=="handleDupStatus") {
			this.handleDupStatus(response);
		}else if (callback=="populateTypeDropDown") {
			this.populateTypeDropDown(response);
		}else if (callback=="updateCityStateV4") {
			this.updateCityStateV4(response);
		}else if (callback=="redirect") {
			this.redirect(response);
		}else if (callback=="renderDegreeInfo") {
			this.renderDegreeInfo(response);
		}else if (callback=="doTrack") {
			this.doTrack(response);
		}else if (callback=="renderOtherDegreeInfo") {
			this.renderOtherDegreeInfo(response);
		}

	},
	
	/*******************************************************************************
	 * 
	 * handleAjaxError() - This function is triggered upon all failed ajax attempts
	 * 
	 * arguments -  XMLHttpRequest,textStatus,errorThrown
	 *******************************************************************************/
	
	handleAjaxError : function(XMLHttpRequest,textStatus,errorThrown){
		//alert(XMLHttpRequest+" "+textStatus+" "+errorThrown);
		
		//alert user
		this.throwError(this.errAjax);
		
		//go back a page
		if(this.currentPage != 8)
		{
			this.gotoPage(this.currentPage-1);
		}
		if(this.currentPage == 8)
		{
			$("#info_otherSchools").html("");
		}
		
	
	    //Turn off the Ajax GIF
	    this.ajaxSpinner(0);
		
		//Reset number of active ajax requests
		this.numActiveAjaxRequests = 0;
	},
	
	/*******************************************************************************
	 * 
	 * ajaxSpinner() - Toggle the ajax spinner .gif
	 * 
	 * arguments -  bool onOff
	 *******************************************************************************/
	
	ajaxSpinner : function(onOff){
	
		if (onOff){
			$("#numSchoolsContent").hide();
			$("#rightcol_default").hide();
			$("#ajaxSpinner").html("<img id='ajaxSpinnerImg' src='"+this.ajaxSpinnerImg+"'/>");
		}else{
			$("#ajaxSpinner").html("");
		}
	},
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*******************************************************************************
	 * HELPER FUNCTIONS
	 *******************************************************************************/
	
	toggleModal : function(dialog) {
		if (!modalOn) {
			$("#maincontent").hide();
			$("#dialog").html(dialog);
			$("#modal").fadeIn("normal");
			modalOn = true;
		}else{
			$("#modal").hide();
			$("#dialog").html("");
			$("#maincontent").fadeIn("normal");
			modalOn = false;
		}
	},
	
	/*******************************************************************************
	 * 
	 * setBool() - disables the onbeforeunload event (the alert seen upon leaving the page)
	 *
	*******************************************************************************/
	
	setBool : function () {
		this.disableBeforeUnloadEvent = true;
	},

	/*******************************************************************************
	 * 
	 * preloadImages() - Preload any images defined in preloadImages
	 * 
	 *******************************************************************************/
	
	preloadImages : function() {
		if (document.images) {
			var debugStr = "";
			for (var picIndex in this.imagesToPreload) {
				pic = new Image(1,1);
				pic.src=this.path + "/skins/" + this.skin + "/images/"+this.imagesToPreload[picIndex];
				debugStr += "<a target='_new' href='"+pic.src+"'>"+pic.src + "</a><BR>";
			}
			this.debug(debugStr);
		}
	},

	/*******************************************************************************
	 * 
	 * throwError() - show Modal Dialog
	 * 
	 * arguments - string "error": text of the error message
	 * dependenceies - 	ui.core.js
	 *					ui.draggable.js
	 *					ui.resizable.js
	 *					jquery.ui.dialog.js
	 *******************************************************************************/
	
	throwError : function(error) {
	    //toggleModal(error);
		alert(error);
		//$.modal("<div id='errorContent'>" + error + "</div>");
	},
	
	/*******************************************************************************
	 * 
	 * getRadioVal() - determines the value of a group of radio buttons
	 * 
	 * arguments - string "radioGroup" - the name of the group of radio buttons
	 * 
	 *******************************************************************************/
	
	getRadioVal : function(radioGroup) {
		if (typeof ($('input[name='+radioGroup+']:radio:checked').val()) == "undefined") {
			return "";
		}else{
			return $('input[name='+radioGroup+']:radio:checked').val();
		}
	},
	
	/*******************************************************************************
	 * 
	 * setRadioVal() - sets the value of a group of radio buttons
	 * 
	 * arguments - string "radioGroup" - the name of the group of radio buttons
	 * 			 - string "value" - the radio button to check
	 * 
	 *******************************************************************************/
	
	setRadioVal : function(radioGroup,value) {
		var radioVal = "";
		$.each($('input[name='+radioGroup+']:radio'), function(i) {
			radioVal = $('input[name='+radioGroup+']:radio:nth('+i+')').val();
			if (value == radioVal) {
				$('input[name='+radioGroup+']:radio:nth('+i+')').attr({"checked":"checked"});
			}
		});
	},
	
	/*******************************************************************************
	 * 
	 * getSelectVal() - determines the value of a selectbox
	 * 
	 * arguments - string "selectbox" - the name of the selectbox
	 * 
	 *******************************************************************************/
	
	getSelectVal : function(selectbox) {
		
		if (typeof ($("#"+selectbox).val()) == "undefined") {
			return "";
		}else{
			return $("#"+selectbox).val();
		}
	},
	
	/*******************************************************************************
	 * 
	 * clearDropdown() - removes all options from a selectbox but the "Please Select"
	 * 
	 * arguments - string "selectbox" - the name of the selectbox
	 * 
	 *******************************************************************************/
	
	clearDropdown : function(selectbox) {
		var dropdown = document.getElementById(selectbox);
		for(var x=dropdown.options.length; x>0; x--) dropdown.options[x] = null;
	},
	

	/*******************************************************************************
	 * 
	 * clearEntireDropdown() - removes all options from a selectbox
	 * 
	 * arguments - string "selectbox" - the name of the selectbox
	 * 
	 *******************************************************************************/
	
	clearEntireDropdown : function(selectbox) {
		var dropdown = document.getElementById(selectbox);
		for(var x=dropdown.options.length; x>=0; x--) dropdown.options[x] = null;
	},

	/*******************************************************************************
	 * 
	 * renderProgressBar() - Render the Progress Bar seen at the upper-right
	 * 
	 * dependencies - jquery.progressbar.min.js
	 * 
	 *******************************************************************************/
	
	renderProgressBar : function() {
	
	    //Progress is 100% complete if on the congrats page (phase 5)
		if (this.phase == 5) {
			percentComplete = 100;
	    //Progress is 90% complete if on the thank you page (phase 3)
		}else if (this.phase == 3) {
			percentComplete = 95;
		}else{
		    //Count Number of Pages
		    numPages = $(".page").size();		
			percentComplete = this.currentPage / numPages * 100;
		}

	    $("#progressbar").progressBar(percentComplete, {showText:false, boxImage: this.progressBarBoxImg, barImage: this.progressBarImg });
	},
	

	/*******************************************************************************
	 * 
	 * isValidEmail() - bool. Performs a RegEx to determine email validity
	 *
	 * arguments - string "email" - the email address to perform check on 
	 * 
	 *******************************************************************************/
	
	isValidEmail : function(email) {	
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		if (filter.test(email))
		{
			return true;
		}
		else
		{
			return false;
		}
	},
	
	/*******************************************************************************
	 * 
	 * isNumeric() - bool. Checks a string for 0-9 characters
	 *
	 * arguments - string "strString" - the string to check
	 * 
	 *******************************************************************************/
	
	isNumeric : function(strString){
		var i = 0; 
		var strValidChars = "0123456789";
		var strChar;
		var blnResult = true;
	
		//test strString consists of valid characters listed above
		for (a = 0; a < strString.length; a++)
		{
			strChar = strString.charAt(a);
			if (strValidChars.indexOf(strChar) == -1)
			{
				blnResult = false;
				break;
			}
		}
	   return blnResult;
	
	},

	/*******************************************************************************
	 * 
	 * dump() - dump an array or object
	 * 
	 *******************************************************************************/
	
	dump : function(arr,level) {
		var dumped_text = "";
		if(!level) level = 0;
		
		//The padding given at the beginning of the line.
		var level_padding = "";
		for(var j=0;j<level+1;j++) level_padding += "    ";
		
		if(typeof(arr) == 'object') { //Array/Hashes/Objects
		 for(var item in arr) {
		  var value = arr[item];
		 
		  if(typeof(value) == 'object') { //If it is an array,
		   dumped_text += level_padding + "'" + item + "' ...<br>";
		   //dumped_text += dump(value,level+1);
		  } else {
		   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"<br>";
		  }
		 }
		} else { //Stings/Chars/Numbers etc.
		 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
		}
		return dumped_text;
	},
	

	/*******************************************************************************
	 * 
	 * removeFromArray() - Remove an element from an array
	 * 
	 *******************************************************************************/	

	removeFromArray : function(arrayName,arrayElement)
	{
		var str = "";
		str += "<BR>Array Before:" + arrayName;
	    
		for(var i=0; i<arrayName.length;i++ )
	     { 
	        if(arrayName[i]==arrayElement)
	            arrayName.splice(i,1); 
		} 

		str += "<BR>Array Removed:" + arrayElement;
		str += "<BR>Array After:" + arrayName;
		this.debug(str);
	},
	

	/*******************************************************************************
	 * 
	 * copyV4Phone() - copy phone from dayphone to nightphone
	 * 
	 *******************************************************************************/
	
	copyV4Phone : function(ffield)
	{
		var f = document.Entry;
		var area = f[this.v4fields.day_phone_area];
		var prefix = f[this.v4fields.day_phone_prefix];
		var suffix = f[this.v4fields.day_phone_suffix];
		var narea = f[this.v4fields.night_phone_area];
		var nprefix = f[this.v4fields.night_phone_prefix];
		var nsuffix = f[this.v4fields.night_phone_suffix];
		samephone = f[this.v4fields.samephone];
		if(samephone.checked)
		{
			//area
			if((ffield.name == this.v4fields.samephone && narea.value == '' && area.value != '') || (ffield.name == this.v4fields.day_phone_area && narea.value.length < area.value.length)) 
			{
				narea.value=area.value;
			} 
	
			if((ffield.name == this.v4fields.samephone && area.value ==  '' && narea.value != '') || (ffield.name == this.v4fields.night_phone_area && area.value.length < narea.value.length))
			{
				area.value=narea.value;
			} 
			
			if(narea.value != area.value) 
			{
				samephone.checked=0;
			} 
			
			//prefix
			if((ffield.name == this.v4fields.samephone && nprefix.value == '' && prefix.value != '') || (ffield.name == this.v4fields.day_phone_prefix && nprefix.value.length < prefix.value.length)) 
			{
				nprefix.value=prefix.value;
			} 
	
			if((ffield.name == this.v4fields.samephone && prefix.value == '' && nprefix.value != '') || (ffield.name == this.v4fields.night_phone_prefix && prefix.value.length < nprefix.value.length)) 
			{
				prefix.value=nprefix.value;
			} 
			
			if(nprefix.value != prefix.value) 
			{
				samephone.checked=0;
			} 
			
			//suffix
			if((ffield.name == this.v4fields.samephone && nsuffix.value == '' && suffix.value != '') || (ffield.name == this.v4fields.day_phone_suffix && nsuffix.value.length < suffix.value.length))
			{
				nsuffix.value=suffix.value;
			} 
	
			if((ffield.name == this.v4fields.samephone && suffix.value == '' && nsuffix.value != '') || (ffield.name == this.v4fields.night_phone_suffix && suffix.value.length < suffix.value.length))
			{
				suffix.value=nsuffix.value;
			} 
			
			if(nsuffix.value != suffix.value) 
			{
				samephone.checked=0;
			} 
		} else {
			if (ffield.name != this.v4fields.samephone && 
				suffix.value!='' &&
			    suffix.value==nsuffix.value &&
				prefix.value!='' &&
				prefix.value==nprefix.value &&
				area.value!='' &&
				area.value==narea.value)
				{
					samephone.checked=1;
				}
		}
	},
	
	/*******************************************************************************
	 * 
	 * getUrlVars() - Returns a structure of URL variables
	 *
	 * arguments - string "url" - the url to perform check on 
	 * 
	 *******************************************************************************/
	
	getUrlVars : function(url) {	
		var map = {};
		var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
		function(m,key,value) {
		map[key] = value;
		});
		return map; 
	}
};


/*******************************************************************************
 * 
 * setBool() - disables the onbeforeunload event (the alert seen upon leaving the page)
 *
*******************************************************************************/

function setBool () {
	app.disableBeforeUnloadEvent = true;
}

/*******************************************************************************
 * 
 * NewWindow() - attempt to pop open a window and set focus to it
 *
*******************************************************************************/

function NewWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable';
	win = window.open(mypage, myname, winprops);
	if (parseInt(navigator.appVersion) >=4 && win != null) { win.window.focus(); }
}