var debug = false;

var iconDir = 'myicons/';
var kmlDir  = 'kml/';

var ie6 = !window.XMLHttpRequest;

/**
 Common Functions
 **/
function logit(text) {
	//logit("caller is " + arguments.callee.caller.toString());
	logitAll("main-"+text);
}
function logitAll(text) {
	if (debug && window.console) {window.console.log(text);};
}
function logitA() {  
	if (debug && window.console) {                                  
	  var putstr = '';                                    
	  for (i = 0; i < arguments.length; i += 1) {         
	    if (putstr !== '') {                               
	      putstr += ',';                                  
	    }                                                 
	    putstr += arguments[i];                           
	  }                                                   
	  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) {
			callback(img);
		} else {
			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 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 calcPosition(containerDiv,popupDiv,mapPoint) {
	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 window
	var top1 = $(containerDiv).offset().top;
	var left1 = $(containerDiv).offset().left;
	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);
	
	var popup_width = $(popupDiv).width();
	var popup_height = $(popupDiv).height();
	logit("popup w/h"+popup_width+'/'+popup_height);
	// calc marker x,y coords
	var x = point1.x;
	var y = point1.y;
	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 - popup_height + 20;
	} else {
		// show below marker 
		logit("show below:"+y);
		y = y - 20;
	}
	if (y < 0) {
		// correct if above google window
		y = 0;
	}
	logit("after y="+y);
	if (x > map_width_middle) {
		logit("show left:"+x);
		// show left
		x =  x - popup_width - 20;
	} else {
		logit("show right:"+x);
		// show right
		x = x + 20;
	}
	logit("after x="+x);
	var xmax = x + popup_width;
	if (x < 0 || xmax > map_width) {
		logit("correct x to null:"+x);
		if (xmax > map_width) {
			x = map_width - popup_width;
		}
		if (x < 0) {
			x = 0;
		}
		if (point1.y > map_height_middle) {
			// show above marker
			logit("show above:"+y+"/"+popup_height);
			y =  point1.y - popup_height - 25;
		} else {
			// show below marker
			logit("show below:"+y);
			y =  point1.y + 5;			
		}
	}
	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;
}
