Array.prototype.isKey = function(){
	  for(i in this){
	    if(i === arguments[0])
	      return true;
	  };
	  return false;
	}; 

String.prototype.tcreplace = stringReplace;

function stringReplace(findText, replaceText) {   
  var originalString = new String(this);

  var pos = 0;
  var len = findText.length;
  pos = originalString.indexOf(findText);
  while (pos != -1) {
    preString = originalString.substring(0, pos);
    postString = originalString.substring(pos + len,originalString.length);
    originalString = preString + replaceText + postString;
    pos = originalString.indexOf(findText);
  }
  return originalString;
}

function getY(oElement) {
	var iReturnValue = 0;
	while (oElement != null) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}
function getX(oElement) {
	var iReturnValue = 0;
	while (oElement != null) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}
function refreshCaptcha(id){
	jQuery("#"+id).attr("src","capatcha.php?x="+Math.floor(Math.random()*1000000));
}
function checkEmail(txtEmail){
	strMail = txtEmail.replace(/ /g,"");
	regex = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	if (regex.test(strMail)) {
			return true;
	}	else {
			return false;
	}
}

function isFloat(objText) {
	var floatPoint = false;
		if (objText.charAt(0) == "." || objText.charAt(0) == ",")
		return false;
		for (i=0; i < objText.length; i++) {
			if (!isDigit(objText.charAt(i))) {
			if (!floatPoint && (objText.charAt(i) == "." || objText.charAt(i) == ","))
			floatPoint = true;
			else
			return false;
			}
		}
		return true;
}
function isDigit (c) {
	return ((c >= "0") && (c <= "9"));
}

function doResetById(formId) {
	form = document.getElementById(formId);
	form.reset();
}


function isNumber(param) {
	strLocalString = param.replace(/ /g, "");
	for (t = 0; t < strLocalString.length; t++) {
		if (!isDigit(strLocalString.charAt(t))) {
			return false;
		}
	}
	return true;
}




function parseFloatCustom(strVal,nDecimals) {
    divider = Math.pow(10,nDecimals);
    subject = parseFloat(strVal.replace(/,/g,"."));
    if (!isNaN(subject)) {
        result = Math.round(subject * divider)/divider;
        return result;
    } else {
        return subject;
    }
}

function ControlExists(strObject){
	return ((document.getElementById(strObject) != null) && (document.getElementById(strObject) != "undefined"));
}



