var get_advanced_options = function(form_id)
{
	_uri = '';

	if ($('#advancedsearch_wrap').css('display') != 'block') return _uri;

	_uri += (_uri != '' ? '&' : '') + 'price_from=' + $('#price_from').val();
	_uri += (_uri != '' ? '&' : '') + 'price_to=' + $('#price_to').val();

	$('#' + form_id ).find(':input').each(function()
	{
		if ($(this).is(':checkbox') && $(this).is(':checked'))
		{
			_uri += (_uri != '' ? '&' : '') + escape(this.name) + '=' + escape(this.value);
		}
	});

	return _uri;
}

var get_subtype_ids = function ( form_id )
{
	_uri = '';

	$('#' + form_id ).find(':input').each(function()
	{
		if ($(this).is(':checkbox') && $(this).is(':checked'))
		{
			_uri += (_uri != '' ? '&' : '') + escape(this.name) + '=' + escape(this.value);
		}
	});

	return _uri;
}

$(document).ready(function()
{
	$('#autocomplete_towncity').keypress(function(e){ if (e.keyCode == 13) { searchDestination(); return false; } });
	$('#title_keyword').keypress(function(e){ if (e.keyCode == 13) { searchDestination(); return false; } });
});

$('#optTypeID').change(function(event)
{
	$('#simple_subTypeName').html('<option>Loading..</option>');

	//$('#autocomplete_towncity').val('Location');
	//$('#title_keyword').val('');

	$('#hpsbtn').attr('name', 'Search');
	$('#hpsbtn').attr('value', 'Search');

	$.post("/Classes/ajaxManager.php", {type: $(this).val(), toDo: 'fetch_sub_types', ajax: 'true'}, function(j)
	{
		/*j = j.split("\n");
		var options = '';
		for (var i = 0; i < j.length - 1; i++)
		{
			tmp = j[i].split('|');
			//urlsafe = make_url_safe(tmp[1]);
			options += '<option value="' + tmp[0] + '">' + tmp[1] + '</option>';
		}*/
		//$("#simple_subTypeName").html(options);
		$("#simple_subTypeName").html(j);
	})

	if ($(this).val() != 'Accommodation')
	{
		if ($('#hpsearchbox').length > 0) $('#hpsearchbox')[0].className = ($(this).val() == 'Transport-Rentals') ? 'trbg' : 'wtsdbg';
		if ($('#accommoptions').length > 0) $('#accommoptions').css({display: 'none'});
	}
	else
	{
		if ($('#hpsearchbox').length > 0) $('#hpsearchbox')[0].className = '';
		if ($('#accommoptions').length > 0) $('#accommoptions').css({display: ''});
	}
});

$('#simple_subTypeName').change(function(){
	//$('#autocomplete_towncity').val('Location');
	//$('#title_keyword').val('');
});

function make_url_safe(A)
{
	var _arr = new Array();

	_arr['/'] = '-';
	_arr['&amp;'] = '-';
	_arr['&'] = '-';
	_arr['('] = '';
	_arr[')'] = '';
	_arr[' '] = '-';
	_arr['--'] = '-';

	for (i in _arr)	{ while (A.indexOf(i) != -1) { A = A.replace(i, _arr[i]); }	}

	return A;
}


function update_select(A)
{
	var _default = _default_type_id;

	if ($(A).is(':input[type=hidden]')) return;

	//return;

	lmnts = $(A).children();
	lmnts.each(function()
	{
		var _id = $(this).val().split('|')[0];
		if (_id == _default) $(this).attr({selected: 'selected'});
		if ($(this).val() == '') return; //$(this).val() == 'all' || 
		//$(this).val($(this).val() + '|' + make_url_safe($(this).val() == 93 ? 'Holiday Park' : $(this).html())); 
	});
}

update_select('#simple_subTypeName');

/* =========================================================================================================================

Location script

========================================================================================================================= */

var w = $('#autocomplete_towncity').width();

