var notInitialized = 0;		//The request is not initialized 
var setUp = 1;				//The request has been set up 
var requestSent = 2;		//The request has been sent 
var requestInProcess = 3;	//The request is in process 
var requestComplete = 4;	//The request is complete

var xmlHttp;
var tmpNewSubReq;

/* New-Subscription-Request control constructor */
function NewSubscriptionRequest(tzLocale,
									urlPrefix,
									signUpSource,
									signUpCode,
									txtEmailAddress,
									txtPostalCode,
									ddlCountryList,
									chkNewsflash,
									chkInformer,
									btnSubmit,
									lblEmalAddressStatus,
									lblPostalCodeStatus,
									lblNewsflashMessage,
									divSignUpPanel,
									divConfirmationPanel,
									divAlmostDonePanel,
									divLoadingPanel,
									spnEmailAddress,
									hrfEmailCorrectionLink,
									spnEmailDomainUrl,
									spnStraightToInbox,
									trackingCallback)
{
	// Set some controls
	this.txtEmailAddress = txtEmailAddress;
	this.txtPostalCode = txtPostalCode;
	this.ddlCountryList = ddlCountryList;
	this.chkNewsflash = chkNewsflash;
	this.chkInformer = chkInformer;
	this.btnSubmit = btnSubmit;
	this.lblEmalAddressStatus = lblEmalAddressStatus;
	this.lblPostalCodeStatus = lblPostalCodeStatus;
	this.lblNewsflashMessage = lblNewsflashMessage;
	this.divSignUpPanel = divSignUpPanel;
	this.divConfirmationPanel = divConfirmationPanel;
	this.divAlmostDonePanel = divAlmostDonePanel;
	this.divLoadingPanel = divLoadingPanel;
	this.spnEmailAddress = spnEmailAddress;
	this.hrfEmailCorrectionLink = hrfEmailCorrectionLink;
	this.spnEmailDomainUrl = spnEmailDomainUrl;
	this.spnStraightToInbox = spnStraightToInbox;
	this.trackingCallback = trackingCallback;
	
	// Set some values
	this.tzLocale = tzLocale;
	this.urlPrefix = urlPrefix;
	this.signUpSource = signUpSource;
	this.signUpCode = signUpCode;
	
	
	// Set some flags
	this.newsflashCheckedDefault = true;
	this.informerCheckedDefault = true;
	this.showFormAfterComplete = false;
	
	// initialize
	this.init();
}

/* New-Subscription-Request control initializing function */
NewSubscriptionRequest.prototype.init = function() {
    var newSubReq = this;

    // assign the onclick event handler for the 
    newSubReq.btnSubmit.onclick = function(e) {
    goodPostalCode = validPostalCode(newSubReq.txtPostalCode.value, newSubReq.ddlCountryList.value, newSubReq.lblPostalCodeStatus, newSubReq.lblNewsflashMessage);
        goodEmailAddress = validEmailAddress(newSubReq.txtEmailAddress.value, newSubReq.lblEmalAddressStatus);

        var newsflashChecked = newSubReq.newsflashCheckedDefault;
        var informerChecked = newSubReq.informerCheckedDefault;

        if (newSubReq.chkNewsflash)
            newsflashChecked = newSubReq.chkNewsflash.checked;

        if (newSubReq.chkInformer)
            informerChecked = newSubReq.chkInformer.checked;

        if (goodPostalCode && goodEmailAddress) {
            tmpNewSubReq = newSubReq;
            
            processSubscriptionRequest();
        }
    };
} 

/* Creates the xmlHttp object */
function GetXmlHttpObject()
{
	xmlHttp = null;
	
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	return xmlHttp;
}

