var ConfirmIt = Class.create();
var jar;
var gmac_jsessionid;
var movingWithinSite = false;  
var ConfirmIT_killSwitch = false;

ConfirmIt.prototype = {

	daysBetweenSurveys: 180,

	frequecy_applicant: 50,
	frequecy_prospect: 0,
	frequecy_customer: 20,

	urlApplicant: "https://survey.gmacfs.com/wix/p1016040504.aspx",
	urlCustomer: "https://survey.gmacfs.com/wix/p1018618943.aspx",
	urlProspect: "https://survey.gmacfs.com/wix/p1025648716.aspx",
	
	initialize:function() {
		try
		{
			jar = new CookieJar({path:'/'});
		}
		catch (ex) {}

	},

	//This method is called at the bottom of "exit pages".  When the page loads, the method loops through
	//links and input elements to see if determine if they will take the user off the site.  If they are internal, 
	//then we listen for the onclick event to set linkIsInternal=true.  If linkIsInternal is false when the page unloads, 
	//then we know they are on their way off of our site so we should try to pop the survey.
	setAsExitPage:function(classRef){
		var myInternalURLs = "gmacmortgage.com".split("|");

		Event.observe(window, 'load', function() 
		{
			if (!ConfirmIT_killSwitch) 
			{ 
				var linkIsInternal;
				//This section handles A tags
				$$('a').each(function(obj) 
				{
					linkIsInternal = false;
					for (i = 0; i < myInternalURLs.length; i++) 
					{
						//elements that don't have an href attribute (bookmark/anchors) may cause this to fail
						try
						{
							if (obj.readAttribute("href").indexOf(myInternalURLs[i]) !== -1) 
							{
								linkIsInternal = true;
							}
							// if it's a relative or absolute URL, so it's internal.
							if (obj.readAttribute("href").indexOf("http://") == -1) 
							{
								linkIsInternal = true;
							}
						}
						catch ( ex ) {}
					}

					if (linkIsInternal == true) 
					{		
						Event.observe(obj, 'click', function()
						{			
							movingWithinSite = true;
						});
					}
				});

				//This section handles submit buttons
				$$('input').each(function(obj) {
					if (obj.readAttribute("name") == "search_btn" || obj.readAttribute("name") == "s_register") {
						Event.observe(obj, 'click', function() {			
							movingWithinSite = true;
						});
					}
				});
			}
		});

		Event.observe(window, 'unload', function(event) {
			if (movingWithinSite == false) {
				classRef.popSurvey();
			}
		});
	},
	
	//this method checks if user has been served a survey within the "daysBetweenSurveys" interval
	checkSurveyDate:function() {
		try
		{
			var jsonCookie = jar.get('confirmit');
			var cookieDateString = jsonCookie.survey_date;
			if (cookieDateString == null)
			{
				return true;
			}
			else 
			{
				var lastSurvey = new Date(cookieDateString);
				var current = new Date();
				var nextSurvey = new Date();
				nextSurvey.setDate(lastSurvey.getDate() + this.daysBetweenSurveys);
				
				if (current.getTime() > nextSurvey.getTime())
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		catch (ex)
		{
			return true;
		}
	},

	//clears cookie values, retaining survey_date and current jsessionid
	resetCookie:function(){
		var jsonCookieOld = jar.get('confirmit');
		var jsonCookieNew = {};
		
		if (jsonCookieOld != null && jsonCookieOld.survey_date != null)
		{
			jsonCookieNew.survey_date = jsonCookieOld.survey_date;
		}
		
		jsonCookieNew.jsessionid = gmac_jsessionid;
		jar.put('confirmit', jsonCookieNew);
		return jsonCookieNew;
	},

	//checks the user's eligibility for recieving a survey 
	//(i.e. surveys are enabled and if they had one in the past, it's not too soon for another)
	surveyEligible:function() {
		try
		{
			return !ConfirmIT_killSwitch && this.checkSurveyDate();			
		}
		catch (ex)
		{
			return false;
		}
	},

	//sets a name value pair into the JSON cookie
	setParam:function(name, value) {
		if (this.surveyEligible())
		{		
			try
			{
				gmac_jsessionid = getCookieValue("JSESSIONID");
				
				var jsonCookie = jar.get('confirmit');
				if (jsonCookie != null) 
				{ 
					if (jsonCookie.jsessionid == null)
					{
						jsonCookie.jsessionid = gmac_jsessionid;
					}
					else
					{
						if (jsonCookie.jsessionid != gmac_jsessionid)
						{
							jsonCookie = this.resetCookie();
						}
					}
				}
				else
				{
					jsonCookie = this.resetCookie();
				}
				
				switch (name)
				{
					case "login_auth":
						jsonCookie.login_auth=value;
						break;
					case "register":
						jsonCookie.register=value;
						break;
					case "start_app":
						jsonCookie.start_app=value;
						break;
					case "save_app":
						jsonCookie.save_app=value;
						break;
					case "submit_app":
						jsonCookie.submit_app=value;
						break;
					case "rate_calcs":
						jsonCookie.rate_calcs=value;
						break;
					case "customer":
						jsonCookie.customer=value;
						break;
					case "web_acct_id":
						jsonCookie.web_acct_id=value;
						break;
					case "survey_date":
						jsonCookie.survey_date=value;
						break;
					case "bill_pay":
						jsonCookie.bill_pay=value;
						break;
					default:
						alert("invalid param name");
						return false;
				}

				jar.remove('confirmit');
				jar.put('confirmit', jsonCookie);	
				return true;
			}
			catch (ex)
			{
				return false;
			}
		}
	},

	//Similar to "setParam" in that it sets a name value pair into the JSON cookie.  
	//However, this version should be used when the call is made within an onclick 
	//event handler (i.e. bill pay links).  It doesn't return a value so that 
	//existing script calls in the event handler are not affected.
	setInlineParam:function(name, value) {
		this.setParam(name, value);
	},

	random_number:function() {
		return Math.floor(Math.random() * 100);
	},
	
	//build query string and open the new window.  Also handles Omniture tracking.
	popSurvey:function() {
		var jsonCookie = jar.get('confirmit');
		if (this.surveyEligible())
		{
			freq_seed = this.random_number();
			freq = 0;
			url = "";
			surveyType = "";

			try
			{
				if (jsonCookie.start_app == "Y")
				{
					surveyType = "applicant";
				}
				else if (jsonCookie.customer == "Y")
				{
					surveyType = "customer";
				}
				else if (jsonCookie.rate_calcs == "Y")
				{
					surveyType = "prospect";
				}
				
				switch(surveyType) {
					case "applicant":
					  freq = this.frequecy_applicant;
					  url = this.urlApplicant;
					  break;
					case "prospect":
					  freq = this.frequecy_prospect;
					  url = this.urlProspect;
					  break;
					case "customer":
					  freq = this.frequecy_customer;
					  url = this.urlCustomer;
					  break;
				}	
				
				if (freq_seed < freq)
				{
					query_string = "Login_Auth=" + (jsonCookie.login_auth ? 'Y' : 'N');
					query_string += "&Register=" + (jsonCookie.register ? 'Y' : 'N');
					query_string += "&Saved_App=" + (jsonCookie.save_app ? 'Y' : 'N');
					query_string += "&Submit_App=" + (jsonCookie.submit_app ? 'Y' : 'N');
					query_string += "&Rate_Calc=" + (jsonCookie.rate_calcs ? 'Y' : 'N');
					query_string += "&Customer=" + (jsonCookie.customer ? 'Y' : 'N');
					query_string += "&Pay_Mtg_Online=" + (jsonCookie.bill_pay ? 'Y' : 'N');
					query_string += "&Unique_Id=" + (jsonCookie.web_acct_id ? jsonCookie.web_acct_id : '');
				
					this.setParam("survey_date", new Date().toDateString());
					var message;
					var surveyWindow = window.open(url + "?" + query_string, "confirmit",'width=700,height=480,location=yes,toolbar=yes,scrollbars=yes');
					if (surveyWindow != null)
					{
						surveyWindow.focus();
						message = 'confirmIT launch success'
					}
					else
					{
						//this should indicate that the pop-up failed (because of an error or a pop-up blocker).
						message = 'confirmIT launch failed'
					}
					
					//pass message to Omniture for tracking
					var s=s_gi(s_account); 
					s.tl(this,'o', message); 
				}
			}
			catch ( ex )	{	}
		}
	}

};