var loading = '<div id="loading_div" style="top:0; left:0; opacity:0.7; filter:alpha(opacity=70); cursor:wait; position:absolute; width:100%; height:100%"><table width="100%" height="100%" border="0"><TR><TD valign="middle" align="center" style="background: #eee;"><img src="/img/frontend/preloader.gif" style="opacity:0.5; filter:alpha(opacity=50); margin:0 auto"></TD></TR></table></div>';
var mapWidth = '526px';
var mapWidth2 = '396px';

function hideSelects() {
	if($.browser.msie) {
		$('#from_amount').css('visibility', 'hidden');
		$('#to_amount').css('visibility', 'hidden');
		$('#currency_switch').css('visibility', 'hidden');
	}
}

function showSelects() {
	if($.browser.msie) {
		$('#from_amount').css('visibility', 'visible');
		$('#to_amount').css('visibility', 'visible');
		$('#currency_switch').css('visibility', 'visible');
	}
}

$(document).ready(function() {


	/****************************/
	/* SEARCH FUNCTIONALITY */
	/****************************/
	var predictive_text_timer;
	$(".predictive_search").keyup(function(e) {
		if (predictive_text_timer) clearTimeout(predictive_text_timer);
		var search_str = stripKeyword($(this).attr('value'));
		if(search_str.length > 2) {
			$(".global-sr").html('<h4>Predictive Search</h4><fieldset><a>Searching...</a></fieldset>');
		} else {
			$(".global-sr").html('<h4>Predictive Search</div><fieldset><a>Min 3 characters required.</a></fieldset>');
		}
		$(".global-sr").show();
		hideSelects();

		predictive_text_timer = setTimeout(function() {
			var search_term = encodeURI(search_str);
			if(search_term.length > 2) {
				data = prepareOptions(searchArr, search_term);
				if(data == false){
					$(".global-sr").html('<h4>Predictive Search</h4><fieldset><a>No results found.</a></fieldset>');
					hideSelects();
					$(".global-sr").show();
				}else{
					$(".global-sr").html(data);
					hideSelects();
					$(".global-sr").show();
				}
			}
		}, 300);
	});
	
	$(".auto_options").live('click', function() {
		var lat = $(this).attr('lat');
		var lng = $(this).attr('lng');
		var zoom = $(this).attr('zoom');
		var val = $(this).attr('rel');
		val = makehtml(val);
		if(lat && IsNumeric(lat) && lng && IsNumeric(lng) && zoom && IsNumeric(zoom)){
			loadMapLocation(lat,lng,zoom);
		}
		
		$(".predictive_search").attr('value',val);
		$(".global-sr").hide();
		showSelects();
	});
	
//	$(".predictive_search").focus(function() {
//		$(".global-sr").show();
//		hideSelects();
//	});
	
	$('.predictive_search').blur(function(e) {
		showSelects();
	});

	function makehtml(text) {
		var textneu = text.replace("&amp;","&");
		//textneu = textneu.replace(/</,"&lt;");
		return(textneu);
	}

	function stripKeyword(str){
		var str_compare, keywords;
		str_compare = str.toLowerCase().replace(/\b([a-z])/gi,function(c){return c.toUpperCase()});
		keywords = new Array('Country:','Land:','Province:','Provinsie:','Region:','Area:','City:','Stad:');
		for(var i = 0; i<keywords.length;i++){
			if(str_compare.substr(0,keywords[i].length) == keywords[i]){
				str = str.substr(keywords[i].length);
				if(str.substr(0,1) == ' '){
					str = str.substr(1,str.length);
				}
			}
		}
		return str;
	}

	function prepareOptions(options,searchTerm)
	{
		var found = false;
		var count_found = false;
		var prov_found = false;
		var region_found = false;
		var city_found = false;
		var est_found = false;

		var div_countries = "<div id='pre_fill_countries' class='search_indi_div sd'><h4>Countries</h4><fieldset>";
		var div_provinces = "<div id='pre_fill_provinces' class='search_indi_div sd'><h4>Provinces</h4><fieldset>";
		var div_regions = "<div id='pre_fill_regions' class='search_indi_div sd'><h4>Regions</h4><fieldset>";
		var div_cities = "<div id='pre_fill_cities' class='search_indi_div sd'><h4>Cities</h4><fieldset>";
		var div_establishments = "<div id='pre_fill_establishments' class='search_indi_div sd'><h4>Establishments</h4><fieldset>";
		var html = '';

		searchTerm = decodeURI(searchTerm);
		searchTerm = eval("/"+ String(searchTerm) + "/i");

		for (x in options)
		{
			var subOptions = options[x];
			// console.log(subOptions.length);
			for(var i=0; i<subOptions.length; i++)
			{
				if(typeof subOptions[i] == 'undefined') continue;
				// console.log(subOptions[i]);
				var valArray = subOptions[i].split("|");
				var searchVal = String(valArray[0]);
				var matchResult = searchVal.search(searchTerm);

				if(matchResult != -1) {
					found = true;
					switch(x){
						case "countries":
							count_found = true;
							div_countries += '<a class="auto_options sd" lat="'+valArray[2]+'" lng="'+valArray[3]+'" zoom="'+valArray[4]+'" rel="Country: '+valArray[0]+'" >'+valArray[0]+'</a><br />';
						break;
						case "provinces":
							prov_found = true;
							div_provinces	+= '<a class="auto_options sd" lat="'+valArray[2]+'" lng="'+valArray[3]+'" zoom="'+valArray[4]+'" rel="Province: '+valArray[0]+'">'+valArray[0]+'</a><br />';
						break;
						case "regions":
							region_found = true;
							div_regions	+= '<a class="auto_options sd" lat="'+valArray[2]+'" lng="'+valArray[3]+'" zoom="'+valArray[4]+'" rel="Region: '+valArray[0]+'">'+valArray[0]+'</a><br />';
						break;
						case "cities":
							city_found = true;
							div_cities	+= '<a class="auto_options sd" lat="'+valArray[2]+'" lng="'+valArray[3]+'" zoom="'+valArray[4]+'" rel="City: '+valArray[0]+'">'+valArray[0]+'</a><br />';
						break;
						case "establishments":
							est_found = true;
							div_establishments += '<a class="auto_options sd" lat="'+valArray[2]+'" lng="'+valArray[3]+'" zoom="'+valArray[4]+'" rel="'+valArray[0]+'">'+valArray[0]+'</a><br />';
						break;
					}
				}
			}
		}

		div_countries += "</fieldset></div>";
		div_provinces += "</fieldset></div>";
		div_regions += "</fieldset></div>";
		div_cities += "</fieldset></div>";
		div_establishments += "</fieldset></div>";
		if(found){
			if(count_found){html += div_countries;}
			if(prov_found){html += div_provinces;}
			if(region_found){html += div_regions;}
			if(city_found){html += div_cities;}
			if(est_found){html += div_establishments;}
		}else{
			html = false;
		}
		
		return html;
	}

	$("#currency_switch").change(function() {
		$("#gen_search_container").append(loading);
		var cur = $(this).val();
		$.ajax({
			type: 'GET',
			url: '/searches/currencychange/'+cur,
			dataType: 'html',
			success: function(html) {
				$("#from_amount").removeOption(/./);
				options = html.split(",");
				for(var i =0;i<options.length;i++){
					var subOptions = options[i].split("=>");
					$("#from_amount").addOption(subOptions[0], subOptions[1]+' '+number_format(subOptions[0], 0, '.', ' '),false);
				}
				$("#from_amount").addOption('noLimit','No Limit',false);
			}
		});
		$.ajax({
			type: 'GET',
			url: '/searches/currencychange/'+cur+'/reverse',
			dataType: 'html',
			success: function(html) {
				$("#to_amount").removeOption(/./);
				options = html.split(",");
				for(var i =0;i<options.length;i++){
					var subOptions = options[i].split("=>");
					$("#to_amount").addOption(subOptions[0], subOptions[1]+' '+number_format(subOptions[0], 0, '.', ' '),false);
				}
				$("#to_amount").addOption('noLimit','No Limit',true);
				$('#loading_div').remove();
			}
		});
	});

	// show/hide floating div general search (accommodation type)
	$('.gen_accommodation_type').click(function(){
		$('.gen_accommodation_div').toggle();
		if($('.gen_accommodation_div').css('display') == 'none') {
			showSelects();
		} else {
			hideSelects();
		}
	});
	// show/hide floating div sub filter (accommodation type)
	$('.fill_accommodation_type').click(function(){
		$('.fill_accommodation_div').toggle();
	});

	// show/hide floating div general(activities, facilities, services)
	$('.gen_afs_type').click(function(){
		$('.gen_afs_div').toggle();
	});

	// show/hide floating div general(activities, facilities, services)
	$('.fill_afs_type').click(function(){
		$('.fill_afs_div').toggle();
	});

	// show/hide floating div general(activities, facilities, services)
	$('.gen_exp_type').click(function(){
		$('.gen_exp_div').toggle();
	});

	// show/hide floating div general(activities, facilities, services)
	$('.fill_exp_type').click(function(){
		$('.fill_exp_div').toggle();
	});

	$('.close_pop_div').click(function(event){
		event.preventDefault();
		$('.gen_accommodation_div').hide();
		$('.fill_accommodation_div').hide();
		$('.gen_afs_div').hide();
		$('.fill_afs_div').hide();
		$('.gen_exp_div').hide();
		$('.fill_exp_div').hide();
		showSelects();
	});

	//close floating divs if not cliecked on them
	$(document).click(function(e) {
		target = $(e.target);
		if(!target.hasClass('at')) {
			$('.gen_accommodation_div').hide();
			$('.fill_accommodation_div').hide();
		}

		if(!target.hasClass('sd')) {
			$('.search_div').css('display','none');
		}

		if(!target.hasClass('afs')) {
			$('.gen_afs_div').hide();
			$('.fill_afs_div').hide();
		}

		if(!target.hasClass('exp')) {
			$('.gen_exp_div').hide();
			$('.fill_exp_div').hide();
		}

		if(!target.hasClass('desr')) {
			$('#dest_region_pop').hide();
		}

		if(!target.hasClass('dest')) {
			$('#dest_top_pop').hide();
		}

		if(!target.hasClass('desp')) {
			$('#dest_province_pop').hide();
		}
	});

	$('.gen_checkAll,.fill_checkAll').click(function(){
		var str_class = '';
		var display_str = '';
		var display_str_short = '';

		if($(this).hasClass('at')){
			str_class = 'at';
		}else if($(this).hasClass('exp')){
			str_class = 'exp';
		}else{
			str_class = 'afs';
		}

		$("#generalSearchForm").find('input:checkbox').each(function(){
			if($(this).hasClass(str_class)){
				display_str += $(this).next().html()+", ";
				$(this).attr('checked','checked');
			}
		})

		$(".filter-by").find('input:checkbox').each(function(){
			if($(this).hasClass(str_class)){
				display_str += $(this).next().html()+", ";
				$(this).attr('checked','checked');
			}
		})

		if(display_str.length > 50){
			display_str_short = display_str.substr(0,50)+'...';
		}else{
			display_str_short = display_str.substr(0,(display_str.length - 2));
		}

		if(str_class == 'at'){
			$('#type_select_box').attr('title',display_str);
			$('#type_select_box').html(display_str_short);
		}else if(str_class == 'exp'){
			$('#exp_select_box').attr('title',display_str);
			$('#exp_select_box').html(display_str_short);
		}else{
			$('#afs_select_box').attr('title',display_str);
			$('#afs_select_box').html(display_str_short);
		}
	});

	$('.gen_uncheckAll,.fill_uncheckAll').click(function(){
		var str_class = '';
		var display_str = '';
		var display_str_short = '';
		if($(this).hasClass('at')){
			str_class = 'at';
		}else if($(this).hasClass('exp')){
			str_class = 'exp';
		}else{
			str_class = 'afs';
		}

		$("#generalSearchForm").find('input:checkbox').each(function(){
			if($(this).hasClass(str_class)){
				$(this).attr('checked',false);
			}
		})

		$(".filter-by").find('input:checkbox').each(function(){
			if($(this).hasClass(str_class)){
				$(this).attr('checked',false);
			}
		})

		if(str_class == 'at'){
			$('#type_select_box').attr('title',display_str);
			$('#type_select_box').html(display_str_short);
		}else if(str_class == 'exp'){
			$('#exp_select_box').attr('title',display_str);
			$('#exp_select_box').html(display_str_short);
		}else{
			$('#afs_select_box').attr('title',display_str);
			$('#afs_select_box').html(display_str_short);
		}
	});

	$('#search_min').click(function(){
		if(!$('#search_min').hasClass('min-on')){
			$('#search_min').addClass('min-on');
			$('#search_max').removeClass('max-on');
			$('.search_hide').hide();
		}
	});
	$('#search_max').click(function(){
		if(!$('#search_max').hasClass('max-on')){
			$('#search_min').removeClass('min-on');
			$('#search_max').addClass('max-on');
			$('.search_hide').show();
			loadMapAjax();
		}
	});

	$('.fill_types,.gen_types').click(function(event){
		var arr = $(this).attr('id').split("_");
		var key = 'gen_';
		if(arr[0] == 'gen'){
			key = 'fill_';
		}
		var id = key+arr[1];

		if($(this).attr("checked")){
			$('#'+id).attr("checked", true);
		}else{
			$('#'+id).attr("checked", false);
		}

		set_title_text('at');
	});

	$('.fill_attractions,.gen_attractions').click(function(event){
		var arr = $(this).attr('id').split("_");
		var key = 'gen_';
		if(arr[0] == 'gen'){
			key = 'fill_';
		}
		var id = key+arr[1];

		if($(this).attr("checked")){
			$('#'+id).attr("checked", true);
		}else{
			$('#'+id).attr("checked", false);
		}

		set_title_text('afs');
	});

	$('.fill_experiences,.gen_experiences').click(function(event){
		var arr = $(this).attr('id').split("_");
		var key = 'gen_';
		if(arr[0] == 'gen'){
			key = 'fill_';
		}
		var id = key+arr[1];

		if($(this).attr("checked")){
			$('#'+id).attr("checked", true);
		}else{
			$('#'+id).attr("checked", false);
		}

		set_title_text('exp');
	});

//	$('#min_max_header').click(function(e){
//		tar = $(e.target);
//		if(tar.hasClass('search_header'))
//		{
//			if(!$('#min_max_header').hasClass('max-on')){
//				$('#min_max_header').removeClass('min-on');
//				$('#min_max_header').addClass('max-on');
//				$('.search_hide').show();
//				loadMapAjax();
//			}else{
//				$('#min_max_header').addClass('min-on');
//				$('#min_max_header').removeClass('max-on');
//				$('.search_hide').hide();
//			}
//		}
//	});

	$('#newsearch_a').click(function(event){
		event.preventDefault();
		$('#min_max_header').removeClass('min-on');
		$('#min_max_header').addClass('max-on');
		$('.search_hide').show();
		$('.search_hide2').show();
		loadMapAjax();
	});

	$('.page_prev,.page_next,.page_numbers,.pager_sort').click(function(event){
		if($(this).attr('tagName') =='A'){
			event.preventDefault();
			var href = $(this).attr('href');
			$('#generalSearchForm').attr('action',href);
			$('#gen_submit').click();
			
			return false;
		}
	});

	$('.gen_sim_search').click(function(event){
		event.preventDefault();
		$('#gen_submit').click();
	})

	$('#gen_submit').click(function(event){
		if(isset('map'))
		{
			$('#gmap_zoom').val(map.getZoom());
			var ctr = map.getCenter();
			var mapLat  = ctr.lat();
			var mapLng  = ctr.lng();
			$('#gmap_lat').val(mapLat);
			$('#gmap_lng').val(mapLng);
		}
	});

	$('.gen_types_lable,.gen_attractions_lable,.gen_experiences_lable,.fill_types_lable,.fill_attractions_lable,.fill_experiences_lable').click(function(event){
		var cls = $(this).attr('rel');
		if($('.'+cls).attr('checked')){
			$('.'+cls).attr('checked',false);
		}else{
			$('.'+cls).attr('checked',true);
		}

		if(cls.substr(0,5) == 'types'){
			str_class = 'at';
		}else if(cls.substr(0,5) == 'attra'){
			str_class = 'afs';
		}else{
			str_class = 'exp';
		}

		set_title_text(str_class);
	});

	$('#filter').click(function(event){
		event.preventDefault();
		var href = $(this).attr('href');
		$('#generalSearchForm').attr('action',href);
		$('#gen_submit').click();
	});
	
	/****************************/
	/* GOOGLE MAP FUNCTIONALITY */
	/****************************/
	function isset(varname)  {
		if(typeof( window[ varname ] ) != "undefined") return true;
		else return false;
	}

	function loadMapAjax()
	{
		if($.cookie('gmap_disabled') == null){
			$.cookie('gmap_disabled', 'false', { expires: 365 , path: '/'});
		}
		
		if($.cookie('gmap_disabled') == 'false' || $.cookie('gmap_disabled') == null)
		{
			var mapZoom = 5;
			if(/*$('#gmap_zoom').val() && */$('#gmap_lat').val() && $('#gmap_lng').val())
			{
				var mapLat  = $('#gmap_lat').val();
				var mapLng  = $('#gmap_lng').val();
//				var mapZoom = $('#gmap_zoom').val();
			}
			else if(isset('map'))
			{
				var ctr = map.getCenter();
				var mapLat  = ctr.lat();
				var mapLng  = ctr.lng();
				mapZoom = map.getZoom();
			}
//			else if($.cookie('gmap_lastLocation'))
//			{
//				var str = $.cookie('gmap_lastLocation');
//				var arr = str.split(",");
//				var mapLat = arr[0];
//				var mapLng = arr[1];
//				var mapZoom = arr[2];
//			}
			else
			{
				var mapLat = -29;
				var mapLng = 24;
			}
			
			if($('#gmap_zoom').val()) {
				mapZoom = $('#gmap_zoom').val();
			}

			
			$("#gmap_div").append(loading);
			$.ajax({
				type: 'GET',
				url: '/searches/map/lat:'+mapLat+'/lng:'+mapLng+'/zoom:'+mapZoom,
				dataType: 'html',
				success: function(html) {
					$('#gmap_div').html(html);
				}
			});
			
			$('#map_div').css('width',mapWidth);
			$('#gmap_div').css('width',mapWidth2);
			$('#googel_map').css('width',mapWidth2);
		}
		else {
			//addtional_disable_options();
			$('#mapEnabled').removeClass('listed')
		}
	}

	if($('#search').css('display') != 'none') {
		loadMapAjax();
	}

	$('#mapEnabled').click(function(event) {
		event.preventDefault();
		if($(this).hasClass('listed')) {
			$(this).removeClass('listed');
			$('#gmap_div').html("");
			$.cookie('gmap_disabled', 'true', { expires: 365, path: '/'});
			//addtional_disable_options();
		} else {
			$(this).addClass('listed');
			$.cookie('gmap_disabled', 'false', { expires: 365, path: '/'});
			loadMapAjax();
			//addtional_enable_options();
		}
	});

	$('#map_click').click(function(event) {
		event.preventDefault();
		if($(this).hasClass('listed')) {
			$(this).removeClass('listed');
			$('#search').show();
			mapWidth = '526px';
			mapWidth2 = '396px';
			$(this).html('View larger map');
		} else {
			$(this).addClass('listed');
			$('#search').hide();
			mapWidth = '915px';
			mapWidth2 = '785px';
			$(this).html('View smaller map');
		}

		loadMapAjax();
	});

	function addtional_disable_options()
	{
		$('#featuredMarkers').attr('style','display:none');
		$('#moreMarkers').attr('style','display:none');
		$('#articleMarkers').attr('style','display:none');
	}

	function addtional_enable_options()
	{
		$('#featuredMarkers').attr('style','display:');
		$('#moreMarkers').attr('style','display:');
		$('#articleMarkers').attr('style','display:');
	}

	$('#moreMarkers').click(function(event) {
		event.preventDefault();
		if($(this).hasClass('listed')) {
			$(this).removeClass('listed');
			remove_markers(map,markerArr,'more');
		} else {
			var amount = count_marker_type(map,markerArr,'more');
			if(amount > 0){$(this).addClass('listed');}
			var enabled = onMapMove(map,markerArr);
			
			if(amount < 1){
				jAlert('There are no non-featured establishments listed on the site yet with GPS co-ordinates', 'No Listings');
			}else if(amount > 0 && enabled < 1){
				jAlert('There are no non-featured establishments listed on the site yet with GPS co-ordinates', 'No Listings');
				//jAlert('no_more_markers_zoom_level', 'no_more_markers_zoom_level_heading');
			}
		}
	});

	$('#featuredMarkers').click(function(event) {
		event.preventDefault();
		if($(this).hasClass('listed')) {
			$(this).removeClass('listed');
			remove_markers(map,markerArr,'featured');
		} else {
			var amount = count_marker_type(map,markerArr,'featured');
			if(amount > 0){$(this).addClass('listed');}
			var enabled = onMapMove(map,markerArr);

			if(amount < 1){
				jAlert('There are currently no sponsored venues listed on our site yet', 'No sponsored venues listed yet');
			}else if(amount > 0 && enabled < 1){
				jAlert('There are currently no sponsored venues listed on our site yet', 'No sponsored venues listed yet');
				//jAlert('no_featured_markers_zoom_level', 'no_featured_markers_zoom_level_heading');
			}
		}
	});

	$('#articleMarkers').click(function(event) {
		event.preventDefault();
		if($(this).hasClass('listed')) {
			$(this).removeClass('listed');
			remove_markers(map,markerArr,'article');
		} else {
			var amount = count_marker_type(map,markerArr,'article');
			if(amount > 0){$(this).addClass('listed');}
			var enabled = onMapMove(map,markerArr);

			if(amount < 1){
				jAlert('There are no travel articles available at present.', 'No Articles');
			}else if(amount > 0 && enabled < 1){
				jAlert('There are no travel articles available at present.', 'No Articles');
				//jAlert('no_article_markers_zoom_level', 'no_article_markers_zoom_level_heading');
			}
		}
	});

	/****************************/
	/* FAVOURITES FUNCTIONALITY */
	/****************************/
	$('#favourites').click(function() {
		var href = $(this).attr('rel');
		$.ajax({
			type: 'GET',
			url: href,
			dataType: 'xml',
			error: function (xhr, desc, exceptionobj) {},
			success: function(xml) {
				var status = $('xmldata', xml).attr('status');
				var msg = $('xmldata message', xml).text();
				if(status == 'success') {
					//jAlert(msg, 'Favourites Success');
					$('#favourites_holder').append(loading);
					$('#favourites_holder').load('/establishments/favourites/get/', null, function(){});
				} else {
					jAlert(msg, 'Favourites Error');
				}
			}
		});
	});

	$('.favourites-add').click(function() {
		var href = $(this).attr('rel');
		$.ajax({
			type: 'GET',
			url: href,
			dataType: 'xml',
			error: function (xhr, desc, exceptionobj) {},
			success: function(xml) {
				var status = $('xmldata', xml).attr('status');
				var msg = $('xmldata message', xml).text();
				if(status == 'success') {
					//jAlert(msg, 'Favourites Success');
					$('#favourites_holder').append(loading);
					$('#favourites_holder').load('/establishments/favourites/get/', null, function(){});
				} else {
					jAlert(msg, 'Favourites Error');
				}
			}
		});
	});

	$('.favourites_select').live('click', function() {
		$('.favourites_checkbox').each(function() {
			$(this).attr("checked", true);
		});

		$('.favourites_select').html('<span>Unselect all</span>');
		$('.favourites_select').addClass('favourites_unselect');
		$('.favourites_select').removeClass('favourites_select');
	});

	$('.favourites_unselect').live('click', function() {
		$('.favourites_checkbox').each(function() {
			$(this).attr("checked", false);
		});
		$('.favourites_unselect').html('<span>Select all</span>');
		$('.favourites_unselect').addClass('favourites_select');
		$('.favourites_unselect').removeClass('favourites_unselect');
	});

	$('.favourites_remove').live('click', function() {
		var something_selected = false;
		$('.favourites_checkbox:checked').each(function() {
			if($('#favourites_holder #loading_div').length < 1) {
				$('#favourites_holder').append(loading);
			}
			something_selected = true;
			var establishment = $(this);
			$.ajax({
				type: 'GET',
				url: '/establishments/favourites/del/'+$(establishment).val()+'.xml', 
				async: false,
				dataType: 'xml',
				error: function (xhr, desc, exceptionobj) {},
				success: function(xml) {}
			});
		});
		if(something_selected == true) {
			$('#favourites_holder').load('/establishments/favourites/get/?random='+Math.random(), null, function(){});
		} else {
			jAlert('Please select the favourites you want to remove first','Favourites Error');
		}
	});

	/****************************/
	/* CONTENT PAGES FUNC       */
	/****************************/
	$('#submit_contact_us').click(function(event){
		event.preventDefault();
		$('#contact_us_form').attr('action','/pages/contact');
		$('#contact_us_form').submit();
	});

	$('#submit_contact_owner').click(function(event){
		event.preventDefault();
		$('#contact_owner_form').attr('action','/pages/owner');
		$('#contact_owner_form').submit();
	});
	
	$('#submit_contact_special').live('click',function(event){
		event.preventDefault();
		$('#contact_special_form').attr('action','/pages/contactSpecial');
		$('#contact_special_form').submit();
	});
	
	$('#submit_get_listed').live('click',function(event){
		event.preventDefault();
		$('#get_listed_form').attr('action','/getlisteds/callmeback');
		$('#get_listed_form').submit();
	});
	/****************************/
	/* COMPARISON FUNCTIONALITY */
	/****************************/

	$('#compare').click(function() {
		var href = $(this).attr('rel');
		
		$.ajax({
			type: 'GET',
			url: href,
			dataType: 'xml',
			error: function (xhr, desc, exceptionobj) {},
			success: function(xml) {
				var status = $('xmldata', xml).attr('status');
				var msg = $('xmldata message', xml).text();
				if(status == 'success') {
					jConfirm2(msg+'\n'+'Would you like to view the comparison tool now ?', '', function(r) {
						if(r == true) {
							window.location = '/establishments/comparisons/get/';
						}
					});
				} else {
					jAlert(msg, 'Comparison Error');
				}
			}
		});
	});

	$('.compare_list').click(function(e) {

		var found = false;//val to check if any was added
		target = $(e.target);
		var href = target.parent().attr('rel');//half the ajax call url
		found = true;
		
		$.ajax({
			type: 'GET',
			url: href,
			dataType: 'xml',
			async: false,
			error: function (xhr, desc, exceptionobj) {},
			success: function(xml) {
				//var status = $('xmldata', xml).attr('status');
				//var msg = $('xmldata message', xml).text();
			}
		});
		
		if(found)
		{
			jConfirm2('View the comparison tool now ?', '', function(r) {
				if(r == true) {
					window.location = '/establishments/comparisons/get/';
				}
			});
		}else{
			jAlert('check_est_to_compare_heading', 'check_est_to_compare_heading');
		}
	});


	$('.remComparison').live('click',function(event){
		event.preventDefault();
		var id = $(this).attr('rel');
		var arr = id.split("-");
		id = arr[0];
		
		$.ajax({
			type: 'GET',
			url: '/establishments/comparisons/del/'+id+'.xml',
			async: false,
			dataType: 'xml',
			error: function (xhr, desc, exceptionobj) {},
			success: function(xml) {}
		});

	});
	

	/****************************/
	/* GALLERY FUNCTIONALITY    */
	/****************************/
	$('.thumb-img-class').live('click',function(){
		var rel = $(this).attr('rel2');
		$(this).parent().parent().find('#main-img-'+rel).attr('src', $(this).attr('rel'));
		$(this).parent().parent().find('.main-img-class-'+rel).attr('href', $(this).attr('href'));
		$(this).parent().parent().find('.main-img-class-'+rel).attr('title', $(this).attr('title'));
		$(this).parent().parent().find('.main-img-class-'+rel).attr('title', $(this).attr('title'));
		$(this).parent().parent().find('#main-img-p-'+rel).html($(this).attr('title'));
	});

	/********************************************/
	/* GPS DOWNLOAD                             */
	/* moved to views/devices/select_device.ctp */
	/********************************************/
	/*
	$('#gps_device').live('change',function(){
		var id = $(this).val();
		$.ajax({
			type: 'GET',
			url: '/devices/getImage/'+id,
			async: false,
			dataType: 'html',
			success: function(html) {
				var img = "<img src='"+html+"'>";
				$('#gps_image').show();
				$('#gps_image').html(img);
			}
		});
		if(id > 0){
			$('#gps_submit').show();
		}else{
			$('#gps_submit').hide();
			$('#gps_image').hide();
		}
	});
	*/
	
	$('#submit_gps_button').live('click', function(event){
		event.preventDefault();
		$('#gps_download_form').submit();
		tb_remove();
	});


	/****************************/
	/* SHOW ACCOMMODATION MODAL */
	/****************************/
	$('.bt-info').click(function(){
		var accommodation_id = $(this).prev().val();
		tb_show('Accommodation details','/accommodations/detail/'+accommodation_id);
	});

	/****************************/
	/* SHOW/REMOVE RATING       */
	/****************************/
//	$('.rates-heading').live('click', function(){
//		if($(this).hasClass('on')) {
//			$(this).removeClass('on');
//		} else {
//			$(this).addClass('on');
//		}
//		$(this).next().toggle();
//	});

	/****************************/
	/* SHOW/REMOVE Welcome Lang */
	/****************************/
	$('.lang_switch').click(function(event){
		event.preventDefault();
		var lang = $(this).attr('id');
		show_welcome(lang);
	});

	function show_welcome(lang)
	{
		var lang_arr = new Array(4);
		lang_arr[0] = 'eng';
		lang_arr[1] = 'ger';
		lang_arr[2] = 'fr';
		lang_arr[3] = 'esp';

		for(var i = 0;i <4;i++)
		{
			if(lang_arr[i] == lang){
				$('#welcome_message_'+lang_arr[i]).show();
				$('#welcom_switch_'+lang_arr[i]).show();
			}else{
				$('#welcome_message_'+lang_arr[i]).hide();
				$('#welcom_switch_'+lang_arr[i]).hide();
			}
		}
	}

	/****************************/
	/* TAB FUNCTIONALITY        */
	/****************************/
	$('.tab-accommodation, .tab-activities-est, .tab-activities-area, .tab-directions, .tab-terms, .tab-specials').click(function(event) {
		// HIDE ALL DIVS
		$('#est-tabs').find('.box-inner').each(function() {
			$(this).hide();
		});
		// SHOW THE NEW DIV
		$('#'+$(this).attr('class')).show();
		// REMOVE ALL CLASSES FROM LI's
		$('#est-tabs ul li').each(function() {
			$(this).removeClass('on');
		});
		// SET THE LI TO ON
		$(this).parent().addClass('on');
	});

	/****************************/
	/* CURRENCY FUNCTIONALITY   */
	/****************************/
	$('.currency-select,#currency_switch').livequery('change', function() {

		switch($(this).val()) {
			case 'ZAR':
				var new_currency_value = '1';
				var new_currency_symbol = 'R';
			break;
			case 'USD':
				var new_currency_value = '7.87';
				var new_currency_symbol = '$';
			break;
			case 'GBP':
				var new_currency_value = '12.72';
				var new_currency_symbol = '£';
			break;
			case 'EUR':
				var new_currency_value = '11.21';
				var new_currency_symbol = '€';
			break;
		}

		$.cookie('Settings[Currency]', $(this).val(), { expires: 365, path: '/'});

		$('#container').find('.money').each(function() {
			var currency_value = $(this).next().html();
			var updated_value = (currency_value/new_currency_value);
			if(updated_value>0){
				$(this).html(updated_value.toFixed(2));
			}else{
				$(this).html('0.00');
			}

		});

		$('#container').find('.symbol').each(function() {
			$(this).html(new_currency_symbol);
		});

		$(".currency-select").selectOptions($(this).val());

	});

	/****************************/
	/* FOOTER NAV               */
	/****************************/
	$('#dest_province').click(function(event) {
		event.preventDefault();
		$('#dest_province_pop').show();
	});

	$('#dest_region').click(function(event) {
		event.preventDefault();
		$('#dest_region_pop').show();
	});

	$('#dest_top').click(function(event) {
		event.preventDefault();
		$('#dest_top_pop').show();
	});

	$('.close_pop_subnav').click(function(event){
		event.preventDefault();
		$('#dest_province_pop').hide();
		$('#dest_region_pop').hide();
		$('#dest_top_pop').hide();
	});

	$('.loadItem').click(function(event){
		event.preventDefault();
		resetGenSearchForm();

		$('#gen_predictive_search').attr('value',$(this).html());
		$('#gen_submit').click();
	});

	$('.load_type').click(function(event){
		event.preventDefault();
		resetGenSearchFormTypes();
		var id = $(this).attr('rel');
		var val = 'gen_types'+id;
		$('#'+val).attr('checked',true);
		$('#gen_submit').click();
	});

	$('.load_region,.load_province,.load_city').click(function(event){
		event.preventDefault();
		//resetGenSearchForm();
		var val = $(this).attr('rel');
		$('#gen_predictive_search').attr('value',val);
		$('#gen_submit').click();
	});

	function resetGenSearchForm()
	{
		$('#gen_predictive_search').attr('value','');
		$('#from_amount').attr('value','0');
		$('#to_amount').attr('value','noLimit');
		//$('#currency_switch');
		
		$("#generalSearchForm").find('input:checkbox').each(function(){
			$(this).attr('checked',false);
		})
	}

	function resetGenSearchFormTypes()
	{
		$("#generalSearchForm").find('input:checkbox').each(function(){
			if($(this).hasClass('gen_types')){
				$(this).attr('checked',false);
			}
		})
	}

	$('.website').click(function(event){
		event.preventDefault();
		var href = $(this).attr('href');
		var str = $(this).attr('rel');
		var arr = str.split("-");
		$.ajax({
			type: 'GET',
			url: '/stats/addstats/action:'+arr[0]+'/section:'+arr[1]+'/table:'+arr[2]+'/id:'+arr[3],
			dataType: 'html',
			success: function(html) {}

		});
		window.open(href);
	});

	/****************************/
	/* Est Detail Page          */
	/****************************/
	$('.goBack').click(function(event){
		event.preventDefault();
		//window.history.back();
		//history.go(-1);
		history.back(1);
	});

	$('.print').click(function(event){
		event.preventDefault();
		$( ".printable" ).print();
	});

	$('.print2').click(function(event){
		event.preventDefault();
		$( ".printable2" ).print();
	});

	$('.print3').live('click', function(event) {
		event.preventDefault();
		$( ".printable3" ).print();
	});

});

