var jsEnabled = function(s){ this.s=s;}
var commentsLangTxt = function(s){ this.s=s;}

inquiryErrorMsg = "";

// define page object
ha.pages.property = {
    
    //Note: init gets called at the bottom of the property page decorator
    init: function(){
		// if the inquiry bean reports that javascript is enabled, then we should 
		// do this javascripty/ajax magic
		var submitViaAjax = false;

		if (jsEnabled.s && $('jsEnabled')) { 
			submitViaAjax = true;
			$('jsEnabled').value = 'true';
		}
		
		if ($j('#comments')){
			var comments = $j("#comments").val();
			
			if (comments == "") {
				$j("#comments").val(commentsLangTxt.s);
				$j("#comments").addClass("inputDefaultText");
			}
			else if (comments.indexOf(ha.strings.propertyCommentsLangTitle) == 0){
				$j("#comments").addClass("inputDefaultText");
			}
			
			$j('#comments').focus(function(){
				var comments = $j("#comments").val();
				if (comments.indexOf(ha.strings.propertyCommentsLangTitle) == 0){
					$j("#comments").val("");
					$j("#comments").removeClass("inputDefaultText");
				}
			});
		}
		
		// Link datepicker pair.
		ha.widget.datePickControl.linkDates("checkInDateString", "checkOutDateString");

        //Set js values and events on the inquiry form.      
        //For setting values, we check that the form exists first because
        //when init gets called in doInquiryCallback, the form may or may not be shown again.
        if($('propertyInquiryForm')) {
        
			//if js is enabled then we don't want to show the real submit button - it is only for when js is not enabled
			$('realSubmitButton').style.display="none";	
			$('jsButton').style.display="inline";
			//sets the localized string rendered in the jsp
			//
			inquiryErrorMsg = lzInquiryErrorMsg;
			
			//Sets localGMTOffset
			//
			$('localGMTOffset').value = getLocalGMTOffset();
			
			//Registers behaviour for onclick of $('submitButton')
			if(!submitViaAjax || submitViaAjax == 'false') {
				// let's submit the form
				$('submitButton').addEvent('click', function(e) { 
					/**
					 * Shows the spinning indicator
					 */
					showStatus(true);
					$('propertyInquiryForm').submit();
				});
			} else {

				$('propertyInquiryForm').addEvent('submit', function(e){
					e = new Event(e);
					e.stop();
				});

				$ES("input","inquiryReplacementDiv").each(function(node){
					node.addEvent("keydown", function(e){
						e = new Event(e);
						if (e.key == 'enter'){
							var comments = $j("#comments").val();
							if (comments.indexOf(commentsLangTxt.s) == 0) $j("#comments").val("");
							
							// stop multiple submits if user presses return more than once
							try{
								$(e.target).blur();
                                                        } catch(e) {
							}
							showStatus(true);
							$('propertyInquiryForm').send({	
								update:$("inquiryReplacementDiv"),
								onComplete: doInquiryCallback, 
								onFailure: doInquiryFailureMessage
							});
						}
					}.bind(node));
				});
				
				$('submitButton').addEvent('click', function(e){
					var comments = $j("#comments").val();
					if (comments.indexOf(commentsLangTxt.s) == 0) $j("#comments").val("");
					
					/**
					 * Shows the spinning indicator
					 */
					showStatus(true);
					/**
					 * send takes care of encoding and returns the Ajax instance.
					 * onComplete updates the page with the errant form fields or with a success screen.
					 * onFailure updates the page with a message indicating that an irrecoverable server side error occured.
					 */
					$('propertyInquiryForm').send({
						update:$("inquiryReplacementDiv"),		
						onComplete: doInquiryCallback, 
						onFailure: doInquiryFailureMessage
					});

				});
			}				
		}       
           
        /**
        * HACK:
        * IE6 was hanging on loading this image for some reason.  It would display the image very small, but wouldn't
        * resize it or fire off the image loaded event.  Our nasty hack around this is to give the image a poke, and force 
        * it to reload.  I don't feel good about this, but it's working. 
        */
        if(window.ie6) { 
        	// get the image tag
        	image = $('regionMapImage');
        	if(image) {
        		imageSourceUrl = image.src
        		image.src="";
        		image.src=imageSourceUrl;
        	}
        }

		/* BeginGearsBlock C SimilarPropertiesLink */
		ha.pages.property.initSimilarProperties();
		/* EndGearsBlock C SimilarPropertiesLink */
    }    



	/* BeginGearsBlock C SimilarPropertiesLink */

	/*
	 * Initialise the country links
	 *
	 */
    , initSimilarProperties: function(){
    	var h2 = $E("h2", $("similarProperties"));
    	
    	//if javascript is turned off the default display is 'block'
    	//otherwise hide the display if javascript is enabled
    	if ($("similarProperties")) $("similarPropertiesContent").setStyle("display", "none");
    	
    	h2.addEvent("click", function(){
    		if($("similarProperties").hasClass("expand")){
    			$("similarProperties").removeClass("expand");
    			$("similarPropertiesContent").setStyle("display", "none");
    		}
    		else{
    			$("similarProperties").addClass("expand");
    			$("similarPropertiesContent").setStyle("display", "block");
    		}
    	});
    }
	/* EndGearsBlock C SimilarPropertiesLink */
    
};



