var ie6 = !window.XMLHttpRequest;
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

ie6_bar_color = "#B9E6FD"; // in stead of opac-background

//uicornerfix('4px'); // for ie only
/**
 Common Functions
 **/
function logit(text) {
	//logit("caller is " + arguments.callee.caller.toString());
	logitAll("main-"+text);
}
function logitAll(text) {
	if (hg_debug && window.console) {window.console.log(text);};
}
function logitA() {  
	if (hg_debug && window.console) {                                  
	  var putstr = '';                                    
	  for (i = 0; i < arguments.length; i += 1) {         
	    if (putstr !== '') {                               
	      putstr += ',';                                  
	    }                                                 
	    putstr += arguments[i];                           
	  }                                                   
	  window.console.log(putstr);
	}
} 
function logitO(objO) { 
	if (!hg_debug) return;
	var putstr = '';
	for (var field in objO) {
		putstr += field+"="+objO[field]+" ";
	} 
  window.console.log(putstr);
} 
// Common function that calls callback when image is already loaded (especially for opera) or when ready loading
//
// in IE7 it is possible that callback is called repeatetly when image is an animated gif
//
function imgLoaded(imgsrc,callback) {
	if ($.browser.opera) {
		var img = new Image();
		img.onload = function() {callback(img)};
		img.src = imgsrc;
	} else {
		var img = new Image();
		img.src = imgsrc;
		if (img.complete) {
			// This may be the case when image can not be found in FF
			//logit("complete");
			callback(img);
		} else {
			//logit("wait for onload");
			img.onload = function() {callback(img)};
		}
	}
}
// same as imgLoaded but image object is passed
function imgLoaded2(img,imgsrc,callback) {
	if ($.browser.opera) {
		img.onload = function() {callback(img)};
		img.src = imgsrc;
	} else {
		img.src = imgsrc;
		if (img.complete) {
			// This may be the case when image can not be found in FF
			//logit("complete");
			callback(img);
		} else {
			//logit("wait for onload");
			img.onload = function() {callback(img)};
		}
	}
}
// String trim functions from : http://www.somacon.com/p355.php
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
// get top margin to be able to show a image in the middle (vertically) of a canvas
function getTopMargin(thisheight,maxheight) {
	topmargin = 0;
	if (thisheight > (maxheight - 10)) {
		topmargin = 0;
	}	else {
		topmargin = parseInt((maxheight - thisheight)/2);
	}
	logit("maxheight/height/topmargin="+maxheight+'/'+thisheight+"/"+topmargin);
	return topmargin;
}
function getLeftMargin(thiswidth,maxwidth) {
	leftmargin = 0;
	if (thiswidth > (maxwidth - 10)) {
		leftmargin = 0;
	}	else {
		leftmargin = parseInt((maxwidth - thiswidth)/2);
	}
	logit("maxwidth/width/leftmargin="+maxwidth+'/'+thiswidth+"/"+leftmargin);
	return leftmargin;
}
/*
  Isolating the Inheritance Part into a Function
  (From the book Object Oriented Javascript,Packt)
	Using this function (or your own custom version of it) will help you keep your
	code clean with regard to the repetitive inheritance-related tasks. This way you can inherit by simply using:

	extend(TwoDShape, Shape);
 */
function extend(Child, Parent) {
	var F = function(){};
	F.prototype = Parent.prototype;
	Child.prototype = new F();
	Child.prototype.constructor = Child;
	Child.uber = Parent.prototype;
}
/*
	Copying Properties
	Since inheritance is about reusing code, you can simply copy properties from the parent to the child. 
	Keeping the same interface as the extend() function above, you can create a function extend2() 
	which takes two constructor functions and copies all of the properties from the parent's prototype 
	to the child's prototype. This will include methods, as methods are just properties that happen to be functions.
*/
function extend2(Child, Parent) {
	var p = Parent.prototype;
	var c = Child.prototype;
	for (var i in p) {
	c[i] = p[i];
	}
	c.uber = p;
}
/*========================================================================================
  
   Function : setCenterBounds

 ========================================================================================*/
