/* All hidden values (anything available in the Aptireport Affilaite Report) and taxonomy need to be included on page 1 except:
	clientdelivery, acknowledge, vendor_test, decode (any decodes - including mode), page, output */
	
/* Variables set to translate values if needed */
var rfiCookieValueMap= {"arts-and-sciences":"9","business-and-management":"1","criminal-justice-and-security":"2","education":"3","nursing-and-health-care":"5","human-services":"4","psychology":"6","technology":"7"};
var rfiProgramValueIDMap={"1":"business-and-management","2":"criminal-justice-and-security","3":"education","4":"human-services","5":"nursing-and-health-care","6":"psychology","7":"technology","9":"arts-and-sciences"};
var programSelect;
var country;
var cList;
var orderID;
var cmCart = false;
var currentPoid = getValue('poid');
var campaignIDInt = getValue('campaignIDInt');
var clientDelivery = getValue('clientdelivery');
var clphone = getValue('clphone');
var cluserid = getValue('cluserid');
var debug  = getValue('v3') ? true : false;
var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
var mode = getValue('mode');
var kw = getValue('kw');
var detail = getValue('detail_code');
var creativeID = getValue('creative_id');
var source = getValue('channel');
var v1 = getValue('v1');
var v2 = APTFormVariables.oid ? APTFormVariables.oid+'-'+APTFormVariables.oiid : getValue('v2');
var v3 = getValue('v3');
var v4 = getValue('v4');
var v5 = getValue('v5');
var v6 = getValue('v6');
var v7 = getValue('v7');
var v8 = getValue('v8');
var country = getValue('country');
var country_codes = getValue('country_codes');
var program_type = getValue('program_type');
var program_type2 = getValue('program_type2');
var program_interest = getValue('program_interest');	
var level_education = getValue('level_education');
var email_address = getValue('email_address');
var postal_code = getValue('postal_code');
var city = getValue('city');
var state = getValue('state');
var first_name = getValue('first_name');
var last_name = getValue('last_name');
var military = getValue("military");
var citizen = getValue("us_citizen");
var foreignCredit = getValue("foreign_credit");
var regNurse = getValue ('registered_nurse');

/* Back Link */
function backLinkClicked () {	
	history.go(-1);
}

/* Conf Page Redirect Function */
function confRedirect(){
	lo.g('Confirmation Redirect');
	var confURL;
	if(orderID > -1){
		confURL = 'https://www.phoenix.edu/experience/thankyou.html?rfi_complete=true&orderID='+orderID;
	}else{ 
		confURL = 'https://www.phoenix.edu/experience/thankyou.html';
	}
	window.location.href = confURL;
}

/* To International Version Link - append kw=intl */
function toINTLRFI(){
	var url = new String(window.location);
	var newurl;
	/* If # exists in the string ... */
	if(url.indexOf('#') !== -1){
		if(url.indexOf('?') !== -1){
			newurl = url.substr(0,url.indexOf('#')) + '&kw=intl';
		}
		else {
			newurl = url.substr(0,url.indexOf('#')) + '?kw=intl';
		}
		window.location = newurl;
	}
	else{
		if(url.indexOf('?') !== -1){
			window.location = url+'&kw=intl';
		}else{
			window.location = url+'?kw=intl';
		}
	}
}

/* Set Coremetrics cookie values */
var cmProfiler = {
	setValues : function(){
		try{
			document.getElementsByName("cmuid")[0].value = cI(cm_JSFCoreCookieName).split("&", 2)[0];
			document.getElementsByName("cmsid")[0].value = cmJSFGetSessionValue(cm_ClientID);
			document.getElementsByName("cmcid")[0].value = cm_ClientID;
			document.getElementsByName("user5")[0].value = cI(cm_JSFCoreCookieName).split("&", 2)[0];
		}catch(err){
			if("console" in window){
				console.log("Error setting Coremetrics cookie values: " + err);
			}
		}
	}
}

