var ccDebug = false;
var ccDebugFilter = "";

var ccBannerDiv = null;
var ccAppWindow = null;

var CC_POLLING_INTERVAL = 2000;
var CC_PRESCREEN_TIMEOUT = 30;

function JSKfoo()
{
	alert("JSKfoo");
} 
//State engine for CC process.  Called from application.cfm once CC process has been enabled
//Evaluates CREDITCARDAPPSTATE cookie to determine current state and coninues process appropriately.
//States: 	inactive - Indicates some credit card processing has been performed but no further
//				action is to be taken.  inactive state is set when prescreen or application is declined
//			prescreensubmitted - Indicates the prescreen request has been submitted but no response
//				has been received.  checkPrescreenResponse() will be called to check the status.
//			prescreenapproved - Indicates the prescreen has been approved and the CC banner should be
//				rendered in any page containing a placeholder.
//			appinprogress - Indicates the user has clicked the cc ad banner but no response is yet
//				available as to the application status.  Could indicate the user is still filling out
//				the application or that they closed the application window without submitting or
//				cancelling.
//			appapproved - Indicates that the credit card application has been approved.  In this state
//				any subsequent page containing payment information will be changed to include the
//				new credit card information.
function resumeCreditCardIntegration()
{
	ccDoDebug("resumeCreditCardIntegration>");

	if(!ccDebug)
	{
		if(findURLArgument("ccDebug").toLowerCase()=="true")
			ccDebug = true;
	}
		
	var ccState = getCreditCardApplicationState();
	if(ccState=="inactive")
		return;
	
	ccDoDebug("resumeCreditCardIntegration:CreditCardAppState=" + ccState);
	//ignoring 'inactive', ''
	switch(ccState)
	{
		case "prescreensubmitted":
			setTimeout('checkPrescreenResponse()', CC_POLLING_INTERVAL)    
			break;
		case "prescreenapproved":
			showCCBanner();
			break;
		case "appinprogress":
			setTimeout('checkInstantCreditApp()',CC_POLLING_INTERVAL)
			break;
		case "appapproved":
			break;
	}
} //resumeCreditCardIntegration

function showCreditCardTNC()
{
	tncURL = unescape(getCreditCardTNCURL());
	ccDoDebug("showCreditCardTNC: Opening TNC URL: " + tncURL);
	window.open(tncURL);
} //showCreditCardTNC

//Invoked after the user has accepted the credit card pitch and their response (Yes) has been
//successfully submitted.
function showCCApplication()
{
	//Call SubmitCustomerResponse web method

	appURL = getCreditCardApplicationURL();
	if(appURL!=null)
	{
		setCreditCardApplicationState("appinprogress");
		appURL = unescape(appURL);
		ccDoDebug("showCCApplication:Opening credit card application; URL=" + appURL);
		ccAppWindow = window.open(appURL,"CCAPPWINDOW");
		resumeCreditCardIntegration();
	}
} //showCCApplication

//Invoked as a response to the user clicking the credit card pitch banner.
function ccBannerResponseYes()
{
	setCreditCardApplicationURL("");
	if(!submitCustomerResponse("1"))
	{
		//What do we do here???
		ccDoError("An error occurred while trying to navigate to the URL: " + getCreditCardApplicationURL(),true);
	}
} //ccBannerResponseYes

//Invoked as a response to the user clicking the credit card pitch banner.
function ccBannerResponseNo()
{
	setCreditCardApplicationURL("");
	submitCustomerResponseAsync("0");
} //ccBannerResponseYes

//Accepts the request containing the markup to be loaded in the banner placeholder and
//assigns it to the innerHTML of the div element.
function renderCCBanner(request)
{
	if(ccBannerDiv!=null)
	{
		
		if(request.responseText.indexOf('ccBannerResponseYes') > 0)
		{
			ccDoDebug("renderCCBanner: Found inner banner; id=" + ccBannerDiv.id);
			ccBannerDiv.innerHTML = request.responseText;
		}
	}
} //renderCCBanner

