﻿
/************************************************************** 
 * Clear Default Text: functions for clearing and replacing default text in
 * <input> elements.
 * by Ross Shannon, http://www.yourhtmlsource.com/
 **************************************************************/

DOMAssistant.DOMReady(init); 

function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && (theInput.className.match(/\bcleardefault\b/) || theInput.id.match(/\SearchForm_SearchForm_Search\b/))) {  
            /* Add event handlers */          
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
            
            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
}

function clearDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == target.defaultText) {
        target.value = '';
    }
}

function replaceDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == '' && target.defaultText) {
        target.value = target.defaultText;
    }
}

/************************************************************** 
 * Cross-browser event handling, by Scott Andrew
 **************************************************************/
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}

/************************************************************** 
 * GRAB UNIT DETAILS
 **************************************************************/

function planPage() {
	if ($$("floorplan")) { 
		$$("floorplan").style.display = 'block';
	}

}

function populate(unit) {
	var ajaxURL = "http://" + location.host + location.pathname + "/unitdetail/" + unit;	//create the url for the request

	$$("spec-loading").style.display = 'block';	// display loading message
	$$("unit-specs").style.display = 'none'; // Show the specs panel only after selecting the unit
	
	DOMAssistant.AJAX.get(ajaxURL, writeData);	// request file via ajax
}


// once ajax request is complete...
function writeData(responseText) {
	var unitDetails = responseText.split("<!--S-->");	// split the page up to use different parts
	
	// replace the unit specification boxes with with the ajaxed data
	eval(unitDetails[1]);	//eval the javascript part
	$$("spec-id-number").replaceContent(UnitNumber);
	$$("spec-id-length").replaceContent(Length + " m");
	$$("spec-id-width").replaceContent(Width + " m");
	$$("spec-id-height").replaceContent(Height + " m");
	$$("spec-id-area").replaceContent(TotalArea + " m<sup>2</sup>");
	$$("spec-id-volume").replaceContent(TotalVolume + " m<sup>3</sup>");
	$$("spec-id-door-width").replaceContent(DoorWidth + " m");
	$$("spec-id-door-height").replaceContent(DoorHeight + " m");
	$$("spec-id-price").replaceContent(Price + " &euro;");
	$$("spec-id-deposit").replaceContent(Deposit + " &euro;");

	// Sets up the data to be printed correctly
	if ($$("unitPrintBox")) {
		$$("unitPrintBox").replaceContent(unitDetails[3]+unitDetails[5]);
	} else {
		$('body').create("div", {
			id : "unitPrintBox"
			}, true, unitDetails[3]+unitDetails[5]);
	}

	// Now set up the ACT NOW form
	var actNowBox = $('div#page.wrapper div.structureleft');

	if ($$("actNowBox")) {
		$$("actNowBox").replaceContent(unitDetails[4]);
	} else {
		actNowBox.create("div", {
			id : "actNowBox"
			}, true, unitDetails[4]);
	}
	
	// Show the specs panel only after selecting the unit
	$$("unit-specs").style.display = 'block';

	// remove loading message
	$$("spec-loading").style.display = 'none';

}

function printUnit(printURL) {
	window.print()  
 }

/************************************************************** 
 * AJAX FORM SENDING
 **************************************************************/


function actNow() {
	var actNowBox = $$('contact-form');
	actNowBox.style.visibility = 'hidden';
	$$("actNowBox").style.display = 'block';
	
	if (!$$('act-now-close')) {
		$$("ActNow").create("a", {
			href : "",
			id : "act-now-close"
		}, true, "&nbsp;");
	}
		$$('act-now-close').addEvent("click", function() {actNowClose();return false;});

	//AJAX submit

	$$("ActNowGranadaForm_ActNowFormCall").setAJAXForm(
		function () { // Function to run before submission
			if (!$$('act-now-loading')) {
				$$("ActNow").create("div", {
					id : "act-now-loading"
				}, true, "&nbsp;");
				$$('act-now-loading').create('p', null,true, "&nbsp;");
			}
			$$('act-now-loading').style.display = 'block';
		}, 
		function (response) { // Function to run to handle the response
			ActNowResponse(response);
		}, 
		{// Setting headers, as an object
//			"X-Requested-With" : "XMLHttpRequest"			
		} 
	);

}

