var searchBoxClosing = false;
var timeAutoCom = false;
var waitingToHide = false;
var globFrm = null;
var old_selectedIndex = 8;
var calendarupdate = 0;
var qsTab = 1;
var showAnyDest = true;
var acLRtab = false;
var acLuxMode = false;
var acLRMode = false;
var is_mobile_user = false;

if (typeof(quick_search_dropdown_type) == "undefined") {
	var quick_search_dropdown_type = "grouped";
}
if (quick_search_dropdown_type == "alpha") {
	function compareQSName(a,b) {
				
		var x = a[0].toLowerCase();
		var y = b[0].toLowerCase();
		
		if (x.substr(0,3) == "the") x = x.substr(4);
		if (y.substr(0,3) == "the") y = y.substr(4);
		
		x = a[2] == 0 && a[1] < 0 ? "0"+x : "1"+x;
		y = b[2] == 0 && b[1] < 0 ? "0"+y : "1"+y;
		
		return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	}
	all_data_dest.sort(compareQSName);
}

function showAutocom(i, frm) {
	if (waitingToHide && i == 3) {
		frm.aclist.style.visibility = 'hidden';
	} else {
		if (i > 0) {
			frm.aclist.style.visibility = 'visible';
			if (i == 1) {
				frm.aclist.focus();
			}
		} else {
			frm.aclist.style.visibility = 'hidden';
			searchBoxClosing = true;
			window.setTimeout("clearSearchBoxClosing()", 500);
			if (frm.autocom.value.length == 0) frm.autocom.value = enter_search_text;
		}
		waitingToHide = false;
	}
}

function clearSearchBoxClosing() {
	searchBoxClosing = false;
}

function reruncalendar() {
	clearTimeout(calendarupdate);
}

function selectItem(v, e, frm) {
	if (calendarupdate != 0) {
		reruncalendar();
	}

	if ((v != 4) && (v == 2 && e && e.keyCode == 27)) {	// esc
		showAutocom(0, frm);
		frm.autocom.focus();
	} else {
		try {
			
			selectedText = frm.aclist.options[frm.aclist.selectedIndex].text;
			selectedText = selectedText.replace(/^(-| )+/gm, ''); // remove spaces and hyphens at the start
			
			if (qsTab == 2) {
				frm.autocom_villa.value = selectedText;
				frm.autocom2_villa.value = frm.aclist.options[frm.aclist.selectedIndex].value;
			} else {
				frm.autocom.value = selectedText;
				frm.autocom2.value = frm.aclist.options[frm.aclist.selectedIndex].value;
			}

			var sel = frm.aclist.options[frm.aclist.selectedIndex].value;
			var type = sel.split(":")[1];
			var id = sel.split(":")[0];

			if (qsTab != 2) {
				if (frm.autocom2.value.split(":")[1] == 5) {
					// country, find regions
					runquery = qsFindRegionsFromCountry();
				} else {
					if (frm.autocom2.value.split(":")[1] == 4) {
						// region group, find regions
						runquery = qsFindRegionsFromGroup();
					} else {
						// got region ID already
						runquery = qsFindRegion();
					}
				}
			}
			if (qsTab != 2) {
				calendarupdate = setTimeout("updateCal(runquery)", 500);
			}
			if ((v == 1 && e && e.keyCode == 0) || (v == 1 && (!e || typeof(e.keyCode)=="undefined")) || (e && e.keyCode == 13) || (v == 3) || (v == 2 && e.keyCode == 9) || (v == 4)) { // || (v == 4)
				if (qsTab != 2) {
					calendarupdate = setTimeout("updateCal(runquery)", 0);
				}
				showAutocom(0, frm);
				if (v != 4) frm.autocom.focus();
				frm.typed.value = 0;
			}

			if (v == 2 && e && e.keyCode == 38 && old_selectedIndex == 0) {
				showAutocom(0, frm);
				frm.autocom.focus();
			}

			old_selectedIndex = frm.aclist.selectedIndex;

		} catch (err) {
		}
	}
}

function moveDown(t, a, frm) {
	if (t.keyCode == 40 || t.keyCode == 34) {
			showAutocom(1, frm);
			if (villaAjaxTimer) window.clearTimeout(villaAjaxTimer);
	}
}