$("#autocomplete_towncity").autocomplete('../Classes/ajaxManager.php?toDo=fetch_locations&field=seo_name&levels=0|1',
{
	selectFirst: false,
	matchContains: true,
	minChars: 2,
	max: 0,
	cacheLength: 1,
	extraParams: 
	{
		type: function() { $('#autocomplete_towncity_id').val(''); return $('#optTypeID').val(); },
		sub_type: function() { return $('#simple_subTypeName').val(); }
	}
}).setOptions({
	width: w
}).result(function(event, data, formatted) {
	$('#autocomplete_towncity_id').val(data[1]);
});

$('#autocomplete_towncity').focus(function() { if ($(this).val() == 'Location') $(this).val(''); });
$('#autocomplete_towncity').blur(function()  { if ($(this).val() == '') $(this).val('Location'); });

/* =========================================================================================================================

Search script

========================================================================================================================= */
function URLEncode( param )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = param;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		encoded += ch;
		} else {
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
};

function searchDestination()
{

	var typeID = $("#optTypeID").val();
	var subtypeID = $("#simple_subTypeName").val();
	var searchTown = $("#autocomplete_towncity").val();
	var keywords = $("#title_keyword").val();

	while ((/\s+/).test(searchTown))
		searchTown = searchTown.replace(' ', '-');

	var path = '';
	var is_default_keywords = (keywords == keyword_examples[0] || keywords == keyword_examples[1] || keywords == keyword_examples[2]);

	var _advanced_uri = '';
	if (_consider_adv_search == 1)
	{
		_advanced_uri = get_advanced_options('advanced_search_form');
	}

	var _sub_type_ids = '';
	if (_consider_sub_types == 1)
	{
		_sub_type_ids = get_subtype_ids('sub_type_id_wrap');
	}

	var is_smartfuel_field_present = ($("#adv_affiliationList_185").val() != undefined && $("#adv_affiliationList_185").val() != '') ? true : false;
	//console.log(_sub_type_ids); return false;

	// Availability Search
	if ($('#searchtype-2:checked').length == 1 && typeID == 'Accommodation')
	{
		path = "/accommodation-newzealand/availability-results.php";

		if (searchTown == 'Location') { searchTown = ''; }
		if (searchTown == '') { alert('Please enter the location you wish to stay in'); $("#autocomplete_towncity").focus(); return false; }

		if (keywords =='Keywords' || is_default_keywords) { keywords = ''; }

		var strSearchTown = trim(URLEncode(searchTown));
		var strSearchKeyword = trim(URLEncode(keywords));

		var myID = searchTown != '' ? $('#autocomplete_towncity_id').val() : '';

		if ($('#checkinDate').val() == '' || $('#checkinMonth').val() == '' || $('#checkinYear').val() == '')
			{ alert('Please enter a valid date to search for'); $('#checkinDate').focus(); return false; }
		
		if ($('#checkinMonth').val() == '02' && $('#checkinDate').val() > 29)
			{ alert('Please enter a valid date to search for'); $('#checkinDate').focus(); return false; }
		
		var dateToday  = $('#checkinDate').val();
		var monthToday = parseInt($('#checkinMonth').val(),10)-1;
		var yearToday  = $('#checkinYear').val();
		
		var dateObject = new Date(yearToday, monthToday, dateToday);
		var formattedMonth = parseInt(dateObject.getMonth(),10)+1;
		var formattedDay = parseInt(dateObject.getDate(),10);
		formattedMonth = ( formattedMonth < 10 ) ? '0' + formattedMonth.toString() : formattedMonth;
		formattedDay   = ( formattedDay < 10 ) ? '0' + formattedDay.toString() : formattedDay;
		
		type_id = subtypeID.split('|')[0] == 'all' ? '1' : subtypeID.split('|')[0];
		sub_type_name = '&subTypeName=' + subtypeID.split('|')[0];

		path += '?typeId=1'+sub_type_name+'&startdate=' + dateObject.getFullYear() + '' + formattedMonth + '' + formattedDay + '&town='+strSearchTown+'&locationId='+myID+'&title='+strSearchKeyword+'&searchtype=on&checkinDate='+dateToday+'&checkinMonth='+monthToday+'&checkinYear='+yearToday+'&checkAvailability=Check+Availability' + (_advanced_uri != '' ? '&' + _advanced_uri : '&price_from=All&price_to=All');


		//Smartfuel tickbox
		if (is_smartfuel_field_present) {
			_smartfuel_tickbox_obj = $("#adv_affiliationList_185");

			if ($(_smartfuel_tickbox_obj).is(':checkbox') && $(_smartfuel_tickbox_obj).is(':checked')) {
				path += (path != '' ? '&' : '') + escape(_smartfuel_tickbox_obj.attr('name')) + '=' + escape(_smartfuel_tickbox_obj.attr('value'));
			}
		}

		location.href = path;
		return;
	}

	/* <![CDATA[ */
	//if ((keywords.length > 0 && !is_default_keywords && (!is_default_keywords || $('#autocomplete_towncity_id').val() == '')) || _advanced_uri != '')
	if ((keywords.length > 0 && !is_default_keywords) || ($('#autocomplete_towncity_id').val() == '' && searchTown != 'Location' && searchTown != '') || _advanced_uri != '' || _sub_type_ids != '' || is_smartfuel_field_present)
	{
		path = "/main/searchresults.php";

		if (searchTown == 'Location') { searchTown = ''; }
		if (keywords =='Keywords' || is_default_keywords) { keywords = ''; }

		var strSearchTown = trim(URLEncode(searchTown));
		var strSearchKeyword = trim(URLEncode(keywords));

		var myID = searchTown != '' ? $('#autocomplete_towncity_id').val() : '';
		if (myID != '') strSearchTown = '';

		if( typeID == 'Accommodation' )
		{
			var date = new Date();
			var dateToday  = date.getDate();
			var monthToday = date.getMonth() + 1;
			var yearToday  = date.getFullYear();

			type_id = subtypeID.split('|')[0] == 'all' ? '1' : subtypeID.split('|')[0];
			sub_type_name = '&subTypeName=' + subtypeID.split('|')[0];

			path += '?typeId=1&startdate=&town='+strSearchTown+'&locationId='+myID+'&title='+strSearchKeyword+'&searchtype=on&checkinDate='+dateToday+'&checkinMonth='+monthToday+'&checkinYear='+yearToday+'&Search=Search' + sub_type_name + (_advanced_uri == '' ? '&price_from=All&price_to=All' : '&' + _advanced_uri);

			//Smartfuel tickbox
			if (is_smartfuel_field_present) {
				_smartfuel_tickbox_obj = $("#adv_affiliationList_185");

				if ($(_smartfuel_tickbox_obj).is(':checkbox') && $(_smartfuel_tickbox_obj).is(':checked')) {
					path += (path != '' ? '&' : '') + escape(_smartfuel_tickbox_obj.attr('name')) + '=' + escape(_smartfuel_tickbox_obj.attr('value'));
				}
			}
		}
		else if( typeID == 'What-to-See-Do' )
		{
			type_id = subtypeID.split('|')[0] == 'all' ? '3%2C2%2C5%2C6%2C10%2C11' : subtypeID.split('|')[0];
			sub_type_name = subtypeID.split('|')[0] == 'all' ? '&subTypeName=all' : '';

			path += '?town='+strSearchTown+'&title='+strSearchKeyword+'&locationId='+myID+'&typeId=' + type_id + '&Search=Search' + sub_type_name + '&' + _sub_type_ids;
		}
		else if( typeID =='Transport-Rentals' )
		{
			type_id = subtypeID.split('|')[0] == 'all' ? '7%2C8%2C30%2C31' : subtypeID.split('|')[0];
			sub_type_name = subtypeID.split('|')[0] == 'all' ? '&subTypeName=all' : '';

			path += '?typeId=' + type_id + '&town=' + strSearchTown + '&title=' + strSearchKeyword + '&locationId=' + myID + '&Search=Search' + sub_type_name+ '&' + _sub_type_ids;
		}
	}
	else
	{

		if (searchTown == 'Location' || searchTown == '')
		{
			searchTown = 'Nationwide';
		}

		if (subtypeID.split('|')[1] == 'All')
			subtypeID = typeID;
		else
			subtypeID = subtypeID.split('|')[1];

		locationID = searchTown.replace(' ', '-');

		//if (typeof console != 'undefined') console.log("/new-zealand/"+locationID+"_"+subtypeID+".html");

		path = "/new-zealand/"+locationID+"_"+subtypeID+".html";
		
	}

	location.href = path;
	/* ]]> */
}