//Locates the div element that will contain any markup for the ad banner
//Attempts to locate a placeholder that will server as a container for the banner markup.
//Searches for a tag named 'ccBanner'.  If found then locates the first child div element
//of ccBanner and returns that element
function getCCBannerDiv()
{
	ccBannerDiv = null;
	
	var outerBannerDiv = document.getElementById("ccBanner");

	if(outerBannerDiv!=null)
	{
		ccDoDebug("getCCBannerDiv: Found outer banner");
		
	   //GET ALL THE TAGS WHICH ARE WITHIN THIS TAG
		var allChildren = outerBannerDiv.getElementsByTagName('*');
		ccBannerDiv = null;
		for (var tagIdx = 0; tagIdx < allChildren.length; tagIdx++)
		{
			if(allChildren.item(tagIdx).tagName.toLowerCase()=="div")
			{
				ccBannerDiv = allChildren.item(tagIdx);
				break;
			}
		}

		if(ccBannerDiv)
		{
			ccDoDebug("getCCBannerDiv: Found inner banner; id=" + ccBannerDiv.id);
		}
	}
	else
	{
		//Outer div not defined.
	}
	
	return ccBannerDiv;
} //getCCBannerDiv

//Clears the markup in the cc banner div element
function hideCCBanner()
{
	getCCBannerDiv();
	if(ccBannerDiv)
	{
		ccBannerDiv.innerHTML = "";
	}
} //hideCCBanner

//If an ad banner is defined starts an asynch request to load an HTML file whose name is the id of the
//child div tag with a '.html' extension.  renderCCBanner() accepts the asynchronous response
//and loads the resulting HTML in the ad banner div tag.
function showCCBanner()
{
	ccDoDebug("showCCBanner>");
	if(getCreditCardApplicationState()!="prescreenapproved")
		return;
		
	getCCBannerDiv();
	if(ccBannerDiv)
	{
		ccDoDebug("showCCBanner: Found inner banner; id=" + ccBannerDiv.id);

		postStr = "/CCBanners/" + ccBannerDiv.id + ".html?foo=foo";
		
		ccDoDebug("showCCBanner: Getting " + postStr);
		doAjaxRequest(postStr,renderCCBanner);
	}
} //showCCBanner


//This function is polled when CreditCardAppState == 'prescreenapproved' until a response is received.
//Initiates an asynchronous request that calls the CheckInstantCreditApp web service.  
//processCheckInstantCreditApp is subsequently called with the response.
function checkInstantCreditApp() 
{
	if(getCreditCardApplicationState()=="inactive")
		return;

	ccDoDebug("checkInstantCreditApp>");
		
	var prescreenResponseId = getCreditCardPrescreenRespId();
	ccDoDebug("checkInstantCreditApp:prescreenResponseId=" + prescreenResponseId);
	if(prescreenResponseId==null)
	{
		return;
	}

	wsProxy = getWSProxyURL();
	if(wsProxy!=null)
	{
		var postStr = wsProxy + "?wsXml=<req><parms><prescreenResponseId>" + prescreenResponseId + "</prescreenResponseId></parms><ret><ConfirmationCode/><DecisionCode/><ErrorCode/><EncryptedCreditCardNumber/><CreditCardExpDate/><AuthorizedAmount/><Signature/></ret></req>&methodName=CheckInstantCreditApp&wsName=AgiCCservices&outputResult=true";
		
		ccDoDebug("checkInstantCreditApp:postStr=" + postStr);
		doAjaxRequest(postStr,processCheckInstantCreditApp);
	}
} //checkInstantCreditApp	