//function rewriteUrl(url){
//	url = url.tcreplace("/","");		
//	url = url.tcreplace("-", "+");
//	url = url.tcreplace(" ", "+");
//	url = url.tcreplace("&#039","");
//	url = url.tcreplace("\"", "");
//	url = url.tcreplace("@", "");
//	url = url.tcreplace("]", "");
//	url = url.tcreplace("[", "");
//	url = url.tcreplace("?", "");
//	url = url.tcreplace("&", "");
//	url = url.tcreplace("!", "");
//	url = url.tcreplace("#", "");
//	url = url.tcreplace("&amp;", "et");
//	url = url.tcreplace("&", "et");
//	url = url.tcreplace(".", "");	
//	url = url.tcreplace(",", "");
//	url = url.tcreplace("(", "");
//	url = url.tcreplace(")", "");
//	url = url.tcreplace("{", "");
//	url = url.tcreplace("}", "");
//	url = url.tcreplace("é","e");
//	url = url.tcreplace("è","e");
//	url = url.tcreplace("ê","e");
//	url = url.tcreplace("ë","e");
//	url = url.tcreplace("É","E");
//	url = url.tcreplace("È","E");
//	url = url.tcreplace("Ê","E");
//	url = url.tcreplace("Ë","E");
//	url = url.tcreplace("à","a");
//	url = url.tcreplace("â","a");
//	url = url.tcreplace("ä","a");
//	url = url.tcreplace("À","A");
//	url = url.tcreplace("Â","A");
//	url = url.tcreplace("Ä","A");
//	url = url.tcreplace("î","i");
//	url = url.tcreplace("ï","i");
//	url = url.tcreplace("Î","I");
//	url = url.tcreplace("Ï","I");
//	url = url.tcreplace("ô","o");
//	url = url.tcreplace("ö","o");
//	url = url.tcreplace("Ô","O");
//	url = url.tcreplace("Ö","O");
//	url = url.tcreplace("ç","c");
//	url = url.tcreplace("Ç","C");
//	url = url.tcreplace("û","u");
//	url = url.tcreplace("ü","u");
//	url = url.tcreplace("Û","U");
//	url = url.tcreplace("Ü","U");
//	url = url.tcreplace("~","+");
//	url = url.tcreplace(";","+");
//	url = url.tcreplace("\/","+");
//	url = url.tcreplace("'","+");
//	url = url.tcreplace(":","+");
//	url = url.tcreplace("%","+");
//	url = url.tcreplace("^","+");
//	url = url.tcreplace("€","+");
//	url = url.tcreplace("$","+");
//	url = url.tcreplace("*","+");
//	url = url.tcreplace("’","+");	
//	return url;
//}
function getFirstStepWithErrors(patternId,nSteps){
	var bBreak = false;
	for(var i = 1; i <= nSteps;i++){
		$("#"+patternId+i+" input,#"+patternId+i+" select").each(function(){
			if($(this).css("background-color") == ERROR_INPUT_BACKGROUND_COLOR){
				bBreak = true;
				return false;
			}
		});
		if(bBreak){
			break;
		}
	}
	return i;	
}
function showSelect(id,bHide){
	$('div', $("#"+id).siblings('.jNiceSelectWrapper')).click();
	$("#popup_error").trigger("click");
}
function getErrorMessages(errors,labelPatern){
	var msg = "";
	jQuery(errors).each(
		function(i, item) {
			var pattern = '$("#" + item.id).prev().prev()';
			if(typeof labelPatern != "undefined"){
				pattern = labelPatern;
			}
			var element = eval(pattern);
			var title = item.id;
			$("#"+item.id).css("background-color",ERROR_INPUT_BACKGROUND_COLOR);
			var bIsSelect = false;
			if($("#"+item.id).is("select")){
				var bIsSelect = true;
				try{
					$("#"+item.id).parents("div .inputSelect").each(function(){
						$(this).css("background-color",ERROR_INPUT_BACKGROUND_COLOR);
					});
				}catch(e){}
			}
			var strFieldName = "";
			if($("label[for='"+item.id+"']").text() != ""){
				strFieldName = $("label[for='"+item.id+"']").text();
			}else if($("#"+item.id).attr('title') != ""){
				strFieldName = $("#"+item.id).attr('title');
			}else if(typeof(element) != "undefined" && element.html() != null){
				strFieldName = element.html().replace(/<.*?>/g, "").tcreplace("*", "");
			}
			if(bIsSelect){
				var js = "";
				title = "<b style='cursor:pointer' onclick='showSelect(\""+item.id+"\");'>"+strFieldName+"</b>";
			}else if(item.id.substr(0,3) == "mda"){
				title = "<b style='cursor:pointer'>"+strFieldName+"</b>";
			}else{
				title = "<b style='cursor:pointer' onclick='$(\"#"+item.id+"\").focus();$(\"#popup_error\").trigger(\"click\");'>"+strFieldName+"</b>";
			}

				switch (item.type) {
				case "mnd":
					msg += title + " is a mandatory field!<br/>";
					break;
				case "url":
					msg += title + " must be a valid url!<br/>";
					break;
				case "nmr":
					msg += title + " is a numeric field!<br/>";
					break;
				case "mnr":
					msg += title + " is a mandatory numeric field!<br/>";
					break;
				case "sel":
					msg += "For field " + title
							+ " a value must be selected!<br/>";
					break;
				case "eml":
					msg += "Field " + title
							+ " must be a valid email address!<br/>";
					break;
				case "dat":
					msg += title + " is a date field!<br/>";
					break;
				case "mda":
					msg += title + " is a mandatory date field!<br/>";
					break;
				case "msm":
					msg += "The passwords you have entered do not match !<br/>";
					break;
				case "unq":
					msg += "For field " + title + " the value \"" + item.value + "\" already exists in the database !<br/>";
					break;
				case "agree":
					msg += "You must agree with the Terms & Conditions !<br/>";
					break;	
				case "unqair":
					msg += "Airport(s) :  <em>" + item.value+"</em> is/are already deserved by others advertisers !<br/>";					
				break;
				case "air_dep":
					$("#fakeAirport0").css("background-color",ERROR_INPUT_BACKGROUND_COLOR);
					var link = "<b style='cursor:pointer' onclick='$(\"#fakeAirport0\").focus();$(\"#popup_error\").trigger(\"click\");'>Choose</b>";
					msg += "You must " + link + " at least one departure airport!<br/>";					
				break;
				case "air_dest":
					$("#fakeDestination0").css("background-color",ERROR_INPUT_BACKGROUND_COLOR);
					var link = "<b style='cursor:pointer' onclick='$(\"#fakeDestination0\").focus();$(\"#popup_error\").trigger(\"click\");'>Choose</b>";
					msg += "You must " + link + " at least one destination airport!<br/>";
					
				break;
				case "captcha":
					msg += "You have entered an invalid security code!<br/>";
					break;	
				case "py_month":
					msg += title + " should be set in the future!<br />";
					break;	
				case "py_year":
					msg += title + " should be set in the future!<br />";
					break;
				}				
			});
	return msg;
}
function odump(object){
	var dump = "";
	for(var tmp in object){
		dump += tmp+" = "+eval("object."+tmp)+"\n";
	}
	return dump;
}
function addLoadingImage($elem,elemId){
	$elem.append('<img style="float:right; padding-right:2px" id="loading_'+elemId+'" src="images/loading.gif" alt="" />');
}
function removeLoadingImage(elemId){
	$("#loading_"+elemId).remove();
}
function objectsAreSame(x, y) {
	if(x == null && y == null){
		return true;
	}
	if((x == null && y != null) ||(x != null && y == null)){
		return false;
	}
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName]) {
         objectsAreSame = false;
         break;
      }
   }
   return objectsAreSame;
}

