/* 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});
			}
			if ($('results-view-alert-banner')) {
				Effect.Fade('results-view-alert-banner', {duration: 1.0});
			}
		}
}

function viewalertRegistration(FormID, EmailAddressID, FrequencyName, LoaderID, gaTracker) {

	/* 	# %PUBLIC%
		# NAME:*		viewalertRegistration
		# DESCR:*		Given an ID of a text field input containing an email address and 
		# :*			the name of radio control containing a frequency, test the email address
		# :*			for validity and initiate an ajax request to register the view alert.		
		# :*			When we are in the live server, we will also track this
		# :*			event using Google Analytic's pageTracker.		
		# 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);

	// Test our EmailAddress for validity.
	if (!testEmailAddress(EmailAddress)) {
		alertBox("Property Alert Registration", "Your email address is not a valid email address. Please check and try again.");
		return false;
	}

	var AlertFrequency = Form.getInputs(FormID,'radio',FrequencyName).find(function(radio) { return radio.checked; }).value;

	// Initialize our ViewAlertRequest object and submit our ajax request to register our ViewAlert.
	var searchParams = "emailaddress=" + EmailAddress  + "&frequency= " + AlertFrequency;
	var ViewAlertRequest = new viewalertRegistrationRequest(searchParams, LoaderID, gaTracker);

	return false;
}

function viewalertRegistrationRequest(searchParams, LoaderID, gaTracker) {

	/* 	# %PUBLIC%
		# NAME:*		viewalertRegistrationRequest
		# DESCR:*		Function to instantiate a new oject to register a view alert via AJAX.
		# USAGE:*		ViewAlertRequest = new viewalertRegistrationRequest(searchParams, [_gaq]);
		# :*			searchParams - URL string of searchparmaters to add to the AJAX url.
		# :*			Specifically - emailaddress=<some email address>&frequency=<some frequency>
		# :*			gaTracker - option param that is used to track a successful view alert registration
		# 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();

	// Initialise properties
	this.LoaderID = LoaderID;
	try {
		this.portalView = PortalApp.portalView;
	} catch(e) {}
	this.portalView = this.portalView || '';

	// 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&portalview=' + this.portalView;
		
	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);
					if (typeof gaTracker != "undefined") {
						var pageTrackerPageURL = '/email/subscribe';
						if (app.portalView) {
							pageTrackerPageURL = '/' + app.portalView + pageTrackerPageURL;
						}
						gaTracker.push(['_trackPageview', pageTrackerPageURL]);
					}
				}		
		}); 

}

viewalertRegistrationRequest.prototype.updateRegistrationResults = function(registrationResults, LoaderID) {

	/*	# %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 our success Result and process - setting registrationSuccessful flag true or false.
	var successDiv = findNodeById('success', nodes);
	registrationSuccessful = (successDiv && successDiv.innerHTML == '1') ? true : false;

	// Display the popup window
	var viewalertregistrationresults = findNodeById('viewalertregistrationresults', nodes);
	if (viewalertregistrationresults) {
		$('popupwindow').innerHTML = viewalertregistrationresults.innerHTML;
		Effect.Appear('popupwindow', {duration:0.015,queue: 'end'});
	}
}

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($(this.LoaderID), { 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($(this.LoaderID), { duration: 0.5});
}

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()) {
		return true;
	} else if (emailAddress == "Email me new properties" || emailAddress == "Email me new businesses") {
		$(ViewAlertFieldID).value = '';
		return true;
	} else 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;
	} else {
		PortalApp.savedSettings.createCookie('view_alert_email', emailAddress, 3);
		return true;
	}
}

function validateLandingPageViewAlert(ViewAlertFieldID) {

	/* 	# %PUBLIC%
		# NAME:*		validateLandingPageViewAlert
		# DESCR:*		Check if ViewAlertFieldID field is a valid email address.
		# USAGE:*		validateLandingPageViewAlert('emailaddress')
		# RETURNS:*		true or false. 
		# :*			before returing false, display error message.
		# %ENDPUBLIC% */

	var emailAddress = $F(ViewAlertFieldID);

	if (emailAddress.blank() || emailAddress == "Enter your email address" || !testEmailAddress(emailAddress)) {
		new Effect.Shake(ViewAlertFieldID);
		alertBox("Property Alert Registration", "Email address is incorrect.\n You must enter your valid email address.\n Please try again.");
		return false;
	}

	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 = '';
		}
}

