//GLOBALS
/*
*
* LEAVE THESES ALONE
*
*/
//FOR CONFIRM FUNCTION
var confirmed = false;
var elementClass = '';
var titleText = '';


// confirmAction()
/*
* Builds arrays where confirmation can take place
*
* @return bool
*/
function confirmAction() {

	//IS DOM SUPPORTED
	if(!document.getElementsByTagName('a')) return false;

	//GET ELEMENTS ON PAGE TO WORK WITH
	var confirmLinks   = document.getElementsByTagName('a');
	var buttons = document.getElementsByTagName('input');
	
	//PROCESS ELEMENTS
	loopElements(confirmLinks);
	loopElements(buttons);
	
	return false;

}

// loopElements()
/*
* Processes passed elements, gets text for confirm box and sends for confirmation
* @return bool @param array of elements
*/
function loopElements(elements) {
	
	for(var i=0; i<elements.length; i++) { //LOOP THROUGH ELEMENTS
	
		elementClass = elements[i].className; //ASSIGN CLASSNAME
		
		if(elementClass != '' && elementClass.indexOf('confirm') > -1) { //DOES CONFIRM CLASSNAME EXIST ON ELEMENT
		
			elements[i].onclick = function() { //ELEMENT CLICKED
			
				titleText = '';
			
				if(this.getAttribute('alt')) {
					
					titleText = this.getAttribute('alt'); //GET TEXT FROM ALT ATTRIBUTE ON BUTTONS
					
				}else if(this.getAttribute('title')) {
					
					titleText = this.getAttribute('title');	//GET TEXT FROM TITLE ON LINKS
					
				}
				
				if(titleText.length > 0) alertText = titleText; //APPLY TEXT TO VARIABLE
				
				confirmed = getConfirmation(alertText); //PASS TEXT TO FUNCTION
				
				return confirmed; //RETURN RESULT
			
			}
		
		}
	
	}
	
}

// getConfirmation()
/*
* Displays confirmation box returns result
* @return bool @param String of text to display
*/
function getConfirmation(text) {

	var result = confirm(text); //SHOW CONFIRMATION BOX

	return result; //RETURN RESULT

}

// externalLinks()
/*
* Allows external links to be opened in a new window without the use of target attribute
* @return bool
*/
function externalLinks() {
	
	//SETS DOMAIN OF SITE
	var domainName=document.domain;
	
	var externalLinks=document.getElementsByTagName("a"); //FIND ALL LINKS ON THE CURRENT PAGE
	
	for(var i=0; i<externalLinks.length; i++) { //LOOP THROUGH LINKS ARRAY
	
		if(externalLinks[i].getAttribute("href") != null) {

                    var attribute = externalLinks[i].getAttribute("href"); //GETS CONTENT OF 'HREF' ATTRIBUTE ON CLICKED LINK

                    var elementClass = externalLinks[i].className; //STORES CLASS NAME OF ELEMENT

                    var contains_http = attribute.indexOf("http://"); //GET VALUE http IN 'HREF' **FOR MOZILLA&&

                    var contains_domain=attribute.indexOf(domainName); //GET VALUE domainName **FOR IE**

                    if(newWindowLink == true) {

                            if(contains_http > -1 && contains_domain==-1) { //DOES CONTAIN AN 'http' OR DOES NOT CONTAIN domainName

                                    setElementAttribute(externalLinks[i], 'target', '_blank');

                            }

                    }

                    if(elementClass.indexOf('new_window') > -1 ) { //FORCE LINK TO OPEN IN NEW WINDOW

                            setElementAttribute(externalLinks[i], 'target', '_blank');

                    }
                }
		
	}
	
}

// setElementAttribute()
/*
* Sets elements attribute
* @return bool; @param element: Element to attach attr to, attr: The attribute to be added, val: value of attribute
*/
function setElementAttribute(element, attr, val) {

	element.setAttribute(attr, val); //SET ATTRIBUTE ON ELEMENT

	return true;

}

// popUpWindows()
/*
* Creates a popup window
* @return bool;
*/
function popUpWindows() {
	
	var links = document.getElementsByTagName('a'); //MAKE ARRAY OF LINKS
	var url = '';
	
	for(var i=0; i<links.length; i++) { //LOOP LINKS
		
		var classes = links[i].className;
		
		if(classes != '') {
			
			var splitClasses = classes.split(' '); //EXPLODE CLASSES ON SPACE ' '
					
			for(var x=0; x<splitClasses.length; x++) { //LOOP THROUGH MULTIPLE CLASSNAMES
					
				if(splitClasses[x].indexOf('popup_window') > -1) { //IS LINK A POPUP WINDOW
				
					links[i].onclick = function() { //LINK CLICKED
			
						var classes = this.className; //GET CLASS NAMES
						
						url = this.getAttribute('href'); //FINDS WHAT PAGE WINDOW IS TO SHOW
								
						var dimentions = getDimentions(splitClasses[x]); //GET DIMENTIONS
								
						var newWindow = window.open(url, '', 'width='+dimentions['width']+', height='+dimentions['height']+', scrollbars=yes, resize=yes'); //SET NEW WINDOW
								
						newWindow; //LAUNCH
								
						return false; //STOP LINK
							
					}
						
				}
				
			}
		
		}
	
	}
	
}