function setCenterBounds(reg1) {
	//
	// Determine the center of the region	
	//
	if (reg1.region_bounds) return;  // do not do it double

	if (reg1.minlat == reg1.maxlat
	 && reg1.minlng == reg1.maxlng) {
	 	reg1.region_bounds = null;
		reg1.center = new GLatLng(reg1.minlat,reg1.minlng);
	} else {
		// Add 5% Margin to bounds to be sure all markers are completely within bounds
		var latMargin = parseFloat((reg1.maxlat - reg1.minlat)*0.05); 
		var lngMargin = parseFloat((reg1.maxlng - reg1.minlng)*0.05);     
		
		var maxlat = reg1.maxlat + latMargin;
		var maxlng = reg1.maxlng + lngMargin;
		var minlat = reg1.minlat - latMargin;
		var minlng = reg1.minlng - lngMargin;
		reg1.sw = new GLatLng(minlat,minlng);   
		reg1.ne = new GLatLng(maxlat,maxlng);

		reg1.region_bounds = new GLatLngBounds(reg1.sw,reg1.ne);     
		reg1.center = reg1.region_bounds.getCenter();
	}
}
/*========================================================================================
  
   Function : getBounds 
   input : array of markers
   output : object with region_bounds & center

 ========================================================================================*/
function getBounds(markerA) {
	var maxlat,maxlng,minlng,minlat;

	var markerNr = 0;
  $.each(markerA,function(key,value) {
  	if (value) {
  		markerNr++;
			var latlng = value.getLatLng();
			var lat = latlng.lat();
			var lng = latlng.lng();
			if (markerNr === 1) {
				maxlat = lat;
				minlat = lat;
				maxlng = lng;
				minlng = lng;
			} else {
				if (lat > maxlat)	maxlat = lat;
				if (lat < minlat) minlat = lat;
				if (lng > maxlng)	maxlng = lng;
				if (lng < minlng) minlng = lng;
			}
		}
	});
	if (markerNr === 0) return null; // no markers

	// Add 5% Margin to bounds to be sure all markers are completely within bounds
	var latMargin = parseFloat((maxlat - minlat)*0.05); 
	var lngMargin = parseFloat((maxlng - minlng)*0.05);     

	// block without the margin
	var block = {};
	block.maxlat = maxlat;
	block.minlat = minlat;
	block.maxlng = maxlng;
	block.minlng = minlng;
	// add margin
	maxlat += latMargin;
	maxlng += lngMargin;
	minlat -= latMargin;
	minlng -= lngMargin;
	
	var sw = new GLatLng(minlat,minlng);   
	var ne = new GLatLng(maxlat,maxlng);
	var region_bounds = new GLatLngBounds(sw,ne);
	var center = region_bounds.getCenter();

	var block = {};
	block.maxlat = maxlat;
	block.minlat = minlat;
	block.maxlng = maxlng;
	block.minlng = minlng;

	return {region_bounds:region_bounds,center:center,block:block};
}
/*========================================================================================

   Function : setZoomCenter

	 Zoom in and set the center  

		NOTE : a different version of this function exists in 2 other modules

		center must be delivered, in case region has only 1 point, then there is no region_bounds.	
 ========================================================================================*/
function setZoomCenter(map,region_bounds,center,defaultZoom) {
	var zoom;
	if (region_bounds) {
		zoom = map.getBoundsZoomLevel(region_bounds);
	} else {
		if (!defaultZoom) {
			zoom = 8;
		} else {
			zoom = defaultZoom;
		}
	}
	logit("zoom level for displaying region="+zoom+',at:'+center.lat()+'/'+center.lng());

	center = region_bounds.getCenter();

	map.setCenter(center);
	map.setZoom(zoom);
}

