var m_index = 0;

var fixed = "";
var pageModals = {};// can persist modals here, if need be...
var loadScreen = {};
var waitMsg = 'Loading...';
var loadScreenTimeOut = 90000; // 1 1/2 min
var vLoadScreenTO = "";
var handleUnknownTimeOut = "";//function
var transferArray = new Array();

var AddressObject = function(){
	this.city = "";
	this.state = "";
	this.zip = "";
	this.cityStateZip = "";
	this.street1 = "";
	this.street2 = "";	
}

var ModalFXWrapper = Class.create({
	initialize: function(id, content, options) {
		this.id = id;
		this.content = content;
		
	    this.options = {}
	    Object.extend(this.options, options || { });

        try {
            trackModal(id)
        } catch(e) {}

	},
	
	show: function(overides) {
		var ths = this;
		hideSelectElem();
		Event.stopObserving('mask','click');
		
		var box = document.getElementById("lightBox");		
		var mask = document.getElementById("mask");
		
		//Reset in case of concurrent calls//////////////		
			for (i = 0; i < box.childNodes.length; i++) {
				box.removeChild(box.childNodes[i]);
			}
			box.style.width="";
			box.style.display="none";
		//////////////////////////////////////////////////		
		
		var vLeft = 0;	
		var popDiv = document.getElementById(ths.id);
		if(!popDiv){
			popDiv = newDiv = document.createElement("div");
			newDiv.id = ths.id;		
			newDiv.innerHTML = ths.content;
			box.appendChild(newDiv);			
		}
		var x = 0;
		for(x=0; x < box.childNodes.length; x++){
			try{
				if(this.id!=box.childNodes.item(x).id){
					box.childNodes[x].style.display = "none";
				}
			}catch(err){}
		}
		
		document.getElementById("mask").style.display = "block";
		document.getElementById("lightBox").style.display = "block";
		document.getElementById("lightBox").style.width = $(ths.id).getWidth()+"px"; // for IE...
		
		document.getElementById(ths.id).display = "block";		
		//mask.style.height = window.screen.availHeight+"px";
		mask.style.height = document.body.scrollHeight+"px";

		if(overides){
			if(typeof overides.header == 'string' &&
					!overides.header.isEmpty()){
				$('acc_module_a_head_text').innerHTML = overides.header;
			}
		}
		var bindMe = this;
		var keyClose = function(e){			
			var args = $A(arguments);
			var keynum = null;
			if(window.event){
			  keynum = e.keyCode;
			}else if(e.which){
			  keynum = e.which;
			}
			if(keynum == 13){
				if(typeof args[1]=="object"){
					var thisModule = args[1];				
					thisModule.hide();		
					Event.stopObserving(document,'keypress');					
				}
			}
			return false;
		}	
		
		var dynaFocus = function(e){			
			try{
				var acm_inputs = $('lightBox').getElementsByTagName("input");
				if(acm_inputs.length>0){
					if(acm_inputs[0].type!="hidden"){//fast focus on first valid input field
						acm_inputs[0].focus();
					}else{
						for(var x=0;x<acm_inputs.length;x++){//find first input thats not hidden
							if(acm_inputs[x].type=="hidden"){
								continue;
							}else{
								acm_inputs[x].focus();
								break;
							}
						}
					}						
				}else if($('modalCloseBttn')){						
					Event.observe(document, 'keypress', keyClose.bindAsEventListener(this,bindMe));							
				}
			}catch(err){}
		}
		
		if(this.id.indexOf('loadingScreen_')<0){
			dynaFocus();		
			Event.observe('mask', 'click', dynaFocus);
		}
		
		//initCanvases();
	/**
	 *	box.style.position = 'fixed';
	 *	box.style.top = '100px';
	 *
	 *  Can Use this (instead of JS positioning) for browsers other than IE, 
	 * 	but this will change the consistantcy in 'feel' across all browsers. 
	 * 	FireFox, Etc., will be smooth, IE will be jumpy		
	 *	
	 */		
		box.style.top = document.viewport.getScrollOffsets().top + 100;
		//vLeft = ((parseInt(screen.availWidth) / 2) - (parseInt(popDiv.offsetWidth)/2));	
		vLeft = ((parseInt((document.all)?document.body.clientWidth:window.innerWidth) / 2) - (parseInt(popDiv.getWidth())/2));
		box.style.left = vLeft;
		
		this.fixed = setInterval("fixPosition();", 1);		
	},
	
	hide: function(){		
		/**
		 *  Remove all event handlers from descendants to prevent performance issues
		 *	i.e. memory leaks
		 */
		var terminalDescendants = $("lightBox").descendants();
		for(i=0; i < terminalDescendants.length;i++){	
			terminalDescendants[i].stopObserving();	
		}		
		// Remove all child nodes of the mask	
		var box = document.getElementById("lightBox");
		for (i = 0; i < box.childNodes.length; i++) {
			box.removeChild(box.childNodes[i]);
		}
		
		Event.stopObserving('mask','click');
		box.removeAttribute("style");
		box.style.display = "none";
		document.getElementById("mask").style.display = "none";
		clearInterval(this.fixed);
		this.fixed = null;
		showSelectElem();
		//initCanvases();
	}
});

function gotoFeaturedPlan(featuredPlan, isNormalized, queryStr) {
	var q = "";
	if(queryStr){
		q =queryStr;		
	}
	var url = '/fpd/' + encodeURIComponent(featuredPlan.stableId) + '/' + featuredPlan.pageName + ".html?"+q;
	if (isNormalized) {
		window.location = url;
	} else {
		module = new ChangeAddressModule({newLocationOnSuccess: url});
		module.show(currentAddress);
	}
}

function ifPromptOwnRent(typeId){
	var ids = ['10271','33','10574'];
	for(var x=0; x<ids.length; x++){
		if(typeId==ids[x]){
			return true;
		}
	}	
	return false;	
}

/**
 * 	Use this public addToCart function instead of the in-page version where found
 */
function addToCartStatus(status) {
	if (status == 'success') {
		this.form.typeId.value = this.typeId;
		this.form.stablePlanId.value = this.stablePlanId;
		
		this.form.submit();
	}
}
additionalInformationReceived = false;

function transferAsIs(form, type, stablePlanId, isNormalized, map) {
	modal = new TransferAsIsModule({
		type:type,
		stablePlanId:stablePlanId,
		isNormalized:isNormalized,
		form:form,
		method:'GET',
		map:map
	});
	
	modal.show();
}

