paging = new Array();
pages = new Array();
revpaging = new Array();
revpages = new Array();
curr=2;

function formatCurr(num, delim,delim2)
{
	num = parseFloat(num).toFixed(2);
	var num_arr = num.split('.');
	fp = num_arr[1];
	num_arr = num_arr[0].split('');
	num_arr = num_arr.reverse();
	var str = '';
	for(var i =0; i< num_arr.length; i++)
	{
		if((i%3)==0 && i!=0)
		{
			str += delim;
		}
		str += num_arr[i];
	}
	num_arr = str.split('');
	num_arr = num_arr.reverse();
	str='';
	for(var i =0;i<num_arr.length;i++)
	{
		str += num_arr[i];
	}
	return str+delim2+fp;
}


$(document).ready(function()
{
	$.getJSON('search.php?'+window.location.search.substring(1),function(data)
	{
		if(data.paging.results==0)
		{
			$('#results').html(data.no_results);
			return;
		}
		var props = data.properties.property;
		img = new Image();
		pages[0]='<dl id = "property-listing">';
		revpages[0]='<dl id = "property-listing">';

		for(var i=0;i<data.paging.results;i++)
		{
			var p = props[i];
			if(!p)
			{
				p=props;
			}
			var page = Math.floor(i/10);
			if(i==0 || (i%10)==0)
			{
				if(i!=0)
				{
					var pagination = '';
					if(page>1)
					{
						pagination = '<a href = "#up.'+0+'" onclick="$.historyLoad(\'up.0\');" class="button_next">Back to Start</a> || ';
					}
					pagination += '<a href = "#up.'+page+'" onclick="$.historyLoad(\'up.'+page+'\');" class="button_next" >next page >></a>';
					paging[page-1]=pagination;
					
					pages[page-1]+='</dl><div class="paginator">'+pagination+'</div>';
					pages[page] = '<dl id = "property-listing">';
				}
			}
			img.src = p.main_image;
			pages[page] += '<dt class="'+((i%2)==0?'odd':'even')+'">';
			pages[page] += '<a href = "property_detail.php?'+data.qs+'&pid='+p.pid+'"><img src = "'+p.main_image+'" alt = "Rental '+p.country+', '+p.town+', '+p.region+', '+p.property_type.name+' - Azur Online" title = "Rental '+p.country+', '+p.town+', '+p.region+', '+p.property_type.name+' - Azur Online" width="150" /></a><a href = "property_detail.php?'+data.qs+'&pid='+p.pid+'">'+p.name+'</a>';
			pages[page] += '<ul class="specifications"><li>ID: '+p.pid+'</li><li>Type: '+p.property_type.name+'</li><li>Sleeps: '+p.sleeps.min+' - '+p.sleeps.max+'</li><li>Bathrooms: '+p.baths+'</li><li>'+p.region+','+p.town+'</li></ul></dt>';
			pages[page] += '<dd  class="'+((i%2)==0?'odd':'even')+'"><h3>Amenities</h3><ul class="amenities">';
			for(var j=0;j<p.amenities.amenity.length;j++)
			{
				pages[page] += '<li title = "header=['+p.amenities.amenity[j].name+'] body=[]"><img src = "'+p.amenities.amenity[j].icon+'" alt = "'+p.amenities.amenity[j].name+'" /></li>';
			}
			pages[page] += '<li title = "header=['+p.quality+' Star Quality] body=[]"><img src = "/images/icn_'+p.quality+'Star.gif" alt = "'+p.quality+' Star Quality" /></li>';
			
			if(p.available=='false')
		    {
		    	pages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_cross.gif" id="cross" alt="No!" height="21" width="20" style="float: left; margin-right: 5px;" /> <strong>Not</strong> available for these dates!</p></li>';
			}
			else
			{
				if(p.greenstar=='true')
				{
					if(data.hide_prices=='1' || p.hide_price=='true')
					{
						pages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_tick.gif" style="float: left; margin-right: 5px;" alt="available" />  Available! <a href="javascript:enquire_price('+p.pid+',\''+data.ainput+'\',\''+data.dinput+'\', \''+p.name+'\')">Contact us for price</a></p></li>';
					}
					else
					{
						pages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_tick.gif" style="float: left; margin-right: 5px;" alt="available" />  Available! Price: <strong><span class="euro">&euro;'+formatCurr(p.price.euro,' ',',')+'</span><span class="pound">&pound;'+formatCurr(p.price.gbp,',','.')+'</span></strong></p></li>';
					}
					
				}
				else
				{
					if(data.hide_prices=='1' || p.hide_price=='true')
					{
						pages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_q.gif" style="float: left; margin-right: 5px;" alt="available" /> <a href="javascript:enquire_price('+p.pid+',\''+data.ainput+'\',\''+data.dinput+'\', \''+p.name+'\')">Contact us for price</a></p></li>';
					}
					else
					{
						pages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_q.gif" style="float: left; margin-right: 5px;" alt="available" />  Estimated Price:  <strong><span class="euro">&euro;'+formatCurr(p.price.euro, ' ',',')+'</span><span class="pound">&pound;'+formatCurr(p.price.gbp,',','.')+'</span></strong></p></li>';
					}
				}
			}
			pages[page] += '</ul>';
			pages[page] += '<ul class="action-buttons">';
			pages[page] += '<li><a href = "property_detail.php?'+data.qs+'&pid='+p.pid+'" title = "Details"  class = "blue-small">Details</a></li>';
			
			if(p.greenstar=='true')
			{
				if(data.reserve_online=='true' && (data.hide_prices=='0' && p.hide_price=='false') && (data.wl==1 || data.wl==41 || data.wl==51))
				{
					pages[page] += '<li style="clear:left"><a href = "https://secure.azurelive.org/ec/bookingform.php?pid='+p.pid+'&date_from='+data.adate+'&date_to='+data.ddate+'&rate='+data.rate+'&cur=euro" ><img src = "/images/reserve.gif" alt="Reserve Online" /></a></li>';
				}	
			}

			pages[page] +='</ul>';
			pages[page] +='<p>'+(p.description.short+ '').replace(/([^>]?)\n/g, '$1'+ '<br />' +'\n')+'</p>';
			pages[page] += '<ul class="features">';
			for(var j=0; j<p.selling_points.selling_point.length;j++)
			{
				pages[page] += '<li>'+p.selling_points.selling_point[j]+'</li>';
			}
			pages[page] += '</ul>';
			pages[page] += '</dd>';	
		}
		
		if(data.paging.results>1)
		{
			props.reverse();
		}
		
		for(var i=0;i<data.paging.results;i++)
		{
			var p = props[i];
			if(!p)
			{
				p=props;
			}
			var page = Math.floor(i/10);
			if(i==0 || (i%10)==0)
			{
				if(i!=0)
				{
					var pagination = '';
					if(page>1)
					{
						pagination = '<a href = "#down.0" onclick="$.historyLoad(\'down.0\');" class="button_next">Back to Start</a> || ';
					}
					pagination += '<a href = "#down.'+page+'" onclick="$.historyLoad(\'down.'+page+'\');" class="button_next">next page >></a>';
					revpaging[page-1]=pagination;
					
					revpages[page-1]+='</dl><div class="paginator">'+pagination+'</div>';
					revpages[page] = '<dl id = "property-listing">';
				}
			}
			img.src = p.main_image;
			revpages[page] += '<dt class="'+((i%2)==0?'odd':'even')+'">';
			revpages[page] += '<a href = "property_detail.php?'+data.qs+'&pid='+p.pid+'"><img src = "'+p.main_image+'" alt = "Rental '+p.country+', '+p.town+', '+p.region+', '+p.property_type.name+' - Azur Online" title = "Rental '+p.country+', '+p.town+', '+p.region+', '+p.property_type.name+' - Azur Online" width="150" /></a><a href = "property_detail.php?'+data.qs+'&pid='+p.pid+'">'+p.name+'</a>';
			revpages[page] += '<ul class="specifications"><li>ID: '+p.pid+'</li><li>Type: '+p.property_type.name+'</li><li>Sleeps: '+p.sleeps.min+' - '+p.sleeps.max+'</li><li>Bathrooms: '+p.baths+'</li><li>'+p.region+','+p.town+'</li></ul></dt>';
			revpages[page] += '<dd class="'+((i%2)==0?'odd':'even')+'"><h3>Amenities</h3><ul class="amenities">';
			for(var j=0;j<p.amenities.amenity.length;j++)
			{
				revpages[page] += '<li title = "header=['+p.amenities.amenity[j].name+'] body=[]"><img src = "'+p.amenities.amenity[j].icon+'" alt = "'+p.amenities.amenity[j].name+'" /></li>';
			}
			revpages[page] += '<li title = "header=['+p.quality+' Star Quality] body=[]"><img src = "/images/icn_'+p.quality+'Star.gif" alt = "'+p.quality+' Star Quality" /></li>';
			
			if(p.available=='false')
		    {
		    	revpages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_cross.gif" id="cross" alt="No!" height="21" width="20" style="float: left; margin-right: 5px;" /> <strong>Not</strong> available for these dates!</p></li>';
			}
			else
			{
				if(p.greenstar=='true')
				{
					if(data.hide_prices=='1' || p.hide_price=='true')
					{
						revpages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_tick.gif" style="float: left; margin-right: 5px;" alt="available" />  Available! <a href="javascript:enquire_price('+p.pid+',\''+data.ainput+'\',\''+data.dinput+'\', \''+p.name+'\')">Contact us for price</a> </p></li>';
					}
					else
					{
						revpages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_tick.gif" style="float: left; margin-right: 5px;" alt="available" />  Available! Price: <strong><span class="euro">&euro;'+formatCurr(p.price.euro,' ',',')+'</span><span class="pound">&pound;'+formatCurr(p.price.gbp,',','.')+'</span></strong></p></li>';
					}
					
				}
				else
				{
					if(data.hide_prices=='1' || p.hide_price=='true')
					{
						revpages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_q.gif" style="float: left; margin-right: 5px;" alt="available" /> <a href="javascript:enquire_price('+p.pid+',\''+data.ainput+'\',\''+data.dinput+'\', \''+p.name+'\')">Contact us for price</a></p></li>';
					}
					else
					{
						revpages[page] += '<li><p style="padding: 5px; background-color: rgb(236, 236, 236); display: block; width: 211px; height: 21px;"><img src="/images/icn_q.gif" style="float: left; margin-right: 5px;" alt="available" />  Estimated Price:  <strong><span class="euro">&euro;'+formatCurr(p.price.euro, ' ',',')+'</span><span class="pound">&pound;'+formatCurr(p.price.gbp,',','.')+'</span></strong></p></li>';
					}
				}
			}
			revpages[page] += '</ul>';
			revpages[page] += '<ul class="action-buttons">';
			revpages[page] += '<li><a href = "property_detail.php?'+data.qs+'&pid='+p.pid+'" title = "Details"  class = "blue-small">Details</a></li>';
			
			if(p.greenstar=='true')
			{
				if(data.reserve_online=='true' && (data.hide_prices=='0'&&p.hide_price=='false') && (data.wl==1 || data.wl==41 || data.wl==51))
				{
					revpages[page] += '<li style="clear:left"><a href = "https://secure.azurelive.org/ec/bookingform.php?pid='+p.pid+'&date_from='+data.adate+'&date_to='+data.ddate+'&rate='+data.rate+'&cur=euro" ><img src = "/images/reserve.gif" alt="Reserve Online" /></a></li>';
				}	
			}

			revpages[page] +='</ul>';
			revpages[page] +='<p>'+(p.description.short+ '').replace(/([^>]?)\n/g, '$1'+ '<br />' +'\n')+'</p>';
			revpages[page] += '<ul class="features">';
			for(var j=0; j<p.selling_points.selling_point.length;j++)
			{
				revpages[page] += '<li>'+p.selling_points.selling_point[j]+'</li>';
			}
			revpages[page] += '</ul>';
			revpages[page] += '</dd>';	
		}
	
		
		revpages[page]+='</dl>';
		pages[page] += '</dl>';
		
		pagination='';
		
		if(page>1)
		{
			pagination = '<a href = "#up.'+0+'" onclick="$.historyLoad(\'up.0\');" class="button_next">Back to Start</a>';
			var revpagination = '<a href = "#down.'+0+'" onclick="$.historyLoad(\'down.0\');" class="button_next">Back to Start</a>';
			revpaging[page]=revpagination;
			paging[page]=pagination;
			pages[page]+='<div class="paginator">'+pagination+'</div>';
			revpages[page]+='<div class="paginator">'+revpagination+'</div>';
		}
		

		$.historyInit(showPage);
		currencyChange(data.curr);
	}
	);
}
);

function showPage(hash)
{

	if(hash=='')
	{
		hash = 'up.0';
	}

	var parts = hash.split('.');
	document.getElementById('results').innerHTML = '<center><img src = "http://www.azur-online.com/images/ajax-loader-aol.gif" style="margin:auto" /><br /></center>';
	var p = parseInt(parts[1]);

	if(parts[0]=='up')
	{
		$('#topPaging').html(paging[p]);
		$('#results').html(pages[p]);
	}
	else
	{
		$('#topPaging').html(revpaging[p]);
		$('#results').html(revpages[p]);
	}
		
	currencyChange(curr);
}



function pricingChange(val)
{
	if(val==1)
	{
		showPage('up.0');
	}
	else if(val==2)
	{
		showPage('down.0');
	}
}
function currencyChange(val)
{
	
	if(val==1)
	{
		$('.euro').show();
		$('.pound').hide();
		curr=val;
		//$.get('set.php?id=curr&val=euro');
	}
	if(val==2)
	{
		$('.euro').hide();
		$('.pound').show();
		curr=val;
		//$.get('set.php?id=curr&val=pound');
	}
}


jQuery.extend({
	historyCurrentHash: undefined,
	
	historyCallback: undefined,
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;
		
		jQuery.historyCurrentHash = current_hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
			jQuery.historyCurrentHash = '#';
		}
		
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
		jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if ($.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						var current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		
		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;
		
		if(jQuery.browser.msie) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});

var spid=0;
function enquire_price(pid,sd,ed,pname)
{
	spid=pid;
	$(document).bind('reveal.facebox',function()
	{
		$('#pid').attr('value',pid);
		$("#e_a_d").datepicker({ 
			dateFormat:'dd/mm/yy',
	    onSelect: function(date) { 
	        dateArr = date.split('/');
	        d = new Date();
	        d.setFullYear(dateArr[2],(dateArr[1]*1)-1,parseInt(dateArr[0],10)+6);
	        $('#e_d_d').datepicker('setDate',d);
	        $('#h_d_d').attr('value',d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate()));
	        $('#h_a_d').attr('value',dateArr[2]+'-'+dateArr[1]+'-'+dateArr[0]);

	    }, 
	    showOn: "button", 
	    buttonImage: "http://www.azur-online.com/beta/images/date_picker.gif", 
	    buttonImageOnly: true 
	});
	$("#e_d_d").datepicker({ 
			dateFormat:'dd/mm/yy',
	    showOn: "button", 
	    buttonImage: "http://www.azur-online.com/beta/images/date_picker.gif", 
	    buttonImageOnly: true ,
	    onSelect : function(date)
	    {
	    	dateArr = date.split('/');
			$('#h_d_d').attr('value',dateArr[2]+'-'+dateArr[1]+'-'+dateArr[0]);

		}
	});
	});
	
	jQuery.facebox({ajax:"/enquiry_form.php?id_prefix=h"+'&departure_date='+ed+'&arrival_date='+sd+'&pname='+pname+'&pid='+pid});
	
}