// subscribeToApp - Instance of the subscribeToApplication() class - created when needed
var subscribeToApp;

function subscribeToApplication(onLandingPage, userSubscribeOnly) {

	// Initialise default values
	this.title = '';
	this.alertType = 0;		// '0' - used for saved search subscribe, '1' - used for view alert subscribe, '2' - used for auction alert subscribe
	this.onLandingPage = onLandingPage;
	this.userSubscribeOnly = userSubscribeOnly;
	this.windowHeight = (userSubscribeOnly) ? 270 : 375;
	this.windowWidth = 360;
	try {
		this.portalView = PortalApp.portalView;
	} catch(e) {}
	this.portalView = this.portalView || '';

	this.ajaxObjects = new Object();	//associative array to hold ajax objects

	// 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();
						//showFailureMessage();
						obj.hideLoader();
						obj.showError('The server did not respond.');
						// 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 ok
			window.clearTimeout(request['timeoutId']);
		}
	});
}

subscribeToApplication.prototype.showError = function(errorString) {
	showMyViewAlertBox(this.title, '<p>' + errorString + '</p><p>Unable to save your ' + this.title + '.</p>');
}

subscribeToApplication.prototype.showLoader = function() {
	try { Effect.Appear($(this.loaderID), { duration: 0.5}); } catch(e) {}
}

subscribeToApplication.prototype.hideLoader = function() {
	try { Effect.Fade($(this.loaderID), { duration: 0.5}); } catch(e) {}
}

subscribeToApplication.prototype.showForm = function(url) {

	showInOverlay(url, '<b>'+this.title+'<b>', this.windowWidth, this.windowHeight);
	this.lastScrollY = undefined;
	if (this.scrollHandlerObj) {
		Event.stopObserving(window, 'scroll', this.scrollHandlerObj);
	}
	this.scrollHandlerObj = this.scrollHandler.bindAsEventListener(this);
	Event.observe(window, 'scroll', this.scrollHandlerObj);
	if (this.closeHandlerObj) {
		Event.stopObserving('lightwindow', 'lightwindow:deactivate', this.closeHandlerObj);
	}
	this.closeHandlerObj = this.closeHandler.bindAsEventListener(this);
	Event.observe('lightwindow', 'lightwindow:deactivate', this.closeHandlerObj);
}

subscribeToApplication.prototype.request = function(alertType, loaderID, gaTracker, paramString) {

	// If we are already processing a request, we ignore further requests until done.
	for (objects in this.ajaxObjects) {
		if (callInProgress(this.ajaxObjects[objects].transport)) {
			return false;
		}
	}

	// alertType values: 0 - saved search; 1 - view alert; 2 - auction alert
	alertType = ((alertType == 1) || (alertType == 2)) ? alertType : 0;		// Make sure a valid value
	// Initialise properties
	this.loaderID = loaderID;
	if (PortalApp.userID) {
		this.title = (alertType == 1) ? 'Email me silmilar properties with Email Alerts' : (alertType == 2) ? 'My Auction Results' :'Save Search';
	}
	else {
		this.title = (alertType == 1) ? 'Sign Up to receive Email Alerts' : (alertType == 2) ? 'My Auction Results' :'Sign in to Save Search';
	}
	var url = '/portal/viewalert';

	// Auction alert (from propertydata) and view alert from landing page need to send the ajax request,
	// others go straight to the subscribe form.
	if ((!this.onLandingPage) && !(alertType == 2)) {
		this.showForm(url + '?rm=subscribetologin&alerttype='+alertType);
		return;
	}

	// On landing page or propertydata auction alert - send off the request to subscribe alert
	var time = new Date().getTime();
	var pars = (this.onLandingPage) ? 'rm=ajaxsignup' : 'rm=subscribeto';
	if (!paramString) { paramString = ''; }
	if (!(/portalview=/.test(paramString))) {
		pars += '&portalview=' + this.portalView;
	}
	pars += '&alerttype=' + alertType + '&' + paramString + '&time=' + time;
	var obj = this;

	this.ajaxObjects['subscribeTo'] = new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: pars,
			onLoading:function() {
				obj.showLoader();
			},
			onComplete: function(responseObj) {
				obj.hideLoader();
				obj.response(responseObj);
				if (typeof gaTracker != "undefined") {
					var pageTrackerPageURL = '/email/subscribe';
					if (obj.portalView) {
						pageTrackerPageURL = '/' + obj.portalView + pageTrackerPageURL;
					}
					gaTracker.push(['_trackPageview', pageTrackerPageURL]);
				}
			}		
		}
	); 
}