function addToCart(form, typeId, stablePlanId, isNormalized, map) {
	var numeric = /^\d+$/;
	var tp = ((numeric.test(typeId))?typeId:serviceTypeInfo[typeId].id)+'';//recognizes numeric Id or shortName (resolves to numeric Id)
	var pid = stablePlanId;	
	var promptOwnRent = false;	
	var rulo = null;	
	var promptPreTerms = false;
	try{		
		if(map && typeof map["c1"] == 'boolean'){
			promptOwnRent = map["c1"];			
		}
		if(promptOwnRent){						
			if(typeof map["c2"] == 'object' && map["c2"].length == 6){				
				rulo = map["c2"];				
			}
		}
	}catch(err){
		alert(err.message);
		promptOwnRent = ifPromptOwnRent(tp);
	}	
	try{
		if(map && typeof map["c3"] == 'boolean' && map["c3"]){
			promptPreTerms = true;
		}
	}catch(err){}
	if(isNormalized=='true' && !fullAddressNeeded && (!directTransfer || !cityStateOrZipOnlyServiceability)){	
		if(promptPreTerms){
			module = new PreAcceptTermsModule({
				typeId:tp,
				form:form,
				stablePlanId:pid,
				isNormalized:isNormalized,
				availible:'',
				map:map,
				newLocationOnSuccess:''					
			});
			module.show();
			//return false;
		}		
		else if(promptOwnRent && currentAddress.ownRent == ''){
			module = new OwnRentModule({
				typeId:tp,
				form:form,
				stablePlanId:pid,
				isNormalized:isNormalized,
				availible:'',					
				newLocationOnSuccess:'',
				rules:rulo	
			});		
			module.show();
			keepThisOpen=false;
		}else {
		    try {
		        trackAddToCart(pid);
		    } catch (e) {}

			if(form.autoSubmit==true){
				form.typeId.value = tp;
				form.stablePlanId.value = pid;			
				
				form.submit();
			}else if(form.rawSubmit){
				var pars = {typeId:tp,
						stablePlanId:pid,				
						sendModalResponse:true}
				new Ajax.Request(dynamicUrls.resolveUrl('/shopping/addToCart.html'), {
					parameters:pars,
					method:'post',
					onSuccess: function(transport){
						window.location = "/checkout/shoppingCartSummary.html";
					}					
				});	
				
			}else{				
				form.typeId.value = tp;
				form.stablePlanId.value = pid;
				
				return true;
			}
		}		
	}else if(promptPreTerms){
				
		var module = new ChangeAddressModule({
			noneOfTheAboveCandidate:false,
			showOwnRent:promptOwnRent,
			newFunctionOnSuccess:function(){
				fullAddressNeeded = false;				
				var module = new PreAcceptTermsModule({
					typeId:tp,
					form:form,
					stablePlanId:pid,
					isNormalized:'true',
					availible:'',
					map:map,
					newLocationOnSuccess:''					
				});
				module.onCancel = function(){
					location.reload(true);
				}
				module.show();
			}
		});
		module.show(currentAddress);
	}else if (promptOwnRent) {
		var pars = {typeId:tp,
				stablePlanId:pid,				
				sendModalResponse:true}	
		
		module = new ChangeAddressModule({
			noneOfTheAboveCandidate:false,
			showOwnRent:promptOwnRent,
			newFunctionOnSuccess:function(){
				new Ajax.Request(dynamicUrls.resolveUrl('/shopping/addToCart.html'), {
					parameters:pars,
					method:'post',
					onSuccess: function(transport){
						window.location = "/checkout/shoppingCartSummary.html";
					}					
				});	
			}
		});
		module.show(currentAddress);
		
		
	}else{		
		bindData = { form: form, typeId: typeId, stablePlanId: stablePlanId };
		module = new ChangeAddressModule({noneOfTheAboveCandidate: false, forceReload: false, onStatus: addToCartStatus.bind(bindData)});
		module.show(currentAddress);
	}		
	
	return false;
}

function fixPosition(){
	if(document.getElementById("lightBox").childNodes[0]){
		document.getElementById("lightBox").style.top =  document.viewport.getScrollOffsets().top + 100;
		document.getElementById("lightBox").style.left = ((parseInt((document.all)?document.body.clientWidth:window.innerWidth) / 2) - (parseInt($(document.getElementById("lightBox").childNodes[0]).getWidth())/2));
	}
}

function forceHide(){
	var box = document.getElementById("lightBox");	
	// Remove all child nodes of the mask
	for (i = 0; i < box.childNodes.length; i++) {
		box.removeChild(box.childNodes[i]);
	}
	box.removeAttribute("style");
	box.style.display = "none";
	document.getElementById("mask").style.display = "none";	
	loadScreen = null;		
	//ls_msg_helper.inuse=false;
	try{	
		clearInterval(fixed);	
		clearInterval(ls_msg_helper.to);
		clearTimeout(vLoadScreenTO);
		fixed = null;
	}catch(err){}
	finally{		
		showSelectElem();
	}
}

function hideSelectElem(){
	var ob = document.getElementsByTagName("body")[0].getElementsByTagName("select");
	var count = 0;
	for(count = 0 ; count<ob.length ; count++){
		ob[count].style.visibility = 'hidden';
	}	
}

function showSelectElem(){
	var ob = null;
	try{
		ob = document.getElementsByTagName("body")[0].getElementsByTagName("select");
	}catch(err){
		ob = null;		
	}
	if(ob!=null){
		var count = 0;
		for(count = 0 ; count<ob.length ; count++){
			ob[count].style.visibility = 'visible';
		}	
	}
	initCanvases();
}

var ls_msg_helper = {to:"",index:0,used:[],inuse:false,msg:""}

var ac_loadScreen_msg = [
"Did you know? Since 1998, millions of people have saved on home services using Allconnect.",
"Allconnect backs up your order with our <strong>Best Price Guarantee!</strong>",
"Allconnect partners with a variety of service providers across the nation.  Giving you the choice to select a plan that best fits you!",
"Allconnect is happy to take your call if you need help with your selections.  We take pride in our <strong>Award-winning 24/7 Customer Service.</strong> <br/><br/><ul><li>HyperQuality Performance Award in 2009.</li></ul>"
];