var arrCacheIndex = new Array();
var arrCacheValue = new Array();

function searchCache(options){
	if(arrCacheIndex.length == 0){
		return false;
	}
	for(var i=0;i<arrCacheIndex.length;i++){
		if(objectsAreSame(arrCacheIndex[i],options)){
			return arrCacheValue[i];
		}
	}
	return false;
}
function getValuesForSelect(table,parent,field,order,id,selectId,firstOption,selected_id,callback){
	//$("label[for='"+selectId+"']").next().append('<img style="float:right; padding-right:2px" id="loading_'+selectId+'" src="images/loading.gif" alt="" />');
	//addLoadingImage($("label[for='"+selectId+"']").next(),selectId);
	
	var settings = new Object();
	settings.method = METHOD_GET_ELEMENTS;
	settings.table = table;
	settings.parent = parent;
	settings.field = field;
	settings.id = id;
	settings.order = order;
	
	var cachedValue = false;//searchCache(settings);
	if(cachedValue !== false){
		var objSelect = document.getElementById(selectId);		
		objSelect.options.length = 0;        		
		if(firstOption != undefined){
			objSelect.options[0] = new Option(firstOption,0);
		}else{
			objSelect.options[0] = new Option(table.toUpperCase(),0);
		}
		$.jNice.SelectRemove(objSelect);
		if(typeof cachedValue != "undefined" && typeof cachedValue.items != "undefined"){						
          	jQuery.each(cachedValue.items, function(i,item){
          		objSelect.options[i+1] = new Option(item.value, item.id);
          	});
          	if(selected_id != undefined && selected_id !== null){
          		$("#"+selectId).val(selected_id);
          	}          	
		}
		$.jNice.SelectAdd(objSelect);
		//removeLoadingImage(selectId);
		if(callback != undefined){
			callback.call( cachedValue );		
		}
		return false;
	}
	ajaxExecuteJson(settings,function(json){
		arrCacheIndex.push(settings);
		arrCacheValue.push(json);
		var objSelect = document.getElementById(selectId);		
		objSelect.options.length = 0;        		
		if(firstOption != undefined){
			objSelect.options[0] = new Option(firstOption,0);
		}else{
			objSelect.options[0] = new Option(table.toUpperCase(),0);
		}
		$.jNice.SelectRemove(objSelect);
		if(typeof json != "undefined" && typeof json.items != "undefined"){						
          	jQuery.each(json.items, function(i,item){
          		objSelect.options[i+1] = new Option(item.value, item.id);
          	});
          	if(selected_id != undefined && selected_id !== null){
          		$("#"+selectId).val(selected_id);
          	}          	
		}
		$.jNice.SelectAdd(objSelect);
		//removeLoadingImage(selectId);
		if(callback != undefined){
			callback.call( json );		
		}
	});		
}
function editCity(options){
	addCountryRegionCityZipFunctionallity(options);
}
function addCountryRegionCityZipFunctionallity(options){
	var countryTable = "country";
	var regionTable = "region";
	var cityTable = "city";
	options.methodCity = METHOD_GET_CITY;
	options.methodAutocomp = METHOD_GET_ZIPCODE;
	if(options.initialCountry != 0){
		getValuesForSelect(regionTable,countryTable,'shortname','shortname',options.initialCountry,options.regionId,'Choose',options.initialRegion);
	}
	if(options.initialRegion != 0){
		getValuesForSelect(cityTable,regionTable,'name','name',options.initialRegion,options.cityId,'Choose',options.initialCity);
	}
	$("#"+options.zipId).attr("disabled","").autocomplete({
		minLength: 4,
		source: function(request, response){
					request.method = options.methodAutocomp;
					request.city_id = $("#"+options.cityId).val() != null ? $("#"+options.cityId).val() : "";					
					ajaxExecuteJson(request, function(data){
						if(data == undefined || data == null || data.length == 0){
							data = new Array();
							obj = new Object();
							obj.id = obj.value = request.term;							
							if(parseInt($("#"+options.cityId).val()) > 0){
								obj.label = "No zip codes were found for this city.<br/>Click to reset selection!";								
								obj.reset = true;
							}else{
								obj.label = "No zip codes were found!";
							}
							
							data.push(obj);
						}
						response(data);
					});
					$("#loading_"+options.zipId).remove();
				},
		select: function(event, ui){
					/*
					 * if reset is force
					 */
					if(ui.item == undefined){
						return false;
					}
					if(typeof ui.item.reset != "undefined"){
						var objSelectCity = document.getElementById(options.cityId);
						$.jNice.SelectRemove(objSelectCity);
						objSelectCity.length = 1;						
						$.jNice.SelectAdd(objSelectCity);
						var objRegionCity = document.getElementById(options.regionId);
						$.jNice.SelectRemove(objRegionCity);
						objRegionCity.length = 1;						
						$.jNice.SelectAdd(objRegionCity);
						return false;
					}
//					if(document.getElementById(options.cityId).options.length > 1 && $("#"+options.zipId).autocomplete( "option", "minLength" ) < 4){
//						return false;
//					}		
					/*
					 * get city,region for zip code
					 */
					if(ui.item.city_id != $("#"+options.cityId).val()){
						var settings = new Object();
						settings.method = options.methodCity;
						settings.id = ui.item.city_id;						
						ajaxExecuteJson(settings,function(city){						
							if(typeof city != "undefined"){
								$("#"+options.countryId).val(city.country_id);
								//changePhoneCodes(city.country_id);
								$.jNice.SelectUpdate(document.getElementById(options.countryId));							
								
								if($("#"+options.regionId).val() != city.region_id){
									getValuesForSelect(regionTable,countryTable,'shortname','shortname',city.country_id,options.regionId,'Choose',city.region_id);
								}
								if($("#"+options.cityId).val() != city.id){
									getValuesForSelect(cityTable,regionTable,'name','name',city.region_id,options.cityId,'Choose',city.id);									
								}
							}
						});	
					}					
				}		
	});
	$("#"+options.countryId).change(function(){
		getValuesForSelect(regionTable,countryTable,'shortname','shortname',this.value,options.regionId,'Choose');
		document.getElementById(options.cityId).options.length = 1;
		$.jNice.SelectUpdate(document.getElementById(options.cityId));
		$("#"+options.zipId).val("");
		//changePhoneCodes(this.value);
	});
	$("#"+options.regionId).change(function(){
		getValuesForSelect(cityTable,regionTable,'name','name',this.value,options.cityId,'Choose');
		$("#"+options.zipId).val("");
	});
	$("#"+options.cityId).change(function(){		
//		if(this.value > 0){
//			$("#"+options.zipId).autocomplete( "option", "minLength", 0 );
//		}else{
//			$("#"+options.zipId).autocomplete( "option", "minLength", 4 );
//		}
		$("#"+options.zipId).val("");
	});
}
function getSessionId(){
	var cookies = document.cookie.split(";");
	for(var i=0;i < cookies.length;i++){
		var tmp = cookies[i].split("=");
		if(tmp[0].toUpperCase() === "PHPSESSID"){
			return tmp[1]; 
		}
	}
	return null;
}
function ajaxExecutePost(options,callback){		
	$.post(AJAX_HOST + "request.php",options,callback);
}
function ajaxExecuteGet(options,callback){
	$.get(AJAX_HOST + "request.php",options,callback);
}
function ajaxExecuteJson(options,callback){
	$.ajax({
		  type: 'POST',
		  url: AJAX_HOST + "request.php",
		  dataType: 'json',
		  data: options,
		  success: callback
		});

	//$.getJSON(AJAX_HOST + "request.php",options,callback);	
}
function gridJson(url,options,callback){
	alert(1);
	$.ajax({
		  type: 'POST',
		  url: url,
		  dataType: 'json',
		  data: options,
		  success: callback
		});

	//$.getJSON(AJAX_HOST + "request.php",options,callback);	
}