var lo = {
	console:false,
	init:function(){
		if(window.console && $('input[name=mode]') && $('input[name=mode]').val() && $('input[name=mode]').val().toLowerCase() == 'test'){
			this.console = true;
			console.log('Debug Active');
		}
	},
	g:function(message){
		if(this.console == true){
			console.log(message);	
		}
	},
	gGroup: function(start, groupName){
		if(this.console == true){
			if(start == true){
				if(window.console.group) console.group(groupName); 
	    		else console.log(groupName+'---------------------------------');
			}else{
				if(window.console.group)console.groupEnd()
	    		else console.log('-------------------------------------------');
	    	}
	    }
	},
	gDir:function(obj){
		if(console.dir)console.dir(obj);	
	},
	info:function(){
		//unused
	}
};

/* Tracking and page change display updates */
var rfi = function(){
	return{
		currentStep : '',
		previousStep : '',
		totalSteps : '',
		displayGroups : '',
		question :{},
		prepop : {},
		poid : {},
		mode : {},
		trackingEvent : false,
		prepopInterval : '',
		intl : false,
		// Writes to the profile(session persistence) cookie
		profileMap : {
			postal_code : 'postalCode',
			state : 'stateProvince',
			city : 'city',
			program_type : 'programType',
			level_education : 'highestLevelOfEducation',
			program_type2 : 'areaOfInterest',
			registered_nurse : 'registeredNurse',
			foreign_credit : 'foreignCredits',
			military : 'militaryService',
			program_interest : 'programOfInterest',
			degree_level : 'degreeInterest',
			pvp_campaign : 'pvp_campaign',
			detail : 'detail_code',
			pvp_campaign_int : 'pvp_campaign_int',
			channel : 'channel',
			provider : 'provider'		
		},
		init : function	(){
			rfi.poid = APTFormUtility.getPoid();
			rfi.mode = getValue('mode').toLowerCase();
			//lo.g('init');
			//v2 = APTFormVariables.oid+'-'+APTFormVariables.oiid;

			lo.g(v2);
			rfi.tracking('pageview', 1);

			//populates rfi.question with all form elements as objects
			//rfi.question.program_interest would return the html object for the program of interest question
			//rfi.question.program_interest.value would return the value of the question.
			$.each($(':input'), function(key,value){
				if(this.name){
					if(this.type == 'radio'){
						if(!rfi.question[this.name]){
							rfi.question[this.name] = $('input[name='+this.name+']');
						}
						if(!rfi.question[this.name][this.value]){
							rfi.question[this.name][this.value] = this;
						}
					}else{
						rfi.question[this.name] = this;
						//$(rfi.question[this.name]).data(pageNumber);
					}
				}				
 			});
 			//Prepopulate inputs with values from the sessionPersistence Cookie
			rfi.setupPrepop();
		},
		initSteps : function(){
			//stores display group information that can be accessed using "rfi.totalSteps"
			this.displayGroups = APTFormUtility.getDisplayGroups(rfi.poid);
			this.totalSteps = rfi.displayGroups.length;
			this.currentStep = APTFormUtility.getCurrentDisplayGroupIndex(rfi.displayGroups)+1;
			if(this.currentStep === 2){
				rfi.cityState();
			}
			//lo.g('Step: '+this.currentStep+' of '+this.totalSteps);
		},
		setupPrepop : function(){
			//Uses profile service to check Session Persistence Values
			//It only checks the cookie for questions which are defined in "rfi.profileMap"
			//rfi.profileMap is used to change aptinet parameter names into Profile parameter names if they are different
			//when a value is found, the question name and the value from the profile cookie are sent to rfi.prepopulateQuestions
			lo.gGroup(true, 'Prepopulate Questions From Profile');
			//Every value in sessionPersistence is checked against the existing form fields using rfi.prepopulateQuestions function
			for(name in this.profileMap){
				if(CQ_Analytics.UpxDataMgr.getProperty(this.profileMap[name])){
		        	this.prepopulateQuestions(name,CQ_Analytics.UpxDataMgr.getProperty(this.profileMap[name]));
				}else if(CQ_Analytics.UpxDataMgr.getProperty(name)){
					this.prepopulateQuestions(name,CQ_Analytics.UpxDataMgr.getProperty(name));
				}
			}
			lo.gGroup(false);
		},
		prepopulateQuestions : function(n,v){
			try{
				//Check rfi.question object to make sure the question exists on the form
				if(rfi.question[n]){
					if(rfi.question[n][v] && rfi.question[n][v].type == 'radio'){ 
						rfi.question[n][v].checked = true;
						if(n == 'registered_nurse')$(rfi.question[n][v]).click();
					}
					//determine question type
					else if(rfi.question[n].type == 'text'){
						//sets the value of a text field
						rfi.question[n].value = v;
					}
					else if(rfi.question[n].type == 'select-one'){	
						//questions that are selects are searched to make sure they contain 
						//an option with the value sent from the profile
						v = v.replace( /\//g, '\\/' );
						if($(rfi.question[n]).find('option[value='+v+']')){
							//If a matching option is found, the option is set to be selected
							$(rfi.question[n]).find('option[value='+v+']').attr('selected','selected');
						} 
						if(n == 'program_interest'){
							lo.g('test')
							//In order to prepopulate program of interest, interval must be set to check dropdown until dynamic select returns the program of interest
							rfi.prepopInterval = setInterval('rfi.prepopulateProgramOfInterest(rfi.question.program_interest, rfi.prepopInterval, CQ_Analytics.UpxDataMgr.getProperty("programOfInterest"))', 200);
						}
					}
					//logs the question name and the value that was prepopulated to the console
					lo.g(n+': '+v);
				}
			}catch( e ){
				lo.g( 'Error prepopulating field: ' + n + ': ' + v );
			}
		},
		prepopulateProgramOfInterest : function(elem, intervalName, val){
		//lo.g('interval');
		//If program of interest exists in sessionPersistence Cookie check program of interest field to auto select that program once dynamic select is displayed
		    if (elem && elem.children && elem.children.length) {
		        if(elem.children.length > 1){
		         	//lo.g('else');
		            if(val && cmCart == false){
			            for (var x = 0; x < elem.children.length; x++) {
			                if (elem.children[x].value == val){
			                	elem.selectedIndex = x;
			                	//Set option in program select to the prepopulated value
				            	$(elem).change();
				            	rfi.tracking('cart');
		                	}	
		                }
		            }
		            clearInterval(intervalName);
		        }
		    }
		    else clearInterval(intervalName);
		},		
		setEvents :function(){
			//sets events to each input on the form which is used to add/update values in sessionPersistence cookie
			$.each(rfi.question, function(index){
				if(rfi.question[index].type !== 'hidden'){
					if(rfi.question[index].tagName){
						rfi.addEvent(rfi.question[index]);
					}else if(rfi.question[index].length > 1){
						for(var x=0;x<rfi.question[index].length;x++){
							rfi.addEvent(rfi.question[index][x]);
						}
					}
				}
			});
		},
		addEvent : function(elem){	
			switch(elem.type.toLowerCase()){
				case "select-one":
					//Bind change events on Selects
					$(elem).change(function(){
						rfi.updateProfile(elem);
						//set add to cart tag each time program of interest select is changed
						/*if(elem.name == 'program_interest'){
							rfi.tracking('cart');
						}*/
					});
					break;
				case "text":
						//unbind existing events to text fields that are set by altcloud scripts
						$(elem).unbind();
						//Bind change events to text
						$(elem).change(function(){
							rfi.updateProfile(elem);
						});
					break;
				case "radio":
						//Bind mousedown events to radios
						$(elem).mousedown(function(){
							rfi.updateProfile(elem);
						});
					break;
			}
		},
		updateProfile : function(elem){
			//checks for the name of the input
			if(elem && elem.name){
				//Checks rfi.profileMap object to find associated profile parameter name
				//Only values which exist in rfi.ProfileMap object will be cookied
				if(this.profileMap[elem.name]){
					CQ_Analytics.UpxDataMgr.setProperty(this.profileMap[elem.name],elem.value);
					lo.gGroup(true,'updateProfile');
					lo.g(this.profileMap[elem.name]+': '+CQ_Analytics.UpxDataMgr.getProperty(this.profileMap[elem.name]));
					lo.gGroup(false);
				}
			}
			//Fire tracking event when user engages with input on page 1 of the RFI
			if(rfi.trackingEvent == false){
				rfi.tracking('event');
			}
		},
		setupPage : function(){
			//Set CLphone number on RFI
			if(rfi.question.clphone && rfi.question.clphone.value !== ""){
				$('.phoneNumber').text(rfi.question.clphone.value);    	
			} 
			else if(CQ_Analytics.UpxDataMgr.getProperty('clphone') && CQ_Analytics.UpxDataMgr.getProperty('clphone') !== ''){
				$('.phoneNumber').text(CQ_Analytics.UpxDataMgr.getProperty('clphone'));
			}
			
			/* Right Column Grey Questions  */
			$("input[name=foreign_credit]").parent().parent().parent().addClass("rightCol");
			$("input[name=us_citizen]").parent().parent().parent().addClass("rightCol");
			$("select[name=military]").parent().parent().addClass("rightCol");

			/* Wrap the rightCol class questions in a rightColumn div */
			$('div.rightCol').wrapAll('<div class="rightColumn" />');
			
			/* Append address field with the cityStateZipHint span */	
			$("input[name=address]").after('<span class="cityStateZipHint"></span>'); 
			
			/* Hide Secondary City, State, Zip Initially */
			$(rfi.question.city2).parent().hide();
			$(rfi.question.state2).parent().hide();
			$(rfi.question.postal_code2).parent().hide();
			
			/* Additional Phone */
			/* Hide alternate phone initially */
			$("input[name=area_code_2]").parents('.fieldset').hide();

			/* Hide phone extensions initially */
			if("phone_extension" in rfi.question){
				$(rfi.question.phone_extension).hide().prev().hide();
			}
			if("phone_extension2" in rfi.question){
				$(rfi.question.phone_extension2).hide().prev().hide();
			}
			
			/* Display additional phone link */	
			$("input[name=phone_extension]").parent().after('<a id="addPhone">+ Additional Phone</a>');
			
			/* Hide city and state */ 
			$("select[name=state]").hide();
			$("input[name=city]").hide();

			/* Default for military value to Not Affiliated */
			$("select[name=military]").children("option:first").html("Not Affiliated");
			
			/* Hide Phone Types */
			$("select[name=preferredphonetype]").parent().parent().hide();
			$("select[name=preferredphonetyp2]").parent().parent().hide();

			/* Show or hide alternate phone when link is clicked */
			$("#addPhone").toggle(
				function (e) {
					e.preventDefault();
					$(this).text('- Additional Phone');
					$("input[name=area_code_2]").parents('.fieldset').show();
				},
				function (e) {
					e.preventDefault();
					$(this).text('+ Additional Phone');
					$("input[name=area_code_2]").parents('.fieldset').hide();
				}
			);
	
			/* Remove rightColumn from DOM and add it at the top of the page */
			$('.rightColumn').remove().prependTo('#Page2');		
		},	
		cityState : function(){
			if( "state" in rfi.question ){
				var qState = (rfi.question.state.value == '-X-') ? '' : rfi.question.state.value;
			}
			var qCity = rfi.question.city.value;
			
			var cityParts = qCity.split(' ');
			for (var i in cityParts){
				cityParts[i] = cityParts[i].substr(0,1).toUpperCase() + cityParts[i].substr(1).toLowerCase();
			}
			qCity = cityParts.join(' ');
			
			var qPostal = rfi.question.postal_code.value;
			$(".cityStateZipHint").html(qCity+', '+qState+' '+qPostal+' <a id="cityState">(Edit)</a>'); 
			
			$('a#cityState').click(function(){
				$('.cityStateZipHint').hide();
				$(rfi.question.postal_code2).val(qPostal).parent().show();
				$(rfi.question.city2).val(qCity).parent().show();
				$(rfi.question.state2).children('option[value='+qState+']').attr('selected','selected');
				$(rfi.question.state2).parent().show();
			});
		},
		changeStep : function(page){
			lo.g('rfi.changeStep('+page+')');
			//called when a displaygroup is changed or when the back button is clicked
			//Records currently active and previously displayed display groups in the rfi object for use in tracking
			this.previousStep = this.currentStep;
			this.currentStep = page;
			if(page == 1){
				$('.contentWrapper').addClass('page1');
				$('.contentWrapper').removeClass('page2');				
			} else if(page == 2){	 
				$('.contentWrapper').removeClass('page1');
				$('.contentWrapper').addClass('page2');
				rfi.tracking('pageview', page);
				/* Calls city state from zip function */
				rfi.cityState();
			}	
			//Set pageview tag whenever page changes
			
			$('#submitButton').attr('value', aptm.submitText[ page - 1 ] );
			
		},
		tracking : function(type, pageNumber){
			/*accepts "pageview", "event", "cart", "order", "reg" for type*/
			//cmStartTagSet();
				
			var cdfLoc = '/aCloud/rfi/corporate/';


			if(type == 'pageview'){
				lo.g('rfi.tracking('+type+', '+pageNumber+')');
				//coremetrics pageview
				cmCreatePageviewTag('RFI: US - Page '+pageNumber+' ('+v2+')', cdfLoc,null);
				//google analytics pageview tracking
				pageTracker._trackPageview('/rfi/altcloud/step'+pageNumber);
				if(pageNumber == '1') {
					pageTracker._trackPageLoadTime();
				}
			}
			//Tracking Event will only be fired once a user engages with a form value 
			//This is called from within the rfi.updateProfile function
			else if(type == 'event' && rfi.trackingEvent == false){
				lo.g('rfi.tracking('+type+', '+pageNumber+')');
				//coremetrics tracking event
				cmCreateConversionEventTag("TWO PAGE: US ("+ v2+")", "1", "RFI: PHX.EDU - US", "0");
				//set rfi.trackingEvent to ensure that we do not fire multiple tracking events if a user goes back and forth on the rfi
				rfi.trackingEvent = true;
			}
			//Fires add to cart tag
			//Is called each time the value in the program of interest dropdown changes, or when the value is prepopulated from a cookied program value
			//This will associate program views and cart ads to the product pages in coremetrics
			else if(type == 'cart' && cmCart == false){	
				cmCart = true;
				clearInterval(rfi.prepopInterval);

				lo.g('rfi.tracking('+type+', '+pageNumber+')');	
				//gets value of selected program of interest
				var prog = rfi.question.program_interest.value;
				var progVal = prog;
				//converts value to lower case
				prog = prog.toLowerCase();
				//clean value to match format used in phoenix.edu site structure
				if(prog.indexOf('/') !== -1) prog = prog.replace('/','-');
				//due to how MBA concentrations are displayed, only parent MBA program is searched for
				//if(prog.indexOf('mba') !== -1) prog = prog.slice(0,prog.indexOf('-'));
				//Search phoenix.edu for page locations and details using solr search engine
				$.ajax({
					//url:'https://www.phoenix.edu/find/search/?fq=path:/content/altcloud/en/programs/degree-programs/* /&q='+prog+'&rows=1&wt=json&json.wrf=?&jsoncallback=?',
					url:'https://www.phoenix.edu/find/search/?fq=path:/content/altcloud/en/programs/degree-programs*/'+prog+'&rows=1&wt=json&json.wrf=?&jsoncallback=?',
					dataType:"jsonp",
					success:function(data){//ajax response returned successfully
						if(data.response.docs[0]){
							var pURL = data.response.docs[0].url;
							pURL = pURL.slice('0',pURL.lastIndexOf('/'))
							//Set shopping tag in coremetrics
							cmCreateShopAction5Tag(progVal, 'Program: '+data.response.docs[0].title, 1,0, "/acloud"+pURL+"/");
							//send shopping tag to coremetrics
							cmDisplayShop5s();

							lo.g('cmCreateShopAction5Tag('+rfi.question.program_interest.value+', Program: '+data.response.docs[0].title+', 1,0, /altcloud'+pURL+'/)');

						}
					}
				});	
			}		
			//fire confirmation tags	
			//coremetrics
			else if('confirm' && orderID > -1){
				lo.g('confirm');
				//Fire completed Event tag on successful RFI submission
				cmCreateConversionEventTag("TWO PAGE: US ("+v2+")", "2", "RFI: PHX.EDU - US", "10");
				var areaOfInterestMap = [{
					1 : "Business and Management",
					2 : "Criminal Justice and Security",
					3 : "Education",
					4 : "Human Services",
					5 : "Nursing and Health Care",
					6 : "Psychology",
					7 : "Technology",
					8 : "Show all",
					9 : "Arts and Sciences",
					10 : "Individual Courses"
				}];
				var program_type2 = areaOfInterestMap[0][ rfi.getVal('program_type2')] ? areaOfInterestMap[0][ rfi.getVal('program_type2') ] : "Show All";
				//Fire Registration tag
				cmCreateRegistrationTag(rfi.getVal('email_address'), rfi.getVal('email_address'),rfi.getVal('city'),rfi.getVal('state'), rfi.getVal('postal_code'), rfi.getVal('country_codes'), program_type2+'-_-'+orderID+'-_-'+rfi.getVal('level_education') );			
				
				cmCreateOrderTag(orderID, "0", "0", rfi.getVal('email_address'), rfi.getVal('city'),  rfi.getVal('state'), rfi.getVal('postal_code'));		

				//Setup and fire order tags
				//This will associate order numbers to the program(product) pages in reporting
				//Additionally will add data into the shopping cart funnel reporting for program(product) adds to cart, and orders
				if(cmCart == true){
					var prog = rfi.question.program_interest.value;
					//clean program value
					prog = prog.toLowerCase();
					if(prog.indexOf('/') !== -1) prog = prog.replace('/','-');
					//if(prog.indexOf('mba') !== -1) prog = prog.slice(0,prog.indexOf('-'));
					//Search phoenix.edu for page locations and details using solr search engine
					$.ajax({
						//url:'https://www.phoenix.edu/find/search/?fq=path:/content/altcloud/en/programs/degree-programs/* /&q='+prog+'&rows=1&wt=json&json.wrf=?&jsoncallback=?',
						url:'https://www.phoenix.edu/find/search/?fq=path:/content/altcloud/en/programs/degree-programs*/'+prog+'&rows=1&wt=json&json.wrf=?&jsoncallback=?',
						dataType:"jsonp",
						success:function(data){//ajax response returned successfully
							if(data.response.docs[0]){
								//Set shopping tag in coremetrics
								//Indicates which product was ordered
								var pURL = data.response.docs[0].url;
								pURL = pURL.slice('0',pURL.lastIndexOf('/'));
								//Order ID is passed to tie ordered product to the Order tag (fired below).
								cmCreateShopAction9Tag(rfi.question.program_interest.value, 'Program: '+data.response.docs[0].title, 1,0, rfi.getVal('email_address'), orderID, 0, "/acloud"+pURL+"/");
								cmDisplayShop9s();
							}
						}
					});	
				}
			}
			//cmSendTagSet();
		},
		getVal : function(name){
			if(rfi.question[name] && rfi.question[name].value) return rfi.question[name].value;
			else return '';
		}
	}
	
}();

/* Derive phone type */
var CheckPhoneType = {
	preferredPhone : {
		fields : ['area_code','phone_prefix','phone_suffix'],
		fieldValues : ['','',''],
		number : '',
		phoneType : '',
		selectName : 'preferredphonetype',
		preference : 'preferred'
	},
	alternatePhone : {
		fields : ['area_code_2','phone_prefix_2','phone_suffix_2'],
		fieldValues : ['','',''],
		number : '',
		phoneType : '',
		selectName : 'preferredphonetyp2',
		preference : 'alternate'
	},
	phoneTypeConv : {
		RESIDENCE : 'home',
		BUSINESS : 'work',
		MOBILE : 'mobile'
	},
	setPhoneEvents : function(type){
		this.phoneField = type;
		if(type == 'preferred'){
			phone = this.preferredPhone;

		}else if(type == 'alternate'){
			phone = this.alternatePhone;
		}
		
		for(var x=0;x<phone.fields.length;x++){
			$('#frmAptiNet input[name='+phone.fields[x]+']').bind('keyup',{
					pFieldValues:phone.fieldValues,//phonefield value array
					phone:phone,
					pType:type,//'preferred' or 'alternate' phone number 
					x:x
				},
				function(event){
					event.data.phone.fieldValues[event.data.x] = $(this).val();	
					// if phone array is 10 digits long send phone array and 'preferred' or 'alternate' phone to check the phone type with ajax
					if(event.data.phone.fieldValues.join('').length == 10){
						CheckPhoneType.lookupPhoneType(event.data.phone);
					}
			});
			if($('#frmAptiNet input[name='+phone.fields[x]+']').val() !== ''){
				phone.fieldValues[x] = $('#frmAptiNet input[name='+phone.fields[x]+']').val();	
			}
		}
		if(phone.fieldValues.join('').length == 10){
			CheckPhoneType.lookupPhoneType(phone);
		}
	},
	lookupPhoneType : function(phone){
		// turn array containing phone number into a string to send to the web service
		phone.number = phone.fieldValues.join('');
		$.ajax({
  			url: '/services/phone?phone='+phone.number,
  			dataType: 'xml',
			success: function(data, textStatus){	
				if($('PhoneType',data).text() !== 'UNKNOWN'){
					lo.g('AJAX: Phone type is '+$('PhoneType',data).text());
					CheckPhoneType.setPhoneType(phone, $('PhoneType',data).text());
				}
 			},
 			error:function(data, textStatus){
   				lo.g('AJAX: lookupPhoneType ERROR');
			}
		});	
	},
	setPhoneType : function(phone,type){
		//lo.g(phone);
		phone.phoneType = this.phoneTypeConv[type];
		var pSelect = '#frmAptiNet select[name='+phone.selectName+']';

		if($(pSelect+' option[value='+phone.phoneType+']') && $(pSelect+' option:selected').val() !== phone.phoneType){
			//FormDebug.log('Change: Phone Type to '+phone.phoneType);
			$(pSelect+' option[value='+phone.phoneType+']').attr('selected','selected');	
		}

		if(phone.phoneType == "work"){
			//disabled functionality to auto display extension when work phone number is entered
			if(phone.preference == 'preferred'){
				$('#frmAptiNet input[name=phone_extension]').show().prev().show();

			}else if(phone.preference == 'alternate'){
				$('#frmAptiNet input[name=phone_extension2]').show().prev().show();

			}
		}
	}
}
/* End Derive phone type */

/* Live Chat link functionality */
$('#chatLive').attr('href','javascript:loadClickToChat();');

/* Chat Live Functionality */
function loadClickToChat(){
	var chatURL = 'https:'+window.location.href.substring(window.location.href.indexOf('//'),window.location.href.indexOf('.edu')+4)+'/chat/chatContainer.jsp?uri=/';
	var parameters = [
		'mode',
		'clphone',
		'pvp_campaign',
		'pvp_campaign_int',
		'channel',
		'unit',
		'provider',
		'initiative', 
		'creative_desc',
		'keyword',
		'user1',
		'user2',
		'user3',
		'user4',
		'user5',
		'mktg_prog',
		'placement',
		'version',
		'classifications',
		'destination',
		'distribution',
		'category',
		'psrc',
		'psrc_url',
		'vrefid',
		'v1',
		'v3',
		'v4',
		'v6',
		'v8',
		'area_interest',
		'tracking',
		'source',
		'detail',
		'cluserid',
		'referring_domain',
		//'referring_url',
		'referring_engine'
	]
	var chatParameters = '';
	for(var x=0;x<parameters.length;x++){
		var pVal = getValue(parameters[x]);
		if((pVal != "") && (pVal != undefined) && (pVal != '-X-')){
			chatParameters += '&'+parameters[x]+'='+encodeURI(pVal);
		}
	}
	if(APTFormUtility.getPoid() != '') chatParameters += ('&poid='+APTFormUtility.getPoid());
	if(getValue('pvp_campaign_int') == undefined)chatParameters += '&pvp_campaign_int=26338_8667_9_95';
	console.log(chatURL+chatParameters);
	window.location.href = chatURL+chatParameters;
}
/* End Click to Chat button functionality */


$('#submitButton').attr('value', aptm.submitText[ 0 ] );

APTFormVariables.DisplayGroupFunctions[ APTFormUtility.getPoid() ] = [ rfi.changeStep ];
APTFormVariables.SubmitFunctions[APTFormUtility.getPoid()] = [function(response){
	try{
		cmFormOnsubmitEvent.call( document.getElementById('frmAptiNet') );
	}catch( e ){
		lo.g( 'Error Submitting Form Report: ' + e );
	}

	$('div#backLink').hide(); // hide back link while processing
	$("html, body").scrollTop(0);
	//set orderID value
	orderID = response.getElementsByTagName("ORDER")[0].getAttribute("ORDERID");
	//if order is successful
	if (orderID > 0) {		
		lo.g('Order: '+orderID);	
		//Set rfi_complete status into the sessionPersistence Cookie
		CQ_Analytics.UpxDataMgr.setProperty("rfi_complete","true"); 
		CQ_Analytics.UpxDataMgr.setProperty("provider",rfi.question.provider.value);

		//Fire Coremetrics Confirmation tags
		rfi.tracking('confirm');
	}else{ //no order created
		lo.g('No order');
		//set rfi_complete to false when the lead is flushed
		CQ_Analytics.UpxDataMgr.setProperty("rfi_complete","false"); 
	}

	setTimeout(confRedirect,1000);

	//Redirec to Thank you page

	//Fire GA thank you pageview tag
	pageTracker._trackPageview('/rfi/altcloud/thank-you');
}];

$(window).load(function(){
	
	rfi.initSteps();	
	rfi.cityState();
	//set phone type check script
	CheckPhoneType.setPhoneEvents('preferred');
	CheckPhoneType.setPhoneEvents('alternate');
	cmProfiler.setValues();
	
	// Fix links and image paths in header and footer
	$( function(){ 
		$('#phxHeader img').each( function( i, elem ){ 
			elem.src = elem.src.replace( 'rfi.phoenix.edu', 'www.phoenix.edu' ); 
		}); 
		$('a', '#phxHeader, #phxFooter').each(function(){ 
			var thisInnerHTML = this.innerHTML; this.href = this.href.replace( /(https|http):\/\/rfi.phoenix.edu/i, "http://www.phoenix.edu" ); 
		this.innerHTML = thisInnerHTML; }
		); 
	});
	
});


lo.init();//initiate debug logging
rfi.init();

rfi.setEvents();
rfi.setupPage();