//Processes the asynchronous response initiated by checkInstantCreditApp.  Determines if application was approved or declined and sets
//appropriate state.  If response is empty then continues polling of checkInstantCreditApp.
function processCheckInstantCreditApp(request)
{
	err = false;

	if(getCreditCardApplicationState()=="inactive")
		return;

	ccDoDebug("processCheckInstantCreditApp>");
	
	ccDoDebug("processCheckInstantCreditApp:before processWebServiceResponse call");
	jsonObj = processWebServiceResponse(request);
	ccDoDebug("processCheckInstantCreditApp:after processWebServiceResponse call");
	if(jsonObj!=null)
	{
		ccDoDebug("processCheckInstantCreditApp:jsonObj not null");
		
		//If web service call was successful
		if (jsonObj.returncode == 0) 
		{
			ccDoDebug("processCheckInstantCreditApp:returnCode = 0; DecisionCode="+jsonObj.DecisionCode);
			
			//If approved
			switch(jsonObj.DecisionCode)
			{
				//Approved
				case "65": //A
					ccNumber = jsonObj.EncryptedCreditCardNumber;
					expDate = jsonObj.CreditCardExpDate;
					postIssuedCCInfo(ccNumber, expDate);
					setCreditCardApplicationState("appapproved");
					hideCCBanner();
					break;
					
				//Pending/Declined
				case "80","68": //P or D
					setCreditCardApplicationState("inactive");
					hideCCBanner();
					break;
					
				//Cancel
				case "67": //C
					setCreditCardApplicationState("inactive");
					hideCCBanner();
					break;
					
				//Error
				case "69": //E
					setCreditCardApplicationState("inactive");
					hideCCBanner();
					break;

				default:			
					setCreditCardApplicationState("inactive");
					hideCCBanner();
			}
		} //returncode == 0
		
		//Prescreen response not ready yet...do nothing
		else if (jsonObj.returncode==1)
		{
		}
		
		//Error...do we continue processing or set inactive and stop??
		else 
		{
			err = true;
			ccDoError("processCheckInstantCreditApp: An unknown response was received when checking the application status.\nReturn Code=" + jsonObj.returncode + "; Return Message=" + jsonObj.errormsg,true);
		}
	}
	else
	{
		ccDoDebug("processCheckInstantCreditApp:jsonObj is null; setting state to inactive");
		setCreditCardApplicationState("inactive")
	}

	resumeCreditCardIntegration();
} //processCheckInstantCreditApp		

//This function is invoked when the user clicks the link to decline the ad offer.
//Initiates an synchronous request that calls the SubmitCustomerResponse web service.  
//processSubmitCustomerResponseAsync is subsequently called with the response.
function submitCustomerResponseAsync(answer)
{
	if(getCreditCardApplicationState()=="inactive")
		return;

	ccDoDebug("submitCustomerResponseAsync>");
		
	var prescreenResponseId = getCreditCardPrescreenRespId();
	ccDoDebug("submitCustomerResponseAsync:prescreenResponseId=" + prescreenResponseId);
	if(prescreenResponseId==null)
	{
		return;
	}

	wsProxy = getWSProxyURL();
	if(wsProxy!=null)
	{
		var postStr = wsProxy + "?wsXml=<req><parms><PrescreenResponseId>" + prescreenResponseId + "</PrescreenResponseId><Answer>" + answer + "</Answer><CommentCategory>0</CommentCategory><Comment> </Comment></parms><ret><SubmitCustomerResponseResult/></ret></req>&methodName=SubmitCustomerResponse&wsName=AgiCCservices&outputResult=true&useStruct=true";
		
		ccDoDebug("submitCustomerResponseAsync:postStr=" + postStr);
		doAjaxRequest(postStr,processSubmitCustomerResponseAsync);
		setCreditCardApplicationState("inactive")
		hideCCBanner();
	}
} //submitCustomerResponseAsync

function processSubmitCustomerResponseAsync(request)
{
	ccDoDebug("processSubmitCustomerResponseAsync>");
} //processSubmitCustomerResponseAsync