function setCookie(key,value) {
   var cookieDate = new Date(2015,11,10,19,30,30);
   document.cookie=key + "=" + escape(value) + "; expires=" + cookieDate.toGMTString(  ) + "; path=/";
}
function readCookie(key) {
  var cookie = document.cookie;

  var first = cookie.indexOf(key+"=");

  // cookie exists
  if (first >= 0) {
    var str = cookie.substring(first,cookie.length);
    var last = str.indexOf(";");

    // if last cookie
    if (last < 0) last = str.length;

    // get cookie value
    str = str.substring(0,last).split("=");
    return unescape(str[1]);
  } else {
    return null;
  }
}
function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")); //.toLowerCase();
    if (strQueryString.substr((strQueryString.length - 1),1) === "#") {
    	strQueryString = strQueryString.substr(0,(strQueryString.length - 1));
    }
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName /*.toLowerCase() */ + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
} 
function CrossFadeOld( elemIn,elemOut) {
	var intervalId = [];
	// Start the opacity at 0
	// Show the element (but you can not see it, since the opacity is 0)
	$(elemIn).css("opacity",0).show();
	// We're going to do a 20 'frame' animation that takes
	// place over one second
	for ( var i = 0; i <= 100; i += 5 ) {
		// A closure to make sure that we have the right 'i'
		(function(){
			var pos = i;
			var posIn = i/100;
			var posOut = 1 - posIn;
			// Set the timeout to occur at the specified time in the future
			intervalId[i] = setTimeout(function(){
				// Set the new opacity of the element
				$(elemIn).css("opacity",posIn);
				$(elemOut).css("opacity",posOut);
			}, ( pos + 1 ) * 10 );
		})();
	}
}
/*
function CrossFade( elemIn,elemOut,duration,CB) {       
 var stepTime  = 5;                                    
 var startTime = now();                                 
 logitA("startTime",startTime);              
                                                        
 // Start the opacity at 0                              
 $(elemIn).css("opacity",0).show();                     
                                                        
 var intervalId = setInterval(function() {              
   // calc opacity                                      
   var timePassed = now() - startTime;   
   logitA("timePassed",timePassed);              
   var opIn = 0;                                        
   var opOut = 0;                                       
   if (timePassed >= duration) {                        
     // end                                             
     clearInterval(intervalId);                         
     opIn  = 100;                                       
     opOut = 0;                                         
   } else {                                             
     var percentPassed = timePassed/duration; 
	   logitA("percentPassed",percentPassed,"timePassed/duration",timePassed,duration);              
     opIn = percentPassed;                              
     opOut = 1 - opIn;                                
   }                             
   logitA("opacity",opIn);                       
   $(elemOut).css("opacity",opOut);                     
   $(elemIn).css("opacity",opIn);                       
   if (opOut = 0) {                                     
     $(elemOut).hide();  // do we need this ?       
     if (CB) CB();                                              
    }                                                   
 },stepTime);                                           
}
function now(){
	return +new Date;
}

function getMapPoint(map1,mapPoint,containerDiv) {
	var point1 = map1.fromLatLngToContainerPixel(mapPoint);
	logit("MapPoint x/y:"+point1.x+"/"+point1.y);
	// get top & left offset from #map_canvas1 to document
	var top1 = $(containerDiv).offset().top;
	var left1 = $(containerDiv).offset().left;
	logit("top/left container="+top1+"/"+left1);
}
*/
function calcPosition(containerDiv,popupDiv,mapPoint,popupHeight,popupWidth,pos) {
	/*
		 ___________________________________________________   	
		|	document                                          |  
		|      ------------------------------------         |
		|     | window                             |        |
		|     |  	  ________________________       |        |
		|		  |		 |google ContainerDiv     |      |        |
		|		  |		 |       _________        |      |        |
		|		 	|	   |	    |popupDiv |       |      |        |
		|		 	|		 |	  P |         |       |      |        |
		|		 	|		 |      |_________|       |      |        |
		|		 	|		 |                        |      |        |
		|		 	|		 |________________________|      |        |
		|		 	|		                                 |        |
		|     |____________________________________|        |
		|                                                   |
		|___________________________________________________|

		1.calculate the best position of popupDiv within ContainerDiv
		  a.Relative to window (viewport)
		  b.Relative to document
		  c.Relative to containerDiv (for use within google maps)
    2.calculate the best position of popupDiv within window
		  a.Relative to window (viewport)
		  b.Relative to document
	*/
	//$(window).scrollTop()
	var point1 = map1.fromLatLngToContainerPixel(mapPoint);
	logit("Container point x/y:"+point1.x+"/"+point1.y);
  //var point1 = map1.fromLatLngToDivPixel(mapPoint);
	//logit("Div point x/y:"+point1.x+"/"+point1.y);
	// get top & left offset from #map_canvas1 to document
	var top1 = $(containerDiv).offset().top;
	var left1 = $(containerDiv).offset().left;
	if (pos === "window") {
		var map_width = $(window).width();
		var map_height = $(window).height();
		var map_width_middle = Math.round(map_width/2);
		var map_height_middle = Math.round(map_height/2);
		// 
		var winHeight = $(window).height();
		var winTop = $(window).scrollTop();
		// x,y relative to window
		var x = point1.x + left1;
		var y = point1.y + top1 - winTop; // top1 relative to document but we want relative to window
	} else {
		var map_width = $(containerDiv).width();
		var map_height = $(containerDiv).height();
		var map_width_middle = Math.round(map_width/2);
		var map_height_middle = Math.round(map_height/2);
		// x,y relative to container
		var x = point1.x;
		var y = point1.y;
	}
	logit("x/y="+x+"/"+y);
	
	// if popup size is set by parameters then take those, otherwise calc from div
	if (!popupWidth) 	popupWidth = $(popupDiv).width();
	if (!popupHeight) popupHeight = $(popupDiv).height();
	
	logit("popup w/h"+popupWidth+'/'+popupHeight);
	logit("mouseover mapPoint="+mapPoint+"/div coords="+point1);
			// now calc position of popup 
	logit("before x,y="+x+","+y+"/middle="+map_width_middle+","+map_height_middle);
	/*
	if (y > map_height_middle) {
		// show show above
		logit("show above:"+y);
		y =  y - popupHeight + 20;
	} else {
		// show below marker 
		logit("show below:"+y);
		y = y - 20;
	}
	*/
	// try to show marker beside marker, marker in middle of popup
	var popup_width_middle = Math.round(popupWidth/2);
	var popup_height_middle = Math.round(popupHeight/2);

	y = y - popup_height_middle; 
	
	if (y < 0) {
		// correct if above window
		y = 0;
	}
	// Try to show popup to the right, only if not enough place then to left
	var marker_margin = 20;

	if ( ((x + marker_margin + popupWidth) > map_width)   // not enough space to the right?
		&& ((x - popupWidth - marker_margin) > 0)           // but enough space to the left?
		) {
		// place to the left
		x =  x - popupWidth - marker_margin;
	} else {
		// place to right
		x = x + marker_margin;
	}
	logit("after x="+x);
	/* cannot happen
	var xmax = x + popupWidth;
	if (x < 0 || xmax > map_width) {
		logit("correct x to null:"+x);
		if (xmax > map_width) {
			x = map_width - popupWidth;
		}
		if (x < 0) {
			x = 0;
		}
		if (point1.y > map_height_middle) {
			// show above marker
			logit("show above:"+y+"/"+popupHeight);
			y =  point1.y - popupHeight - 25;
		} else {
			// show below marker
			logit("show below:"+y);
			y =  point1.y + 5;			
		}
	}
	*/
	// Correct if the popup will be below the screen
	logit("y/popupHeight/map_height="+y+"/"+popupHeight+"/"+map_height);
	if ((y + popupHeight) > map_height) {
		y = map_height - popupHeight;
		if (y < 0) y = 0;
		logit("new y:"+y);
	}
	if (pos === "window") {
		x_ = x;
		y_ = y;
	} else {
		// now calc x/y relative to document
		x_ = left1 + x;  // when used as Goverlay we only need offset
		y_ = top1 + y;
	}	
	logit("after x_,y_="+x_+","+y_+"/offset x,y="+x+'/'+y);
	return {x: x_,y: y_,xoffset:x,yoffset:y};
}
function rand( min, max ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    var randnum =Math.floor(Math.random() * (max - min + 1)) + min;
	  //logit("Random between:"+min+'/'+max+'='+randnum);
	  return randnum;
}
//
// IE fix for jQuery UI rounded corners
// see : http://www.filamentgroup.com/lab/achieving_rounded_corners_in_internet_explorer_for_jquery_ui_with_dd_roundi/
function uicornerfix(r) {
  DD_roundies.addRule('.ui-corner-all', r);
  DD_roundies.addRule('.ui-corner-top', r+' '+r+' 0 0');
  DD_roundies.addRule('.ui-corner-bottom', '0 0 '+r+' '+r);
  DD_roundies.addRule('.ui-corner-right', '0 '+r+' '+r+' 0');
  DD_roundies.addRule('.ui-corner-left', r+' 0 0 '+r);
  DD_roundies.addRule('.ui-corner-tl', r+' 0 0 0');
  DD_roundies.addRule('.ui-corner-tr', '0 '+r+' 0 0');
  DD_roundies.addRule('.ui-corner-br', '0 0 '+r+' 0');
  DD_roundies.addRule('.ui-corner-bl', '0 0 0 '+r);
};
function formatDate(day,month,year,dateO) {
	//
	// Will format in dd.mm.yyyy format
	//
	if (typeof(day) === "undefined" || day === null) {
		//
		// No date specified then get current date
		//
		if (dateO) {
			var now = dateO;
		} else {
			var now = new Date();
		}
		day = now.getDate();
		month = now.getMonth() + 1; // 0 = Januari !!!!
		year = now.getFullYear();
	}
	var date_ = '';
	if (day < 10) date_ +='0';
	date_ += day;
	date_ += '.';
	if (month < 10) date_ += '0';
	date_ += month;
	date_ += '.';
	date_ += year;
	return date_;
}			
function formatTime(hours,minutes) {
	//
	// Will format in hh:mm:ss format
	//
	// input can be hours,minutes or a date-object
	//
	if (typeof(hours) === "undefined" || hours === null) {
		//
		// No date specified then get current date
		//
		var now = new Date();
		hours = now.getHours();
		minutes = now.getMinutes();
	}
	var time_ = '';
	if (hours < 10) time_ +='0';
	time_ += hours;
	time_ += ':';
	if (minutes < 10) time_ += '0';
	time_ += minutes;
	logitA("formatTime:",hours,minutes,time_);

	return time_;
}	
		
