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

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

jQuery(document).ready(
	function(){
		
		jQuery('#constantcontact').click(function(){
		  jQuery.blockUI({
				message: jQuery('#subscribetopromos'), 
				css: {
					width: '300px'
					} 
			});
			return false;
		 });
		 jQuery('#subscribetopromosclose').click(function(){
				jQuery.unblockUI();
		 });
	 
		jQuery('#ientry-bar-right').click(function(){
		if(jQuery('#loginbuttonvalue').val() == 'Log In'){
			window.location.href = '/login.php';
		}else{
			if(confirm("Do you really wish to log out?"))
				window.location.href = '/process.php';
			else
				return false;
		}
		});
	
		jQuery('#registerform').submit(function(){
			return validateRegistration();	
		});
	/* hotel search page functions */
	if(window.location.pathname == '/register.php'){
		
		if(jQuery('#agencyinformation').length > 0){
			jQuery('#agencyinformation').slideUp();
			jQuery('#hotelinformation').slideUp();
			jQuery('#accounttype').change();
			jQuery('#accounttype').change(function(){
				var selectedvalue = jQuery('#accounttype').val();
				switch (selectedvalue) {
					case 'agency':
						jQuery('#agencyinformation').slideDown();
						jQuery('#hotelinformation').slideUp();
						break;
					case 'hotel':
						jQuery('#agencyinformation').slideUp();
						jQuery('#hotelinformation').slideDown();
						break;
					default:
						jQuery('#agencyinformation').slideUp();
						jQuery('#hotelinformation').slideUp();
				}
			});
		}
	}	
	
	if(window.location.pathname == '/agents.php' || window.location.pathname == '/hotel.php'){
		jQuery('#content').width('900px');
		jQuery('#innercontent').width('940px').css('background','url("/img/subbg.jpg") bottom right no-repeat').css('margin-top','-10px');
	}else{
		jQuery('#content').css('background', 'url("/images/frontbg.jpg") bottom right no-repeat');
	}
	if(window.location.pathname == '/hsearch.php'){
		var queryString =jQuery.deparam.querystring(); 
		
		if(queryString.action == 'getResults' || queryString.action == 'details'){		
			
			jQuery('#sendtofriendform').ajaxForm(function() { 
	            alert("Message sent, thank you."); 
	        });
			
			jQuery('a.anicon').click(function(){
				var propid = jQuery(this).attr('title');
				jQuery('#emailtofriendpropid').val(propid);
				
				jQuery.blockUI({
					message: jQuery('#sendtofrienddiv'), 
					css: {
						width: '300px'
						} 
				});
				return false;
			});
			jQuery('#sendtofriendclose').click(function(){
				jQuery.unblockUI();
			});
			
			jQuery('#sendtofriendbutton').click(function(){
		        jQuery('#sendtofriendform').submit();
		        jQuery.unblockUI();
		      });
			
			jQuery('.theicons').qtip({
				style: { name: 'blue', tip: true },
				position: {
				      corner: {
				         target: 'topLeft',
				         tooltip: 'bottomRight'
				      }
				   } 
			});
		}
		if(!queryString.action){ // no action requested, render main search page
			// check for values on returning to current search
			
			jQuery('#amenities').toggle();
			jQuery('#moreoptions').click(function(){
				var wordIs = jQuery("b",this).text() == 'More'? 'Less' : 'More';
				jQuery("b",this).text(wordIs);
				jQuery('#amenities').toggle();
				return false;
			});
			
			currentPropCountry = jQuery.cookie('currentpropcountry');
			currentAirportCode = jQuery.cookie('currentairportcode');
			
			jQuery("#country").change(function(){
					if(jQuery(this).val() == ""){
							return false;
					}
					populateStates();
			});
			jQuery("#state").change(function(){
					populateCities();
			});
		}else{ 
			if(queryString.action == 'modifysearch'){
				if(currentAirportCode != "") {
					jQuery('#aircode').val(currentAirportCode);
				}
				
				if(currentPropCountry != null && currentPropCountry != "" ){
					jQuery('#country').selectOptions(currentPropCountry);
					populateStates();
				}else{
					jQuery("select#country option:first").attr("selected","selected");
				}
				updateOtherFields(); 
			}
			if(queryString.action == 'details'){
				//jQuery("img[rel]").overlay({effect: 'apple'});
				if(doMap()){
					
					var myLong = jQuery('#longitudeval').val();
					var myLat = jQuery('#latitudeval').val();
					try{
						startGmapping();
					}catch(err){
					//	if(console) console.log(err);
						//do nothing
					}
					jQuery('#discounttype').change(function(){
						startGmapping();
					});
				}
				jQuery('#closeme').click(function(){
					jQuery('#floatingdetails').css({"display":"none","z-index":"-999"});
				});
			}
		}
	}
});
	