/****************************/
/* Functions                */
/****************************/
function convertCurrency(currency_value, currency) {

		switch(currency) {
			case 'ZAR':
				var new_currency_value = '1';
				var new_currency_symbol = 'R';
			break;
			case 'USD':
				var new_currency_value = '7.87';
				var new_currency_symbol = '$';
			break;
			case 'GBP':
				var new_currency_value = '12.72';
				var new_currency_symbol = '£';
			break;
			case 'EUR':
				var new_currency_value = '11.21';
				var new_currency_symbol = '€';
			break;
		}

		var updated_value = (currency_value/new_currency_value);
		updated_value = updated_value.toFixed(2);

		var return_data = new Array();
		return_data['value'] = updated_value;
		return_data['symbol'] = new_currency_symbol;
		return return_data;

}

/****************************/
/* PHP FUNCTIONS TO JS      */
/****************************/
function number_format (number, decimals, dec_point, thousands_sep) {
		// +     bugfix by: Brett Zamir (http://brett-zamir.me)
		// *     example 1: number_format(1234.56);
		// *     returns 1: '1,235'
		// *     example 2: number_format(1234.56, 2, ',', ' ');
		// *     returns 2: '1 234,56'
		// *     example 3: number_format(1234.5678, 2, '.', '');
		// *     returns 3: '1234.57'
		// *     example 4: number_format(67, 2, ',', '.');
		// *     returns 4: '67,00'
		// *     example 5: number_format(1000);
		// *     returns 5: '1,000'
		// *     example 6: number_format(67.311, 2);
		// *     returns 6: '67.31'
		// *     example 7: number_format(1000.55, 1);
		// *     returns 7: '1,000.6'
		// *     example 8: number_format(67000, 5, ',', '.');
		// *     returns 8: '67.000,00000'
		// *     example 9: number_format(0.9, 0);
		// *     returns 9: '1'
		// *     example 10: number_format('1.20', 2);
		// *     returns 10: '1.20'
		// *     example 11: number_format('1.20', 4);
		// *     returns 11: '1.2000'
		// *     example 12: number_format('1.2000', 3);
		// *     returns 12: '1.200'
		var n = number, prec = decimals;

		var toFixedFix = function (n,prec) {
				var k = Math.pow(10,prec);
				return (Math.round(n*k)/k).toString();
		};

		n = !isFinite(+n) ? 0 : +n;
		prec = !isFinite(+prec) ? 0 : Math.abs(prec);
		var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
		var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

		var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

		var abs = toFixedFix(Math.abs(n), prec);
		var _, i;

		if (abs >= 1000) {
				_ = abs.split(/\D/);
				i = _[0].length % 3 || 3;

				_[0] = s.slice(0,i + (n < 0)) +
							_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
				s = _.join(dec);
		} else {
				s = s.replace('.', dec);
		}

		var decPos = s.indexOf(dec);
		if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
				s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
		}
		else if (prec >= 1 && decPos === -1) {
				s += dec+new Array(prec).join(0)+'0';
		}
		return s;
}