function typeWord(t, a, frm) {
	var typed = frm.autocom.value.replace(/^\s+|\s+$/g,"");
	if (qsTab == 2) typed = frm.autocom_villa.value.replace(/^\s+|\s+$/g,"");

	if ((t.keyCode == 13 || t.keyCode == 9) && a == 2 && frm.aclist.options.length == 1) { // enter or tab pressed when in text field and one value to choose
		frm.aclist.selectedIndex = 0;
		selectItem(3, null, frm);
		showAutocom(0, frm);
	}

	if (t.keyCode >= 60 && t.keyCode < 130 || t.keyCode == 8 || t.keyCode == 32 || t.keyCode == 46) {
		if (qsTab == 1 && frm.autocom.value.length == 0) {
			setDestListUp(frm);
			showAutocom(2, frm);
		} else if (qsTab == 2 &&  frm.autocom_villa.value.length == 0) {
			showAutocom(0, frm);
		} else {
			setListUp(typed, frm);
			showAutocom(2, frm);
		}

	} else if (t.keyCode == 27) {	// esc
		showAutocom(0, frm);
	} else if (t.keyCode == 13 && frm.aclist.options.length == 1) {	// enter
		frm.aclist.selectedIndex = 0;
		selectItem(0, null, frm);
		showAutocom(0, frm);
	} else if (t.keyCode == 13 && qsTab == 2) {	// enter when multiple options
		var all_data_len = all_data.length;
		for (var i=0;i<all_data_len;i++) {
			// if its a villa and it matches
			if (all_data[i][data_pos_item_type] == 3 && all_data[i][0].replace(/\((.*?)\)/g, "").replace(/^\s+|\s+$/g,"").toLowerCase() == frm.autocom_villa.value.replace(/^\s+|\s+$/g,"").toLowerCase()) {
				frm.autocom_villa.value = addtextopt(i);
				frm.autocom2_villa.value = all_data[i][1] + ":" + all_data[i][data_pos_item_type] + ":" + i;
				break;
			}
		}
		showAutocom(0, frm);
	}
	frm.typed.value = 1;

	if (t.keyCode == 13) t.keyCode = 0;

}

function addtextopt(v_ind) {

	var this_all_data = all_data_dest;
	if (qsTab == 2) {
		this_all_data = all_data;
	}

	// if its a villa
	if (this_all_data[v_ind][data_pos_item_type] == 3) {
		var regName = "";
		var allLen = this_all_data.length;
		for (var i=0;i<allLen;i++) {
			if (this_all_data[i][1] == this_all_data[v_ind][2]) {
				for (var j=0;j<allLen;j++) {
					if (this_all_data[j][1] == this_all_data[i][2]) {
						regName = " (" + this_all_data[j][0] + ")";
						break;
					}
				}
				break;
			}
		}
		return this_all_data[v_ind][0] + regName;
	}	else {
		return this_all_data[v_ind][0];
	}
}

function setDestListUp(showBox) {
	var b;
	if (acLRtab) {	// Populate LR activity dropdown
		b = document.quicksearch.destDropdown;
	} else {
		b = document.quicksearch.aclist;
	}
	b.options.length = 0;
	var leng = all_data_dest.length;
	var any_dest = Array();
	
	var currentCountry = "";
	var currentRegionGroup = "";
	var padRegion = false;
	var padRegionGroup = false;
	
	var addedItemsList = ",";

	for (var i=0;i<leng;i++) {
		
		/* if its not a resort, 
			or its in leisure resort mode and the region has leisure resorts
			or its luxury
		*/
		if (all_data_dest[i][data_pos_item_type] != 2
				&& (!acLRMode || all_data_dest[i][1] == -1 || all_data_dest[i][4] == 1)
				&& (!acLuxMode || all_data_dest[i][1] == -1 || all_data_dest[i][1] == -3 || all_data_dest[i][1] == -4 || all_data_dest[i][5] == 1)
		) {
		
			optionText = all_data_dest[i][0];
			
			if (quick_search_dropdown_type == "grouped") {
				if (all_data_dest[i][3] == 5) {
					addedItemsList = ",";
					currentCountry = optionText;
				} else if (all_data_dest[i][3] == 4) {
					currentRegionGroup = optionText;
				}
				if (all_data_dest[i][1] > 0) {
					if (all_data_dest[i][3] == 1) { //region
						padRegion = (all_data_dest[i][2] > 0);
						padRegionGroup = (all_data_dest[i][6] > 0) && currentRegionGroup != currentCountry;
						
					} else if (all_data_dest[i][3] == 5) { //country
						padRegion = false;
						padRegionGroup = false;
						
					} else if (all_data_dest[i][3] == 4) { //region group
						padRegion = false;			
						padRegionGroup = (all_data_dest[i][2] > 0);
					}
				}
			}
			
			if (addedItemsList.indexOf("," + all_data_dest[i][0] + ",") == -1) {
				new_option = new Option(all_data_dest[i][0], all_data_dest[i][1]+":" + all_data_dest[i][3] + ":" + i, false, false);
				addedItemsList = addedItemsList + all_data_dest[i][0] + ",";
			
				if (padRegion && padRegionGroup) {
					new_option.text = "-- " + new_option.text;
	
				} else if (padRegion || padRegionGroup) {
					new_option.text = "- " + new_option.text;
				}							
				
				if (all_data_dest[i][1] < 0) new_option.className = 'searchSpecialOpt';
				if ((canydest_switch == 3 || canydest_switch == 0) && (all_data_dest[i][1] < 0)) {
					any_dest[any_dest.length] = new_option;
				} else {
					if (all_data_dest[i][1] > -1 || showAnyDest) {
						b.options[b.options.length] = new_option;
					}
				}
			}
		}
	}

	if (canydest_switch == 3 && any_dest.length > 0) {
		for (var i=0;i<any_dest.length;i++) { b.options[b.options.length] = any_dest[i]; }
	}

	if (showBox > 0 && !searchBoxClosing) {
		document.getElementById('aclist').style.visibility='visible';
		if (showBox > 1)
			document.getElementById('aclist').focus();
	}
	searchBoxClosing = false;
}