// getDimentions()
/*
* Gets dimentions of popup window
* @return array; @param thisClass: Classname of link clicked
*/
function getDimentions(thisClass) {

	var parts = thisClass.split('_'); //EXPLODE CLASSNAME ON UNDERSCORE _
	var winWidth = parts[parts.length-2]; //WIDTH IS SECOND LAST ELEMENT
	var winHeight = parts[parts.length-1]; //HEIGHT IS LAST ELEMENT
	
	var dimentions = new Array();
	
	dimentions['width']  = winWidth;
	dimentions['height'] = winHeight;
	
	return dimentions; //RETURN

}


// sendPostData(path, data, callback)
/*
* Sends POST data to the specified path.
* @param path String Location to page of interest.
* @param data String NVP format.
* @param callback String Function to call on state change.
*/
function sendPostData(path, data, callback) {
    if (callback != 'undefined') {
        http.onreadystatechange=callback;
    }
    http.open("POST", path);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", data.length);
    http.setRequestHeader("Connection", "close");
    http.send(data);
}


/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 
 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
 
(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);


// AJAX Powered.
// 9xb.com

function createRequestObject() {
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}

var http = createRequestObject();


// JavaScript Document

// EDIT THESE VALUES IF REQUIRED
var alertText = 'Are you sure you wish to perform this action' + "\n"; //DEFAULT TEXT DISPLAYED ON CONFIRM BUTTONS/LINKS WHEN NO ALT/TITLE
var newWindowLink = true; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?


var woms = new Array(); //CREATE ARRAY OF FUNCTIONS TO LAUNCH ONLOAD

//ONLOAD MANAGER
function womOn(){
  window.onload = womGo;
}

function womGo(){
  for(var i = 0;i < woms.length;i++)
    eval(woms[i]);
}

function womAdd(func){
  woms[woms.length] = func;
}

function CreateBookmarkLink() {

	title = document.title;
	url = window.location.href;
	
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,"");
	} else if(window.external) {
		window.external.AddFavorite( url, title); 
	} else if(window.opera && window.print) {
		return true;
	}
	
}

