var gmarkers = [];
var htmls = [];
var titles = [];
var propids = [];
var thelabels = [];
var map;

$(document).unload(function(){
	GUnload();
});

$(document).ready(
	function(){
	
	// $('#welcomecontainer').animate({left:730,opacity: 'show'},5000);
	
	$('#welcomecontainer').click(function(){
			$(this).fadeOut(2000);
	});
	
	accordion = $('#navigation').Accordion({
		active: true,
    header: '.head',
    navigation: true,
    event: 'click',
    autoheight: true,
    animated: 'easeslide'
	});
	
	$('#loginbutton').click(function(){
		if($('#loginbutton').val() == 'Log In'){
			window.location.href = '/login.php';
		}else{
			if(confirm("Do you really wish to log out?")) window.location.href = '/process.php';
		}
	});
		
	$('.media').media( {  width: 955, height: 154, autoplay: true } );

	$('.rounded').corner("sc:#009 round 8px").parent().css('padding', '4px').corner("round 10px")

	/* hotel search page functions */
	if(window.location.pathname == '/hsearch.php'){
		if(!$.jqURL.get('action') || $.jqURL.get('action') == 'newsearch' || $.jqURL.get('action') == 'modifysearch'){ // no action requested, main search page
					// Active the search area
					
					// check for values on returning to current search
					currentPropCountry = $.cookie('currentpropcountry');
					currentAirportCode = $.cookie('currentairportcode');
					
					if($.jqURL.get('action') == 'modifysearch'){
						if(currentAirportCode != "") {
							$('#aircode').val(currentAirportCode);
						}
						
						if(currentPropCountry != null && currentPropCountry != "" && $.jqURL.get('action') == 'modifysearch'){
							$('#country').selectOptions(currentPropCountry);
							populateStates();
						}else{
							$("select#country option:first").attr("selected","selected");
						}
						updateOtherFields();
					}
					$("#country").change(function(){
							if($(this).val() == ""){
									return false;
							}
							populateStates();
  				});
					$("#state").change(function(){
							populateCities();
					});
		}
		if($.jqURL.get('action') == 'details'){
			accordion.activate(2);

			if(doMap()){
				var myLong = $('#longitudeval').val();
				var myLat = $('#latitudeval').val();
				try{
					startGmapping();
				}catch(err){
					if(console) console.log(err);
					//do nothing
				}
				$('#discounttype').change(function(){
					startGmapping();
				});
			}
		}
		if($.jqURL.get('action') == 'getResults'){
			accordion.activate(2);
		}
		$('#closeme').click(function(){
				$('#floatingdetails').css({"display":"none","z-index":"-999"});
		});
		}
		if($.jqURL.get('action') == 'block'){
			init();
		}
		
	});
	
function updateOtherFields(){
	var currenthoteltype = $.cookie('currenthoteltype');
	var currenthotelchain = $.cookie('currenthotelchain');
	var currentdiscounttype = $.cookie('currentdiscounttype');
	   
	if(currenthoteltype != null && currenthoteltype.length > 0) $('#hoteltype').selectOptions(currenthoteltype);
	if(currenthotelchain != null && currenthotelchain.length > 0) $('#hotelchain').selectOptions(currenthotelchain);	
	if(currentdiscounttype != null && currentdiscounttype.length > 0) $('#discounttype').selectOptions(currentdiscounttype);
	
}
function activateRightMenu(){
	myareas = array();
	accordion.activate(2);
	
	$(document).find('a').filter(function(){
 		if(this.href == 'http://hfhcurrent/hsearch.php?action=modifysearch'){   
  		$(this).addClass('current');
  		console.log(this.href);
		}
	});
}
/* 
 * 
 * check for values in lat/long and supported countries 
 */
function doMap(){
	var validcountry = false;
	var validvalues = false;
	$.each(["UNITED STATES","CANADA","UNITED KINGDOM","JAPAN","IRELAND","FRANCE","GERMANY","ITALY","SPAIN","BRAZIL"],function(i,n){
				if($('#propcountry').val() == n) validcountry = true;
	});
	if( typeof($('#gmapping]')) == 'object' &&	$('#longitudeval').val() != "" && $('#latitudeval').val() != ""){
		validvalues = true;
	}
	return validcountry && validvalues;
}