function arrcontains(num,arr){
	for(var x=0;x<arr.length;x++){
		if(arr[x]==num){
			return true;
		}
	}
	return false;
}
function rotateLSMsg(){
	var xx=0,rvar = 0;
	ls_msg_helper.inuse=true;
	rvar = (Math.floor(Math.random()*ac_loadScreen_msg.length));
	if(!arrcontains(rvar,ls_msg_helper.used) && rvar!=ls_msg_helper.index){
		ls_msg_helper.index=rvar;
		ls_msg_helper.used.push(rvar);
	}else if(ls_msg_helper.used.length==ac_loadScreen_msg.length){
		ls_msg_helper.used = [];
		ls_msg_helper.index=rvar;
		ls_msg_helper.used.push(rvar);
	}else{
		return rotateLSMsg();
	}	
	
	if($('loadScreen')){
		try{
			if($('loadScreen_rvprop')){				
				ls_msg_helper.msg = ac_loadScreen_msg[ls_msg_helper.index];
				$('loadScreen_rvprop').innerHTML = ac_loadScreen_msg[ls_msg_helper.index];
			}
		}catch(err){}
	}
	
	return false;
}
function showLoadingScreen(lstate){
	var m_to_state  = (null!=lstate && ""!=lstate)?lstate:"default";
	if(document.getElementById("loadingScreen_"+m_to_state)){
		m_to_state+='_tk';
	}
	loadScreen = new ModalFXWrapper(('loadingScreen_'+m_to_state),'<div id="loadScreen"><div><img src="/01/img/art/spinner.gif"/><span>'+waitMsg+'</span></div><div id="loadScreen_rvprop_spacer">Did you know...</div><div id="loadScreen_rvprop"><!-- --></div></div>');
	//loadScreen = new ModalFXWrapper(('loadingScreen_'+m_to_state),'<div id="loadScreen"><img src="/01/img/art/spinner.gif"/><span>'+waitMsg+'</span></div>');
	loadScreen.show();
	if(!ls_msg_helper.inuse){
		rotateLSMsg();
	}else{
		if($('loadScreen_rvprop')){			
			$('loadScreen_rvprop').innerHTML = ls_msg_helper.msg;
		}
	}
	//ls_msg_helper.to = setInterval(rotateLSMsg,6000);
	if(handleUnknownTimeOut==""){
		handleUnknownTimeOut = function(){ //This functionallity can be changed/reassigned as this is a global var
			forceHide();
		}	
	}
	try{
		clearTimeout(vLoadScreenTO);
	}catch(err){}
	vLoadScreenTO = setTimeout("if($(('loadingScreen_"+m_to_state+"'))){handleUnknownTimeOut();}", loadScreenTimeOut);//Check to see if this screen is not still up after specified time
	
}
var WidgetModule = Class.create({
	initialize:function(options){
		this.options = {
			id:'',
			widget:'',
			submitUrl:'',
			content:'',
			formName:'',
			fieldsToCheck:[],
			options:''
		}	
		Object.extend(this.options,options||'');	
	},
	show:function(){
		me = this;		 
		var w_wrap = '<div id="accWidgetWrapper"><div>'+ me.options.content+'</div><div id="accWidgetWrapper_bottom"><img id="widgetCloseBttn" src="/01/img/buttons/bttn_closewindow.gif" align="center" vspace="10" onclick="pageModals[\''+me.options.id +'\'].hide()" /></div></div>';		
		me.wrapper = new ModalFXWrapper('acc_widget', w_wrap);
		me.wrapper.show();		
	},
	hide:function(){	
		if(this.options.id=="reminderWidget"){
			if(getCookie('auto_reminder_e')=='true'){
				setCookie('auto_reminder_e','false',365);
			}			
		}
		this.wrapper.hide();
	},
	onSubmit:function(){
		me = this;		
		var pass = validate();	//all widgets should include their own validations.
		
		if(pass){
			//showLoadingScreen('submittingReminderInfo');
			var wpars = '';
			var x = 0;
			var wForm = document[me.options.formName];
			for(x=0; x < me.options.fieldsToCheck.length;x++){				
				if($(me.options.fieldsToCheck[x]) && $(me.options.fieldsToCheck[x]).value){
					wpars += ('&'+me.options.fieldsToCheck[x]+'='+$(me.options.fieldsToCheck[x]).value);
				}
			}			
			new Ajax.Request(dynamicUrls.resolveUrl(me.options.submitUrl), {
				parameters: wpars,	
				method:'POST',
				onSuccess:  function(transport) {				
					response = eval('(' + transport.responseText + ')');
					
					if(response.status=='success'){
						success_module = new WidgetModule({							
							content:response.content,
							widget:me.options.id,
							id:"w_thanks"							
						});
						
						pageModals['w_thanks'] = success_module;						
						success_module.show();
					}
					
					eval(response.javascript);
					
				},
				onFailure: function(){
					showUnexpectedError();
				}
			});
		}
	}
});

var PreAcceptTermsModule = Class.create({
	initialize:function(options){
		this.options = {
			preCart:true,	
			type:'',
			stablePlanId:'',
			form:'',
			isNormalized:'',
			newLocationOnSuccess:'',
			newFunctionOnSuccess:'',
			method:'',
			map:{}
		}
		Object.extend(this.options,options||'');	
	},
	show:function(){
		module = this;
		var pars = {stablePlanId:this.options.stablePlanId}
		var cont = false;
		new JSONRequest(dynamicUrls.resolveUrl('/identify/preTermsAccept.html'), {
			parameters: pars,	
			method:"GET",
			onSuccess:  function(transport) {
				response = transport;				
				
				module.wrapper = new ModalFXWrapper('TermsAcceptanceModule', replace800Number(response.content));
				module.wrapper.show();

				eval(response.javascript);
				try{
					var termM = new termsModal({
						onSubmit:module.onSubmit.bind(module),
						onCancel:module.onCancel.bind(module)
					});
				}catch(err){
					alert(err.message);
				}
				
			}
		});
		
	},
	onSubmit:function(e){
		Event.stop(e);
		var pars = {stablePlanId:this.options.stablePlanId,acceptTermsAndConditions:true}
		new JSONRequest(dynamicUrls.resolveUrl('/identify/preTermsAccept.html'), {
			parameters: pars,	
			method:"POST",
			onSuccess:  function(transport) {
				//response = eval('(' + transport.responseText + ')');			
				try{
					if(null!=module.options.form && typeof module.options.form == 'object'){
						module.options.map["c3"] = false;
						module.options.form["autoSubmit"] = true;
						showLoadingScreen("addtocart_preTerms");
						addToCart(module.options.form, module.options.typeId,module.options.stablePlanId, module.options.isNormalized, module.options.map);	
					}else if(null!=module.options.newFunctionOnSuccess && module.options.newFunctionOnSuccess!='' && typeof module.options.newFunctionOnSuccess == 'function'){
						(module.options.newFunctionOnSuccess)();
					}else{
						module.wrapper.hide();
					}
				}catch(err){
					alert(err.message);
				}
				
			},
			onFailure:function(transport){
				alert('failed');
			}
		});
		
	},
	onCancel:function(){
		module.wrapper.hide();
	}
	
});