function objToggle(obj) { 

	var obj = document.getElementById(obj);

	if(obj.style.display == "block") { 
		obj.style.display = "none";
	} else { 
		obj.style.display = "block";
	}

}







	/**
	 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
	 */
	// Declaring valid date character, minimum year and maximum year
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;

	function isInteger(s){
		var i;
		for (i = 0; i < s.length; i++){   
			// Check that current character is number.
			var c = s.charAt(i);
			if (((c < "0") || (c > "9"))) return false;
		}
		// All characters are numbers.
		return true;
	}

	function stripCharsInBag(s, bag){
		var i;
		var returnString = "";
		// Search through string's characters one by one.
		// If character is not in bag, append to returnString.
		for (i = 0; i < s.length; i++){   
			var c = s.charAt(i);
			if (bag.indexOf(c) == -1) returnString += c;
		}
		return returnString;
	}

	function daysInFebruary (year){
		// February has 29 days in any year evenly divisible by four,
		// EXCEPT for centurial years which are not also divisible by 400.
		return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}
	function DaysArray(n) {
		for (var i = 1; i <= n; i++) {
			this[i] = 31
			if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
			if (i==2) {this[i] = 29}
	   } 
	   return this
	}
	
	function isDate(dtStr)
	{
		if(dtStr!='')
		{
			var daysInMonth = DaysArray(12)
			var pos1=dtStr.indexOf(dtCh)
			var pos2=dtStr.indexOf(dtCh,pos1+1)
			var strDay=dtStr.substring(0,pos1)
			var strMonth=dtStr.substring(pos1+1,pos2)
			var strYear=dtStr.substring(pos2+1)
			strYr=strYear
			if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
			if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
			for (var i = 1; i <= 3; i++) {
				if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
			}
			month=parseInt(strMonth)
			day=parseInt(strDay)
			year=parseInt(strYr)
			if (pos1==-1 || pos2==-1){
				alert("The date format should be : dd/mm/yyyy")
				return false;
			}
			if (strMonth.length<1 || month<1 || month>12){
				alert("Please enter a valid month")
				return false;
			}
			if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
				alert("Please enter a valid day")
				return false;
			}
			if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
				alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
				return false;
			}
			if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
				alert("Please enter a valid date")
				return false;
			}
			return true
		}
	}

	function checkinput()
	{
		var start_date = document.getElementById('start_date').value;
		var finish_date = document.getElementById('end_date').value;

		if (isDate(start_date)==false && isDate(finish_date)==false )
		{
		
		}
		else
		{
			Date.prototype.toDDMMYYYYString = function () {return isNaN (this) ? 'NaN' : [this.getDate() > 9 ? this.getDate() : '0' + this.getDate(), this.getMonth() > 8 ? this.getMonth() + 1 : '0' + (this.getMonth() + 1), this.getFullYear()].join('/')}
			
			Date.fromDDMMYYYY = function (s){return (/^(\d\d?)\D(\d\d?)\D(\d{4})$/).test(s) ? new Date(RegExp.$3, RegExp.$2 - 1, RegExp.$1) : new Date (s)}

			var start = Date.fromDDMMYYYY (start_date);
			var finish = Date.fromDDMMYYYY (finish_date);
			
			if(start >= finish)
			{
				alert('Please make sure the departure date is after the arrival date');
			}
			else
			{	
				document.getElementById('hidden_start').value = start_date;
				document.getElementById('hidden_finish').value = finish_date;
				i_ve_moved_so_refresh_me(true);	
			}
		}
	}




	function favourites(property_id, element)
	{
		// this function adds a property to favourites if the user is logged in on the google maps side of things.
		// see googleMapsInfo.php for usage
		// although it relates to the google map, i've plonked it here as its main javascript snizzle
		$.ajax(
		{
		   type: "POST",
		   url: "ajax_favourite.php",
		   data:"id="+property_id,
		   success: function(msg)
		   {
				//document.getElementById(element).innerHTML = '<a href="favourites">Saved to favourites</a>';
				//document.getElementById(element).innerHTML = 'Saved&nbsp;&nbsp;';
				document.getElementById(element).innerHTML = '<a href="favourites">Saved</a>';
				
				if(document.getElementById('fav')){ document.getElementById('fav').innerHTML = '<a href="favourites">Saved</a>'; }
				if(document.getElementById('fav2')){ document.getElementById('fav2').innerHTML = '<a href="favourites">Saved</a>'; }
				if(document.getElementById('fav3')){ document.getElementById('fav3').innerHTML = '<a href="favourites">Saved</a>'; }
				if(document.getElementById('favRight')){ document.getElementById('favRight').innerHTML = '<a href="favourites">Saved Favourite</a>'; }
		   }
		});
	}
	
	function favouritesRight(property_id, element)
	{
		// this function adds a property to favourites if the user is logged in on the google maps side of things.
		// see googleMapsInfo.php for usage
		// although it relates to the google map, i've plonked it here as its main javascript snizzle
		$.ajax(
		{
		   type: "POST",
		   url: "ajax_favourite.php",
		   data:"id="+property_id,
		   success: function(msg)
		   {
				//document.getElementById(element).innerHTML = '<a href="favourites">Saved to favourites</a>';
				document.getElementById(element).innerHTML = '<a href="favourites">Saved to favourites</a>';
				
				if(document.getElementById('fav')){ document.getElementById('fav').innerHTML = '<a href="favourites">Saved</a>'; }
				if(document.getElementById('fav2')){ document.getElementById('fav2').innerHTML = '<a href="favourites">Saved</a>'; }
				if(document.getElementById('fav3')){ document.getElementById('fav3').innerHTML = '<a href="favourites">Saved</a>'; }
				if(document.getElementById('favRight')){ document.getElementById('favRight').innerHTML = '<a href="favourites">Saved Favourite</a>'; }
		   }
		});
	}


	function confirm_login(sroot, dest)
	{
		if (confirm("You need to be logged in to save your favourites.  Would you like to login now?"))
		{
			window.location.href = sroot + 'index.php?page=login&bounceto=' + dest;	
		}
	}
	
	function force_login(sroot, dest)
	{
		if (confirm("You need to be logged in to submit a review.  Would you like to login/register now?"))
		{
			window.location.href = sroot + 'index.php?page=login&bounceto=' + dest;
		}
	}
	
	
	function confirmSubmit(whatwhat)
	{
		var agree=confirm("Are you sure you wish to delete this "+ whatwhat +"?");
	
		if (agree)
	
			return true ;
	
		else
	
			return false ;
	}
	
	function confirmSubmitAgain(whatwhat)
	{
		var agree=confirm(whatwhat);
	
		if (agree)
	
			return true ;
	
		else
	
			return false ;
	}
	
	function toggle(id)
	{
		if (document.getElementById(id).style.display == 'block')
		{
			document.getElementById(id).style.display = 'none';
		} 
		else 
		{
			document.getElementById(id).style.display = 'block';
		}
	}
	