//This function is invoked when the user responds to the ad banner.
//Initiates a synchronous request that calls the SubmitCustomerResponse web service.  
//Accepts the CC application URL returned by SubmitCustomerResponse web service and
//calls showCCApplication which will open the application window.
function submitCustomerResponse(answer)
{
	ret = false;
	
	if(getCreditCardApplicationState()!="inactive")
	{

		ccDoDebug("submitCustomerResponse>");
			
		var prescreenResponseId = getCreditCardPrescreenRespId();
		ccDoDebug("submitCustomerResponse:prescreenResponseId=" + prescreenResponseId);
		if(prescreenResponseId!=null)
		{
			wsProxy = getWSProxyURL();
			if(wsProxy!=null)
			{
				var postStr = wsProxy + "?wsXml=<req><parms><PrescreenResponseId>" + prescreenResponseId + "</PrescreenResponseId><Answer>" + answer + "</Answer><CommentCategory>0</CommentCategory><Comment> </Comment></parms><ret><SubmitCustomerResponseResult/></ret></req>&methodName=SubmitCustomerResponse&wsName=AgiCCservices&outputResult=true&useStruct=true";
				
				ccDoDebug("submitCustomerResponse:postStr=" + postStr);
				request = doSynchRequest(postStr);
				
				
				//doAjaxRequest(postStr,processSubmitCustomerResponse);
			
				jsonObj = processWebServiceResponse(request);
				ccDoDebug("submitCustomerResponse:after processWebServiceResponse call");
				if(jsonObj!=null)
				{
					ccDoDebug("submitCustomerResponse:jsonObj not null");
					
					//If web service call was successful
					if (jsonObj.returncode == 0) 
					{
						ccDoDebug("submitCustomerResponse:returnCode = 0; SubmitCustomerResponseResult="+jsonObj.SubmitCustomerResponseResult);
			
						//We are only providing for a 'yes' response so always show the application
						setCreditCardApplicationURL(jsonObj.SubmitCustomerResponseResult);
						ccDoDebug("submitCustomerResponse: url=" + getCreditCardApplicationURL());
						showCCApplication();
						ret = true;
						
					} //returncode == 0
					
					//response not ready yet...do nothing
					else if (jsonObj.returncode==1)
					{
					}
					
					//Error...do we continue processing or set inactive and stop??
					else 
					{
						err = true;
						ccDoError("submitCustomerResponse: An unknown response was received when submitting the customer response.\nReturn Code=" + jsonObj.returncode + "; Return Message=" + jsonObj.errormsg,true);
					}
				}
			} //wsProxy != null
			else
			{
				ccDoDebug("submitCustomerResponse: JSON object is null");
			}
		} //prescreenResponseId != null
	} //appstate != inactive

	return ret;
} //submitCustomerResponse	

//This function is polled when CreditCardAppState == 'prescreensubmitted' until a response is received.
//Initiates an asynchronous request that calls the CheckPrescreenResponse web service.  
//processCheckPrescreenResponse is subsequently called with the response.
function checkPrescreenResponse(prescreenRequestId)
{
	if(getCreditCardApplicationState()=="inactive")
		return;

	ccDoDebug("checkPrescreenResponse>");

	//If we've reached the prescreen timeout, set to inactive an stop processing
	if(CheckForPrescreenTimeout())
	{
		setCreditCardApplicationState("inactive");
		return;
	}
	
	var prescreenRequestId = getCreditCardPrescreenReqId();
	ccDoDebug("checkPrescreenResponse:prescreenRequestId=" + prescreenRequestId);
	if(prescreenRequestId==null)
	{
		return;
	}

	wsProxy = getWSProxyURL();
	if(wsProxy!=null)
	{
		var postStr = wsProxy + "?wsXml=<req><parms><prescreenRequestId>" + prescreenRequestId + "</prescreenRequestId></parms><ret><PrescreenResponseId/><DecisionStatus/><DecisionMessage/><PrescreenId/><TncUrl/><ExpDate/><PartnerId/><ResponseDate/></ret></req>&methodName=CheckPrescreenResponse&wsName=AgiCCservices&outputResult=true";
		
		ccDoDebug("checkPrescreenResponse:postStr=" + postStr);
		doAjaxRequest(postStr,processCheckPrescreenResponse);
	}

} //checkPrescreenResponse	