function setListUp(value, frm) {
	frm.aclist.options.length = 0;
	var added = 0;
	var maxn = 12;
	var checkWord;
	var any_dest = false;
	var this_all_data = all_data_dest;
	if (qsTab == 2) this_all_data = all_data;
	var added_list = "|";
	var option_text;
	var isDest;
	var isLR;
	var isLux;
	
	for (i=0; i<this_all_data.length; i++) {
		isDest = (this_all_data[i][data_pos_item_type] != 3);
		isLR = (!acLRMode || this_all_data[i][4] == 1);
		isLux = (!acLuxMode || this_all_data[i][5] == 1);
		checkWord = this_all_data[i][0].replace(/the/i, "").replace(/^villa/i, "").replace(/^casa/i, "").replace(/^vista/i, "").replace(/^los/i, "").replace(/^el/i, "").replace(/^la/i, "").replace(/^il/i, "").replace(/^li/i, "").replace(/^can/i, "").replace(/^sa/i, "").replace(/^\s+|\s+$/g,"").toUpperCase();
		if ((checkWord.substring(0, value.length).toUpperCase() == value.toUpperCase() || this_all_data[i][0].substring(0, value.length).toUpperCase() == value.toUpperCase()) && ((isDest && qsTab == 1) || (!isDest && qsTab == 2)) && isLR && isLux) {
			option_text = addtextopt(i);
			if (added_list.indexOf("|" + option_text + "|") == -1) {
			added++;
				new_option = new Option(addtextopt(i), this_all_data[i][1]+":" + this_all_data[i][data_pos_item_type] + ":" + i, false, false);
				added_list = added_list + option_text + "|";
			if ((canydest_switch == 3 || canydest_switch == 0) && all_data_dest[i][1] == -1) {
				any_dest = new_option;
			} else {
				if ((this_all_data[i][1] != -1 && this_all_data[i][1] != -2 && this_all_data[i][1] != -3) || showAnyDest) {				
					document.quicksearch.aclist.options[document.quicksearch.aclist.options.length] = new_option;
						
					}
				}
			}
		}
		if (added > maxn) break;
	}

	if (canydest_switch == 3 && any_dest) document.quicksearch.aclist.options[document.quicksearch.aclist.options.length] = any_dest;

}

function qsFindRegion() {
	var region_id = -1;
	var arr = document.quicksearch.autocom2.value.split(":");

	if (arr && arr.length > 2) {

		/*
			If the selected item doesnt match the data in the set position, re-find it.
			This can happen when the region/resort/country array is changed, e.g. a new resort added which causes the stored indexes to be incorrect
		*/
		if (all_data_dest[arr[2]][0] != document.quicksearch.autocom.value) {
			for (i=0; i<all_data_dest.length; i++) {
				if (all_data_dest[i][1] == arr[0] && all_data_dest[i][data_pos_item_type] == arr[1]) {
					var tmparr = all_data_dest[i][1] + ":" + all_data_dest[i][data_pos_item_type] + ":" + i;
					arr = tmparr.split(":");
					break;
				}
			}
		}

		var obj = all_data_dest[arr[2]];
		var level = obj[data_pos_item_type];
		if (arr[1] != 4) { // if it is not a region_group
			for (i=0; i<level-1; i++) {
				var tmp_obj = qsFindObjParent(obj);
				if (tmp_obj != null) {
					obj = tmp_obj;
				}
			}

			if (obj && obj.length > 1) {
				region_id = obj[1];
			}
		}
	}
	return region_id;
}