function set_title_text(str_class)
{
	var display_str = '';
	var display_str_short = '';

	$("#generalSearchForm").find('input:checkbox').each(function(){
		if($(this).hasClass(str_class)){
			if($(this).attr('checked')){
				display_str += $(this).next().html()+", ";
			}
		}
	})

	if(display_str.length > 50){
		display_str_short = display_str.substr(0,50)+'...';
	}else{
		display_str_short = display_str.substr(0,(display_str.length - 2));
	}

	if(str_class == 'at'){
		$('#type_select_box').attr('title',display_str);
		$('#type_select_box').html(display_str_short);
	}else if(str_class == 'exp'){
		$('#exp_select_box').attr('title',display_str);
		$('#exp_select_box').html(display_str_short);
	}else{
		$('#afs_select_box').attr('title',display_str);
		$('#afs_select_box').html(display_str_short);
	}
}

function logStats(action,section,table,id)
{
	

	return 'true';
}

function IsNumeric(sText)
{
	var ValidChars = "-0123456789.";
	var IsNumber=true;
	var Char;


	for (i = 0; i < sText.length && IsNumber == true; i++)
	{
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1)
		{
			IsNumber = false;
		}
	}
	return IsNumber;

}


$.dpText = {
		TEXT_PREV_YEAR		:	'Previous year',
		TEXT_PREV_MONTH		:	'Previous month',
		TEXT_NEXT_YEAR		:	'Next year',
		TEXT_NEXT_MONTH		:	'Next month',
		TEXT_CLOSE			:	'Close',
		TEXT_CHOOSE_DATE	:	'Choose date'
	};
$.alerts.okButtonText = 'OK';
$.alerts.cancelButtonText = 'Cancel';

function rta(url, id) {

	$(id).html('<p class="availability checking">Checking availability...&nbsp;</p>');
	$.ajax({
		type: 'POST',
		url: url,
		dataType: 'xml',
		success: function(xml) {
			var available = $('status', xml).attr('data');
			if(available == 'available') {
				$(id).html('<p class="availability available">Available&nbsp;&nbsp;</p>');
				$(id+"_text").html('Make a booking');
			} else if(available == 'unavailable') { 
				$(id).html('<p class="availability not-available">Not available&nbsp;</p>');
			} else if(available == 'unknown') { 
				$(id).html('<p class="availability unknown">Availability unknown&nbsp;</p>');
			}

		}
	});
	return false;

}