//Processes the asynchronous response initiated by checkPrescreenResponse.  Determines if prescreen was approved or declined and sets
//appropriate state.  If response is empty then continues polling of checkPrescreenResponse.
function processCheckPrescreenResponse(request)
{
	err = false;

	if(getCreditCardApplicationState()=="inactive")
		return;

	ccDoDebug("processCheckPrescreenResponse>");
	//alert("in processPrescreenWebServiceResponse:" + request.responseText);
	
	ccDoDebug("processCheckPrescreenResponse:before processWebServiceResponse call");
	jsonObj = processWebServiceResponse(request);
	ccDoDebug("processCheckPrescreenResponse:after processWebServiceResponse call");
	if(jsonObj!=null)
	{
		ccDoDebug("processCheckPrescreenResponse:jsonObj not null");
		
		//If web service call was successful
		if (jsonObj.returncode == 0) 
		{
			ccDoDebug("processCheckPrescreenResponse:returnCode = 0; DecisionStatus="+jsonObj.DecisionStatus);
			
			//If approved
			switch(jsonObj.DecisionStatus)
			{
				//Prescreen Approved
				case "1":
					ccDoDebug("processCheckPrescreenResponse:Prescreen approved");
					setCreditCardApplicationState("prescreenapproved");
					setCreditCardPrescreenRespId(jsonObj.PrescreenResponseId);
					
					ccDoDebug("processCheckPrescreenResponse: TNC URL=" + jsonObj.TncUrl);
					setCreditCardTNCURL(jsonObj.TncUrl);
					break;
					
				//Prescreen Denied
				case "2":
					ccDoDebug("processCheckPrescreenResponse:Prescreen denied");
					setCreditCardApplicationState("inactive");
					break;
			
				//Error returned from Barclays...Will subsequent calls succeed or fail?
				case "999":		
					ccDoDebug("processCheckPrescreenResponse:Prescreen response 999");
					setCreditCardApplicationState("inactive");
					break;
					
				default:			
					ccDoDebug("processCheckPrescreenResponse:Unknown prescreen response");
					setCreditCardApplicationState("inactive");
			}
		} //returncode == 0
		
		//Prescreen response not ready yet...do nothing
		else if (jsonObj.returncode==1)
		{
		}
		
		//Error...do we continue processing or set inactive and stop??
		else 
		{
			err = true;
			ccDoError("processCheckPrescreenResponse: An unknown response was received when checking the prescreen response.\nReturn Code=" + jsonObj.returncode + "; Return Message=" + jsonObj.errormsg,false);
		}
	}
	else
	{
		ccDoDebug("processCheckPrescreenResponse:jsonObj is null; setting state to inactive");
		setCreditCardApplicationState("inactive")
	}

	resumeCreditCardIntegration();
} //processCheckPrescreenResponse		

//Parses the HTTP object to check the readyState.  If the readyState==4 then the
//JSON object is parsed from the responseText and returned.
function processWebServiceResponse(request)
{
	err = false;
	ret = null;
	
	errMsg = "";
	
	ccDoDebug("processWebServiceResponse:in response\nreadystate=" + request.readyState);
	//ccDoDebug("processWebServiceResponse:responseText = " + request.responseText,true);
	// did ajax call complete successfully?
	if (request.readyState == 4) 
	{
		//alert("readystate=4");
		try 
		{
			//alert(request.responseText);
			jsonText = this.stripJSONFromHTML(request.responseText);
			ccDoDebug("processWebServiceResponse:JSON=" + jsonText);
			ret = eval('('+jsonText+')');	
		}
		catch(e) 
		{
			err = true;
			ret = null;
			errMsg = e.message;
			//$('wsResponse').value = e;
		}
		
	}
	else 
	{
		err = true;
		//$('result').innerHTML = 'Page Not Ready';
	}
	if (err) 
	{
		ccDoError('processWebServiceResponse:There was an error:' + errMsg,false);
	}
	
	return ret;
} //processWebServiceResponse