var TransferAsIsModule = Class.create({
	initialize:function(options){
		this.options = {
			type:'',
			stablePlanId:'',
			form:'',
			isNormalized:'',
			newLocationOnSuccess:'',
			method:'',
			map:{}
		}
		Object.extend(this.options,options||'');	
	},
	show:function(){
		module = this;
		
		var pars = {stablePlanId:module.options.stablePlanId,
				type:module.options.type}
		var method = (module.options.method.toUpperCase()=='GET')?'GET':'POST';
		new Ajax.Request(dynamicUrls.resolveUrl('/shopping/transferAsIs.html'), {
			parameters: pars,	
			method:method,
			onSuccess:  function(transport) {
				response = eval('(' + transport.responseText + ')');				
				
				module.wrapper = new ModalFXWrapper('transferAsIs_modal', replace800Number(response.content));
				module.wrapper.show({header:module.options.header});
				
				eval(response.javascript);
				if(module.options.showSimilarPlans){
					if(response.status && response.status!='success'){
						$('closeWindow').src = '/01/img/splash/transfer/similarPlansBtn.gif';
						module["cancel"] = function(){
							var typeUrl = serviceTypeInfo[module.options.type].url;
							window.location = typeUrl;
						}
					}					
				}				
				var tModule = new transferM({
					onSubmit:module.onSubmit.bind(module),
					onCancel:module.cancel.bind(module)
				});				
			},
			onFailure:function(){
				showUnexpectedError();
			}
		
		});
	},
	onSubmit:function(dataObj){
		showLoadingScreen('submittingZip');
		var pars = {zipCode:dataObj.zipCode,
				stablePlanId:dataObj.stablePlanId,
				type:dataObj.type}
		
		new Ajax.Request(dynamicUrls.resolveUrl('/shopping/transferAsIs.html'), {
			parameters: pars,	
			method:'POST',
			onSuccess:  function(transport) {
				
				var submitResponse = eval('(' + transport.responseText + ')');				
				
				var successM = new ModalFXWrapper('transferAsIs_success', submitResponse.content);				
				successM.show({header:module.options.header});
				
				eval(submitResponse.javascript);
				if(module.options.showSimilarPlans){
					if(submitResponse.status && submitResponse.status!='success'){
						$('closeWindow').src = '/01/img/splash/transfer/similarPlansBtn.gif';
						module["cancel"] = function(){
							var typeUrl = serviceTypeInfo[module.options.type].url;
							window.location = typeUrl;
						}
					}					
				}
				var tModule = new transferM({
					onSubmit:module.onSubmit.bind(module),
					onAddToCart:module.onAddToCart.bind(module),
					onCancel:module.cancel.bind(module)
				});
							
			},
			onFailure:function(){
				showUnexpectedError();
			}
		
		});
	},
	onAddToCart:function(){
		if(this.options.form.rawSubmit){
			this.options.form["autoSubmit"] = false;
		}else{
			this.options.form["autoSubmit"] = true;
		}
		addToCart(this.options.form, this.options.type, this.options.stablePlanId, this.options.isNormalized, this.options.map);		
	},
	cancel:function(){
		forceHide();
	}
	
});


