window.addEvent('domready', function() {

	new Accordion($('tc'), '#tc_click', '#tc',{
  		display: -1,
		alwaysHide: true});
});

function GetXmlHttpObject()
{
  if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }
  if (window.ActiveXObject)
  {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  alert ("Browser does not support HTTP Request");
    return;
}

function HolidayChoices(loc)
{
  var choice = $("holiday_type").value;
  
  
  if(loc == 'rightCol') {
  	if(choice == '') {
  		$('holidayOptions').setStyle('display','none');
  	} else {
  		$('holidayOptions').setStyle('display','inline');
  	}
  }

  if (choice == 'tents_touring') {
	$('hot_tub').style.display='none';  
	$('decking').style.display='none';  
	$('dog').style.display='inline';  
	$('nights_apartments').style.display='none';
	$('nights_tents').style.display='inline';
  } else if (choice == 'holiday_homes') {
	$('hot_tub').style.display='inline';  
	$('decking').style.display='inline';  	  
	$('dog').style.display='none';
	$('dog0').selected=true;
	$('nights_apartments').style.display='inline';
	$('nights_tents').style.display='none';
  } else if (choice == 'holiday_homes_pet') {	  
	$('hot_tub').style.display='none';  
	$('decking').style.display='inline';  
	$('dog').style.display='inline'; 
	$('nights_apartments').style.display='inline';
	$('nights_tents').style.display='none';
  } else if (choice == 'apartments') {	  
	$('hot_tub').style.display='none';  
	$('decking').style.display='none';  
	$('dog').style.display='none'; 
	$('dog0').selected=true;
	$('nights_apartments').style.display='inline';
	$('nights_tents').style.display='none';
  }
	
}

function hotTubDecking() {
	
	if($('hot_tub_chk').checked == true && $('holiday_type').value == 'holiday_homes') {
		$('decking_chk').set('checked','checked');
	} else {
		$('decking_chk').set('checked','');
	}
}

/*function BuildCal() {
	var choice;
	var date = $('arrival_date');
	if ($("nights"))
		choice = $("nights").value;
if ($('cal')) {
  if (choice == '3 Nights (Fri-Mon)') {
	  $('cal').innerHTML = '<input class="formText roundedAll formDate" type="text" name="arrival_date" id="arrival_date" value="'+$('arrival_date').value+'" onclick="scwShow(this,event,0,1,2,3,4,6);" /><img src="/imgs/bookOnline/calendar.png" class="calImg" border="0" onclick="scwShow($(\'arrival_date\'),event,0,1,2,3,4,6);" />';
  } else if (choice== '4 Nights (Mon-Fri)') {
	$('cal').innerHTML = '<input class="formText roundedAll formDate" type="text" name="arrival_date" id="arrival_date" value="'+$('arrival_date').value+'" onclick="scwShow(this,event,0,2,3,4,5,6);" /><img src="/imgs/bookOnline/calendar.png" class="calImg" border="0" onclick="scwShow($(\'arrival_date\'),event,0,2,3,4,5,6);" />';  
  } else {
	$('cal').innerHTML = '<input class="formText roundedAll formDate" type="text" name="arrival_date" id="arrival_date" value="'+$('arrival_date').value+'" onclick="scwShow(this,event);" /><img src="/imgs/bookOnline/calendar.png" class="calImg" border="0" onclick="scwShow($(\'arrival_date\'),event);" />';
  }
}	
}*/


function BuildCal(selectList) {
	var choice;
	
	if (selectList == 1) {
		choice = '';
	} else {
		choice = $('nights').value;
	}

	var html = '<input class="formText roundedAll formDate" type="text" name="arrival_date" id="arrival_date" value="'+ $('arrival_date').value +'" /><img id="datePicker" class="calImg" src="/imgs/bookOnline/calendar.png" border="0" />';
	
	if ($('cal')) {
		
		$('cal').innerHTML = html;
		
		if (choice == '3 Nights (Fri-Mon)') {
			
			new CalendarEightysix('arrival_date', { 
							'toggler': 'datePicker',
							'disallowUserInput': true,
							'offsetX': -200,
							'minDate': '03/16/2012',
							'maxDate': '11/04/2012',
							'format': '%d %B %Y',
							'excludedWeekdays': [0, 1, 2, 3, 4, 6]
						});

			
		} else if (choice == '4 Nights (Mon-Fri)') {
			
			new CalendarEightysix('arrival_date', { 
							'toggler': 'datePicker',
							'disallowUserInput': true,
							'offsetX': -200,
							'minDate': '03/16/2012',
							'maxDate': '11/04/2012',
							'format': '%d %B %Y',
							'excludedWeekdays': [0, 2, 3, 4, 5, 6]
						});
			
		} else if (choice == '7 Nights') {
			
			new CalendarEightysix('arrival_date', { 
							'toggler': 'datePicker',
							'disallowUserInput': true,
							'offsetX': -200,
							'minDate': '03/16/2012',
							'maxDate': '11/04/2012',
							'format': '%d %B %Y',
							'excludedWeekdays': [0, 2, 3, 4]
						});
		
		} else if (choice == '14 Nights') {
			
			new CalendarEightysix('arrival_date', { 
							'toggler': 'datePicker',
							'disallowUserInput': true,
							'offsetX': -200,
							'minDate': '03/16/2012',
							'maxDate': '11/04/2012',
							'format': '%d %B %Y',
							'excludedWeekdays': [0, 1, 2, 3, 4, 5]
						});
		
		} else {
			
			new CalendarEightysix('arrival_date', { 
							'toggler': 'datePicker',
							'disallowUserInput': true,
							'offsetX': -200,
							'minDate': '03/16/2012',
							'maxDate': '11/04/2012',
							'format': '%d %B %Y'
						});
		}
	}	
}