/* =========================================================================================================================

Keywords script

========================================================================================================================= */
var title_keyword_timer;
var keyword_examples = new Array('Keywords: e.g. pets by arrangement', 'Keywords: e.g. Lakeside Motel', 'Keywords: e.g. swimming pool');
function shift_title_keyword( )
{
  var date = new Date();
  var seconds = date.getSeconds();
  var index = seconds % 3;
  document.getElementById('title_keyword').value = keyword_examples[index];
}

$(document).ready(function() {
	var el = document.getElementById('title_keyword');

	$("#title_keyword").bind("click", function(e){
			clearInterval(title_keyword_timer);
			var value = document.getElementById('title_keyword').value;
			var is_default_value = (value == keyword_examples[0] || value == keyword_examples[1] || value == keyword_examples[2]);
			if(is_default_value){
				document.getElementById('title_keyword').value= '';
			}
	});
	$("#title_keyword").bind("focus", function(e){
			clearInterval(title_keyword_timer);
			var value = document.getElementById('title_keyword').value;
			var is_default_value = (value == keyword_examples[0] || value == keyword_examples[1] || value == keyword_examples[2]);
			if(is_default_value){
				document.getElementById('title_keyword').value= '';
			}
	});
	$("#title_keyword").bind("blur", function(e){
		if (document.getElementById('title_keyword').value == '')
		{
			title_keyword_timer = setInterval( "shift_title_keyword()", 2000);
		}
	});
	
	$("#title_keyword").bind("keypress", function(e){
		clearInterval(title_keyword_timer);
	});

	$("#title_keyword").bind("keydown", function(e){
		clearInterval(title_keyword_timer);
	});

	$("#title_keyword").bind("change", function(e){
		clearInterval(title_keyword_timer);
	});

	if ($("#title_keyword").val() == '') title_keyword_timer = setInterval( "shift_title_keyword()", 2000);
});