subscribeToApplication.prototype.response = function(responseObj) {
	// Convert the response from the given JSON string to Javascript object
	var response;
	if (responseObj && responseObj.responseText) {
		if (typeof(JSON) == 'object') {							// Check for native JSON support
			response = JSON.parse(responseObj.responseText);	// and use built in browser JSON
		} else {
			response = responseObj.responseText.evalJSON(true);	// else use prototype's JSON
		}
	}
	// Process the response
	if (response) {
		var url = response.PopupURL;
		if (url) {
			var regex = /^(http|\/)/;
			if (regex.test(url)) {
				this.showForm(url);
				return;
			}
		} else if (response.ResponseHTML) {
			this.close(response);
			return;
		}
	}
	this.showError('Invalid response received from server.');
}

subscribeToApplication.prototype.close = function(response, alreadyShown) {

	// response may provide a tracking url that must be applied.
	// This can be a single url (in response.TrackingURL), or multiple url's in (response.TrackingURLs)
	if (response.TrackingURL) {
		floodlightTracker.track(response.TrackingURL);
	}
	if (response.TrackingURLs && (response.TrackingURLs.length > 0)) {
		for (var i = 0; i < response.TrackingURLs.length; i++) {
			if (response.TrackingURLs[i]) {
				floodlightTracker.track(response.TrackingURLs[i]);
			}
		}
	}

	if (response.ResponseHTML) {
		// We have a response to show
		if (typeof updateEmailAlertDiv == 'function') {	// If the page has the updateEmailAlertDiv() function - use that
			// Show the response in the email alert div
			updateEmailAlertDiv(response.ResponseHTML);
		} else if (!alreadyShown) {
			// Show the response in an alert box
			showMyViewAlertBox(this.title, response.ResponseHTML);
		}
	}
	if (this.alertType == 2) {	// For auction alert, showing the response is sufficient
		return;		// No need for further processing
	}
	if (response.AlertSuccess) {
		if ($('viewalert')) {
			Effect.Fade('viewalert', {duration: 1.0});
		}
		if ($('viewalert2')) {
			Effect.Fade('viewalert2', {duration: 1.0});
		}
		if ($('results-view-alert-banner')) {
			Effect.Fade('results-view-alert-banner', {duration: 1.0});
		}
		if ($('subscribeToAlertLink')) {
			Effect.Fade('subscribeToAlertLink', {duration: 1.0});
		}
		if ($('subscribeToAlertButton')) {
			$('subscribeToAlertButton').innerHTML = 'Back';
			$('subscribeToAlertButton').onclick = function(){history.back();return false;};
		}
	}
	if (response.SearchSuccess) {
		if ($('subscribeToSearchLink')) {
			Effect.Fade('subscribeToSearchLink', {duration: 1.0});
		}
	}
	if (response.AlertSuccess || response.SearchSuccess) {
		var links = $$('#pagelinks a','.paging a');
		function changeLinks(param) {
			var regex = new RegExp('&'+param+'=\d.','g');
			var count = 0;
			links.each(function(a){
				var href = a.href;
				if (href) {
					href = href.replace(regex);		// First remove any existing instances of the param
					href += '&' + param + '=1';		// Then we can simply add it
				}
				a.href = href;
			});
		}
		if (response.AlertSuccess) {
			changeLinks('alertsaved');
		}
		if (response.SearchSuccess) {
			changeLinks('searchsaved');
		}
	}

	setMyViewCounts(response.SavedSearchCount, response.EmailAlertsCount, response.ShortlistCount);
}