function togglePitchBox(acc_sel,phpsess) {
	if ($('specific_pitch_request_(per_pitch)').checked)
		$('pitch_box').style.display = 'block';
	else {
		$('pitch_box').style.display = 'none';
		$('pitch').value="";
	}
 	CalcSubTotal(acc_sel,phpsess);
}

function ToggleCarRegistration() {
	if ($('driving').checked)
		$('vehicle_reg').style.display = 'block';
	else
		$('vehicle_reg').style.display = 'none';	
}

function toggleTC() {
	alert($('tc').style.display);
	if ($('tc').style.display == 'block')
		$('tc').style.display = 'none';
	else if ($('tc').style.display == 'none')
		$('tc').style.display = 'block';	
}

function hideConfirm() {
	$('bookingConfirm').style.display = 'none';
	$('confirmTitle').style.display = 'none';
	$('backBtn').style.display = 'none';
	$('confirmBtn').style.display = 'none';
	$('depositInfo').style.display = 'none';
}

function showBusyCursor() {
	document.body.style.cursor = "wait";
}

function PostcodeAnywhere() {
	var pcode = $("postcode").value;
	
	if (pcode == '')
		return;
	document.body.style.cursor = "wait";
	xmlhttp=GetXmlHttpObject();
	var url="/gateway/ajaxBookOnline.php"
	var params="addr_lookup=1&pcode="+encodeURIComponent(pcode);
	xmlhttp.onreadystatechange= function() { 
		if (xmlhttp.readyState==4) {
			if (xmlhttp.status==200) {
				SetAddr(xmlhttp);
			}
		}
	}
	xmlhttp.open("POST",url,true);
	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	function SetAddr() {
		$('addr_sel').style.display = 'block';
		$('addr_sel').innerHTML=xmlhttp.responseText;
		document.body.style.cursor = "default";
	}
}

function SelectAddr() {
	var choice = $("sel_addr").value; 

	xmlhttp=GetXmlHttpObject();
	var url="/gateway/ajaxBookOnline.php"
	var params="addr_get=1&addr_id="+encodeURIComponent(choice);
	xmlhttp.onreadystatechange= function() { 
		if (xmlhttp.readyState==4) {
			if (xmlhttp.status==200) {
				SetAddrFields(xmlhttp);
			}
		}
	}
	xmlhttp.open("POST",url,true);
	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	function SetAddrFields() {
		var vals = xmlhttp.responseText.split('||~||');
		$('addr1').value=vals[0];
		$('addr2').value=vals[1];
		$('county').value=vals[2];
		$('addr_sel').style.display = 'none';
	}
}

function SortData(usage,dogs_cnt,holiday_type,adate,ldate,a,c,i,d,h,peak) {
	/*if ($("sort_results") == null)
		return;*/
	
	if ($('sort_results')) {
		var choice = $("sort_results").value;
	} else {
		var choice = 'price_low';
	}

/*	if (choice == '')
		return false;*/
	
	if(peak) {
		$('hiddenMsgTxt').innerHTML = 'We\'re just finding the accommodation for your perfect holiday.<br />The minimum stay during peak periods is 4 nights, we have amended your stay accordingly - please click Amend Booking if you want to change your arrival date';	
	} else {
	
		if (usage == 'sort') {
			$('hiddenMsgTxt').innerHTML = 'Just a second while we re-sort the list.';
		} else {
			$('hiddenMsgTxt').innerHTML = 'We\'re just finding the accommodation for your perfect holiday.';
		}
	}
	
	showPopup('400 150');
	xmlhttp=GetXmlHttpObject();
	var url="/gateway/ajaxBookOnline.php"
	var params="sort_search_results=1&dogs="+dogs_cnt+"&holiday_type="+encodeURIComponent(holiday_type)+"&sortby="+encodeURIComponent(choice);
	params=params+"&arrival_date="+encodeURIComponent(adate)+"&leave_date="+encodeURIComponent(ldate)+"&adults="+encodeURIComponent(a);
	params=params+"&children="+encodeURIComponent(c)+"&infants="+encodeURIComponent(i)+"&decking="+encodeURIComponent(d);
	params=params+"&hot_tub="+encodeURIComponent(h);
	xmlhttp.onreadystatechange= function() { 
		if (xmlhttp.readyState==4) {
			if (xmlhttp.status==200) {
				SortList(xmlhttp);
			}
		}
	}
	xmlhttp.open("POST",url,true);
	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	function SortList() {
		var resp = trim(xmlhttp.responseText);
		if (resp == '')
			alert("nothing here");
		$("search_results").innerHTML=resp;
		$("sum_arr_date").innerHTML = adate;
		$("sum_lea_date").innerHTML = ldate;
		Mediabox.scanPage();
		killPopup();
	}
}