function ActNowResponse(response) {

	// Remove loading sign
	$$('act-now-loading').style.display = 'none';

	// Remove any previous validation errors
	$('#ActNow span.message.required').remove();	
	
	//No response received
	if (response == "" || response == "Loading..." || response == null) { 
			statusMessage('Error', 'bad', '<p>Error in request. Your message could not be sent. Please try again later or contact us via another method.</p><p>Error en la petición. Su mensaje NO ha sido enviado. Por favor intentelo de nuevo mas tarde o contacte con nosotros a través del numero de teléfono u otra forma.</p>');
	}

	//Full page received from SS
	if (response.length >= 1000) {
			statusMessage('Error', 'bad', '<p>Error in request. Your message could not be sent. Please try again later or contact us via another method.</p><p>Error en la petición. Su mensaje NO ha sido enviado. Por favor intentelo de nuevo mas tarde o contacte con nosotros a través del numero de teléfono u otra forma.</p>');
	}
	
	
	var ajaxresponse = response.split("<!--S-->");	// if sends back html/js data
	if (!ajaxresponse[1]) { //Checks to see if split worked. if not, use original data.
		eval(response);
	} else { // if split worked, use JS portion of return
		eval(ajaxresponse[1]);
	}

}

	function validationError(field, errormessage, type) {
		$$(field).create("span", {
			className : "message required"
			}, true, errormessage);	
	}

	function statusMessage(status, type, message) {
		if (status == 'Validation failed') return;
		
		if (status == 'Spam') {
			$$('ActNow').create("div", {
				id : "act-now-form-spam"
				}, true, message);	
			var formUnder = $("div#ActNow form"); //hide the form so that IE 6 doesn't display the thanks message over the select element
			formUnder.addClass("none"); 
		}
		
		if (status == 'Sent' || status == "Error") {
			$$('ActNow').create("div", {
				id : "act-now-form-complete"
				}, true, message);	
			$$("act-now-close").addClass("finish"); 
		}
		
		
	}

function actNowClose() {
	var actNowBox = $$('contact-form');
	actNowBox.style.visibility = 'visible';
	$$("actNowBox").style.display = 'none';
}
	
/************************************************************** 
 * AJAX IMAGE GALLERY
 **************************************************************/

function ReplaceImage(NewImage, ThumbID) {
	//Show loading message
	$$("spec-loading").style.display = 'block';	// remove loading message
	

	//Get Image
	var imgContainer = $$('gallery-image-swap');

	TheImagePre = new Image();
		TheImagePre.onload=function(){
			$$('preloader-image').src = NewImage;
    		var TheImage = document.createElement('img');
    		TheImage.onload = function (evt) {
        		imgContainer.src=this.src;
				isLoadingVar = "false";
				isLoading();
	    	}
			TheImage.src = NewImage;
			TheImagePre.onload=function(){};	//	clear onLoad, IE behaves irratically with animated gifs otherwise 
		}
	TheImagePre.src = NewImage;


	//Remove highlight from old image
	if ($$("ImageGallery").elmsByClass("current", "a") != "") {
		$$("ImageGallery").elmsByTag("a").each(function () {
		this.setAttribute('class', '');
		this.setAttribute('className', '');
		});
	}

	//Highlight current image
	var SetCurrentThumb = $$(ThumbID);
	SetCurrentThumb.setAttribute('class', 'current');
	SetCurrentThumb.setAttribute('className', 'current');


	return false;
}

	// Check if either image is loading, remove loading image if not.
	function isLoading () {
		if (isLoadingVar == "true") {
			//do nothing
			}
		else { //neither are loading any more
			$$('spec-loading').style.display="none";	// hide loading bar once image is preloaded
			}
	}

	//////////////////////////////////
	// add containers for loading bar
	
function initGallery() {
	// adding preload img element to page
	var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id','preloader-image');
		$$('image-parent').appendChild(objLightboxImage);
	// adding loading box element to page
	var objLoading = document.createElement("div");
		objLoading.setAttribute('id','spec-loading');
		$$("image-parent").appendChild(objLoading);
	// adding loading image element to page
	var objLoadingImage = document.createElement("p");
		objLoadingImage.innerHTML = "Loading Image";
		objLoading.appendChild(objLoadingImage);

}
