/* PortalApplication Object / Class */

function PortalApplication() {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication
		# DESCR:*		Portal Application constructor.
		# :*			Sets up the Javascript Portal Object,
		# :*			loads saved settings, booked marked properties
		# :*			and viewed Properties.
		# USAGE:*		PortalApp = new PortalApplication();
		# :*			Used in the body onload="PortalApp = new PortalApplication();"
		# :*			stage of the Portal page wrap.
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	this.savedSettings = new SavedSettings();
	this.propertyRequest = null;
	this.ajaxWait = null;
}

PortalApplication.prototype.obtainSearchResults = function() {

	/*	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.obtainSearchResults
		# DESCR:*		Public funtion to grab the saved search settings from the cookie and
		# :*			load the search page. This replaces the PortalSearch.obtainSearchResults
		# :*			function as Realestateview.com.au will not use ajax searches.
		# USAGE:*		<button class="buttonSmall" type="submit" onClick="PortalApp.saveSearch('refinesearch');PortalApp.obtainSearchResults();return false;">Search</button>
		# RETURNS:*		Returns nothing. The browser is directed to load a new URL link.
		# :*			results.
		# %ENDPUBLIC% */

	var searchParams = PortalApp.savedSettings.toURLString();

	var url = "/results.php?" + searchParams;
	window.location = url;
}

PortalApplication.prototype.obtainSoldSearchResults = function() {

	/*	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.obtainSearchResults
		# DESCR:*		Public funtion to grab the saved search settings from the cookie and
		# :*			load the search page. This replaces the PortalSearch.obtainSearchResults
		# :*			function as Realestateview.com.au will not use ajax searches.
		# USAGE:*		<button class="buttonSmall" type="submit" onClick="PortalApp.saveSearch('refinesearch');PortalApp.obtainSearchResults();return false;">Search</button>
		# RETURNS:*		Returns nothing. The browser is directed to load a new URL link.
		# :*			results.
		# %ENDPUBLIC% */

	var searchParams = PortalApp.savedSettings.toURLString();

	var url = "/results-sold.php?" + searchParams;
	window.location = url;
}

PortalApplication.prototype.getCheckBoxInputArray = function(formName, formInputName) {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.getCheckBoxInputArray
		# DESCR:*		Obtain the values of the check boxes within a form.
		# :*			if they are checked.
		# USAGE:*		var CheckBoxArrayValue = this.getCheckBoxInputArray(formName, name);
		# :*			fromName: Name of the form to look for
		# :*			formInputName: name of the checkboxes to get values from
		# RETURNS:*		Returns array of forms input values
		# :*			if they are checked. 
		# %ENDPUBLIC% */

	var CheckBoxen = document.forms[formName][formInputName];
	var CheckBoxValues = new Array();
	for(var i = 0;i < CheckBoxen.length; i++) {
		if (CheckBoxen[i].checked)
			CheckBoxValues.push(CheckBoxen[i].value);
	}

	return CheckBoxValues;
}

PortalApplication.prototype.saveSearch = function(formName) {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.saveSearch
		# DESCR:*		Saves the form search settings to the savedSettings object.
		# :*			Uses the forms input names as class member accessors
		# USAGE:*		PortalApp = new PortalApplication(); PortalApp.saveSearch(nameOfForm);
		# :*			nameOfForm: Name of the form to save values from.
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	// Obtain all form elements
	var el = document.forms[formName].elements;

	// for each form element found
	for(var i = 0; i < el.length; i++) {
		var value = null;
		var name = el[i].name;

		// input type
		switch (el[i].type) {

			case 'checkbox': //currently all check boxes are array of same names
				//if(el[i].checked)
					//gets all the values of same named checkboxes in an array
					value = this.getCheckBoxInputArray(formName, name);
				break;

			case 'text':
					value = el[i].value;
				break;

			case 'search':
					value = el[i].value;
				break;

			case 'select-one':

				if (el[i].selectedIndex!=-1) {
					if (el[i].options[el[i].selectedIndex].value != "") {
						value = new Array(el[i].options[el[i].selectedIndex].value);
					}
				}

			case 'select-multiple':
				value = new Array();
				for(var j = 0;j < el[i].length;j++) {
					if (el[i].options[j].selected) {
						value.push(el[i].options[j].value);
					}
				}
				break;

			case 'hidden':
				value = el[i].value;
				break;

			default:
				break;
		}

		if (value != null) {
			// save the value in the object, use it's name to reference it
			this.savedSettings[name] = value;
		}
	}

	// tell object to write cookies
	this.savedSettings.saveSettings();
}