function showPopupMsg(dim) {
	
	if($('hiddenMsgTxt').innerHTML != 'ignore') {
		showPopup(dim);
		setTimeout('killPopup()',3000);
	}
}

function showPopup(dim) {
	Mediabox.open('#mb_hiddenMsg','',dim);
	$('mbCloseLink').setStyle('display','none');
	$('mbBottom').setStyle('min-height','0');
}
function killPopup() {
	Mediabox.close();
	$('mbCloseLink').setStyle('display','block');
	$('mbBottom').setStyle('min-height','50px');
	return false;
}

function CalcSubTotal(val,phpsessid) {
	var subt = parseFloat($("subtotal").innerHTML);

	xmlhttp=GetXmlHttpObject();
	var url="/gateway/ajaxBookOnline.php"
	var params = "calc_subtotal=1&phpsessid="+encodeURIComponent(phpsessid)+"&accommo_selected="+encodeURIComponent(val)+"&tent_nights="+$('tent_nights').innerHTML;
	
	if ($('cot'))
		params=params+"&cot="+$('cot').value;
	if ($('high_chair'))
		params=params+"&high_chair="+$('high_chair').value;
	if ($('bed_guard'))
		params=params+"&bed_guard="+$('bed_guard').value;
	if ($('push_chair'))
		params=params+"&push_chair="+$('push_chair').value;
	if ($('safety_gate'))
		params=params+"&safety_gate="+$('safety_gate').value;
	if ($('single_set_linen'))
		params=params+"&single_set_linen="+$('single_set_linen').value;
	if ($('double_set_linen'))
		params=params+"&double_set_linen="+$('double_set_linen').value;
	if ($('swimming_pool_pass_adult_weekly'))
		params=params+"&swimming_pool_pass_adult_weekly="+$('swimming_pool_pass_adult_weekly').value;
	if ($('swimming_pool_pass_child_weekly'))
		params=params+"&swimming_pool_pass_child_weekly="+$('swimming_pool_pass_child_weekly').value;
	if ($('extra_vehicle')) {
		if ($('extra_vehicle').checked)
			params=params+"&extra_vehicle="+$('extra_vehicle').value;
	}
	if ($('wifi_-_1_day')) {
		if ($('wifi_-_1_day').checked)
			params=params+"&wifi_-_1_day="+$('wifi_-_1_day').value;
	}
	if ($('wifi_-_2_days')){
		if ($('wifi_-_2_days').checked)
			params=params+"&wifi_-_2_days="+$('wifi_-_2_days').value;
	}
	if ($('wifi_-_week')) {
		if ($('wifi_-_week').checked)
			params=params+"&wifi_-_week="+$('wifi_-_week').value;
	}
	if ($('wifi_-_month')) {
		if ($('wifi_-_month').checked)
			params=params+"&wifi_-_month="+$('wifi_-_month').value;
	}
	if ($('specific_pitch_request_(per_pitch)')) {
		if ($('specific_pitch_request_(per_pitch)').checked)
			params=params+"&specific_pitch_request_(per_pitch)=yes";
	}
	
	xmlhttp.onreadystatechange= function() { 
		if (xmlhttp.readyState==4) {
			if (xmlhttp.status==200) {
				ShowSubTotal(xmlhttp);
			}
		}
	}
	xmlhttp.open("POST",url,true);
	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
//	xmlhttp.setRequestHeader("User-Agent",ua);
	xmlhttp.send(params);
	function ShowSubTotal() {
		var txt = trim(xmlhttp.responseText);
		$("subtotal").innerHTML=txt;
// don't want to update this - it's not the subtotal, it's the accommo charge		
// 		$("subtotalLeft").innerHTML=txt;
	}
}

function trim (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

function printMe(elem) {
	var printContents = $(elem).innerHTML;
	var originalContents = document.body.innerHTML;

	document.body.innerHTML = printContents;
	window.print();
	document.body.innerHTML = originalContents;
}

function submitForm(formName, navigateValue) {
	if (navigateValue != null && navigateValue != "") {
		document.forms[formName].navigate.value = navigateValue;
	}
    document.forms[formName].submit();
}

/*
function utf8_encode (argString) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // +   bugfixed by: Rafal Kukawski
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    if (argString === null || typeof argString === "undefined") {
        return "";
    }

    var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
        start, end, stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);
            }
            utftext += enc;
            start = end = n + 1;
        }
    }

    if (end > start) {
        utftext += string.slice(start, stringl);
    }

    return utftext;
}

function base64_encode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Rafał Kukawski (http://kukawski.pl)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    data = this.utf8_encode(data + '');

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1 << 16 | o2 << 8 | o3;

        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');
    
    var r = data.length % 3;
    
    return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}*/