function validateRegistration(){
	var returnval = true;
	var message = '';
	var registerfields = new Array(
			'#contact',
			'#email',
			'#phone'
	);
	switch(jQuery('#accounttype').val()){
	case 'agency':
		registerfields.push('#agency','#iata','#pseudo');
		break;
	case 'hotel':
		registerfields.push('#hotelbrand','#chaincode');
		break;
	default:
		registerfields.push('#accounttype');
	}
	
	jQuery.each(registerfields,function(i,n){
		if(jQuery(n).val() == ''){
			jQuery(n).addClass('registererror');
			returnval = false;
		}else{
			jQuery(n).removeClass('registererror');
		}		
	});	
	if(!returnval){
		jQuery.growlUI('Error!', 'Some fields were left blank. Please review your entries.'); 
	}
	return returnval;
}

function updateOtherFields(){
	var currenthoteltype = jQuery.cookie('currenthoteltype');
	var currenthotelchain = jQuery.cookie('currenthotelchain');
	var currentdiscounttype = jQuery.cookie('currentdiscounttype');
	   
	if(currenthoteltype != null && currenthoteltype.length > 0) jQuery('#hoteltype').selectOptions(currenthoteltype);
	if(currenthotelchain != null && currenthotelchain.length > 0) jQuery('#hotelchain').selectOptions(currenthotelchain);	
	if(currentdiscounttype != null && currentdiscounttype.length > 0) jQuery('#discounttype').selectOptions(currentdiscounttype);
	
}
function activateRightMenu(){
	myareas = array();
		
	jQuery(document).find('a').filter(function(){
 		if(this.href == 'http://hfhcurrent/hsearch.php?action=modifysearch'){   
  		jQuery(this).addClass('current');
  		console.log(this.href);
		}
	});
}
/* 
 * 
 * check for values in lat/long and supported countries 
 */
function doMap(){
	var validcountry = false;
	var validvalues = false;
	jQuery.each(["UNITED STATES","CANADA","UNITED KINGDOM","JAPAN","IRELAND","FRANCE","GERMANY","ITALY","SPAIN","BRAZIL"],function(i,n){
				if(jQuery('#propcountry').val() == n) validcountry = true;
	});
	
	if( typeof(jQuery('#gmapping')) == 'object' &&	jQuery('#longitudeval').val() != "" && jQuery('#latitudeval').val() != ""){
		validvalues = true;
	}
	
	return validcountry && validvalues;
}

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

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

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

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


/* search form MUST have 3 chars airport code or a country selected */
function validateSearchForm(){
	
	var returnValue = true;
	var aircodeValue = jQuery('#aircode').val();
	var countryValue = jQuery('#country').val();
	var cityValue = jQuery('#city').val();
	var stateValue = jQuery('#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){
		jQuery.cookie('currentpropcountry',countryValue);
		jQuery.cookie('currentpropstateprov',stateValue);
		jQuery.cookie('currentpropcity',cityValue);
		jQuery.cookie('currentairportcode',jQuery('#aircode').val());
		jQuery.cookie('currenthoteltype',jQuery('#hoteltype').val());
		jQuery.cookie('currenthotelchain',jQuery('#hotelchain').val());	
		jQuery.cookie('currentdiscounttype',jQuery('#discounttype').val());
		jQuery.growlUI('Searching...', '');
		//jQuery('#blocker').block('<div class="progressbar">Searching...</div>', { border: '3px solid #cecece' });
	}else{
		jQuery.growlUI('Error!', 'Please select a Country/State/City OR <br />Type in an Airport Code.');
	}
	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 == '');
}