PortalApplication.prototype.updateForm = function(formName, elementName) {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.updateForm
		# DESCR:*		Sets forms input variables with saved settings in savedSettings Object
		# :*			originally read from cookie.
		# USAGE:*		PortalApp = new PortalApplication(); PortalApp.updateForm(nameOfForm, elementName);
		# :*			nameOfForm: the form to update
		# :*			elementName: the element to update
		# :*			if elementName is blank, all elements are update
		# :*			else only elements matching that name are updated
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */


	// Obtain all form elements
	var el;
	try {
		el = document.forms[formName].elements;
	} catch(e) {
		// do nothing. We want el to be defined.
	}
	// for each form element
	if (el) {
		for(var i = 0;i < el.length; i++) {
		
			var name = el[i].name;
		
			if ((elementName == '') || (name == elementName)) {
				// input type
				switch (el[i].type) {
					case 'checkbox':
						var selected = false;
						var arr = this.savedSettings[name];

						if (arr != null) {
							// loop through stored values to find ones we need to select
							for(var j = 0; j < arr.length; j++) {
								if (arr[j] == el[i].value) {
									// selected value found so select it
									selected = true;
								}
							}

							// if array is empty
							if (arr.length == 0) {
								selected = false;
							}
					
							el[i].checked = selected;
						}
						break;

					case 'text':
						el[i].value = this.savedSettings[name];
						break;
	
					case 'search':
						el[i].value = this.savedSettings[name];
						break;

					case 'select-one':
					  	var value = this.savedSettings[name];

						if (typeof(value) == 'object') {
							value = value[0];
						}
					
						for(var j = 0; j < el[i].length; j++) {
							if (el[i].options[j].value ==  value) {
								//found match so select it
								el[i].options[j].selected = true;
							}
						}
						break;

					case 'select-multiple':
					  	var value = this.savedSettings[name];
						for(var j = 0; j < el[i].length; j++) {
							for(var l = 0; l < value.length; l++) {
								if (el[i].options[j].value ==  value[l]) {
									//found match so select it
									el[i].options[j].selected = true;
								}
							}
						}
						break;

					case 'hidden':
						// Skip updating "rm", "P", "portalsection, "portalview",  "con" or "ptr" if they are in the form.
						if (name != "P") {
							el[i].value = this.savedSettings[name];
							// Debug
							// alert(name + "=" + value);
						}
						break;

					default:
						break;
				}
			}
		}
	}
}

PortalApplication.prototype.updateSortControl = function(elementID) {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.updateSortControl
		# DESCR:*		Sets Sort Control with saved settings in savedSettings Object
		# :*			originally read from cookie.
		# USAGE:*		PortalApp = new PortalApplication(); PortalApp.updateSortControl(elementName);
		# :*			elementName: the sort Select control id to update
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

		var value = this.savedSettings['Order'];

		if (typeof(value) == 'object') {
			value = value[0];
		}
		if ($(elementID) != null){				
			$(elementID).val(value).attr("selected", "selected");
		}	
}