function populateStates(){
	clearOptions('state');
	clearOptions('city');
	
	if($('#country').val() == 'UNITED STATES' || $('#country').val() == 'CANADA'){
		$("select#state").removeAttr('disabled');
		getStates();
	}else{
		$("select#state").attr('disabled',true);
		populateCities();
	}
}

function getStates(){
	currentStateVal = $.cookie('currentpropstateprov');
	$.get("/cityRequest.php",{action: 'getStates', country: $("select#country").val()}, function(data){
    	$("select#state").removeAttr('disabled');
			$("select#state").html(data);
			$("select#state option:first").attr("selected","selected");
			if(currentStateVal != null && currentStateVal != "" && $.jqURL.get('action') == 'modifysearch'){
				$('#state').selectOptions(currentStateVal);
				$('#state').trigger("change");
			}else{
				$("select#state option:first").attr("selected","selected");
			}
		});
}

function populateCities(){
	currentCityVal = $.cookie('currentpropcity');
	clearOptions('city');
	$.get("/cityRequest.php",{action: 'getCities', state: $('#state').val(), country: $("select#country").val()}, function(data){
		$("select#city").html(data);
		if(currentCityVal != null && currentCityVal != "" && $.jqURL.get('action') == 'modifysearch'){
			$('#city').selectOptions(currentCityVal);
			$('#city').trigger("change");
		}else{
			$("select#city option:first").attr("selected","selected");
		}
	});
}

function clearOptions(which){
	var options = '<option value="" selected="selected">-- Select --</option>';
	$("select#"+which).html(options);
}


/* search form MUST have 3 chars airport code or a country selected */
function validateSearchForm(){
	var returnValue = true;
	var aircodeValue = $('#aircode').val();
	var countryValue = $('#country').val();
	var cityValue = $('#city').val();
	var stateValue = $('#state').val();
	var errorMessage = '';
		
	if(aircodeValue.length == 3){
		returnValue = true;
	}else{
		if(countryValue == ""){
			errorMessage = errorMessage + "You must enter an airport code or select a country from the dropdown\n.";
			returnValue = false;
		}
		if((countryValue == 'UNITED STATES' || countryValue == 'CANADA') && stateValue == ''){
			errorMessage = errorMessage + "You must select a state when searching U.S. or Canada";
			returnValue = false;
		}
		if(cityValue == '' && aircodeValue.length != 3 ){
			errorMessage = errorMessage + "You must select a city";
			returnValue = false;
		}
	}
	
	
	
	if(returnValue){
		$.cookie('currentpropcountry',countryValue);
		$.cookie('currentpropstateprov',stateValue);
		$.cookie('currentpropcity',cityValue);
		$.cookie('currentairportcode',$('#aircode').val());
		$.cookie('currenthoteltype',$('#hoteltype').val());
		$.cookie('currenthotelchain',$('#hotelchain').val());	
		$.cookie('currentdiscounttype',$('#discounttype').val());		
		$('#blocker').block('<div class="progressbar">Searching...</div>', { border: '3px solid #cecece' });
	}
	return returnValue;
}

/* function to prompt user whether he/she really intends to log out. */
function logoutPropmpt(){
		var answer;
		answer = confirm("Do you really wish to log out?");
		if(answer)
				return true;
		else
				return false;
}

/* function to prompt user whether he/she really intends to delete a record. */
function deletePropmpt(){
		var answer;
		answer = confirm("Do you really wish to set this record to completed?");
		if(answer)
				return true;
		else
				return false;
}