function qsFindObjParent(n) {
	for (j=0; j<all_data_dest.length; j++) {
		if (all_data_dest[j][1] == n[2]) {
			return all_data_dest[j];
		}
	}
	return null;
}

function qsFindRegionsFromCountry() {
	var arr = document.quicksearch.autocom2.value.split(":");
	var country_id = arr[0];
	var arr_region = new Array();
	var allDLen = all_data_dest.length;
	for (var i=0;i<allDLen;i++) {
		if (all_data_dest[i][data_pos_item_type] == 1 && all_data_dest[i][2] == country_id) {
			arr_region[arr_region.length] = all_data_dest[i][1];
		}
	}
	return arr_region.join(",");
}

function qsFindRegionsFromGroup() {
	var arr = document.quicksearch.autocom2.value.split(":");
	var group_id = arr[0];
	var arr_region = new Array();
	var groups = groupData.split(";");
	for (var i=0;i<groups.length;i++) {
		if (groups[i].substring(0,groups[i].indexOf(",")) == group_id) {
			return groups[i].substring(groups[i].indexOf(",")+1);
		}
	}
}

function qsAddItm(n, t) {
	for (var i=0;i<all_data.length;i++) {
		if (all_data[i][data_pos_item_type] == t && all_data[i][1] == n) {
			document.quicksearch.autocom.value = all_data[i][0]; //addtextopt(i);
			document.quicksearch.autocom2.value = all_data[i][1]+":"+all_data[i][data_pos_item_type]+":"+i;
			break;
		}
	}
	if (t != 4) updateCal(qsFindRegion());
	qsShowPicker();
}

function qsShowPicker() {
	var d = document.getElementById('destmode2');
	if (d) d.style.visibility = (d.style.visibility == "hidden") ? "visible" : "hidden";
}

function startAutoHide(frm) {
	waitingToHide = true;
	globFrm = frm;
	timeAutoCom = setTimeout("showAutocom(0, globFrm)",100);
	if (frm.aclist.length == 1 && frm.aclist[0].text.toLowerCase() == frm.autocom.value.toLowerCase()) {
		frm.aclist.selectedIndex = 0;
		selectItem(4, null, frm);
	}
}

function stopAutoHide() {
	if (timeAutoCom) clearTimeout(timeAutoCom);
	waitingToHide = false;
}