function datetime(date_,time_) {
	/*
	  input:
	  date format dd.mm.yyyy
	  time format hh:mm
	  output:
	  yyyymmddhhmm
	 */
	var datetime = date_.substr(6,4)+date_.substr(3,2)+date_.substr(0,2)+time_.substr(0,2)+time_.substr(3,2);
	logit("datetime:"+datetime);
	return datetime;
}
function nextTime(hours,minutes) {
	logitA('nextTime h:m ',hours,minutes);
	minutes++;
	if (minutes > 59) {
		minutes = 0;
		hours++;
		if (hours > 23) {
			hours = 0;
		}
	}
	logitA('nextTime after:',hours,minutes);
	return formatTime(hours,minutes); 
}
function nextDate(day,month,year) {
	dateO = new Date(year,month,day);
	// add 1 day
	// see http://michiel.wordpress.com/2008/11/24/the-javascript-date-object-and-how-to-add-days-to-a-date-variable/

	logit("date before="+dateO);
	dateO.setTime(dateO.getTime()+86400000);
	logit("date after="+dateO);
	
	return formatDate(null,null,null,dateO); 
}
function nextDatetime(datetime) {
	logit("nextDatetime:"+datetime);
	var hours = parseInt(datetime.substr(11,2),10);
	var minutes = parseInt(datetime.substr(14,2),10);
	var day   = parseInt(datetime.substr(8,2),10);
	var month = parseInt(datetime.substr(5,2),10);
	var year  = parseInt(datetime.substr(0,4),10);
	
	var dateA,timeA;
	timeA = nextTime(hours,minutes);
	if (timeA === '00:00') {
		dateA = nextDate(day,month,year);
	} else {
		dateA = null;
	}

	// dateA now in format dd.mm.yyyy or null
	// timeA now in format hh:mm
	var new_datetime;
	if (dateA === null) {
		new_datetime = datetime.substr(0,11)+timeA+':00';
	} else {
		new_datetime = convertMysqlDateTime(dateA,timeA);
	}
	logit("new datetime:"+new_datetime);
	return new_datetime;
}
function formatDatetime() {
	// gets current datetime
	var date_ = formatDate();
	var time_ = formatTime();
	return convertMysqlDateTime(date_,time_);
}
function convertMysqlDateTime(date_,time_) {
	// convert date 'dd.mm.yyyy' and time 'hh:mm'
	// to 'yyyy-mm-dd hh:mm:00'
	//     0    5  8 11 14
	if (!date_) return '';
	if (!time_) time_ = '00:00';
	var timestamp_ = date_.substr(6,4)+'-'
									+date_.substr(3,2)+'-'
									+date_.substr(0,2)+' '
									+time_+':00';
	return timestamp_;
}
function convertMysqlDate(date_) {
	// convert date 'dd.mm.yyyy' and time 'hh:mm'
	// to 'yyyy-mm-dd'
	if (!Date) return '';
	var mysql_date = date_.substr(6,4)+'-'
									+date_.substr(3,2)+'-'
									+date_.substr(0,2)+' '
	return mysql_date;
}
function countDays(start_date,end_date) {
	// date format dd.mm.yyyy
	var start = new Date(start_date.substr(6,4),start_date.substr(3,2),start_date.substr(0,2));
	var end   = new Date(end_date.substr(6,4),end_date.substr(3,2),end_date.substr(0,2));
	var one_day=1000*60*60*24;
	var days = Math.ceil((end - start)/one_day) + 1;
	logit("days between "+start_date+' and '+end_date+' is '+days);
	return days;
}
function countMysqlDays(start_date,end_date) {
	// date format yyyy-mm-dd
	var start = new Date(start_date.substr(0,4),start_date.substr(5,2),start_date.substr(8,2));
	var end   = new Date(end_date.substr(0,4),end_date.substr(5,2),end_date.substr(8,2));
	var one_day=1000*60*60*24;
	var days = Math.ceil((end - start)/one_day) + 1;
	logit("days between "+start_date+' and '+end_date+' is '+days);
	return days;
}