/* =========================================================================================================================

Online button script

========================================================================================================================= */

function set_button()
{
	if ($('#searchtype-1:checked').length == 1)
	{
		_hideOnlineBooking();
	}
	else
	{
		_showOnlineBooking();
	}
}

function _hideOnlineBooking()
{
	$('#dateLabel').css({display: 'none'});
	$('#datePicker').css({display: 'none'});
	//$('input.submitavail').removeClass('submitsearch submitavail').addClass('submitsearch');
	//$('input.submitavail').attr('class','');
	$('input.submitavail').attr('class','submitsearch');
	$('input.submitsearch').attr('name', 'Search');
	$('input.submitsearch').attr('value', 'Search');
	//$('#' + _button_id).attr('name', 'Search');
	//$('#' + _button_id)[0].value = 'Search';
	//$('#' + _button_id).css({width: '80px'});
}				

function _showOnlineBooking()
{
	$('#dateLabel').css({display: 'block'});
	$('#datePicker').css({display: 'block'});
	$('input.submitsearch').attr('name', 'checkAvailability');
	$('input.submitsearch').attr('value', 'Check Availability');
	//$('input.submitsearch').removeClass('submitsearch').addClass('submitsearch submitavail');
	//$('input.submitsearch').attr('class','');	
	$('input.submitsearch').attr('class','submitsearch submitavail');
	//$('#' + _button_id).attr('name', 'checkAvailability');
	//$('#' + _button_id).attr('value', 'Check Availability');
	//$('#' + _button_id).css({width: '120px'});
}

/* =========================================================================================================================

Search script

========================================================================================================================= */

