/* View Alert global javascript */

var emailAddressFieldDefaultValue = true;
var registrationSuccessful = false;

function checkEmailAddressFieldNotDefault(FieldID) {

	/* 	# %PUBLIC%
		# NAME:*		checkEmailAddressFieldNotDefault
		# DESCR:*		Check to see if our emailaddress text input field contains the
		# :*			default text string value. If it does, blank it out.			
		# USAGE:*		checkEmailAddressFieldNotDefault(FieldID);
		# RETURNS:*		Nothing. If the FieldID is not null / blank, it's value will become "". 
		# %ENDPUBLIC% */


	if (emailAddressFieldDefaultValue == true) {
		removeTextFromTextField(FieldID);
		emailAddressFieldDefaultValue = false;
	}

}

function closeViewAlertRegistration() {

	/* 	# %PUBLIC%
		# NAME:*		closeViewAlertRegistration
		# DESCR:*		Close the View Alert Pop Up Window and remove it's contents.			
		# USAGE:*		closeViewAlertRegistration();
		# RETURNS:*		Nothing. The Pop Up Window is closed and it's contents will become "". 
		# %ENDPUBLIC% */

		// Zero out the contents of the pop up viewalert window and hide it.
		Effect.Fade('popupwindow', {duration: 1.0});
		$('popupwindow').innerHTML = "";

		if (registrationSuccessful == true) {
			Effect.Fade('viewalert', {duration: 1.0});
			if ($('viewalert2')) {
				Effect.Fade('viewalert2', {duration: 1.0});
			}
		}
}

function viewalertRegistration(EmailAddressID, FrequencyID) {

	/* 	# %PUBLIC%
		# NAME:*		viewalertRegistration
		# DESCR:*		Given an ID of a text filed input containg an email adress an an ID
		# :*			of a select control containing a frequceny selection, Test the email address
		# :*			for validity and initiate an ajax request to register the view alert.		
		# USAGE:*		viewalertRegistration('emailaddress', 'frequency');
		# RETURNS:*		false always. The return from the ajax request is handled by
		# :*			the viewalertRegistrationRequest() object that is created.
		# %ENDPUBLIC% */

	var EmailAddress = $F(EmailAddressID);
	var AlertFrequency = $F(FrequencyID);

	// Test our EmailAddress for validity.

	if (!testEmailAddress(EmailAddress)) {
		alertBox("ViewAlert Registration", "Your email address is not a valid email address. Please check and try again.");
		return false;
	}

	// Initialize or ViewAlertRequest object and submit our ajax request to register our ViewAlert.

	var searchParams = "emailaddress=" + EmailAddress  + "&frequency= " + AlertFrequency;

	var ViewAlertRequest = new viewalertRegistrationRequest(searchParams);

	return false;
}

function viewalertRegistrationRequest(searchParams) {

	/* 	# %PUBLIC%
		# NAME:*		viewalertRegistrationRequest
		# DESCR:*		Function to instantiate a new oject to register a view alert via AJAX.
		# USAGE:*		ViewAlertRequest = new viewalertRegistrationRequest(searchParams);
		# :*			searchParams - URL string of searchparmaters to add to the AJAX url.
		# :*			Specifically - emailaddress=<some email address>&frequency=<some frequency>	
		# RETURNS:*		Nothing. Creates new object and registers new AJAX responder.
		# :*			Upon completion of the AJAX request, the object method updateRegistrationResults()
		# :*			is called.
		# %ENDPUBLIC% */

	// Assocative array to hold ajax objects
	this.ajaxObjects = new Object();

	// Register global responders that will occur on all AJAX requests
	var obj = this;

	Ajax.Responders.register({

		onCreate: function(request) {

			request['timeoutId'] = window.setTimeout(
					
				function() {
						
					// If we have hit the timeout and the AJAX request is active, abort it and let the user know
						
					if (callInProgress(request.transport)) {
						request.transport.abort();
						alertBox('ViewAlert Registration', 'The server did not respond. Uable to register your ViewAlert.');

						// Run the onFailure method if we set one up when creating the AJAX object
						if (request.options['onFailure']) {							
							request.options['onFailure'](request.transport, request.json);
						}
					}

				}, 30000);
		},

		onComplete: function(request) {
			// Clear the timeout, the request completed
				window.clearTimeout(request['timeoutId']);
			}
	});

	// Collect our ViewAlert params and send off the request.

	var today = new Date();
	var time = today.getTime();

	// Save 'this' for callback
	var app = this;
	var url = "/portal/viewalert?rm=register";
		
	var pars = searchParams + '&time=' + time;

	// Abort all objects if they exist
	for (objects in this.ajaxObjects) {
		if (callInProgress(this.ajaxObjects[objects].transport)) {
			this.ajaxObjects[objects].transport.abort();
			window.clearTimeout(app.ajaxObjects[objects]['timeoutId']);
		}
		this.ajaxObjects[objects] = null;
	}

	this.ajaxObjects['ViewAlertRegistration'] = new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: pars,
			onLoading:function() {
					app.showLoader();
				},
			onComplete: function(obj) {
					app.updateRegistrationResults(obj);
				}		
		}); 

}