/* ------------------------------------------------------------- */
/* home page                                                     */
/* ------------------------------------------------------------- */

jQuery.fn.fadeIn = function(speed, callback) {
	return this.animate({opacity: 'show'}, speed, function() {
		if (jQuery.browser.msie) 
			this.style.removeAttribute('filter'); 
		if (typeof callback == 'function') 
			callback(); 
	});
};

jQuery.fn.fadeOut = function(speed, callback) {
	return this.animate({opacity: 'hide'}, speed, function() {
		if (jQuery.browser.msie) 
			this.style.removeAttribute('filter'); 
		if (typeof callback == 'function') 
			callback();
	});
};

jQuery.fn.fadeTo = function(speed,to,callback) {
	return this.animate({opacity: to}, speed, function() {
		if (to == 1 && jQuery.browser.msie)
			this.style.removeAttribute('filter'); 
		if (typeof callback == 'function') 
			callback(); 
	});
};

$(document).ready(function() 
{			
	// (a little sooner than page load)
	$('#latest').hide();
	
	$('#showFeat').click(function() 
	{
		$('#latest').hide();
		$('#featured').fadeIn(1);
		
		$('#featured_tab').attr("class", "selected");
		$('#featured_latest_link').attr("href", "featured_properties");
		$('#latest_tab').attr("class", "");
		
		$('#featured_tab').ScrollTo(800);
		
		return false;
	});
	
	$('#showLatest').click(function() 
	{
		$('#featured').hide();
		$('#latest').fadeIn(1);
		
		$('#featured_tab').attr("class", "");
		$('#featured_latest_link').attr("href", "latest_properties");
		$('#latest_tab').attr("class", "selected");
		
		$('#latest_tab').ScrollTo(800);
		
		return false;
	});
	
	
	// calendar hide/show on property.php
	$('.over12').hide();
	var over12 = false;
	
	$('.twoyears').click(function()
	{
		if(over12==true)
		{
			$('.over12').hide();
			over12 = false;
			$('.twoyears').html('View 2 Years');
		}
		else
		{
			$('.over12').show();
			over12 = true;
			//$('.twoyears').html('View 1 Year');
			$('.twoyears').parent().hide();
		}
	});
	
});



$(function()
{
	// if country selected, update the regions and towns
	$("select#country").change(function()
	{
		if($(this).val() == 0)
		{
			$('#town').attr('disabled', 'disabled');
			$('#region').attr('disabled', 'disabled');
			$('#town option:first').attr('selected', 'selected');
			$('#region option:first').attr('selected', 'selected');
		}
		else
		{
		
			// towns
			
			$.getJSON("search_dropdowns_no.php",{id: $(this).val()}, function(j)
			{
				var options = '';
				
				options += '<option value="">Town or City (optional) </option><option value="0">All </option>';
				
				for (var i = 0; i < j.length; i++) 
				{
					options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
				}
				$("#town").html(options);
				$('#town option:first').attr('selected', 'selected');
				$('#town').removeAttr('disabled');
			})
			
			// regions
			$.getJSON("search_dropdown_regions_no.php",{id: $(this).val()}, function(j)
			{
				var regionOptions = '';
				
				regionOptions += '<option value="">Region (optional) </option><option value="0">All </option>';
				
				for (var i = 0; i < j.length; i++)
				{
					regionOptions += '<option value="' + j[i].optionRegionValue + '">' + j[i].optionRegionDisplay + '</option>';
				}
				$("#region").html(regionOptions);
				$('#region option:first').attr('selected', 'selected');
				$('#region').removeAttr('disabled');
			})
		
		}
		
	})
	
	// if region changed, narrow down the towns further
	$("select#region").change(function()
	{
		// towns
		$.getJSON("search_dropdowns_no.php",{countid: $('select#country').val(), region: true, regionid: $('select#region').val()}, function(j)
		{
			var options = '';
			
			options += '<option value="">Town or City (optional) </option><option value="0">All </option>';
			
			for (var i = 0; i < j.length; i++) 
			{
				options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
			}
			$("#town").html(options);
			$('#town option:first').attr('selected', 'selected');
		})
	})			
})