function checkFields() {
	missinginfo = "";
	if ((document.blockspace.numrooms.selectedIndex == 0) ||
	(document.blockspace.roomtype.selectedIndex == 0) ||
	(document.blockspace.occupants.selectedIndex == 0) ||
	(document.blockspace.checkin.value == "") ||
	(document.blockspace.checkout.value == "")) {
		missinginfo += "\n     -  All Room Details fields must be filled out.";
	}

	if(!checkDates(document.blockspace.checkin.value))
		missinginfo += "\n     -  Check-In Date must be 48 hours in advance.";

	if (document.blockspace.requested_by.value == "") {
		missinginfo += "\n     -  Requested by is missing.";

	}
	if(document.blockspace.traveler1.value == "") {
		missinginfo += "\n     -  Traveller Name is missing.";
	}
	if(document.blockspace.ccnum.value == "") {
		missinginfo += "\n     -  Credit Card Number is missing.";
	}
	if(document.blockspace.expdate.value == "") {
		missinginfo += "\n     -  Credit Card Expiration Date is missing.";
	}
	if (document.blockspace.agent.value == "") {
		missinginfo += "\n     -  Agent's Name is missing.";

	}

	if ((document.blockspace.agentemail.value == "") ||
	(document.blockspace.agentemail.value.indexOf('@') == -1) ||
	(document.blockspace.agentemail.value.indexOf('.') == -1)) {
		missinginfo += "\n     -  Agent Email Address is missing";
	}

	if (document.blockspace.agentemail.value != document.blockspace.agentemailcheck.value) {
		missinginfo += "\n     -  Agent's Email do not match.";

	}
	if (document.blockspace.agentphone.value == "") {
		missinginfo += "\n     -  Agent's Phone Number is missing.";

	}
	if (document.blockspace.agentfax.value == "") {
		missinginfo += "\n     -  Agent's Fax Number is missing.";

	}
	if (document.blockspace.agency_name.value == "") {
		missinginfo += "\n     -  Agency Name is missing.";

	}

	if (document.blockspace.iata.value == "") {
		missinginfo += "\n     -  Agency ID is missing.";

	}
	if (document.blockspace.idtype.selectedIndex == 0) {
		missinginfo += "\n     -  Agency ID type is missing.";

	}



	if (missinginfo != "") {
		missinginfo ="_____________________________\n" +
		"You failed to correctly fill in your:\n" +
		missinginfo + "\n_____________________________" +
		"\nPlease re-enter and submit again!";
		alert(missinginfo);
		return false;
	}
	return true;
}

function checkDates(checkindate){
	selectedDate = checkindate;
	var dateArray = selectedDate.split("-");
	dateArray[1]--;
	var bookdate = new Date();
	bookdate.setFullYear(dateArray[0],dateArray[1],dateArray[2]);

	var today = new Date();

	var maxDate = new Date();
	maxDate.setDate(today.getDate()+2);
	if(bookdate >= maxDate)
		return true
	else
		return false;

}

function validateBlockspaceAdmin(){
	missinginfo = "";

	if (document.blockspace.type.selectedIndex == 0) {
		missinginfo += "\n     -  Select and Action.";
		alert(missinginfo);
		return false;
	}

	var myType = document.blockspace.type.options[document.blockspace.type.selectedIndex].value;
	if(myType == 'faxcomplete' || myType == 'completed'){
		if(document.blockspace.confnumber.value == ""){
			alert("Confirmation number must be provided to flag the record as completed.");
			return false;
		}
	}
	var answer;
	answer = confirm("Do you really wish to set this record as "+myType+"?");
	if(answer)
		return true;
	else
		return false;

}

function toggleLayer(whichLayer){
	if (document.getElementById){
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = style2.display? "":"block";
	}else if (document.all){
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = style2.display? "":"block";
	}else if (document.layers){
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = style2.display? "":"block";
	}
}

function changeLink(){
	var fileSelected = 		document.news.existingfilename.selectedIndex;
	var filenameSelected = 	document.news.existingfilename.options[fileSelected].value;
	document.getElementById('downloadAnchor').innerHTML=filenameSelected;
	var url = '/downloadfile.php?filename='+filenameSelected;
	document.getElementById('downloadAnchor').href=url;
	//document.getElementById('downloadAnchor').target="_blank"

}

function MM_findObj(n, d) { //v4.01
  	var p,i,x;
  	if(!d)
		d=document;
  	if((p=n.indexOf("?"))>0&&parent.frames.length) {
    	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
  	if(!(x=d[n])&&d.all)
		x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++)
		x=d.forms[i][n];
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++)
		x=MM_findObj(n,d.layers[i].document);
  	if(!x && d.getElementById)
		x=d.getElementById(n);
	return x;
}

/* macromedia functions used to validate some form (on hold) */
function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) {
  	test=args[i+2]; val=MM_findObj(args[i]);
    if (val) {
		nm=val.name;
		if ((val=val.value)!="") {
      		if (test.indexOf('isEmail')!=-1) {
				p=val.indexOf('@');
        		if (p<1 || p==(val.length-1))
					errors+='- '+nm+' must contain an e-mail address.\n';
      		} else if (test!='R') { num = parseFloat(val);
        		if (isNaN(val))
					errors+='- '+nm+' must contain a number.\n';
        		if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          			min=test.substring(8,p); max=test.substring(p+1);
          		if (num<min || max<num)
					errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    		}
		}
	} else if (test.charAt(0) == 'R')
		errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}