function nl2br(str, is_xhtml){
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';	 
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
function getJson(data){
	var json = null;
	try{
		json = $.parseJSON(data);
	}catch(e){
		//$('<p>'+data+'</p>').appendTo('body');
		jError(data,"Server Side Error - Invalid JSON");
		return false;
	}
	return json;
}
function resolveCheckboxes(){
	$("form input[type='checkbox']").each(function(){
		if(this.id.substring(0,3) == "chk" || this.id == "ndbAgree"){
			$('input[type="hidden"][name="'+this.id+'"]').remove();
			 var input = document.createElement("input");
			 input.type = "hidden";
			 input.name = this.id;
			 input.value = (this.checked ? 1 : 0);
			 $(input).appendTo($(this).parents("form"));
		}
	});
}
function removeErrors(jsonErrors){
	if(jsonErrors != null){
		jQuery(jsonErrors).each(function(i, item) {
			$("#"+item.id).css("background-color","#FFFFFF");
			if($("#"+item.id).is("select")){
				try{
					$("#"+item.id).parents("div .inputSelect").each(function(){
						$(this).css("background-color","#FFFFFF");
					});
				}catch(e){}
			}
		});
	}
}
function verifyAnswer(data,onerror,onsuccess){
	var json = getJson(data);
	if (json === false || json === null) {
		return false;
	}
	if (typeof json.errors != "undefined" && json.errors.length > 0) {
		jsonErrors = json.errors;
		var strErrMsg = getErrorMessages(json.errors);
		strErrMsg += "<br/><hr/>";
		strErrMsg += "* Click on the field name (letters in bold),<br/> to go directly to that field!";
		jError(strErrMsg, "Mandatory Fields",function(){
			if(onerror != undefined){
				onerror.call(json);
			}
		});
	}else if(json.status == 7){
		if(typeof json.message != "undefined"){
			jError(json.message, "Database error",function(){
				if(onerror != undefined){
					onerror.call(json);
				}
			});
		}
	}else if(json.status == 8){
		if(typeof json.message != "undefined"){
			jError(json.message, "File upload error",function(){
				if(onerror != undefined){
					onerror.call(json);
				}
			});
		}
	}else if(json.status == 9){
		if(typeof json.message != "undefined"){
			jError(json.message, "Error",function(){
				if(onerror != undefined){
					onerror.call(json);
				}
			});
		}
	}else if(json.status == 0){
		if(onsuccess != undefined){
			onsuccess.call();
		}
		return true;
	}
	return false;
}

function increaseDateTime(dDate, tTime, strAmPm, nIncrement) {
	arrTime = tTime.split(":");
	nHours = parseInt(arrTime[0], 10);
	nMinutes = parseInt(arrTime[1], 10);
	if(strAmPm == "PM") {
		nHours += 12;
	}
	arrDate = dDate.split("/");
	d = new Date(arrDate[2], arrDate[0] - 1, arrDate[1], nHours, nMinutes, 0, 0);
	d.setMinutes(d.getMinutes() + nIncrement);
	strAmPm = "AM";
	nHours = d.getHours();
	nMinutes = d.getMinutes();
	if(nHours > 12) {
		nHours -= 12;
		strAmPm = "PM";
	}
	nMonth = parseInt(d.getMonth()) + 1;
	if(nMonth < 10) {
		nMonth = "0" + nMonth;
	}
	
	return d.getDate() + "-" + nMonth + "-" + d.getFullYear() + "," + nHours + ":" + nMinutes + ":" + strAmPm;
}

function addDaysToDate(dDate, nDays) {
	arrDate = dDate.split("/");
	d = new Date(arrDate[2], arrDate[0] - 1, arrDate[1], 0, 0, 0, 0);
	d.setDate(d.getDate() + nDays);
	
	nMonth = d.getMonth() + 1;
	if(nMonth < 10) {
		nMonth = "0" + nMonth;
	}
	nDay = d.getDate();
	if(nDay < 10){
		nDay = "0" + nDay;
	}
	return nMonth + "/" + nDay + "/" +  d.getFullYear();
}
function getImgHeight(imgSrc){
	var newImg = new Image();
	newImg.src = imgSrc;
	return newImg.height;
}
function getImgWidth(imgSrc){
	var newImg = new Image();
	newImg.src = imgSrc;
	return newImg.width;
}
var objSelectionMap = null;
/**
 * find the next input based on certain criteria
 * used in showSelectionMap()
 * @return
 */
function goToNextInput(divId,curentId){
	$next = $("#"+currentId).next("input[value='']");
}
function showSelectionMap(selectedLocation,match,method,parentDivId,position,dimension,callback) {
	if(selectedLocation == undefined || selectedLocation == null ){
		return false;
	}
	if(document.getElementById("mapContiner") == null){
		$('<div id="mapContiner" style="overflow: hidden;" title="Select/click on airport to validate"></div>').appendTo("body");
		$("#mapContiner").html('<div style="height:20px" id="mapMessage">&nbsp;</div>'
				+'<div style="width:'+(dimension[0]-20)+'px;height:'+(dimension[1]-30)+'px;" id="map"></div>');
	}
	$("#mapContiner").dialog({ height: dimension[1] + 30,width : dimension[0],position:position});
	if(objSelectionMap == null){
		objSelectionMap = new GMap2(document.getElementById("map"));	
		objSelectionMap.removeMapType(G_HYBRID_MAP);
		objSelectionMap.removeMapType(G_SATELLITE_MAP);		
		objSelectionMap.addControl(new GLargeMapControl());
		//objSelectionMap.setUIToDefault();
	}else{
		objSelectionMap.clearOverlays();
	}
	objSelectionMap.setCenter(new GLatLng(selectedLocation.lat, selectedLocation.lng), 7);

	ajaxExecuteJson({method:method,country_id:1,radius:40,lat:selectedLocation.lat,lng:selectedLocation.lng},
			function(airports) {
				if (GBrowserIsCompatible()) {
					var blueIcon = new GIcon(G_DEFAULT_ICON);
					//blueIcon.image = "http://www.hf.faa.gov/webtraining/visualdisplays/VisDispImages/fireworksPNG/planelarge.png";
					//blueIcon.shadow = null;
					blueIcon.image = "images/planelarge.png";
					blueIcon.shadow = "images/chart.png";
					blueIcon.iconSize = new GSize(15, 15);
					blueIcon.iconAnchor = new GPoint(5,10);	
					
					$(airports).each(function(i,airport){						
						var airportMarker = new GMarker(new GLatLng(airport.lat, airport.lng),{icon:blueIcon});
						GEvent.addListener(airportMarker, "click",function(a){
							var bContinue = true;
							$("#"+parentDivId+" input[value='"+airport.id+"'][type='hidden']").each(function(j,item){
								
								//if($("#"+parentDivId+" input[value='"+airport.id+"'][type='hidden'][id!='true"+match+j+"']").size() > 0){										
										jAlert("This airport has already been selected!","Error",function(){
//											$("#true"+match+j).val("");
//											$("#fake"+match+j).val("");
										});		
										bContinue = false;
										return false;
								//}
								
							});
							if(bContinue){
								$freeTrueInput = $("#"+parentDivId+" input[type='hidden'][id^='true'][value='']").eq(0);
								if(typeof $freeTrueInput.attr('id') === "undefined"){
									// this means we have to overwrite exsiting items
									jAlert("To change an existing airport please remove it!","All the airports have been selected!");
									return false;
								}
								$freeFakeInput = $freeTrueInput.prev("#"+parentDivId+" [type!='hidden'][id^='fake']");
								$freeTrueInput.val(airport.id);
								$freeFakeInput.val(airport.label);								
								//$("#map").dialog( "close" );
								if(callback != undefined){
									callback.call();
								}
							}
							//}	
						});
						
						GEvent.addListener(airportMarker, 'mouseover', function(pointM) {
								$("#mapMessage").html(airport.label);
//								$("#mapMessage").reversegeocode({
//							        lat: airport.lat,
//							        lng: airport.lng,
//							        msg: airport.label
//							    });
						});
						objSelectionMap.addOverlay(airportMarker);
					});							
				}
	});
}
function changePhoneCodes(id){		
	return false;
	ajaxExecuteJson({method:METHOD_GET_COUNTRY,id:id},function(country){
		if(country != undefined && country != null){
			$("input[name='ndbPhoneCode'][readonly='readonly']").val(country.phone_code != 0 ? country.phone_code : "");
		}
	});
}
function changePhoneCodesForCountry(id,arrIds){
	if(parseInt(id) <= 0){
		return false;
	}
	ajaxExecuteJson({method:METHOD_GET_COUNTRY,id:id},function(country){
		if(country != undefined && country != null){
			$(arrIds.join(",")).val(country.phone_code != 0 ? country.phone_code : "");			
		}
	});
}
var listCountriesForPopulate = null;
function populateSelectWithCountries(arrSelects,bName,selectedValue,callback){
	if(listCountriesForPopulate != null){
		//alert("get cities static");
		$(arrSelects).each(function(i,selectId){
			var objSelect = document.getElementById(selectId);
			// countries not already loaded
			if(objSelect.length <= 1){
				objSelect.options.length = 1;        				
				objSelect.options[0] = new Option("Choose",0);														
	          	$.each(listCountriesForPopulate, function(i,item){
	          		objSelect.options[i+1] = new Option(item.name,(bName ? item.name : item.id));
	          	});			          					
			}
			if(selectedValue != -1){
				$("#"+selectId).val(selectedValue);
			}
          	//alert("#"+selectId+ " : " +selectedValue);
			$.jNice.SelectUpdate(objSelect);
		});		
		if(callback != undefined || callback != null){
			callback.call();
		}
		return false;
	}	
	ajaxExecuteJson({method:METHOD_GET_COUNTRIES},function(countries){
//		alert("get cities");
		listCountriesForPopulate = countries;
		$(arrSelects).each(function(i,selectId){
			var objSelect = document.getElementById(selectId);
			// countries not already loaded
			if(objSelect.length <= 1){
				objSelect.options.length = 1;        				
				objSelect.options[0] = new Option("Choose",0);				
				if(typeof countries != "undefined" && countries != null){						
		          	jQuery.each(countries, function(i,item){
		          		objSelect.options[i+1] = new Option(item.name,(bName ? item.name : item.id));
		          	});
				}
				//alert("#"+selectId+ " : " +selectedValue);							
			}
			if(selectedValue != -1){
				$("#"+selectId).val(selectedValue);
			}
			$.jNice.SelectUpdate(objSelect);	
		});		
		if(callback != undefined || callback != null){
			callback.call();
		}
	});
}

function dateDiff(dDate1, tTime1, bIsAM1, dDate2, tTime2, bIsAM2) {
	date1 = new Date();
	date2 = new Date();
	diff  = new Date();

	arrDate = dDate1.split("/");
	arrTime = tTime1.split(":");

	if(bIsAM1 == 1) {
		arrTime[0] = parseInt(arrTime[0]) + 12;
	}
	
	date1temp = new Date(arrDate[2], arrDate[0] - 1, arrDate[1], arrTime[0], arrTime[1]);
	date1.setTime(date1temp.getTime());
	
	arrDate = dDate2.split("/");
	arrTime = tTime2.split(":");
	
	if(bIsAM2 == 1) {
		arrTime[0] = parseInt(arrTime[0]) + 12;
	}
	
	date2temp = new Date(arrDate[2], arrDate[0] - 1, arrDate[1], arrTime[0], arrTime[1]);
	date2.setTime(date2temp.getTime());

	// sets difference date to difference of first date and second date
	
	diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
	
	timediff = diff.getTime();
	
	weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
	timediff -= weeks * (1000 * 60 * 60 * 24 * 7);
	
	days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
	timediff -= days * (1000 * 60 * 60 * 24);
	
	hours = Math.floor(timediff / (1000 * 60 * 60)); 
	timediff -= hours * (1000 * 60 * 60);
	
	mins = Math.floor(timediff / (1000 * 60)); 
	timediff -= mins * (1000 * 60);
	
	secs = Math.floor(timediff / 1000); 
	timediff -= secs * 1000;
	
	if(weeks > 0) {
		hours += (7 * 24) * weeks;
	}
	
	if(days > 0) {
		hours += 24 * days;
	}
	
	return hours;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
	num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	}
	return (((sign)?'':'-')  + num);
}
function printPage(){
	var DocumentContainer = document.getElementById('printContent');
	if(DocumentContainer.innerHTML != ""){
		var WindowObject = window.open('', "Print","width=10,height=10");
		WindowObject.document.writeln(DocumentContainer.innerHTML);
		WindowObject.document.close();
		WindowObject.focus();
		WindowObject.print();
		WindowObject.close();
	}
}
function prewiewPage(type,page_id){
	var WindowObject = window.open("print-preview.php?page_id="+(page_id != undefined ? page_id : 0)+"&type="+type, "Print","width=630,height=400,toolbars=no,scrollbars=yes,status=no,resizable=no");
}
function addCountryRegionCityZipFunctionallity2(options,bUpdate){
	if(typeof(bUpdate) != "undefined" && bUpdate == true){
		$("#"+options.countryId + '> option[value="'+options.initialCountry+'"]').attr("selected","selected");
		$.jNice.SelectUpdate(document.getElementById(options.countryId));		
		$("#"+options.regionId + '> option[value="'+options.initialRegion+'"]').attr("selected","selected");
		$.jNice.SelectUpdate(document.getElementById(options.regionId));		
		return false;
	}
	var countryTable = "country";
	var regionTable = "region";
	var cityTable = "city";
	options.methodCity = METHOD_GET_CITY;
	options.methodAutocomp = METHOD_GET_ZIPCODE;
	var nOldCountry = $("#"+options.countryId).val();
	if(options.initialCountry != 0){
		if(nOldCountry != options.initialCountry && document.getElementById(options.regionId).length <= 1){
			getValuesForSelect(regionTable,countryTable,'shortname','shortname',options.initialCountry,options.regionId,'Choose',options.initialRegion);
		}		
		$("#"+options.countryId + '> option[value="'+options.initialCountry+'"]').attr("selected","selected");
		$.jNice.SelectUpdate(document.getElementById(options.countryId));		
	}
//	if(options.initialRegion != 0){
//		getValuesForSelect(cityTable,regionTable,'name','name',options.initialRegion,options.cityId,'Choose',options.initialCity);
//	}
	var zipAutocompleteOptions = {
		minLength: 4,
		source: function(request, response){
					request.method = options.methodAutocomp;
					request.city_id = $("#"+options.cityId).val() ? $("#"+options.cityId).val() : "";
					request.region_id = $("#"+options.regionId).val() ? $("#"+options.regionId).val() : "";
					request.country_id = $("#"+options.countryId).val() ? $("#"+options.countryId).val() : "";
					ajaxExecuteJson(request, function(data){
						if(data == undefined || data == null || data.length == 0){
							data = new Array();
							obj = new Object();
							obj.id = obj.value = request.term;							
							if(parseInt($("#"+options.cityId).val()) > 0){
								obj.label = "No zip codes starting with "+$("#"+options.zipId).val()+" were found for "+$("#"+options.cityNameId).val()+".<br/>Click here to reset selection!";								
								obj.reset = true;
							}else{
								obj.label = "No zip codes were found!";
							}
							
							data.push(obj);
						}
						response(data);
					});
					$("#loading_"+options.zipId).remove();
				},
		select: function(event, ui){
					/*
					 * if reset is force
					 */
					if(ui.item == undefined){
						return false;
					}
					if(typeof ui.item.reset != "undefined"){						
						$("#"+options.cityNameId).val("");									
						$("#"+options.cityId).val("");						
						var objRegionCity = document.getElementById(options.regionId);
						objRegionCity.length = 1;
						$.jNice.SelectUpdate(objRegionCity);
						$("#"+options.zipId).autocomplete("search");
						return false;
					}
					/*
					 * get city,region for zip code
					 */
					if(ui.item.city_id != $("#"+options.cityId).val()){
						var settings = new Object();
						settings.method = options.methodCity;
						settings.id = ui.item.city_id;						
						ajaxExecuteJson(settings,function(city){						
							if(typeof city != "undefined"){
								var beforeCountry = $("#"+options.countryId).val();
								$("#"+options.countryId).val(city.country_id);
								changePhoneCodes(city.country_id);
								$.jNice.SelectUpdate(document.getElementById(options.countryId));							
								
								if(city.country_id != beforeCountry){
									getValuesForSelect(regionTable,countryTable,'shortname','shortname',city.country_id,options.regionId,'Choose',city.region_id);
								}
								if($("#"+options.regionId).val() != city.region_id){
									$("#"+options.regionId).val(city.region_id);
									$.jNice.SelectUpdate(document.getElementById(options.regionId));
								}
								if($("#"+options.cityId).val() != city.id){
									$("#"+options.cityNameId).val(city.name);									
									$("#"+options.cityId).val(city.id);
								}
							}
						});	
					}					
				}		
	};	
	var cityAutocompleteOptions = {minLength: 4,
		source: function(request, response){
					request.method = 14;
					request.region_id = $("#"+options.regionId).val() ? $("#"+options.regionId).val() : "";
					request.country_id = $("#"+options.countryId).val() ? $("#"+options.countryId).val() : "";
					ajaxExecuteJson(request, function(data){
						if(data == undefined || data == null || data.length == 0){
							data = new Array();
							obj = new Object();
							obj.id = obj.value = request.term;
							if(parseInt($("#"+options.regionId).val()) > 0){
								obj.label = "No city starting with "+$("#"+options.cityNameId).val()+" was found for region "+$("#"+options.regionId+" option:selected").text()+".<br/>Click here to reset selection!";								
								obj.reset = true;
							}else{
								obj.label = "No city was found!";
							}
							data.push(obj);
						}
						response(data);
					});
				},
		select: function(event, ui){
				if(ui.item == undefined){
						return false;
				}	
				if(typeof ui.item.reset != "undefined"){
					$("#"+options.zipId).val("");
					$("#"+options.regionId+" option:selected").attr("selected","");
					$("#"+options.regionId+" option").eq(0).attr("selected","selected");
					if($("#"+options.regionId+" option").eq(0).attr("value") != "0"){						
						getValuesForSelect(regionTable,countryTable,'shortname','shortname',$("#"+options.countryId).val(),options.regionId,'Choose',null,function(){
							$("#"+options.cityNameId).autocomplete("search");
						});
					}else{
						var objRegionCity = document.getElementById(options.regionId);
						$.jNice.SelectUpdate(objRegionCity);
						$("#"+options.cityNameId).autocomplete("search");
					}
					return false;
				}
				$("#"+options.cityId).val(ui.item.id);
				$("#"+options.countryId).val(ui.item.country_id);
				$.jNice.SelectUpdate(document.getElementById(options.countryId));
				$("#"+options.regionId).val(ui.item.region_id);
				$.jNice.SelectUpdate(document.getElementById(options.regionId));
				$("#"+options.zipId).val("");
		}		
	};
	$("#"+options.zipId).attr("disabled","");//.autocomplete(zipAutocompleteOptions);
	
	if($.inArray( parseInt(options.initialCountry), arrCountriesWithZips ) != -1){
		$("#"+options.zipId).autocomplete(zipAutocompleteOptions);
		$("#"+options.cityNameId).autocomplete( cityAutocompleteOptions );
	}
//	$("#"+options.cityNameId).val("Choose").click(function(){
//		if(this.value == "Choose"){
//			this.value = "";
//			}
//		}
//	).focusout(function(){
//		if(this.value == ""){
//			this.value = "Choose";
//			}
//		}
//	);
	//$("#"+options.cityNameId).autocomplete(cityAutocompleteOptions);
	$("#"+options.countryId).change(function(){
		getValuesForSelect(regionTable,countryTable,'shortname','shortname',this.value,options.regionId,'Choose');
		//document.getElementById(options.cityId).options.length = 1;
		//$.jNice.SelectUpdate(document.getElementById(options.cityId));
		$("#"+options.zipId).val("");
		$("#"+options.cityNameId).val("");
		$("#"+options.cityId).val("");
		//changePhoneCodes(this.value);
		if($.inArray(parseInt(this.value), arrCountriesWithZips ) != -1){
			$("#"+options.zipId).autocomplete( zipAutocompleteOptions );
			$("#"+options.cityNameId).autocomplete( cityAutocompleteOptions );
		}else{
			$("#"+options.zipId).autocomplete( "destroy" );
			$("#"+options.cityNameId).autocomplete( "destroy" );
		}
	});
	$("#"+options.regionId).change(function(){
		$("#"+options.cityNameId).val("");									
		$("#"+options.cityId).val("");
		$("#"+options.zipId).val("");
	});
	$("#"+options.cityNameId).change(function(){		
		if($("#"+options.cityNameId).val() == ""){
			$("#"+options.cityId).val("");
		}
	});
	//alert(nOldCountry + " :: " +"#"+options.countryId + " :: " + $("#"+options.countryId).val());
	return false;
}
function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}
function empty(obj){
	return (typeof(obj) == "undefined" || obj == null || obj == "");
}
function reloadCaptcha(id){
	var src = document.getElementById(id).src.split("?");
	document.getElementById(id).src = src[0]+ '?' +(new Date()).getTime();
}
function loadjscssfile(filename, filetype){
	 if (filetype=="js"){ //if filename is a external JavaScript file
	  var fileref=document.createElement('script');
	  fileref.setAttribute("type","text/javascript");
	  fileref.setAttribute("src", filename);
	 }
	 else if (filetype=="css"){ //if filename is an external CSS file
	  var fileref=document.createElement("link");
	  fileref.setAttribute("rel", "stylesheet");
	  fileref.setAttribute("type", "text/css");
	  fileref.setAttribute("href", filename);
	 }
	 if (typeof fileref!="undefined")
	  document.getElementsByTagName("head")[0].appendChild(fileref)
}
$(document).ajaxSend(function(event, request, settings){
	if(settings.data != null){
		if(settings.data.search("&sec_tkn=") === -1){
			settings.data = settings.data + "&sec_tkn=" + encodeURIComponent(SEC_TKN);
		}
	}else{
		settings.data = "sec_tkn=" + encodeURIComponent(SEC_TKN);
	}
});