viewalertRegistrationRequest.prototype.updateRegistrationResults = function(registrationResults) {

	/*	# %PRIVATE%
		# NAME:*		viewalertRegistrationRequest.prototype.updateRegistrationResults
		# DESCR:*		Update the DOM with the returned registration results. Handle
		# :*			hiding the 'viewalertloader' div.
		# USAGE:*		Do not call directly. Internal routine used by the
		# :*			AJAX object after the XMLHttpRequest is complete.
		# RETURNS:*		Returns nothing.
		# %ENDPRIVATE% */

	this.hideLoader();

	// Obtain the string from the request object
	var doc = registrationResults.responseText;

	// Create a new node to store html DOM passed from AJAX
	var tempNode = document.createElement('div');

	// Populate the html
	tempNode.innerHTML = doc;

	// Obtain the array of the container divs
	var nodes = tempNode.childNodes;

	// Find and update the Search Results
	var viewalertregistrationresults = findNodeById('viewalertregistrationresults', nodes);
	this.updatePopUpWindow(viewalertregistrationresults);

	// Find our success Result and process.
	var registrationSuccess = findNodeById('success', nodes);

	// debug
	//alert(tempNode.innerHTML);
	//alert(registrationSuccess.innerHTML);

	if (registrationSuccess.innerHTML == 1) {
		registrationSuccessful = true; 
	} else {
		registrationSuccessful = false;
	}

	//Debug
	//alert(registrationSuccessful);

}

viewalertRegistrationRequest.prototype.updatePopUpWindow = function(WindowContents) {

	/*	# %PRIVATE%
		# NAME:*		viewalertRegistrationRequest.prototype.updatePopUpWindow
		# DESCR:*		Given an Object containing the <div id="popupwindow"></div>,
		# :*			replace the DOM <div id="results"></div> with its contents.
		# USAGE:*		Do not call directly. Internal routine.
		# RETURNS:*		Returns nothing.
		# %ENDPRIVATE% */

	try {
		if (WindowContents != false) {

			$('popupwindow').innerHTML = WindowContents.innerHTML;
			//new Effect.Center('popupwindow');
			Effect.Appear('popupwindow', {duration:0.015,queue: 'end'});

		}

	} catch(e) {
		// An exception occurred. Print the error.
		printDebug("updatePopUpWindow()", e);	
	}
}

viewalertRegistrationRequest.prototype.showLoader = function() {

	/*	# %PRIVATE%
		# NAME:*		viewalertRegistrationRequest.prototype.showLoader
		# DESCR:*		Show the <div id="viewalertloader"><div> 
		# USAGE:*		Internal Function. Do not use.
		# RETURNS:*		Returns nothing. The 'loader' div will be displayed with effects.
		# %ENDPRIVATE% */

	Effect.Appear('viewalertloader', { duration: 0.5});
}
	
viewalertRegistrationRequest.prototype.hideLoader = function() {

	/*	# %PRIVATE%
		# NAME:*		viewalertRegistrationRequest.prototype.hideLoader
		# DESCR:*		Hide the <div id="viewalertloader"><div> 
		# USAGE:*		Internal Function. Do not use.
		# RETURNS:*		Returns nothing. The 'loader' div will be hidden with effects.
		# %ENDPRIVATE% */

	Effect.Fade('viewalertloader', { duration: 0.5});
}

function printDebug(message, e) {

	/*	# %PUBLIC%
		# NAME:*		printDebug
		# DESCR:*		Print a debugging message on the page. 
		# USAGE:*		printDebug(message, e);
		# :*
		# :*			try {
		# :*				// Do something that may throw an exception
		# :*			} catch(e) {
		# :*				printDebug("updateSearchCriteria()", e);
		# :*			}
		# :*
		# :*			message : error message string
		# :*			e : exception that was raised
		# RETURNS:*		Returns nothing. An Alert box will appear on page.
		# %ENDPUBLIC% */

	var errorMessage = "";
	if (e != undefined){
		if (e.message)
			errorMessage = e.message;
		else 
			errorMessage = e;
	}

	alertBox(message, errorMessage);
	
}

function checkViewAlertEmail(PortalApp, ViewAlertFieldID, ViewAlertDiv) {

    /* 	# %PUBLIC%
		# NAME:*		checkViewAlertEmail
		# DESCR:*		Check if ViewAlertFieldID field is a valid email address
        # :*            If the field is valid, remove the div from the search form and 
        # :*            set the cookie view_alert_email via PortalApp object
		# :*			
		# USAGE:*		checkViewAlertEmail(PortalApp, 'view_alert_email', 'view_alert_email_div')
		# RETURNS:*		true of false. 
		# :*			returns true if the ViewAlertFieldID field is empty or is a valid email adsress
		# %ENDPUBLIC% */
        
    var emailAddress = $F(ViewAlertFieldID);
    
    if(emailAddress.blank()) {
      //  $(ViewAlertDiv).remove();
        return true;
    }
    else {
	  if(emailAddress == "Email me new properties" || emailAddress == "Email me new businesses") {
        $(ViewAlertFieldID).value = '';
		return true;
      }
      if (!testEmailAddress(emailAddress)) {
		new Effect.Shake(ViewAlertFieldID);
		alertBox("Error:", "Email address is incorrect.\n You must enter your valid email address or leave this field empty.\n Please try again.");
		return false;
      }
    }
    //$(ViewAlertDiv).remove();
    PortalApp.savedSettings.createCookie('view_alert_email', emailAddress, 3);
    return true;
}

function checkSuburbText(SuburbSearch) {

    /* 	# %PUBLIC%
		# NAME:*		checkViewAlertEmail
		# DESCR:*		Check if ViewAlertFieldID field is a valid email address
        # :*            If the field is valid, remove the div from the search form and 
        # :*            set the cookie view_alert_email via PortalApp object
		# :*			
		# USAGE:*		checkViewAlertEmail(PortalApp, 'view_alert_email', 'view_alert_email_div')
		# RETURNS:*		true of false. 
		# :*			returns true if the ViewAlertFieldID field is empty or is a valid email adsress
		# %ENDPUBLIC% */
		
		if ($(SuburbSearch).value == 'Suburbs,Postcodes'){
			$(SuburbSearch).value = '';
		}


}