function pageMonth(systemId, propertyId, unitId, offset) {
	url="/propertyAvailabilityNextPrevious.htm?systemId=" + systemId + "&propertyId=" + propertyId + "&uni_id=" + unitId + "&offset=" + offset;
	var myAjax = new Ajax(url, {method: 'get', onComplete: doMonthCallback, onFailure: doFailureMessage });
	myAjax.request();
}

function doFailureMessage(response) {
	alert(ha.strings.errorMessage);
}
function doMonthCallback(responsetext) {
	$("availabilityCalendars").innerHTML=responsetext;
}

function currencyChange(systemId, propertyId, unitId, currency) {
	url="/propertyCurrencyChange.htm?systemId=" + systemId + "&propertyId=" + propertyId + "&uni_id=" + unitId + "&currency=" + currency;
	var myAjax = new Ajax(url, {method: 'get', onComplete: doCurrencyCallback, onFailure: doFailureMessage});
	myAjax.request();
}
function doCurrencyCallback(responsetext) {
	$("rates").innerHTML=responsetext;
}
function openWindow(page,width,height,scrolling){
	var winWidth = width;
	var winHeight = height;
	var posLeft = (screen.availWidth - winWidth) / 2;
	var posTop = (screen.availHeight - winHeight) / 2;
	var winInfo = 'width=' + winWidth + ',height=' + winHeight + ',left=' + posLeft + ',top=' + posTop + ',location=no,menubar=no,toolbar=no,status=no,scrollbars=' + scrolling + ',resizable=yes';
	var poplaunch = window.open(page, 'poplaunch', winInfo);
        poplaunch.focus();
}

/* Validation used in sendToFriend popup */
/* deprecated; we need a js form validation framework */

var regexPatterns = new Object();
regexPatterns["required"] 		= /[^.*]/;
regexPatterns["email"] 			= /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
regexPatterns["alpha"] 			= /^[a-z ._-]+$/i;
regexPatterns["alphanumeric"] 	= /^[a-z0-9 ._-]+$/i;
regexPatterns["zip"] 			= /(^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$)/;


/**
 * Runs validation for the send to a friend form, and if validation fails, prints an alert message.
 * 1. Adds an error if the name field is empty
 * 2. Adds an error if the from email field fals validation
 * 3. Splits the string, and adds an error for any to email that fails validation
 * 4. Prints an alert for any errors created.
 * 5. Returns false if there are any errors.
 */