/* Processes a subscription request */
function processSubscriptionRequest()
{
    xmlHttp = GetXmlHttpObject();
	
	if (xmlHttp == null)
	{
		alert ("Your browser does not support AJAX!");
		// In this case redirect the user to a sign up page
		return;
    }
	
	var url = "/NewSubscriptionRequestHandler.ashx";
	url = url + "?emailAddress=" + urlEncode(tmpNewSubReq.txtEmailAddress.value);
	url = url + "&postalCode=" + urlEncode(tmpNewSubReq.txtPostalCode.value);
	url = url + "&countryCode=" + tmpNewSubReq.ddlCountryList.value;
	url = url + "&signUpSource=" + urlEncode(tmpNewSubReq.signUpSource);
	url = url + "&signUpCode=" + urlEncode(tmpNewSubReq.signUpCode);
	url = url + "&newsflash=" + tmpNewSubReq.chkNewsflash.checked;
	url = url + "&informer=" + tmpNewSubReq.chkInformer.checked;
	url = url + "&tzLocale=" + tmpNewSubReq.tzLocale;
	url = url + "&urlPrefix=" + tmpNewSubReq.urlPrefix;
	url = url + "&sid=" + Math.random();
	
	xmlHttp.onreadystatechange = stateChanged;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

/* Defines the action on the state-changed event*/
function stateChanged() {
	// fade out the sign up panel when the request is sent
    if (xmlHttp.readyState == requestSent) {
        fadeOut(tmpNewSubReq.divSignUpPanel.id, 100);
        
        tmpNewSubReq.txtEmailAddress.disabled = true;
        tmpNewSubReq.txtPostalCode.disabled = true;
        tmpNewSubReq.btnSubmit.disabled = true;
        tmpNewSubReq.ddlCountryList.disabled = true;
    }
	
	// fade in the loading panel when the request is processed
	if (xmlHttp.readyState == requestInProcess)
		fadeIn(tmpNewSubReq.divLoadingPanel.id, 100);
		
	if (xmlHttp.readyState == requestComplete)
	{
		var returnId;
		var returnValues;
		var emailDomain;
		var emailDomainUrl;

		setTimeout('fadeOut(\'' + tmpNewSubReq.divLoadingPanel.id + '\', 0)', 1000);

		if (tmpNewSubReq.showFormAfterComplete)
		    setTimeout('fadeIn(\'' + tmpNewSubReq.divSignUpPanel.id + '\', 0)', 1000);
		
		returnValues = xmlHttp.responseText.split('|');
		
		returnId = returnValues[0];
		
		if (returnValues.length > 1)
		{
			emailDomain = returnValues[1];
			emailDomainUrl = returnValues[2];
        }

		if (isNumeric(returnId))
		    setTimeout('fadeIn(\'' + tmpNewSubReq.divConfirmationPanel.id + '\', 0)', 1000);
		else if (returnId == 'currentmember')
		{
		    window.location = 'http://' + tmpNewSubReq.urlPrefix + 'top20.travelzoo.com/Confirm.aspx?currentmember';
		}
		else
		{
			tmpNewSubReq.spnEmailAddress.innerHTML = tmpNewSubReq.txtEmailAddress.value;
			tmpNewSubReq.hrfEmailCorrectionLink.href = 'http://' + tmpNewSubReq.urlPrefix + 'top20.travelzoo.com/SignUp.aspx?uid=' + returnId + '&se=1';

			if (emailDomain && emailDomainUrl && tmpNewSubReq.spnStraightToInbox && tmpNewSubReq.spnEmailDomainUrl) {
			    tmpNewSubReq.spnStraightToInbox.style.display = '';
			    tmpNewSubReq.spnEmailDomainUrl.innerHTML = '<a href="' + emailDomainUrl + '" target="_blank">' + emailDomain + '</a>';
			}
				
			setTimeout('fadeIn(\'' + tmpNewSubReq.divAlmostDonePanel.id + '\', 0)', 1000);

        }

        if (typeof tmpNewSubReq.trackingCallback == 'function') {
            tmpNewSubReq.trackingCallback();
        }
    }
}

/* The Javascript escape and unescape functions do not correspond with what browsers actually do ... */
function urlEncode(plainText)
{
	var SAFECHARS = '0123456789' +					// Numeric
					'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +	// Alphabetic
					'abcdefghijklmnopqrstuvwxyz' +
					'-_.!~*\'()';					// RFC2396 Mark characters
	var HEX = '0123456789ABCDEF';
	var encoded = '';
	
	for (var i = 0; i < plainText.length; i++ ) {
		var ch = plainText.charAt(i);
	    if (ch == ' ') {
		    encoded += '+';				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    // Unicode Character cannot be encoded using 
			    // standard URL encoding. URL encoding only 
			    // supports 8-bit characters. A space (+) will 
			    // be substituted.
				encoded += '+';
			} else {
				encoded += '%';
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}