function validateSearch() {
	
	/* MOD050109NAB01 Adding validation check to quick search input to stop incorrect dates causing an error */
	var sDate = document.quicksearch.dep_date.value;
	var sDay = 0;
	var sMonth = 0;
	var sYear = 0;

	sDate = sDate.replace(/(\/)/g, ""); // removes forward slashes

	// checks that the date number is numeric
	if (!isNaN(sDate) && sDate > 0 && (sDate.length == 6 || sDate.length == 8)){
		// 14/02/11
		if (sDate.length == 6){
			sDay = sDate.substr(0,2);
			sMonth = sDate.substr(2,2);
			sYear = sDate.substr(4,2);		
		// 14/02/2011
		} else {
			sDay = sDate.substr(0,2);
			sMonth = sDate.substr(2,2);
			sYear = sDate.substr(4,4);
		}
	}
	
	if (document.quicksearch.autocom2.value == "") {
		return ("Please select a destination");	
	} else if (sDay == 0 || sMonth == 0 || sYear == 0) {
		return  ("Please select a date from the calendar or enter a full date to search on (dd/mm/yyyy).");
	} else if (sMonth > 12) {
		return  ("Please enter number up to 12 for your departure month.");
	} else if (sDay > 31) {
		return  ("Please enter number up to 31 for your departure day.");		
	} else {		
		if (document.quicksearch.duration.selectedIndex == -1 || document.quicksearch.duration.value == "") {
			return ("Please select a duration");
		} else {
			if (google_analytics_switched_on) {
				document.quicksearch.CTA.value = form_action_search_tracking;
			}			
			document.quicksearch.autocom.value = document.quicksearch.autocom.value.replace(/\(|\)|\'/g, "");
			//document.quicksearch.submit();
			return null;
		}
	}

}

function submitSearch() {
	var msg = validateSearch();
	if (msg == null) {
		document.quicksearch.submit();
	} else {
		alert(msg);
	}
}

function submitVillaSearch() {
	if (document.quicksearch.autocom_villa.value.trim().length == 0) {
		alert("You must enter a villa name");
	} else {
	
	
		var villaParts = document.quicksearch.autocom2_villa.value.split(':');
		if (villaParts.length < 3) {
			alert("Please select a villa from the list.\n\nIf no villas are returned then you may need to adjust the spelling.");	
		} else {
	
			if (google_analytics_switched_on) {
				document.quicksearch.CTA.value = form_action_villa_search_tracking;
			}
			document.quicksearch.autocom_villa.value = document.quicksearch.autocom_villa.value.replace(/\(|\)|\'/g, "");
			
			var newLocation = villaParts[3]+'?vsearch=yes'; 
			window.location = newLocation;
		}
	}
}

function submitLeisureResortSearch() {
	var destinationText = $('#destDropdown option:selected').text();
	destinationText = destinationText.replace(/\((.*?)\)/g,""); // remove all text surrounded by brackets
	destinationText = destinationText.replace(/[^0-9A-Za-z ]+/g,""); // remove all non alphanumeric characters or spaces
	destinationText = $.trim(destinationText); // trim the destination
	destinationText = destinationText.replace(/  /g, ' ').replace(/ /g, '-').toLowerCase();
	
	var activities = new Array();
	$('#lractivities :checked').each(
		function() {
			activities[activities.length] = $(this).attr('id').substring(2).toLowerCase();
		}
	);
	
	var lrSearchUrl = '/leisure-resorts/search/' + destinationText + '/';
	if (activities.length > 0) {
		lrSearchUrl += activities.join('-') + '/';
	}
	
	window.location.href = lrSearchUrl;
}

function showHideCal(which) {
	var cc = document.getElementById('cc');
	cc.style.display = (which == 'show' && cc.style.display == 'none') ? '' : 'none';
	var cbox = document.getElementById('dep_date');
	cbox.style.display = (which == 'show') ? 'none' : '';
	var lbldate = document.getElementById('lbldate');
	lbldate.style.display = (which == 'show') ? 'none' : '';
	var cicon = document.getElementById('cal_icon');
	cicon.style.display = (which == 'show') ? 'none' : '';
	var duration_select = document.getElementById('duration_select');
	duration_select.style.display = (which == 'show') ? 'none' : '';
}

function updateCal(region_id_list) {
	if (region_id_list < 10 && region_id_list >= 0) region_id_list = "0" + region_id_list;

	if (typeof(region_id_list) == "string" && region_id_list.indexOf(",") > -1) {
		var tmpArr = region_id_list.split(",");
		for (var i=0;i<tmpArr.length;i++) {
			if (tmpArr[i] < 10) tmpArr[i] = "0" + tmpArr[i];
		}
		region_id_list = tmpArr.join(",");
	}

	c_r(region_id_list);
	if (document.getElementById('dep_date').value != "") {
		try {
			var dep_date = document.getElementById('dep_date').value.split("/");
			qsGetDuration(cr, new Date(dep_date[2],dep_date[1]-1,dep_date[0]), 0);
		}
		catch (e) {
			qsGetDuration(cr, new Date(cy,cm-1,1), 0);
		}
	}
	else {
		qsGetDuration(cr, new Date(cy,cm-1,1), 0);
	}

	/*
		If the selected month in the calendar does not match the month set up in the JavaScript, load the first month.
		This handles when the clients date is not in the calendar (i.e. an old date).
	*/
	if (document.getElementById('cselmy').value != cpad(cm) + "_" + cy) {
		if (firstSelect) {
			c_first(region_id_list);
			firstSelect = false;
		}
	}

	portActions();
	//document.getElementById('dep_date').value = "";
}

// pass a region id and date and it'll populate the duration field
function qsGetDuration(ir, idt, ifx) {
	var r,s,e,d;	
	var ir2 = ","+ir.toString()+",";	
	var durationOptions = new Array();
	// for each duration record
	for (var i = 0; i < dur_data.length; i++) {
		// find the dest, start and end date
		r = dur_data[i].substr(0,2);
		s = new Date(parseInt("20" + dur_data[i].substr(6,2)),dur_data[i].substr(4,2)-1,dur_data[i].substr(2,2));
		e = new Date(parseInt("20" + dur_data[i].substr(12,2)),dur_data[i].substr(10,2)-1,dur_data[i].substr(8,2));
		
		// if the duration record applies
		if (ir2.indexOf(","+r+",") > -1 && s <= idt && e > idt && dur_data[i].length > 14) {
			// for each duration available
			d = dur_data[i].substr(14);
			for (var j = 0; j < d.length; j += 2) {
				var n = (d.substr(j,2) < 10) ? d.substr(j,2).substr(1) : d.substr(j,2);
				var durationOptionFound = false;
				// find if this duration has already been added
				for (var k = 0; k < durationOptions.length; k++) {
					if (!durationOptionFound && durationOptions[k].value == n) {
						durationOptionFound	= true
					}
				}
				if (!durationOptionFound) {
					durationOptions[durationOptions.length] = new Option(n + " " + convertSpecialCharacters(nights_text), n);
				}		
			}
		}
	}
	
	// sort the duration options
	durationOptions.sort(function (a, b) {return parseInt(a.value) - parseInt(b.value);});
	
	// rebuild the duration options
	var selDur = document.quicksearch.duration;
	var curVal = selDur.value;
	selDur.options.length = 0;
	for (var i = 0; i < durationOptions.length; i++) {
		selDur.options[selDur.options.length] = durationOptions[i];
		if (durationOptions[i].value == curVal) selDur.selectedIndex = selDur.options.length - 1;
	}
	
	if (selDur.options.length == 0) {
		var num_options = 0;

		if(showAllDestExtraDur == '1'){
			if(ir == -1 && (iswebquote || (idt.getMonth() != 6 && idt.getMonth() != 7))){
				selDur.options[num_options] = new Option("3 " + convertSpecialCharacters(nights_text), 3);
				num_options++;
				selDur.options[num_options] = new Option("4 " + convertSpecialCharacters(nights_text), 4);
				num_options++;
			}
		}
		
		selDur.options[num_options] = new Option("7 " + convertSpecialCharacters(nights_text), 7);
		num_options++;
		
		if(showAllDestExtraDur == '1'){
			selDur.options[num_options] = new Option("10 " + convertSpecialCharacters(nights_text), 10);
			num_options++;
			selDur.options[num_options] = new Option("11 " + convertSpecialCharacters(nights_text), 11);
			num_options++;
		}
		
		selDur.options[num_options] = new Option("14 " + convertSpecialCharacters(nights_text), 14);
		num_options++;
		selDur.options[num_options] = new Option("21 " + convertSpecialCharacters(nights_text), 21);
		num_options++;
		
		var found_dur = false;
		for(var i=0;i<selDur.options.length;i++) {
			if(selDur.options[i].value == curVal){
				found_dur = true;		
			}
		}
		if(found_dur){
			selDur.value = curVal;
		}
		else{
			selDur.value = 7;
		}
	}
}

function convertSpecialCharacters (string) {
	return string.replace(/&#(\d+);/g, function() {return String.fromCharCode(arguments[1]);});
}

function switchQSTabButton (t, id) {
	var div = document.getElementById("div" + id);
	var tab = document.getElementById("tab" + id);
	if (div && tab) {	
		div.style.display = (t) ? "block" : "none";
		if (tab.className.indexOf("smallTab") > -1) {
			tab.className = (t) ? "smallTab active" : "smallTab";
		} else {
			tab.className = (t) ? "active" : "";	
		}
	}
}

function switchQSTab(t) {
	qsTab = t;
	document.quicksearch.search_type.value = t;
	document.quicksearch.aclist.length = 0;
	document.getElementById('divDest').style.display = (t == 1) ? "block" : "none";
	document.getElementById('divVilla').style.display = (t == 2) ? "block" : "none";
	
	switchQSTabButton((t == 1), "Dest");
	switchQSTabButton((t == 2), "Villa");
	if (qs_resort_tab) switchQSTabButton((t == 3), "Resort");

	document.getElementById('airport_select').style.display = (t == 1) ? "block" : "none";
	document.getElementById('duration_select').style.display = (t == 1) ? "block" : "none";
	document.getElementById('labelDest').style.display = (t == 1) ? "block" : "none";
	document.getElementById('divDestInput').style.display = (t == 1 || t == 3) ? "block" : "none";
	
	document.getElementById('divVillaInput').style.display = (t == 2) ? "block" : "none";
	document.getElementById('labelVilla').style.display = (t == 2) ? "block" : "none";
	
	if (qs_resort_tab) {
		acLRtab = (t == 3);
		document.getElementById('labelResort').style.display = (t == 3) ? "block" : "none";
		document.getElementById('destHolder').style.display = (t == 3) ? "none" : "block";
		document.getElementById('lrToggle').style.display = (t == 1) ? "block" : "none";
	}
	
	var package = document.getElementById('divPackageOpt');
	if (package) package.style.display = (t == 1) ? "block" : "none";
	if(is_mobile_user){
		setDestListUp();
	}
}

function toggleLuxury(val) {
	acLuxMode = val;
	document.quicksearch.autocom_villa.value = "";
	if (val) {
		c_srd("lux");
	} else {
		c_srd();
	}
	if(is_mobile_user){
		setDestListUp();
	}
}

function toggleLeisureResort(val) {
	acLRMode = val;
	document.quicksearch.autocom_villa.value = "";
	if (val) {
		c_srd("lr");
	} else {
		c_srd();
	}
	if(is_mobile_user){
		setDestListUp();
	}
}

function port(id,name,type) {
	this.id = id;
	this.name = name;
	this.type = type;
}

function portActionsFunction(run_mode) {
	if (run_mode == 1) {
		var autocom2 = document.getElementById('autocom2').value.split(":");
		var ferryRegions = ",63,64,71,77,82,83,89,28,34,35,80,84,19,17,47,";
		var ferryRegGroups = ",7,8,12,";
		var ferryCountries = ",10,";
		
		if ((
				(autocom2.length >= 3 && ferryRegGroups.indexOf("," + autocom2[0] + ",") > -1 && autocom2[1] == 4)
				|| (autocom2.length >= 3 && ferryCountries.indexOf("," + autocom2[0] + ",") > -1 && autocom2[1] == 5)
				|| (ferryRegions.indexOf("," + cr + ",") > -1)
			) && showAnyDest) {
			var isFerry = true;
			document.getElementById('lbl_airport').style.display = "none";
			document.getElementById('lbl_port').style.display = "";
		} else {
			var isFerry = false;
			document.getElementById('lbl_airport').style.display = "";
			document.getElementById('lbl_port').style.display = "none";
		}

		var selAir = document.quicksearch.dep_air_id;
		var curAirId = selAir.value;
		selAir.length = 0;

		for (var i=0;i<ports.length;i++) {
			if (ports[i].type == 1 || (isFerry && (ports[i].type == 2 || ports[i].id == 15 || ports[i].id == 16 || ports[i].type == 0)) || (!isFerry && ports[i].id != 15 && ports[i].id != 16 && ports[i].type != 2)) {
				var name = ports[i].name;
				if (isFerry && ports[i].type == 0 && ports[i].id != 15 && ports[i].id != 16 && ports[i].id != -1) name += " Airports";
				selAir.options[selAir.length] = new Option(name, ports[i].id);
				if (ports[i].type == 0) selAir.options[selAir.length-1].className = "searchSpecialOpt";
				if (ports[i].id == curAirId) selAir.value = curAirId;
			}
		}
	}
}

function initQSFunction(p_autocom,p_duration,p_air) {
	var selDate = new Date(cy, cm-1, 1);

	/*
	 If we've come from a page where only the region ID has been passed through, the "autocom2" value containing the index
	 for the JavaScript array won't be known (equals 0), so we need to work out that value, then process everything else (eg the calendar) as normal.
	 Used by the lates page for example
	*/

	var ac2 = document.quicksearch.autocom2.value;
	var ac2split = ac2.split(":");
	if (ac2split.length >= 3 && ac2split[2] == 0) {
		for (i=0; i<all_data_dest.length; i++) {
			if (all_data_dest[i][1] == ac2split[0] && all_data_dest[i][data_pos_item_type] == ac2split[1]) {		// ID == region/group ID and type == region/group/resort/villa
				document.quicksearch.autocom.value = all_data_dest[i][0];
				document.quicksearch.autocom2.value = all_data_dest[i][1] + ":" + all_data_dest[i][data_pos_item_type] + ":" + i;
				for (j=0; j<document.quicksearch.aclist.length; j++) {
					if(document.quicksearch.aclist[j].value == all_data_dest[i][1] + ":" + all_data_dest[i][data_pos_item_type] + ":" + i){
						document.quicksearch.aclist.selectedIndex = j;
						break;
					}
				}
				
				break;
			}
		}
	}

	if (document.quicksearch.autocom.value == p_autocom) {
		document.quicksearch.autocom.select();
		updateCal(-1);
	} else {
		if (document.quicksearch.autocom2.value.split(":")[1] == 5) {
			// country, find regions
			updateCal(qsFindRegionsFromCountry());
		} else {
			if (document.quicksearch.autocom2.value.split(":")[1] == 4) {
				// region group, find regions
				updateCal(qsFindRegionsFromGroup());
			} else {
				// got region ID already
				updateCal(qsFindRegion());
			}
		}
	}

	// this block sets the duration to the current value, or defaults to 7 nights if not found
	var found = false;
	for (var i = 0; i < document.quicksearch.duration.length; i++) {
		if (document.quicksearch.duration[i].value == p_duration) {
			document.quicksearch.duration.selectedIndex = i;
			found = true;
			break;
		}
	}
	if (!found) {
		for (var i = 0; i < document.quicksearch.duration.length; i++) {
			if (document.quicksearch.duration[i].value == 7) {
				document.quicksearch.selectedIndex = i;
				break;
			}
		}
	}
	if (p_air != "") {
		var dep_air_obj = document.getElementById('dep_air_id');//.value = p_air;
		for (var i=0; i<dep_air_obj.options.length; i++) {
			if (dep_air_obj.options[i].value == p_air || dep_air_obj.options[i].value == "0"+p_air) {
				dep_air_obj.selectedIndex = i;
				break;
			}
		}
	}
	if (document.getElementById('dep_air_id').value == "") {
		document.getElementById('dep_air_id').selectedIndex = 0;
	}
	prepareSearchFormAction();
}

/* Remove Any Dest option */
function togglePackage(val) {
	var arr = document.quicksearch.autocom2.value.split(":");
	if (arr[0] <= -1) { 
		document.quicksearch.autocom2.value = document.quicksearch.autocom.value = "";
	}
	if (val == "package") {
		showAnyDest = false;
	} else {
		showAnyDest = true;
	}
	setDestListUp();
	portActions();
}

function rebuildLRDestinations() {	
	var dest = document.getElementById('destDropdown');
	if (dest) {
		switchQSTab(qsTab);
		setDestListUp(false);
	}
}

function buildResortsDropdown() {
	var dd = document.getElementById('resortsDropdown');
	if (dd) {
		dd.options.length = 1;

		lr_data = new Array();
		for (var i=0;i<all_data_dest.length;i++) {
			if (all_data_dest[i][3] == 2 && all_data_dest[i][4] == 1) { // resort
				lr_data[lr_data.length] = all_data_dest[i];
			}
		}
		lr_data.sort(compareLRName);
		
		for (var i=0;i<lr_data.length;i++) {
			dd[dd.length] = new Option(cropWord(lr_data[i][0]), lr_data[i][1]);
		}
		
	}
}

function compareLRName(a,b) {
	var x = a[0].toLowerCase();
	var y = b[0].toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}	

function cropWord(word, maxLen) {
	if (maxLen == undefined) maxLen = 28;
	var le = word.split(" ");
	var c = 0;
	var newWord = "";
	for (var i=0;i<le.length;i++) {
		if (newWord.length + le[i].length <= maxLen) {
			if (newWord != "") newWord += " ";
			newWord += le[i];
		} else {
			newWord += "...";
			break;
		}
	}
	return newWord;
}

function submitLeisureResort() {
	if ($('#resortsDropdown').val() != -1) {
		$('#search_mode').val('resort');
		$('#quicksearch').attr('action', '/leisure-resorts/search/').submit();		
	} else {
		alert("Please select a Leisure Resort");
	}
}

function numPerCountry(results, countryId) {
	var num = 0;
	for (var i=0;i<results.length;i++) {
		if (results[i].countryId == countryId) {
			num++;
		}
	}
	return num;
}

function setLRFilters() {
	document.getElementById('destId').value = document.getElementById('destDropdown').value;
	if (typeof setFilters == 'function') {
		setFilters();
	}
}

function hoverQs(state) {
	var arrow = document.getElementById('qs_arrow');
	var src;
	if(arrow){
		switch (state) {
			case 1:
				arrow.src = '/images/arrows/qs_arrow_hover.gif';
				break;
			case 2:
				arrow.src = '/images/arrows/qs_arrow_click.gif';
				break;
			default:
				arrow.src = '/images/arrows/qs_arrow.gif';
		}
	}
}

function prepareSearchFormAction() {
	var newAction = "";
	if (validateSearch() == null) {
		var paxa = document.quicksearch.paxa;
		var paxc = document.quicksearch.paxc;
		var paxi = document.quicksearch.paxi;

		newAction = "/qsearch/?autocom2="+document.quicksearch.autocom2.value + "&autocom=" + document.quicksearch.autocom.value;
		newAction = newAction + "&dep_date=" + document.quicksearch.dep_date.value + "&duration=" + document.quicksearch.duration.value ;
		newAction = newAction + "&paxa=" + paxa.options[paxa.selectedIndex].text + "&paxc=" + paxc.options[paxc.selectedIndex].text + "&paxi=" + paxi.options[paxi.selectedIndex].text;
		newAction = newAction + "&dep_air_id=" + document.quicksearch.dep_air_id.value;
	
		if (document.quicksearch.lux && document.quicksearch.lux[0].checked) {
			newAction = newAction + "&lux=1";	
		}
		if (document.quicksearch.lr && document.quicksearch.lr[0].checked) {
			newAction = newAction + "&lr=1" ;	
		}
	} else {
		newAction = "";
	}
	document.getElementById("qsearchButton").href=newAction;
}