function validateSendToFriendForm(theForm) {
	var errorMessage="";
    
	// 1. Verifies name has been set.
    if ($("name").value.length < 1) { 
        errorMessage += errorStrings["name"];
	}
    
	// 2. Verifies 
	if ($("email").value.length < 1 || !validateField( "email", $("email").value))
	{
		errorMessage += errorStrings["email"];
	}
	
	// 3. split the emails and check each one
	var i=0;
	var emailAddresses = $("toEmail").value.split(",");
	
	for(i=0 ; i< emailAddresses.length ; i++ )
	{
		var email = emailAddresses[i].trim();
		if (email.length < 1 || !validateField( "email", email)) {
			var appendedString = (email.length<1 ? "" : "(" + email + ")");
	    	errorMessage += errorStrings["toEmail"] + appendedString + "\n";
		}
	}	
    
    
    if (errorMessage.length > 0) {
    	alert(errorStrings["errorTitle"] + errorMessage);
    	errorMessage="";
    	return false;
    }
    // Success! Submit form.
	document.sendToFriendForm.submit();

}

function validateField(sType, sValue) {
	return (regexPatterns[sType]).test(sValue);
}



/*Begin inquiry form methods */		
function showStatus(show) {
	if (show) {
		if ($('submitButton')) {
			$('submitButton').onclick = null;
		}
		
		$('InquiryStatus').style.visibility = "visible";
		return; // force a return because the debugger jumped down to line 194!!
	} else {
		if ($('submitButton')) {
			$('submitButton').onClick = "submitInquiry()";
		}
		$('InquiryStatus').style.visibility = "hidden";
	}					
}

/* BeginGearsBlock C hasOmnitureTracking */

// Create a publisher for the ajax response event
var ajaxInquirySubmittedWithErrors = new Observer;

/* EndGearsBlock C hasOmnitureTracking */

function doInquiryCallback(responsetext) {

	
	var isMac = (navigator.userAgent.toLowerCase().indexOf("mac") != -1);

	//if jsEnabled id is available then form errors exist
	//do not setStyle(s) and propertyInquiry border
	//due to an IE/Datepicker conflict set the float here instead of the css
	if (!$('jsEnabled'))
	{
		$$("body").addClass("inquirySuccess");

		if (jQuery.browser.mozilla && isMac) { 
			$j("#propertyInquiry").css({position:"static"});
		}

		$("propertyInquiryBox").addClass("inquiryBox");

		/* BeginGearsBlock C SimilarPropertiesLink */
		if ($("propertyContactInformation")) $("propertyContactInformation").setStyle("display", "none");
		if ($("similarProperties")) {
		
			$("similarProperties").addClass("expand");
			$("similarPropertiesContent").setStyle("display", "block");
			
		}
		/* EndGearsBlock C SimilarPropertiesLink */

		// Fire off the inquiry confirmation vbis tracking data
		submitInqTracker();

		/* BeginGearsBlock C GoogleAnalytics */
		pageTracker._trackPageview("inquiry.form.success")
		/* EndGearsBlock C GoogleAnalytics */

		// load iframe ads
		$j("iframe[@rel]").each(function(){
			$j(this).attr("src", $j(this).attr("rel"));
		});

	}
	else {

		/* BeginGearsBlock C hasOmnitureTracking */
			// Fire the event and notify subscribers
	  		var errs="";
	    	$j("span.formError", "#propertyInquiryForm").each(function(i){
		   		errs+=$j(this).text() + " ";
		    });
			ajaxInquirySubmittedWithErrors.fire(true);
		/* EndGearsBlock C hasOmnitureTracking */


		datePickerController.create();
		ha.pages.property.init();
	}
	//
	// hide the progress display		       
	showStatus(false);
		
}

function doInquiryFailureMessage() {

	var newHtml = '<div style="text-align:center">';
	newHtml += '<p class="formError">' + inquiryErrorMsg + '</p>';
	newHtml += '<p>&nbsp;</p>';
	newHtml +='</div>';
	$("inquiryReplacementDiv").innerHTML=newHtml;
	
	// hide the progress display
	showStatus(false);
}

function getLocalGMTOffset() {
	now = new Date();
	return now.getTimezoneOffset()/60;
}
/*End inquiry form methods*/

var adHtml = function (s){ this.s = s; }

function setDoubleClickHtml() {
	var id = document.getElementById('successAd');
	if (id) {
		document.write(adHtml.s);
	}
}
			
			