// subscribeToApplication.prototype.scrollHandler() - Handle window scroll events
subscribeToApplication.prototype.scrollHandler = function(e) {
	var lightwindowHeight = parseFloat(parent.$('lightwindow_container').getStyle('height'));
	var arrayPageSize = obtainPageSize();
	var windowHeight = arrayPageSize[3];
	var topOffset = (this.userSubscribeOnly) ? 140 : 215;
	var bottomOffset = (this.userSubscribeOnly) ? 85 : 140;
	var scrollY = obtainDocumentScrollTop();	// Get current scroll position
	if (this.lastScrollY == undefined) {		// If no last saved value, start with the current value
		this.lastScrollY = scrollY;
	}
	var newTop = undefined;
	if (lightwindowHeight > windowHeight) {		// Lightwindow longer than browser window - align it with top or bottom as required
		if (scrollY < this.lastScrollY) {		// Scroll up - align with top
			newTop = topOffset;
		} else if (scrollY > this.lastScrollY) {// Scroll down - align with bottom
			newTop = windowHeight - lightwindowHeight + bottomOffset;
		}
	} else {									// Ligtwindow height less than or equal to browser window - check if 
		var currentTop = parseFloat(parent.$('lightwindow').getStyle('top'));
		if (currentTop < topOffset) {			// We are off the page - bring it back down
			newTop = topOffset;
		}
	}
	if (newTop != undefined) {					// Adjust the 'top' postion of the lightwindow if required
		parent.$('lightwindow').setStyle({top:newTop+'px'});
	}
	this.lastScrollY = scrollY;
}

// subscribeToApplication.prototype.closeHandler() - Handle event for closing of the lightwindow
subscribeToApplication.prototype.closeHandler = function(e) {
	if (this.scrollHandlerObj) {
		Event.stopObserving(window, 'scroll', this.scrollHandlerObj);
		delete this.scrollHandlerObj;
	}
	if (this.closeHandlerObj) {
		Event.stopObserving('lightwindow', 'lightwindow:deactivate', this.closeHandlerObj);
		delete this.closeHandlerObj;
	}
}

function subscribeToSearch(loaderID, gaTracker) {

	/* 	# %PUBLIC%
		# NAME:*		subscribeToSearch
		# DESCR:*		Sends an Ajax request to save a search
		# USAGE:*		subscribeToSearch({'loaderID', _gaq);
		# RETURNS:*		false always. The return from the ajax request is handled by
		# :*			the subscribeToApplication() object that is created.
		# %ENDPUBLIC% */

	// Initialize our subscribeToApplication object if not already done
	if (!subscribeToApp) {
		subscribeToApp = new subscribeToApplication(0, 0);
	}
	if (PortalApp && PortalApp.userID == 0) {
		// Need to log in - so make the window bigger
		subscribeToApp.windowWidth = 400;
		subscribeToApp.windowHeight = 450;
	}
	else {
		subscribeToApp.windowWidth = 380;
		subscribeToApp.windowHeight = 250;
	}
	// Make the request to save the search
	subscribeToApp.request(0, loaderID, gaTracker, '');
	return false;
}

function subscribeToAlert(loaderID, gaTracker, onLandingPage, paramString) {

	/* 	# %PUBLIC%
		# NAME:*		subscribeToAlert
		# DESCR:*		Sends an Ajax request to register a view alert
		# USAGE:*		subscribeToAlert('loaderID', _gaq);
		# RETURNS:*		false always. The return from the ajax request is handled by
		# :*			the subscribeToApplication() object that is created.
		# %ENDPUBLIC% */

	// Initialize our subscribeToApplication object if not already done
	if (!subscribeToApp) {
		var userSubscribeOnly = (onLandingPage) ? 1 : 0;
		subscribeToApp = new subscribeToApplication(onLandingPage, userSubscribeOnly);
	}
	// Make the request to register the alert
	subscribeToApp.request(1, loaderID, gaTracker, paramString);
	return false;
}

function subscribeToAuctionAlert(paramString) {

	/* 	# %PUBLIC%
		# NAME:*		subscribeToAuctionAlert
		# DESCR:*		Sends an Ajax request to register an auction alert
		# USAGE:*		subscribeToAuctionAlert(paramString);
		# RETURNS:*		false always. The return from the ajax request is handled by
		# :*			the subscribeToApplication() object that is created.
		# %ENDPUBLIC% */

	// Initialize our subscribeToApplication object if not already done
	if (!subscribeToApp) {
		subscribeToApp = new subscribeToApplication(0, 1);
	}
	// Make the request to register the alert
	subscribeToApp.request(2, '', '', paramString);
	return false;
}

function getSubscribeToObj() {

	/* 	# %PUBLIC%
		# NAME:*		getSubscribeToObj
		# DESCR:*		Returns the subscribe to object (for use by code running in an iframe)
		# USAGE:*		var localObjRef = parent.getSubscribeToObj();
		# RETURNS:*		The subscribeToApplication object
		# %ENDPUBLIC% */

	// Initialize our subscribeToApplication object if not already done
	if (!subscribeToApp) {
		subscribeToApp = new subscribeToApplication();
	}
	// Return the object
	return subscribeToApp;
}