//Performs a synchronous HTTP request and returns the HTTP object
function doSynchRequest(url)
{
	ret = null;
	try
	{
		ccDoDebug("doSynchRequest> url=" + url);
		ccajaxreq = new ccajax(url, {method: 'get', asynch: false});
		ccDoDebug("doSynchRequest: gotccajax object");
		ccajaxreq.requestsynch();
		ret = ccajaxreq.transport;
		ccDoDebug("doSynchRequest: ret=" + ret);
	}
	catch(ex)
	{
		ccDoDebug("doSynchRequest:Exception=" + ex.message);
		//Simulate a JSON response in the responseText with a returncode of -1 and passing in the exception message
		//responseFunction({'responseText':"{'returncode':-1, 'errormsg':'" + escape(ex.message) + "'" + "}",'readyState':4});
		err = ex.message;
		ret = {'responseText':"{'CCJSONStruct':'true','returncode':-1, 'errormsg':'" + escape(err) + "'" + "}",'readyState':4};
	}
	
	return ret;
} //doSynchRequest

//Performs an asynchronous HTTP request that will pass the HTTP object to responseFunction when complete.
function doAjaxRequest(url, responseFunction)
{
	ret = null;
	try
	{
		ccDoDebug("doAjaxRequest> url=" + url);
		new ccajax(url, {method: 'get', onComplete: responseFunction, asynch: true});
	}
	catch(ex)
	{
		ccDoDebug("doAjaxRequest:Exception=" + ex.message);
		//Simulate a JSON response in the responseText with a returncode of -1 and passing in the exception message
		//responseFunction({'responseText':"{'returncode':-1, 'errormsg':'" + escape(ex.message) + "'" + "}",'readyState':4});
		err = ex.message;
		ret = {'responseText':"{'CCJSONStruct':'true','returncode':-1, 'errormsg':'" + escape(err) + "'" + "}",'readyState':4};
	}
	
	return ret;
} //doAjaxRequest

//Parses the JSON object from the input markup.  Some sites are including additional markup so the
//JSON object must be parsed.  Expects first member of the JSON object to be named 'CCJSONStruct'
//so that it can be located within the string.
function stripJSONFromHTML(html)
{
	ret = "";
	start = html.indexOf("{'CCJSONStruct");  
	if(start>=0)
	{
		levels = 1;
		for (var strIdx = start+1; strIdx < html.length; strIdx++)
		{
			if(html.substring(strIdx,strIdx + 1)=="{")
				levels++;
			else if(html.substring(strIdx,strIdx + 1)=="}")
				levels--;
				
			//alert("start=" + start + ";strIdx=" + strIdx + ";levels=" + levels + ";char=" + html.substring(strIdx,strIdx + 1) + ";str=" + html.substring(start,strIdx + 1));
			if(levels==0)
			{
				end = strIdx;
				break;
			}
		} //foreach char after start
	
		//alert("start=" + start + ";end=" + end + ";str=" + html.substring(start,end + 1));
		if((end>=0)&&(end>start))
		{
			ret = html.substring(start,end + 1);
		}
	}
	
	return ret;
} //stripJSONFromHTML

//Returns the value of the webServiceInvokeURL.  This variable is to be set within the site specific library.
function getWSProxyURL()
{
	var ret = null;
	try
	{
		ret = webServiceInvokeURL;
	}
	catch(ex)
	{
	}
	
	return ret;
} //getWSProxyURL

function setCreditCardTNCURL(tncURL)
{
	ccSetCookie("CREDITCARDTNCURL",tncURL);
} //setCreditCardTNCURL

function getCreditCardTNCURL()
{
	var tncURL = ccGetCookie("CREDITCARDTNCURL");
	
	return tncURL;
} //getCreditCardTNCURL

function setCreditCardApplicationURL(appURL)
{
	ccSetCookie("CREDITCARDAPPURL",appURL);
} //setCreditCardApplicationURL

function getCreditCardApplicationURL()
{
	var appURL = ccGetCookie("CREDITCARDAPPURL");
	
	return appURL;
} //getCreditCardApplicationURL

function setCreditCardApplicationState(ccState)
{
	ccSetCookie("CREDITCARDAPPSTATE",ccState);
} //setCreditCardApplicationState

function getCreditCardApplicationState()
{
	var ccState = ccGetCookie("CREDITCARDAPPSTATE");
	if(ccState==null)
	{
		ccDoDebug("getCreditCardApplicationState:CreditCardAppState is null");
		ccState = "inactive";
	}
	
	return ccState;
} //getCreditCardApplicationState