function retrieveMysqlDateTime(datetime_) {
	// convert  'yyyy-mm-dd hh:mm:00'
	// back to date 'dd.mm.yyyy' and time 'hh:mm'
	var dateO = {};
	if (datetime_) {
		dateO.date_ = datetime_.substr(8,2)+'.'
								 +datetime_.substr(5,2)+'.'
				 	 			 +datetime_.substr(0,4);
		
		dateO.time_ =datetime_.substr(11,2)+':'
							 	+datetime_.substr(14,2);
	}	else {
		dateO.date_ = '';
		dateO.time_ = ''; 
	}
	return dateO;
}
function retrieveMysqlDate(date_) {
	if (!date_) return '';
	// convert  'yyyy-mm-dd'
	// back to date 'dd.mm.yyyy'
	var mydate_ = date_.substr(8,2)+'.'
						 	+	date_.substr(5,2)+'.'
					 	 	+	date_.substr(0,4);
	return mydate_;
}
function initFgButton(node) {
	logit("init the FG BUTTONS")
	$(".fg-button:not(.ui-state-disabled)",node)
	.hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	)
	.mousedown(function(){
			$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
			if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
			else { $(this).addClass("ui-state-active"); }	
	})
	.mouseup(function(){
		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
			$(this).removeClass("ui-state-active");
		}
	});
}
function createCustomIcon(icon_source) {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = iconDir+"shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 32);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	return new GIcon(baseIcon,iconDir+icon_source);
}