//TODO put this into the ChangeAddressModule Object
var OwnRentModule = Class.create({
	initialize:function(options){
		this.options = {
			typeId:'',
			availible:'',
			rules:[],
			newLocationOnSuccess:'',
			additionalInfo:{}
		}
		Object.extend(this.options,options||'');	
	},
	show:function(additionalInfo,errors){		
		ownRent_module = this;			
		var pars = {typeId:this.options.typeId}		
		
		new JSONRequest(dynamicUrls.resolveUrl('/identify/ownRent.html'), {
			parameters: pars,	
			onSuccess:  function(response) {
				ownRent_module.wrapper = new ModalFXWrapper('ownRentModal', replace800Number(response.content));
				ownRent_module.wrapper.show();
				eval(response.javascript);
				
				var rules = ownRent_module.options.rules;				
				var addrModule = new ownRentM({
					rules:rules,
					onSubmit:ownRent_module.process.bind(ownRent_module),
					onCancel:ownRent_module.cancel.bind(ownRent_module)
				});	
				
				//clear errs
				$('m_dwelling_error').innerHTML = "";
				$('m_ownershipStatus_error').innerHTML = "";
				$('m_street_error').innerHTML = "";
				$('m_city_state_zip_error').innerHTML = "";
				
				//process errs
				if(typeof errors == 'object'){					
					errors.each(function(error) {						
						if (error.fieldName == 'dwellingType'){						
							if($('m_dwelling_error')){
								$('m_dwelling_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						} else if(error.fieldName == 'ownershipStatus'){
							if($('m_ownershipStatus_error')){
								$('m_ownershipStatus_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}							
						}else if(error.fieldName == 'street1'){
							if($('m_street_error')){
								$('m_street_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						}else if(error.fieldName == 'cityStateZip'){
							if($('m_city_state_zip_error')){
								$('m_city_state_zip_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						}
					});				
				}				
				//pre pop
				if(typeof additionalInfo == 'object'){
					document.ownRentForm.dwellingType.value = additionalInfo.fullAddress.dwellingType; 
					if(additionalInfo.fullAddress.ownershipStatus == 'own'){						
						$('m_own').checked = true;						
					}else if(additionalInfo.fullAddress.ownershipStatus == 'rent'){						
						$('m_rent').checked = true;										
					}
					if($('m_rent').checked || $('m_own').checked){
						$('m_dwelling').show();
					}														
					if(additionalInfo.checkAddress){
						document.ownRentForm.street1.value = additionalInfo.fullAddress.street1;
						document.ownRentForm.street2.value = additionalInfo.fullAddress.street2;
						document.ownRentForm.cityStateZip.value =  additionalInfo.fullAddress.cityStateZip;
					}
					addrModule.onClick();
				}
				
			}			
		});
	},
	validate:function(additionalInfo){
		var errs = [];		
		if(!additionalInfo.form.ownershipStatus[0].checked && !additionalInfo.form.ownershipStatus[1].checked){			
			errs[errs.length] = {fieldName:'ownershipStatus',status:'100'}			
		}
		if(additionalInfo.fullAddress.dwellingType == 'intro' &&
				(additionalInfo.form.ownershipStatus[0].checked || 
						additionalInfo.form.ownershipStatus[1].checked)){
			errs[errs.length] = {fieldName:'dwellingType',status:'100'}			
		}
		if(additionalInfo.checkAddress && additionalInfo.fullAddress.dwellingType != 'intro' &&
				(additionalInfo.form.ownershipStatus[0].checked || 
						additionalInfo.form.ownershipStatus[1].checked) || 
							additionalInfo.fullAddress.dwellingType == 'intro' && keepThisOpen){
			if(additionalInfo.fullAddress.street1.trim().isEmpty()){
				errs[errs.length] = {fieldName:'street1',status:'100'}	
			}			
			if(additionalInfo.fullAddress.cityStateZip.trim().isEmpty()){
				errs[errs.length] = {fieldName:'cityStateZip',status:'100'}	
			}
		}
		
		return errs;	
	},
	process:function(additionalInfo){
		ownRent_module.options.form.typeId.value = ownRent_module.options.typeId;
		ownRent_module.options.form.stablePlanId.value = ownRent_module.options.stablePlanId;	
		ownRent_module.options.additionalInfo = additionalInfo;
		var pars = {typeId:this.options.typeId,
				stablePlanId:this.options.stablePlanId,
				sendModalResponse:true}
		var errs = ownRent_module.validate(additionalInfo);
		
		if(errs.length > 0){
			//ownRent_module = new OwnRentModule(this.options);
			ownRent_module.show(additionalInfo,errs);
			
		}else{
			new Ajax.Request(dynamicUrls.resolveUrl('/shopping/addToCart.html'), {
				parameters:pars,
				method:'post',
				onSuccess: function(transport){
					response = eval('(' + transport.responseText + ')');				
					ownRent_module.updateAddress(ownRent_module.options.additionalInfo);
				}
				
			});	
		}
	},
	updateAddress:function(additionalInfo){		
			var address = {
					street1:additionalInfo.fullAddress.street1,
					street2:additionalInfo.fullAddress.street2,
					cityStateZip:additionalInfo.fullAddress.cityStateZip,
					city:'',
					state:'',
					zipCode:'',
					dwellingType:additionalInfo.fullAddress.dwellingType,	
					ownershipStatus:additionalInfo.fullAddress.ownershipStatus
			}
			var ch_address_module = new ChangeAddressModule({
				newLocationOnSuccess:"/checkout/shoppingCartSummary.html",
				onFieldErrors:function(address,errors){					
					ownRent_module.show(ownRent_module.options.additionalInfo,errors);					
				}							
			});			
			ch_address_module.updateAddress(address,cityStateOrZipOnlyServiceability);
	},
	cancel:function(){
		forceHide();
	}
	
});


var ChangeAddressModule = Class.create({
	initialize: function(options) {
	    this.options = {
	    	forceReload: true,
	    	noneOfTheAboveCandidate: true,
	    	persistAddress: true,
	    	newLocationOnSuccess: "",
	    	newFunctionOnSuccess:"",	    	
	    	onFieldErrors:this.show.bind(this)
	    }
	    Object.extend(this.options, options || { });
	},
	
	show: function(address, addressFieldErrors) {
		module = this;
		var pars = {};
		if(module.options.showOwnRent && module.options.showOwnRent==true){
			pars.showOwnRent=true;
		}
	    JSONRequest(dynamicUrls.resolveUrl('/identify/fullAddressNeeded.html'), {
	    	parameters:pars,
		    onSuccess:  function(response) {
				eval(response.javascript);

				module.wrapper = new ModalFXWrapper('fullAddressModal', replace800Number(response.content));
				module.wrapper.show();
				try{
					addrModule = new AddressModule(address, {
						onSubmit: module.updateAddress.bind(module),
						onCancel: module.cancelActiveModal.bind(module)
					});
				}catch(err){}
				if(module.options.header){
					$('acc_module_a_head_text').innerHTML = module.options.header;
				}
				if (addressFieldErrors) {
					if(address.ownershipStatus && address.ownershipStatus!="" && address.ownershipStatus!="null"){
						if(address.ownershipStatus == "own" || address.ownershipStatus == "y"){
							$('m_own').checked = true;
						}else{
							$('m_rent').checked = true;
						}
					}
					if(address.dwellingType && address.dwellingType!="" && address.dwellingType !="intro"){
						$('dwellingOption').value = address.dwellingType;
					}
					addressFieldErrors.each(function(error) {
						if (error.fieldName == 'street1') {
							if ($('m_street_error')) {
								$('m_street_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						} else if (error.fieldName == 'street2') {
							if ($('m_apt_condo_error')) {
								$('m_apt_condo_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						} else if (error.fieldName == 'cityStateZip' || error.fieldName == 'zipCode') {
							if ($('m_city_state_zip_error')) {
								$('m_city_state_zip_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						} else if (error.fieldName == 'dwellingType') {						
							if ($('m_dwelling_error')) {
								$('m_dwelling_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}
						} else if (error.fieldName == 'ownershipStatus') {
							if ($('m_ownershipStatus_error')) {
								$('m_ownershipStatus_error').innerHTML = '<span class="fieldError">Field is required.</span>';
							}							
						}
					});
				}
		    },
			onFailure:  function() {		
		    	showUnexpectedError();
		    }						
	    });
	},
	
	showUnexpectedError: function() {
		this.wrapper = new ModalFXWrapper("unexpected_error", unexpectedErrorModal.content);
		this.wrapper.show();
		
		clearTimeout(vLoadScreenTO);
	    
		new UnexpectedErrorModule({
		    onCancel: this.cancelActiveModal.bind(this)
		});
	},
	
	showAddressNotFound: function(providedAddress, showUSPSMessage) {
//		this.wrapper = new ModalFXWrapper("fullAddress_addressNotFound", addressNotFoundModal.content);
		this.wrapper = new ModalFXWrapper("fullAddress_addressNotFound_B",addressNotFoundCallUsModal.content);
		this.wrapper.show();

		if (typeof showUSPSMessage == "undefined") {
			showUSPSMessage = false;
		}

//		new UnrecognizedAddressModule(providedAddress, {
//			showUSPSMessage: showUSPSMessage,
//			onCancel: this.cancelActiveModal.bind(this)
//		});
		
		new UnrecognizedAddressCallUsModule({
			onCancel: this.cancelActiveModal.bind(this)
		});	
	},
	
	showProblemAddress: function(address, addressFieldErrors) {
		var pars = {street1:address.street1,
				street2:address.street2,
				cityStateZip:address.cityStateZip}

	    addressFieldErrors.each(function(error) {
			if (error.fieldName == 'street2') {
				pars.street2status = error.status;
			} else if (error.fieldName == 'pobox') {
				pars.poboxstatus = error.status;
			}
		});

	    new JSONRequest(dynamicUrls.resolveUrl('/identify/problemAddress.html'),	{	
		    parameters: pars,	
			onSuccess:  function(response) {
				eval(response.javascript);

			    module.wrapper = new ModalFXWrapper("problemAddress", replace800Number(response.content));
				module.wrapper.show();
					
			    addrModule = new ProblemAddressModule(address, {
				    onSubmit: module.updateAddress.bind(module),
				    onCancel: module.cancelActiveModal.bind(module)
				});
		    },
			onFailure:  function() {	
		    	showUnexpectedError();
		    }						
	    });
	},
	
	showNoCandidateAddresses: function(address) {
		var pars = {street1:address.street1,
				street2:address.street2,
				cityStateZip:address.cityStateZip}	

	    new JSONRequest(dynamicUrls.resolveUrl('/identify/noCandidateAddresses.html'),	{	
		    parameters: pars,	
			onSuccess:  function(response) {
				eval(response.javascript);

			    module.wrapper = new ModalFXWrapper("noCandidateAddresses", replace800Number(response.content));
				module.wrapper.show();
				
				addrModule = new NoCandidateAddressesModule(address, {
			    	onSubmit: module.updateAddress.bind(module),
				    onCancel: module.cancelActiveModal.bind(module)
				});
		    },
			onFailure:  function() {	
		    	showUnexpectedError();
		    }						
	    });	
	},
	
	cancelActiveModal: function() {
		this.wrapper.hide();
		
		if (this.options.onCancel) {
			this.options.onCancel();
		}
	},

	updateAddress: function(address, zipOnly, fullAddressNeeded) {		
		module = this;
		this.updatePars = {};
		
		if (typeof zipOnly == "undefined") {
			zipOnly = false;
		}

		if (typeof fullAddressNeeded == "undefined") {
			fullAddressNeeded = false;
		}
		
		showLoadingScreen('updatingAddress');
		
		fieldError = false;
		var addressFieldErrors = [];
		
        if (!zipOnly && address.street1.trim() == '') {
        	fieldError = true;
            addressFieldErrors[addressFieldErrors.length] = {fieldName:'street1',status:'100'};
        }
        if (typeof address.cityStateZip != "undefined") {
        	if (address.cityStateZip.trim() == ''
				|| address.cityStateZip.trim().toUpperCase() == 'REQUIRED'
				||address.street1.trim().toUpperCase()== 'REQUIRED') {
        		fieldError = true;
	            addressFieldErrors[addressFieldErrors.length] = {fieldName:'cityStateZip',status:'100'};
        	}
        } else {
	        if (address.city == '') {
	            fieldError = true;
	            addressFieldErrors[addressFieldErrors.length] = {fieldName:'city',status:'100'};
	        }
	        if (address.state == '') {
	            fieldError = true;
	            addressFieldErrors[addressFieldErrors.length] = {fieldName:'state',status:'100'};
	        }
	        if (address.zipCode == '') {
	            fieldError = true;
	            addressFieldErrors[addressFieldErrors.length] = {fieldName:'zipCode',status:'100'};
	        }	        
        }       
        if(address.ownershipStatus){        	
        	if (address.ownershipStatus == 'null' || address.ownershipStatus == '') {
	            fieldError = true;
	            addressFieldErrors[addressFieldErrors.length] = {fieldName:'ownershipStatus',status:'100'};
        	}
        }
        if(address.dwellingType){	        	
        	if (address.dwellingType == 'intro' || address.dwellingType == '') {
	            fieldError = true;
	            addressFieldErrors[addressFieldErrors.length] = {fieldName:'dwellingType',status:'100'};
        	}
        }

        if (fieldError) {
        	if (module.options.onFieldErrors) {
        		module.options.onFieldErrors(address, addressFieldErrors);
        		if (loadScreen) {
        			loadScreen.hide();
        		}
			} else {
				module.showAddressNotFound(address);
			}
        	return;
        }

	    var pars = {street1:address.street1,
	    		street2:address.street2}
	    if (typeof address.cityStateZip != "undefined") {
	    	pars.cityStateZip = address.cityStateZip;
	    } else {
	    	pars.city = address.city;
	    	pars.state = address.state;
	    	pars.zipCode = address.zipCode;
	    }
	    
	    pars.zipOnlyServiceability = zipOnly;
	    
	    if (address.dwellingType) {	    	
	    	pars.dwellingType = address.dwellingType;
	    	this.updatePars['dwellingType'] = encodeURI(address.dwellingType);
	    }
	    if (address.ownershipStatus) {
	    	pars.ownershipStatus = address.ownershipStatus;
	    	this.updatePars['ownershipStatus']= encodeURI(address.ownershipStatus);
	    }
	    
	    if (typeof module.options.noneOfTheAboveCandidate != "undefined") {
	    	pars.noneOfAbove = module.options.noneOfTheAboveCandidate;
	    }

	    new JSONRequest(dynamicUrls.resolveUrl('/identify/addressNormalize.html'),	{	
		    parameters: pars,	
			onSuccess:  function(response) {
				eval(response.javascript);

				if (response.status == 'exactMatch') {
				    normalized = true;
			    	module.saveAddress(correctedAddress, zipOnly, fullAddressNeeded);//persist
				} else if (response.status == 'addressSelect') {
				    module.wrapper = new ModalFXWrapper("addressNormalize_1", response.content);
					module.wrapper.show();

				    addrModule = new AddressNormalizeModule({
					    onSubmit: module.saveAddress.bind(module),
					    onCancel: module.cancelActiveModal.bind(module)
					});
				} else if (response.status == 'moreInfoNeeded') {
					if (module.options.noneOfTheAboveCandidate) {
						module.showProblemAddress(address, addressFieldErrors);
					} else {
						module.showAddressNotFound(address, true);
					}
				} else if (response.status == 'invalidFields') {
					if (module.options.onFieldErrors) {
						loadScreen.hide();
						module.options.onFieldErrors(address, addressFieldErrors);
					} else {
						module.showAddressNotFound(address);
					}
				} else if (response.status == 'noCandidatesAddress') {
					module["flagStatus"] = 'noCandidatesAddress';
					if (module.options.noneOfTheAboveCandidate) {
						module.showNoCandidateAddresses(address);
					} else {
						module.showAddressNotFound(address, true);
					}
				} else if (response.status == 'unrecognizedAddress') {
					module.showAddressNotFound(address);
				} else {
					module.showUnexpectedError();
				}
		    },
			onFailure:  function(){	
		    	showUnexpectedError();
		    }						
	    });	
	},

	saveAddress: function(address, zipOnly, fullAddressNeeded) {
		module = this;
		
		if (!module.options.persistAddress && module.options.onStatus) {
			module.options.onStatus('success', address);
			return;
		}

		if (typeof zipOnly == "undefined") {
			zipOnly = false;
		}
		
		if (typeof fullAddressNeeded == "undefined") {
			fullAddressNeeded = false;
		}

		var pars = {street1:address.street1,
	    	street2:address.street2}
	    if (address.cityStateZip) {
	    	pars.cityStateZip = address.cityStateZip;
	    } else {
		    pars.city = address.city;
		    pars.state = address.state;
		    pars.zipCode = address.zipCode;
	    }
	    pars.zipOnlyServiceability = zipOnly;
	    pars.fullAddressNeeded = fullAddressNeeded;
	    module["flagStatus"] = (fullAddressNeeded)?"fullAddressNeeded":"ok";
	  
	    if(address.ownershipStatus){	    	
	    	pars.ownershipStatus = address.ownershipStatus;
	    }else if(module.updatePars.ownershipStatus){
	    	pars.ownershipStatus = module.updatePars.ownershipStatus;
	    }
	    
	    if(address.dwellingType){	    	
	    	pars.dwellingType = address.dwellingType;	    
	    }else if(module.updatePars.dwellingType){
	    	pars.dwellingType = module.updatePars.dwellingType;
	    }
	    
	    showLoadingScreen('savingAddress');

	    //persist	    
	    new JSONRequest(dynamicUrls.resolveUrl('/identify/addressUpdate.html'), {	
		    parameters: pars,	
			onSuccess: function(response) {
	    		if (module.options.onStatus) {
					module.options.onStatus(response.status, address);
				}
	    		if (response.status == 'success') {
	    			vcAddr = pars;
		    		if (null != module.options.newLocationOnSuccess && module.options.newLocationOnSuccess != "") {					
						if(module.options.newLocationOnSuccess=="reload" || 
								module.options.newLocationOnSuccess=="."){							
							location.reload(true);
						}else{
						    if (navigator.userAgent.indexOf("Firefox") != -1 && typeof window.history.pushState != "undefined") {
							    window.history.pushState(null, null, window.location.href);
							}
							window.location.href = module.options.newLocationOnSuccess+"";
						}
					} else if (null != module.options.newFunctionOnSuccess && module.options.newFunctionOnSuccess !="") {					
						(module.options.newFunctionOnSuccess)();
					} else if (response.status == 'success' && module.options.forceReload) {
		    			location.reload(true);
					}
				} else if (response.status == 'addressNotUnique') {				
					module.updateAddress(address, zipOnly);
				}
	    	},
			onFailure:  function(){	
	    		showUnexpectedError();
		    }
	    });
	}	
});

var topPlanReceived = false;
function getExpressFeaturedItem(filter,goToPromo) {
	var pars = {};
	
	if (filter) {
		if (filter.providerId.trim() != '') {
			pars.providerId = filter.providerId.trim();
		}
		if (filter.category.trim() != '') {
			pars.category = filter.category.trim();
		}
		if (filter.subCategory.trim() != '') {
			pars.subCategory = filter.subCategory.trim();
		}
	}
	var expressWait = setTimeout("if(!topPlanReceived){showExpressWait();}",1000);	
	
	new Ajax.Request(dynamicUrls.resolveUrl('/features/expressFeaturedItem.html'),	{	
	    parameters: pars,	
		method:'post',
		onSuccess:  function(transport) {
			var planInfo = null;
    		try{	    			
    			planInfo = eval('(' + transport.responseText + ')');    			
	    		topPlanReceived = true;    	
	    		clearTimeout(expressWait);    		
	    		topPlan = planInfo;	    		
	    		if(topPlan.planName=="null"){
	    			clearTimeout(expressWait); 
	        		hideExpressTopPlan();
	    		}else{
		    		var q = "";
		    		if(goToPromo){
		    			q="tab=promo";
		    		}
		    		
		    		var featUrl = "javascript:gotoFeaturedPlan({stableId:\'" + planInfo["stableId"] + "',pageName:'" + planInfo["urlName"] + "'}, addressNormalized)";
		    		var featDescription = '<a href="'+featUrl+'">'+ planInfo["planName"]+'</a>';    	
		    		var featPriceDollars = planInfo["pricing"].dollars;
		    		var featPriceCents = planInfo["pricing"].cents;
		    		var pricingType = planInfo["pricing"].type;
		    		var x = 0;
		    		var highlights = "<ul>";    		 
		    		var showNewBase = false;
		    		
		    		$('expressTopPlan_Content').insert({after: '<div id="expressTopPlan_Price"><div id="expressTopPlan_BasePrice"><!--  --></div></div>'});
		    		$('expressTopPlan_Description').innerHTML = featDescription;
		    		
		    		if(planInfo["promotions"]){	    			
		    			for(var x=0; x<planInfo.promotions.promoList.length; x++){
		    				if(x<2){
		    					var promo = planInfo.promotions.promoList[x];
			    				if(promo.promotionType=="BASE_MONTHLY_DISCOUNT"){
			    					showNewBase = true;
			    				}		    				
		    					highlights+="<li class='promoBullet'><div class='promotionPriceColor' style='display:inline;font-weight:bold;'>"+((promo.shortDescription.length>50)?(promo.shortDescription.substring(0,47)+"..."):promo.shortDescription)+"</div></li>";
		    				}else{
		    					var featUrl = "javascript:gotoFeaturedPlan({stableId:\'" + planInfo["stableId"] + "',pageName:'" + planInfo["urlName"] + "'}, addressNormalized,'tab=promo')";
		    					var tmp="<li class='promoBullet'><div class='promotionPriceColor' style='display:inline;font-weight:bold;'><a id='morePromos' href=\""+featUrl+"\">More Promotions</a></div></li>";
		    					highlights+=tmp;	    					
		    					break;
		    				}
		    			}			
		    		}else{
			    		for(x=0; x < 3; x++){
			    			if(planInfo["highLights"][x]){
			    				highlights+="<li><span>"+planInfo["highLights"][x]+"</span></li>";
			    			}
			    		}	    		
		    		}
		    		highlights+="</ul>";    		
		    		$('expressTopPlan_Highlights').innerHTML = highlights; 
		    		
		    		if(showNewBase && planInfo["originalBasePricing"] && (planInfo["originalBasePricing"].price!=planInfo["pricing"].price)){
						$('expressTopPlan_BasePrice').innerHTML = "<span style='color:#666666;font-weight:normal;'>"+getPricingLabel(pricingType)+" <del>$"+planInfo["originalBasePricing"].dollars+"."+planInfo["originalBasePricing"].cents+"  "+getPricingSuffix(pricingType)+"</del></span>";
		    			$('expressTopPlan_BasePrice').insert({after:'<div id="expressTopPlan_PromotionPrice"><span class="promotionPriceColor"> Promo '+getPricingLabel(pricingType)+' $'+featPriceDollars+'.'+featPriceCents+' '+getPricingSuffix(pricingType) +'</span></div>'});
					}else{
						$('expressTopPlan_BasePrice').innerHTML = getPricingLabel(pricingType)+" $"+featPriceDollars+"."+featPriceCents+"  "+getPricingSuffix(pricingType);
					}    		   		
		    		
		    		initCanvases();
	    		}
    		}catch(err){	
    			clearTimeout(expressWait); 
        		hideExpressTopPlan();
    		}
    	},
		onFailure:  function(){	
    		clearTimeout(expressWait); 
    		hideExpressTopPlan();
	    }
    });
}
function getPricingSuffix(type){
	var suffix = "";		
	switch(type){
		case "MONTHLY":
			suffix = "/mo."; 	
			break;
		case "STARTING":
			suffix= "/mo.";	
			break;
		case "PERTHERM":
			suffix = "/therm";
			break;
		case "PERKWH":
			suffix = "/kWh";
			break;
		case "OTHER":
			suffix = "/mo.";
			break;
		default:
			suffix = "/mo.";
	}
	
	return suffix;
	
}
function getPricingLabel(type){
	if (type == 'STARTING') {
		return 'Starting At:';
	}
	else {
		return 'Base Price:';
	}
}
function hideExpressTopPlan(){
	$('SplashModuleContainer_content_left').style.width = "";
	$('SplashModuleContainer_content_right').innerHTML = "";	
	$('TopPlanPanel').style.display = "none";
	$('SplashModuleContainer_content_left').style.margin = "0px";
	
	if($('expressTypeOfService')){
		var tos = '<div id="error_TypeOfService" class="expressFieldError"><!-- error --></div>'+$('expressTypeOfService').innerHTML;
		$('expressTypeOfService').innerHTML = tos;
		var sub = '<div id="error_submit" class="expressFieldError"><!-- error --></div>'+$('expressSubmit').innerHTML;
		$('expressSubmit').innerHTML = sub;
	}
	initCanvases();	
}

function showExpressWait(){
	if($('expressTopPlan_Description')){
		$('expressTopPlan_Description').innerHTML = '<div id="expressTopPlanWaitMsg"><img src="/01/img/art/spinner.gif"/><br/><span>'+'Loading Top Plan...'+'</span></div>';
	}
}

// This function displays trusted providers. These are based on the most recent address entered by the user, or are
// based on the location of the user's IP address if no address has been entered yet. Note that this function will 
// not display anything if category or subcategory filtering is used, and no applicable results are returned by serviceability.
// 
// The function accepts an optional argument object that wraps the possible parameters that can be passed to it. Here 
// are the parameters and their possible values:
//
// source     : dynamic | cms  -- defaults to dynamic
// category   : phone | internet | tv | bundles | etc. -- defaults to all categories 
// subcategory: cableTV | localPhone | etc. -- defaults to all subcategories
// bundle     : bundle1 | bundle2 | etc. -- defaults to all bundles
// text       : the text to be displayed above the trusted providers; 
//              the token [location] will be replaced by the city/state string
// tag        : the html element tag that the header text will be wrapped in, for example "h2"
// hdrXXX     : parameters of this form will be inserted into the tag around the header. For example, if the 
//              parameter hdrClass:BigGreen is passed to this function then class="BigGreen" will be inserted
//              into the element surrounding the header text.
//
// So a call for trusted phone providers based on a call to serviceability might look like this:
//
// getTrustedProviders("category":"phone", "hdrStyle":"font-size:x-large", "text":"Choose from these providers in [location]"})
// 
// A call with no parameters does a dynamic lookup of all providers and falls back
// to the CMS providers only if serviceability fails.
function getTrustedProviders(args) {
	var url = "/features/trustedProviders.html?";
	
	for (var argName in args) {
		url += argName + "=" + args[argName] + "&";
	}
	var id = "trustedProviders" + Math.floor(Math.random()*100000000);
	if(typeof window['ac_i_hsa']=='boolean' && ac_i_hsa){
		document.write('<div id=\"' + id + '\"> <!-- Trusted Providers placeholder --> </div>');		
	}else{
		document.write('<div id=\"' + id + '\"> <!-- Trusted Providers placeholder --> </div>');
	}
	new Ajax.Updater(id, url, { onComplete:initCanvases });	
}

function getPlanAvailability(serviceTypeId, dwellingTypeId, rentOwn){
	if(serviceTypeId){
		var numeric = /^\d+$/;
		var dwelling = (dwellingTypeId)?dwellingTypeId:currentAddress.locationType+"";
		var ownRent = (rentOwn)?rentOwn:currentAddress.ownRent;	
		var type = "";
		
		try{
			type = ((numeric.test(serviceTypeId))?serviceTypeId:serviceTypeInfo[serviceTypeId].id)+'';
		}catch(err){
			type = "NA";
		}
		try{
			if(!ownRentRules[type]){
				return true;
			}else if(ownRent=="y"){
				switch(dwelling){
					case "8":
						return ownRentRules[type].ownHouse;
						break;
					case "7":
						return ownRentRules[type].ownApt;
						break;
					case "2001":
						return ownRentRules[type].ownTownHome;
						break;
					default:
						return null;			
				}		
			}else if(ownRent=="n"){
				switch(dwelling){
					case "8":
						return ownRentRules[type].rentHouse;
						break;
					case "7":
						return ownRentRules[type].rentApt;
						break;
					case "2001":
						return ownRentRules[type].rentTownHome;
						break;
					default:
						return null;			
				}	
			}
			return null;		
		
		}catch(err){
			
		}
	}
	return null;
}

function transferService(serviceType, providerId, modalTitle){
	var numeric = /^\d+$/;
	var pars = "";
	pars+="serviceType="+serviceType;
	pars+="&providerId="+(((providerId)&&numeric.test(providerId))?providerId:0);	
	modal = new ChangeAddressModule({
		header:modalTitle,
		newFunctionOnSuccess:function(){
			new Ajax.Request(dynamicUrls.resolveUrl('/features/splashTransferService.html'), { //finds a transfer plan by provider and serviceType
				parameters: pars,	
				onSuccess:  function(transport) {
					response = eval('(' + transport.responseText + ')');					
					if(response.status=="success"){
						transferModule = new TransferAsIsModule({
							header:modalTitle,
							type:response.serviceTypeId,
							stablePlanId:response.serviceStablePlanId,
							isNormalized:'true',
							showSimilarPlans:true,
							form:{rawSubmit:true}
						});
						transferModule.show();						
					}else{
						transferModule = new TransferAsIsModule({							
							method:'get', //get failure view if no planId is provided 
							header:modalTitle,
							showSimilarPlans:true,
							type:serviceType
						});
						transferModule.show({header:modalTitle});						
					}					
				},
				onFailure: function(){
					showUnexpectedError();
				}
			});
		}
	});	
	modal.show();
	return false;
}

function integratedCall(planMemberArray){
	var x = 0;
	var pars = ""
	var handleResult_1 = function(planElem){//for variable handling of results
		//do somthing
	}
	new Ajax.Request(dynamicUrls.resolveUrl('/features/integratedServ.html'),{		
		onSuccess:function(transport){
			var inteCallResponse = eval('(' + transport.responseText + ')');				
			var contentArray = (!inteCallResponse.content.isEmpty())?inteCallResponse.content.split("*--delim--*"):null;			
			eval(inteCallResponse.javascript);				
			try{//process messages
				if(null!= contentArray && contentArray.length>0){
					var p = new inteServModalProcess({content:contentArray});					
					p.next();
				}
			}catch(err){alert(err.message)}
			try{//process valid Items
				var vItems = validItems;
				var planID = null;
				var planWait_elem = null;
				var planImage_elem = null;				
				for(var x=0;x < vItems.length;x++){
					planID = vItems[x];			
					planWait_elem = $(("pw_"+planID));	
					planImage_elem = $(("pi_"+planID));				
					if(planWait_elem){
						planWait_elem.hide();
						planImage_elem.show();
					}
					initCanvases();
				}		
			}catch(err){}
		},
		onFailure: function(){
			alert('failed!');
		}
	});	
}

function replace800Number(str) {

    var elem = document.getElementById("the800Number");

    if(elem != null) {
        var current800Number = elem.innerHTML;

        var regex = /1\-\d{3}\-\d{3}\-\d{4}/g;

        return str.replace(regex, current800Number);
    } else {
        return str;
    }
}