function setCreditCardPrescreenRespId(respID)
{
	ccSetCookie("CREDITCARDPRESCREENRESPID",respID);
} //setCreditCardPrescreenRespId

function getCreditCardPrescreenRespId()
{
	var respID = ccGetCookie("CREDITCARDPRESCREENRESPID");
	
	return respID;
} //getCreditCardPrescreenRespId

function getCreditCardPrescreenReqId()
{
	var reqID = ccGetCookie("CREDITCARDPRESCREENREQID");
	
	return reqID;
} //getCreditCardPrescreenReqId

function ccSetCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	path = "/";
	document.cookie = name + "=" +escape( value ) +
	 ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	 ( ( path ) ? ";path=" + path : "" ) + 
	 ( ( domain ) ? ";domain=" + domain : "" ) +
	 ( ( secure ) ? ";secure" : "" );
} //ccSetCookie

// this function gets the cookie, if it exists
function ccGetCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
} //ccGetCookie

function ccDoDebug(msg, doAlert)
{
	if(ccDebug)
	{
		doAlert = doAlert || false;
		
		if(ccDebugFilter=="")
			disp = true;
		else
		{
			if(msg.length < ccDebugFilter.length)
			{
				disp = false;
			}
			else
			{
				if(msg.substring(0,ccDebugFilter.length)==ccDebugFilter)
					disp = true;
				else
					disp = false;
			}
		}
		if(disp)
		{

			var debugDiv = document.getElementById("debugDiv");
			if(debugDiv!=null && !doAlert)
			{
				var debugTxt = document.getElementById("debugTxt");
				if(debugTxt==null)
				{
					debugDiv.innerHTML = '<textarea id="debugTxt" rows=10  style="width:100%" wrap="off">';
					debugTxt = document.getElementById("debugTxt");
				}

				debugTxt.value = debugTxt.value + "\n" + msg;
				debugTxt.scrollTop = debugTxt.scrollHeight;
			}
			else
			{
				alert(msg);
			}
		
		}
	}
} //ccDoDebug

function ccDoError(msg,doAlert)
{
	if(doAlert)
		alert(msg);
	else
		ccDoDebug(msg,false);
} //ccDoError

//Locates a name value pair in the URL of the current window and returns the value
function findURLArgument(argName)
{
	try
	{
		var regexS = "[\\?&]"+argName+"=([^&#]*)";  
		var regex = new RegExp( regexS );  
		var results = regex.exec( window.location.href );  
		if( results == null )    
			return "";  
		else    
			return results[1];
		}
	catch(ex)
	{
		return "";
	}
} //findURLArgument

function getSelectOptionByValue(selectID, optionValue)
{
	var ret = null;
	var selectObject = document.getElementById(selectID);
	
	for (var optionIdx=0;optionIdx<selectObject.length;optionIdx++) 
	{
		if (selectObject[optionIdx].value == optionValue) 
		{
			ret = selectObject[optionIdx];
			break;
		}
	}
	
	return ret;
} //getSelectOptionByValue

//Implements a cross-page timeout for waiting for a prescreen response
//First time called a cookie is set with current time plus the timeout in seconds
//Subsequent calls compare the value in that cookie with current time.
//Returns true if timeout has expired, false if not
function CheckForPrescreenTimeout()
{
	//Default to false which continues polling
	var ret = false;
	
	try
	{
		var expireString = ccGetCookie("PRESCREENTIMEOUT");
		
		//First call to CheckForPrescreenTimeout...set the timeout and return
		if(expireString==null)
		{
			var dt = new Date();
			dt.setSeconds(dt.getSeconds() + CC_PRESCREEN_TIMEOUT);
			
			expireString = dt.toString();
			ccSetCookie("PRESCREENTIMEOUT",expireString);
		}
		//Subsequent calls
		else
		{
			var expireDate = new Date(expireString);
			var dt = new Date();
			if(dt>expireDate)
				ret = true;
		}
	}
	catch(ex)
	{
	}
	
	
	return ret;
} //GetCurrentTimeStamp