function createScenicIcon(icon_src) {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = iconScenicDir+"shadow.png";
	//baseIcon.iconSize = new GSize(12, 31);
	//baseIcon.shadowSize = new GSize(52, 29);
	//baseIcon.iconAnchor = new GPoint(9, 32);
	//baseIcon.infoWindowAnchor = new GPoint(9, 2);

	baseIcon.iconSize = new GSize(21, 31);
	baseIcon.shadowSize = new GSize(52, 29);
	baseIcon.iconAnchor = new GPoint(7, 30);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	return new GIcon(baseIcon,iconScenicDir+icon_src);
}
function getIconSrc(loc_type) {
  var icon_src = "info.png";
	if (loc_type) {
		switch(loc_type) {
			case 'bigcity': 		icon_src = "city_big_blue.png";break;
			case 'city': 				icon_src = "city_red2.png";break;
			case 'village': 		icon_src = "village_blue2.png";break;
			case 'historiccity':icon_src = "historical_city.png";break;
			case 'mountainvillage':icon_src = "mountain_village_orange.png";break;
			case 'hillstation':	icon_src = "hill_station.png";break;
			case 'church': 			icon_src = "church.png";break;
			case 'mosque': 			icon_src = "mosque.png";break;
			case 'temple': 			icon_src = "temple.png";break;
			case 'market': 			icon_src = "fishing.png";break;
			case 'museum': 			icon_src = "building.png";break;
			case 'park': 				icon_src = "nature_park.png";break;
			case 'hotel': 			icon_src = "hotel.png";break;
			case 'camping': 		icon_src = "campground.png";break;
			case 'restaurant': 	icon_src = "food.png";break;
			case 'home': 				icon_src = "house.png";break;
			case 'bar': 				icon_src = "drinks.png";break;
			case 'hike': 				icon_src = "hike.png";break;
			case 'ski': 				icon_src = "sski.png";break;
			case 'beach': 			icon_src = "spa.png";break;
			case 'swim': 				icon_src = "swim.png";break;
			case 'scenic': 			icon_src = "scenic.png";break;
			case 'pause': 			icon_src = "pause.png";break;
			default:						icon_src = "info.png";
		}
	}
	return icon_src;
}