PortalApplication.prototype.selectAllCheckboxes = function(formName, CheckboxArrayName) {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.selectAllCheckboxes
		# DESCR:*		Given a name of a form and a checkbox Array Name, Check all of the 
		# :*			checkbox Array contents.
		# USAGE:*		PortalApp = new PortalApplication(); PortalApp.selectAllCheckboxes(formName, CheckboxArrayName);
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

		var CheckBoxen = document.forms[formName][CheckboxArrayName];

		// Make all of the checkboxes in the CheckboxArrayName checked = true.
		for (i = 0; i < CheckBoxen.length; i++) {
			if (CheckBoxen[i].type == 'checkbox') {
				CheckBoxen[i].checked = true;
			}
		}
}

PortalApplication.prototype.checkIfAllCheckboxesEmpty = function(formName, CheckboxArrayName) {

	/* 	# %PUBLIC%
		# NAME:*		PortalApplication.prototype.checkIfAllCheckboxesEmpty
		# DESCR:*		Given a name of a form and a checkbox Array Name, verify if all of the 
		# :*			checkbox Array contents are unchecked. If they are all unchecked, make them all
		# :*			checked.
		# USAGE:*		PortalApp = new PortalApplication(); PortalApp.checkIfAllCheckboxesEmpty(formName, CheckboxArrayName);
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

		var CheckBoxen = document.forms[formName][CheckboxArrayName];
		// Assume form Checkbox Array is all unchecked
		var uncheckedArrayOfCheckboxes = true;

		for (i = 0; i < CheckBoxen.length; i++) {
			if (CheckBoxen[i].type == 'checkbox') {
				if (CheckBoxen[i].checked == true) {
					uncheckedArrayOfCheckboxes = false;
				}
			}
		}

		if (uncheckedArrayOfCheckboxes == true) {
			// If our array is all unckecked, check them all.
			this.selectAllCheckboxes(formName, CheckboxArrayName);
		}
}

/* SavedSettings Object / Class */

function SavedSettings() {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings
		# DESCR:*		SavedSettings Object constructor.
		# :*			Loads Portal users settings from cookies.
		# :*			Sets up storage for Portal users settings.
		# USAGE:*		this.savedSettings = new SavedSettings();
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	// last search storage
	this.IKW = ""; 				// Keyword
	this.PT = new Array();		// Property Type
	this.CS = new Array();		// CityState location
	this.Sub = new Array();		// Suburb Name / Post Code / ID
	this.BeL = 0;				// Bedroom Low
	this.BeH = 9999;			// Bedroom High
	this.BaL = 0;				// Bathroom Low
	this.BaH = 9999;			// Bathroom High
	this.PrL = 0;				// Price Low
	this.PrH = 99999;			// Price High
	this.PaL = 0;				// Parking Low
	this.PaH = 99999;			// Parking High
	this.Order = "updated";		// Sorting
	this.CID = 0;				// ClientID for Agent
	this.GID = 0;				// GroupID for Agent
	this.StaffID = 0;			// Staff ID
	this.LaL = 0;				// Land Area Low
	this.LaH = 9999;			// Land Area High
	this.FaL = 0;				// Floor Area Low
	this.FaH = 999999;			// Floor Area High
	this.Con = "S";				// Contract Type
	this.PTr = "";				// Propert Type range
	this.Fur = 0;				// Furnished listings
	this.ExSold = 0;			// Sold listings
	this.ExAuct = 0;			// Auction Listings
	this.OFI = 0;				// Listings without OFI times
	this.Surr = "";				//Surrounding Suburbs
	this.BS = 10;				// Bin Size
	this.SearchType = "";		// Type (Homes / Land / Commercial)

	// Grab Cookie Settings
	this.loadSettings();
}

SavedSettings.prototype.loadSettings = function() {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.loadSettings
		# DESCR:*		load our settings from thier respective cookies
		# USAGE:*		Internal Function. Do Not Use.
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	// Load the last search the user did
	var str = this.readCookie('lastSearch');
	if (str != null) {
		this.fromURLString(str);
	}

}

SavedSettings.prototype.saveSettings = function() {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.saveSettings
		# DESCR:*		Save our settings to thier respective cookies
		# USAGE:*		Internal Function. Do Not Use.
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	this.createCookie('lastSearch', this.toURLStringCookie(), 365);
	this.createCookie('pdf', this.toURLString(), 365);
}

SavedSettings.prototype.toURLStringCookie = function() {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.toURLString
		# DESCR:*		returns a URL string of search parameters
		# USAGE:*		Internal Function. Do Not Use.
		# RETURNS:*		String containing the Search URL Parameters. 
		# %ENDPUBLIC% */
 	
	if(this.IKW == "Keyword") {
		this.IKW = "";	
	}

	var urlString = "IKW=" + encodeURIComponent(this.IKW) + "&BeL=" + this.BeL + "&BeH=" + this.BeH + "&BaL=" + this.BaL +
					"&BaH=" + this.BaH + "&Order=" + encodeURIComponent(this.Order) + "&CID=" + this.CID +
					"&GID=" + this.GID + "&Con=" + encodeURIComponent(this.Con) + 
					"&LaL=" + this.LaL + "&LaH=" + this.LaH + "&FaL=" + this.FaL + "&FaH=" + this.FaH + "&PTr=" + this.PTr +
					"&PaL=" + this.PaL + "&PaH=" + this.PaH + 
					"&Fur=" + this.Fur + "&ExSold=" + this.ExSold + "&ExAuct=" + this.ExAuct + 
					"&OFI=" + this.OFI + "&Surr=" + this.Surr+ "&BS=" + this.BS+ "&SearchType=" + this.SearchType+ "&StaffID=" + this.StaffID;
                    
    urlString += "&PrL=" + this.PrL + "&PrH=" + this.PrH;
	
	for(var i = 0; i < this.Sub.length; i++) {
 		urlString += "&Sub=" + this.Sub[i];
	}
	
	for(var i = 0; i < this.PT.length; i++) {
 		urlString += "&PT=" + this.PT[i];
	}

	for(var i = 0; i < this.CS.length; i++) {
 		urlString += "&CS=" + this.CS[i];
	}

	return urlString;
}

SavedSettings.prototype.toURLString = function() {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.toURLString
		# DESCR:*		returns a URL string of search parameters
		# USAGE:*		Internal Function. Do Not Use.
		# RETURNS:*		String containing the Search URL Parameters. 
		# %ENDPUBLIC% */

	if(this.IKW == "Keyword") {
		this.IKW = "";	
	}
	
	var urlString = "IKW=" + encodeURIComponent(this.IKW) + "&BeL=" + this.BeL + "&BeH=" + this.BeH + "&BaL=" + this.BaL +
					"&BaH=" + this.BaH + "&Order=" + encodeURIComponent(this.Order) + "&CID=" + this.CID +
					"&GID=" + this.GID + "&Con=" + encodeURIComponent(this.Con) + 
					"&LaL=" + this.LaL + "&LaH=" + this.LaH + "&FaL=" + this.FaL + "&FaH=" + this.FaH + "&PTr=" + this.PTr +
					"&PaL=" + this.PaL + "&PaH=" + this.PaH + 
					"&Fur=" + this.Fur + "&ExSold=" + this.ExSold + "&ExAuct=" + this.ExAuct + 
					"&OFI=" + this.OFI + "&Surr=" + this.Surr+ "&BS=" + this.BS+ "&SearchType=" + this.SearchType+ "&StaffID=" + this.StaffID;
                    
    urlString += "&PrL=" + this.PrL + "&PrH=" + this.PrH;
	
	if(this.Sub.length > 0) {
		urlString += "&Sub=";
	}
	for(var i = 0; i < this.Sub.length; i++) {
 		urlString += this.Sub[i]+",";
	}
	urlString = urlString.substring(0,urlString.length-1);
		
	for(var i = 0; i < this.PT.length; i++) {
 		urlString += "&PT=" + this.PT[i];
	}

	for(var i = 0; i < this.CS.length; i++) {
 		urlString += "&CS=" + this.CS[i];
	}

	return urlString;
}

SavedSettings.prototype.fromURLString = function(URLString) {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.fromURLString
		# DESCR:*		Parses a URL search string and sets the
		# :*			SavedSettings Object Constants with the values
		# :*			passed. Used for decoding the 'lastSearch'
		# :*			cookie string.
		# USAGE:*		Internal Function. Do Not Use.
		# RETURNS:*		String containing the Search URL Parameters. 
		# %ENDPUBLIC% */

	var params = URLString.split('&');
	for(var i = 0; i < params.length; i++) {
		var str = params[i];
		var name = str.substring(0, str.indexOf('='));
		var value = str.substring(str.indexOf('=') + 1, str.length);
		if (value != '') {
        
			switch(name) {

				case 'IKW':
					this.IKW = decodeURIComponent(value);
					break;

				case 'Sub':
					SubArray = new Array();
					SubArray = value.split(",");
					this.Sub.push(SubArray);
					break;

				case 'BeL':
					this.BeL = value;
					break;

				case 'BeH':
					this.BeH = value;
					break;

				case 'BaL':
					this.BaL = value;
					break;

				case 'BaH':
					this.BaH = value;
					break;

				case 'PrL':
					this.PrL = value;
					break;

				case 'PrH':
					this.PrH = value;
					break;

				case 'PaL':
					this.PaL = value;
					break;

				case 'PaH':
					this.PaH = value;
					break;

				case 'Order':
					this.Order = decodeURIComponent(value);
					break;

				case 'CID':
					this.CID = value;
					break;

				case 'GID':
					this.GID = value;
					break;
					
				case 'LaL':
					this.LaL = value;
					break;

				case 'LaH':
					this.LaH = value;
					break;

				case 'FaL':
					this.FaL = value;
					break;

				case 'FaH':
					this.FaH = value;
					break;

				case 'PTr':
					this.PTr = value;
					break;

				case 'PT':
					this.PT.push(value);
					break;

				case 'CS':
					this.CS.push(value);
					break;

				case 'Con':
					this.Con = decodeURIComponent(value);
					break;

				case 'Fur':
					this.Fur = value;
					break;

				case 'ExSold':
					this.ExSold = value;
					break;

				case 'ExAuct':
					this.ExAuct = value;
					break;
					
				case 'OFI':
					this.OFI = value;
					break;
					
				case 'Surr':
					this.Surr = value;
					break;
					
				case 'BS':
					this.BS = value;
					break;	
					
				case 'SearchType':
					this.SearchType = value;
					break;
				
				case 'StaffID':
					this.StaffID = value;
					break;

				default:
					break;
			}
		}
	}
}

/* SavedSettings cookie helpers */

SavedSettings.prototype.createCookie = function(name, value, expiredays) {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.createCookie
		# DESCR:*		Create a Cookie with the values supplied.
		# USAGE:*		this.savedSettings = new SavedSettings();
		# :*			this.createCookie('lastSearch', urlstring, ExpireDays);
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	if (expiredays) {
		var date = new Date();
		date.setTime(date.getTime() + (expiredays * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else {
		var expires = "";
	}
	document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

SavedSettings.prototype.readCookie = function(name) {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.readCookie
		# DESCR:*		Read the contents of the named cookie
		# USAGE:*		this.savedSettings = new SavedSettings();
		# :*			var somestring = this.readCookie('lastSearch');
		# RETURNS:*		null or contents of the Cookie. 
		# %ENDPUBLIC% */

	var nameEQ = name + "=";
	var CookieArray = document.cookie.split(';');

	for(var i=0; i < CookieArray.length; i++) {
		var c = CookieArray[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) { 
			return unescape(c.substring(nameEQ.length, c.length));
		}
	}

	return null;
}

SavedSettings.prototype.eraseCookie = function(name) {

	/* 	# %PUBLIC%
		# NAME:*		SavedSettings.prototype.eraseCookie
		# DESCR:*		Erase A Cookie. 
		# :*			name - name of the cookie to erase.
		# USAGE:*		this.savedSettings = new SavedSettings();
		# :*			this.eraseCookie('lastSearch');
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	this.createCookie(name, "", -1);
}

/* General non Class / object Functions */

function setRadioGroupValue(formName, radioGroupName, newValue) {

	/* 	# %PUBLIC%
		# NAME:*		setRadioGroupValue
		# DESCR:*		Given a form name, radio button group name
		# :*			and a radio button group value, Set the
		# :*			with the paramaters passed.
		# USAGE:*		setRadioGroupValue('nameOfForm', 'nameOfRadioGroup', 'someValue');
		# RETURNS:*		True if the value was found and checked in the radio button group,
		# :*			false if the value is not in the radio buttton group. 
		# %ENDPUBLIC% */

	if (!radioGroupName && !formName && !newValue) {
		return false;
	}

	var radioGroup = document.forms[formName].elements[radioGroupName];
	var radioOptionFound = false;

	for(var i = 0; i < radioGroup.length; i++) {
		radioGroup[i].checked = false;
		if (radioGroup[i].value == newValue.toString()) {
			radioGroup[i].checked = true;
			radioOptionFound = true;
		}
	}

	return radioOptionFound;
}

function obtainRadioGroupValue(formName, radioGroupName) {

	/* 	# %PUBLIC%
		# NAME:*		obtainRadioGroupValue
		# DESCR:*		Given a form name, radio button group name, obtain the
		# :*			value of the selected Radio button.			
		# USAGE:*		obtainRadioGroupValue('nameOfForm', 'nameOfRadioGroup');
		# RETURNS:*		zero(0) no form name and radio group name is passed or
		# :*			the value of the selected button in radio buttton group is returned. 
		# %ENDPUBLIC% */

	if (!radioGroupName && !formName) {
		return 0;
	}

	var radioGroup = document.forms[formName].elements[radioGroupName];

	var radioGroupValue = "";
	for(var i = 0; i < radioGroup.length; i++) {

		if (radioGroup[i].checked) {
			radioGroupValue = radioGroup[i].value
		}
	}

	return radioGroupValue;
}

function removeTextFromTextField(FieldID) {
	/* 	# %PUBLIC%
		# NAME:*		removeTextFromTextField
		# DESCR:*		Given an ID of a text input field, makes it value blank.			
		# USAGE:*		removeTextFromTextField(FieldID);
		# RETURNS:*		Nothing. If the FieldID is not null / blank it's value will become "". 
		# %ENDPUBLIC% */

	if (FieldID) {
		$(FieldID).value = "";
	}

}

function findNodeById(id, nodeArray){

	/*	# %PUBLIC%
		# NAME:*		findNodeById
		# DESCR:*		search in an array of nodes for the one with the passed id 
		# USAGE:*		var results = findNodeById('results', nodes);
		# :*			id : string, the id of the node to find
		# :*			nodeArray : array of nodes
		# RETURNS:*		Returns node if found or false if not
		# %ENDPUBLIC% */

	for(var i = 0; i < nodeArray.length; i++) {
		
			if (nodeArray[i].id == id) {
				return nodeArray[i];
			}
	}

	return false;
}

function slideSwitch() {
    var $active = $('#slideshow DIV.active');
 
    if ( $active.length == 0 ) $active = $('#slideshow DIV.slide:last');
 
    // use this to pull the divs in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('#slideshow DIV.slide:first');
 
    // uncomment below to pull the divs randomly
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );
 
 
    $active.addClass('last-active');
 
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

	var type="";
	function checkSuburb(val) {
				type = val;
		 		$.ajax({ type: "GET", cache: "false", url: "/getsuburb.php", data: "type="+type, success: function(content){ $("#qs-suburbs").html(content); } });
				$.ajax({ type: "GET", cache: "false", url: "/price.php", data: "type="+type, success: function(content){ $("#qs-price").html(content); } });
				$.ajax({ type: "GET", cache: "false", url: "/getpt.php", data: "type="+type, success: function(content){ $("#qs-proptype").html(content); } });
	};

	function setValues(val) {
		$("#Con").val(val);
		checkSuburb(val);
	};

function validateAlert(formData, jqForm, options) { 
    var emailValue = $('input[name=Email]').fieldValue(); 
 
    if (!emailValue[0]) { 
        alert('Please enter a email address'); 
        return false; 
    } else {
		//valid email
		var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/
		if(!regex.test(emailValue[0])){
			alert('Sorry, your email address is invalid. Please try again!');
			return false;
		}
	}
}

function messageAlert() {
	$('#alert-form-message').html('Thank you for registering.'); $('#alert-form-fields').html(''); $('#alert-button').html('');
}

function validateContact(formData, jqForm, options) { 
    var nameValue = $('input[name=name]').fieldValue(); 
    var emailValue = $('input[name=email]').fieldValue(); 

	if (!nameValue[0]) { 
        alert('Please enter a contact name'); 
        return false; 
    }
	
    if (!emailValue[0]) { 
        alert('Please enter a email address'); 
        return false; 
    } else {
		//valid email
		var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/
		if(!regex.test(emailValue[0])){
			alert('Sorry, your email address is invalid. Please try again!');
			return false;
		}
	}
}

function messageContact() {
	$('#contact-form-content').html('<div class="inner">An contact email has been sent to the listing agent(s).</div>');
}

function validateContract(formData, jqForm, options) { 
    var nameValue = $('input[name=Name]').fieldValue(); 
    var emailValue = $('input[name=email]').fieldValue(); 

	if (!nameValue[0]) { 
        alert('Please enter a contact name'); 
        return false; 
    }
	
    if (!emailValue[0]) { 
        alert('Please enter a email address'); 
        return false; 
    } else {
		//valid email
		var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/
		if(!regex.test(emailValue[0])){
			alert('Sorry, your email address is invalid. Please try again!');
			return false;
		}
	}
}

function messageContract() {
	$('#contract-form-content').html('<div class="inner">An email has been sent with your request.</div>');
}

function validateEmail(formData, jqForm, options) { 
	var nameValue = $('input[name=Name]').fieldValue(); 
    var emailValue = $('input[name=Email]').fieldValue();
    var myemailValue = $('input[name=MyEmail]').fieldValue();	

	if (!nameValue[0]) { 
        alert('Please enter your name'); 
        return false; 
    }
	
    if (!emailValue[0]) { 
        alert('Please enter your friends email address'); 
        return false; 
    } else {
		//valid email
		var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/
		if(!regex.test(emailValue[0])){
			alert('Sorry, your friends email address is invalid. Please try again!');
			return false;
		}
	}
	
	if (!myemailValue[0]) { 
        alert('Please enter your email address'); 
        return false; 
    } else {
		//valid email
		var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/
		if(!regex.test(myemailValue[0])){
			alert('Sorry, your email address is invalid. Please try again!');
			return false;
		}
	}
}

function messageEmail() {
	$('#email-form-content').html('<div class="inner">An email has been sent to your friend.</div>');
}


$(document).ready(function(){ 
		setInterval( "slideSwitch()", 5000 );				   
        $("#toggleSearchForm").click(function () { 
			$(this).toggleClass("down-arrow");
			$(this).toggleClass("up-arrow");
			$("#search-form").slideToggle();
			var htmlStr = $(this).html();
			if(htmlStr == "Open Search") { $(this).html("Close Search"); $.cookie('showSearch', 'open'); } else { $(this).html("Open Search"); $.cookie('showSearch', 'closed'); }
		});
		var showSearch = $.cookie('showSearch');  
	    if (showSearch == 'closed') {  
			$("#search-form").hide();
			$("#toggleSearchForm").html("Open Search");
			$("#toggleSearchForm").addClass("down-arrow");
			$("#toggleSearchForm").removeClass("up-arrow");
		}; 
		$("#validateForm").validate();
		var tally = $("#property-tally").html();
		$("#tally").html(tally);
		$(".useDefault").addDefaultText();
		$(".useDefault2").addDefaultText();
		$(".useFormDefault").addDefaultText();
		PortalApp = new PortalApplication();
		$("#buying-tab").addClass("selected");
		$("#renting-tab").removeClass("inactive");
		$("#renting-tab").removeClass("selected");
		$("#renting-tab").addClass("inactive");
		setValues('S');
		$("#loading").attr("disabled","disabled").val("Updating...");
		$("#loading").ajaxStart(function(){ $(this).attr("disabled","disabled").val("Updating..."); });
		$("#loading").ajaxStop(function(){ $(this).attr("disabled","").val("Search"); });
		$("#contract-form-content").hide();
		$("#email-form-content").hide();
		jQuery("a[href^=http]").each(
		    function(){
	            if(this.href.indexOf(location.hostname) == -1) { 
			        jQuery(this).attr('target', '_external');
					jQuery(this).addClass("external");
      			}
    		}
  		);
		var options = { beforeSubmit: validateAlert, success: messageAlert };
		$('#alert-form').ajaxForm(options);
		var options2 = { beforeSubmit: validateEmail, success: messageEmail };
		$('#validateEmailForm').ajaxForm(options2);
		var options3 = { beforeSubmit: validateContract, success: messageContract };
		$('#validateContractForm').ajaxForm(options3);
		var options4 = { beforeSubmit: validateContact, success: messageContact };
		$('#validateContactForm').ajaxForm(options4);

		$("#contact-form-header").click(function () { 
			$('#email-form-content').slideUp(); 
			$('#contract-form-content').slideUp(); 
			$('#contact-form-content').slideDown();
			$('#contact-form-icon').addClass('minus'); 
			$('#contract-form-icon').addClass('plus'); 
			$('#email-form-icon').addClass('plus');
			$('#contact-form-icon').removeClass('plus'); 
			$('#contract-form-icon').removeClass('minus'); 
			$('#email-form-icon').removeClass('minus');
		});
		$("#contract-form-header").click(function () { 
			$('#email-form-content').slideUp(); 
			$('#contract-form-content').slideDown(); 
			$('#contact-form-content').slideUp();
			$('#contact-form-icon').addClass('plus'); 
			$('#contract-form-icon').addClass('minus'); 
			$('#email-form-icon').addClass('plus');
			$('#contact-form-icon').removeClass('minus'); 
			$('#contract-form-icon').removeClass('plus'); 
			$('#email-form-icon').removeClass('minus');
		});
		$("#email-form-header").click(function () { 
			$('#email-form-content').slideDown(); 
			$('#contract-form-content').slideUp(); 
			$('#contact-form-content').slideUp();
			$('#contact-form-icon').addClass('plus'); 
			$('#contract-form-icon').addClass('plus'); 
			$('#email-form-icon').addClass('minus');
			$('#contact-form-icon').removeClass('minus'); 
			$('#contract-form-icon').removeClass('minus'); 
			$('#email-form-icon').removeClass('plus');
		});
		

		$('.staffthumb a').qtip({ 
		position: {
			corner: {
				tooltip: 'bottomMiddle',
				target: 'topMiddle'
			}
		},
		style: { 
			border: {
                     width: 3,
                     radius: 5
                  },
                  padding: 5, 
                  textAlign: 'center',
				  name: 'cream', tip: true
			}
		});
    });