function geocode(point_,CB_){
	logit("geocode");
	var geo = new GClientGeocoder();
  geo.getLocations(point_, function(addresses){
  	logit("getLocations");
  	var adr = {};
    if(addresses.Status.code != 200 || addresses.Placemark.length == 0){
    	// no adress found
      logit("No adres data found");
    }else {
    	try {
	    	var res1 = addresses.Placemark[0].AddressDetails.Country;
	    	adr.geo_country = res1.CountryName;
	    	adr.geo_country_cd = res1.CountryNameCode;
	    	if (res1.AdministrativeArea) {
					var res2 = res1.AdministrativeArea;
		    	if (res2.Locality) {
		    		if (res2.Locality.LocalityName)	adr.geo_city = res2.Locality.LocalityName;
		    	} else {
			    	if (res2.SubAdministrativeArea) {
			    		if (res2.SubAdministrativeArea.Locality) {
			    			adr.geo_city = res2.SubAdministrativeArea.Locality.LocalityName;
			    		} else {
			 		   		if (res2.AdministrativeAreaName) {
			    				adr.state = res2.AdministrativeAreaName;
			    			}
			    		}
			    	}
		    	}
		    }
		  } catch(err) {
		  	//alert("error");
		  }
    }
    //alert("cont");
    adr.country = adr.geo_country;
    adr.city = adr.geo_city;
    adr.geo_lat = point_.lat(); // save lat/lng for the stored geo-adres, check later if it needs to be updated
    adr.geo_lng = point_.lng();
  	CB_(point_,adr);
  });
}
/*
 Adds Text to toadd with sep as seperator
 */
function addText(toadd,text,sep) {
	if (text) {
		if (toadd === "") {
			return text;
		} else {
			return toadd+sep+text; 
		}
	} else {
		return toadd;
	}
}

/*
funtion integer(value) {
	// Because if value starte with 0, then result will be hexadeciaml !!!!! 
	parseInt(value,10);
}
*/	
function showLoading(text) {
	var backgr = $("#map_background");

	if (text) {
	
		$("#map_background p").html(text);
	
		var ah = $(backgr).height();
		var ph = $(window).height();
		var mh = (ph - ah) / 2;
		logit("mh="+mh);
	
		backgr.css('top', mh).css("opacity",0.3).show();
	} else {
		backgr.hide("slow");
	}
}
function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}
// from http://www.mredkj.com/javascript/nfbasic.html
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
