// global arrays
var bufferArray = new Array(); // objects buffered (not added)
var presentArray = new Array(); // objects present on map
// var hasBeenPresentArray = new Array(); // objects that has been on screen, deprecated  
var smi = new Array();

// global vars
var recordCount;
var map; // the map
var timeOutTimeInMs = 30000; // global timeout for markers
var fetched = 0; // to be able to see if data has been fetched for first time
var bufferMaxSize = 3000;   // failsafe
var unregisterInterval = 200;
var addInterval = 1000; // is changed at runtime 
var fetchInterval = 5000;  

 



// -----------
// wrapper
// -----------
function toArray(array, value){
	array.push(value);
}
 
 



// -----------
// just closes infowin
// -----------
function onCloseInfoWin(){
	Effect.BlindUp('infowindow-general', { duration: 0.3 });
	
	 
}
      


// -----------
// displays info window onklick
// -----------
function displayInfoWin(id){
	
	setInfoWinPos();
	 
	var markers = [];
	 
	 
 var url = "result_data.php?" + new Date().getTime() + "&id=" + id; 
	 
	
	GDownloadUrl(url, function(data, responseCode) {
 
		// parse xml
		var xml = GXml.parse(data);
		
		// extract node
		var markers = xml.documentElement.getElementsByTagName("marker");
	 	
	  	// extract variabeles
	  	var id = markers[0].getAttribute("id");
	  	var fromcity = markers[0].getAttribute("fromcity");
	 
	  	var tocity = markers[0].getAttribute("tocity");
	  	var fromcountry = markers[0].getAttribute("fromcountry");
	  	var tocountry = markers[0].getAttribute("tocountry");
	  	var fromdate = markers[0].getAttribute("fromdate");
	  	var todate = markers[0].getAttribute("todate");
	  	var tor = markers[0].getAttribute("tor");
	  	var childamount = markers[0].getAttribute("childamount");
	  	var grownamount = markers[0].getAttribute("grownamount");
	  	var price = markers[0].getAttribute("price");
 	 
	  	// add to li arr 
	  	var liC = "";
	  	if(tor=="1"){liC = liC + '<li><strong>Detta är en tur och retur resa</strong></li>';}else{liC = liC + '<li><strong>Detta är en enkelresa</strong></li>';};

	  	if(fromcity!=""){liC = liC + '<li><strong>Från:</strong> ' + fromcity + ', ' + fromcountry +'</li>';};
		if(fromcountry!=""){liC = liC + '<li><strong>Till:</strong> ' + tocity + ', ' + tocountry +'</li>';};
	  	
	  	if(fromdate!=""){liC = liC + '<li><strong>Utresedatum:</strong> ' + fromdate + '</li>';};
	  	if(todate!=""){liC = liC + '<li><strong>Hemresedatum:</strong> ' + todate + '</li>';};
	  	
	  	if(grownamount!=""){liC = liC + '<li><strong>Antal vuxna:</strong> ' + grownamount + '</li>';};
	  	if(childamount!=""){liC = liC + '<li><strong>Antal barn:</strong> ' + childamount + '</li>';};
	  	if(price!=""){liC = liC + '<li><strong>Pris:</strong> ' + price + ' kr</li>';};
	  	if(id!=""){liC = liC + '<li>' + "<a target=\"_blank\" style=\"color:#ffffff\" href=\"http://www.flygresor.se/showresult.php?id=" + id + "\">" + "Klicka här för att se hela sökresultatet »</a>" + '</li>';};
	  	//if(link!=""){liC = liC + '<li><strong>Pris:</strong> ' + price + '</li>';};
	 	
	  	
	  	// close img
	   var cbtn = '<img style="float:right;clear:both;position:relative;top:5px;right:5px;" onclick="onCloseInfoWin()" src="http://www.flygradar.nu/images/closebtn.gif" alt="Stäng"/>';

 		var content = "";
       var content = content + cbtn;
	   var content = content + "<ul>" + liC + "</ul>" ;
		
		 
		document.getElementById('infowindow-general').innerHTML = content;
		
		
		//Effect.BlindDown('infowindow-general');
		 
		Effect.BlindDown('infowindow-general', { duration: 0.0 });

		
	 
		
	});
	
	
} 




// -----------
// creates marker
// -----------
function createMarker(point, infoText, img, id, sweCity){
	
    icon = new GIcon();
    icon.image = 'images/custompriceicon.png';
    icon.iconSize = new GSize(75, 36);
    icon.iconAnchor = new GPoint(58, 33);
    icon.infoWindowAnchor = new GPoint(25, 7);

    var entry="test";
  	var markerid = "marker"+ id;
  	 
    var html = "<div  style=\"font-size:12px;display:none;\">";
    var title = infoText  ;
    var label = "sdfsdf";
    var rank = 0;
    html += "</div>";

      // create the marker
    var markerOpts = {};

  markerOpts = {
	"icon": icon,
	"clickable": true,
	"labelText": title,
	"labelOffset": new GSize(-45, -36)
	};
  var newPoint = point;
  var marker = new LabeledMarker(newPoint, markerOpts);
  
 
   //   msap.addOverlay(marker);
   //   cm_mapMarkers.push(marker);

      //cm_mapHTMLS.push(html);
     // bounds.extend(point);
       
  
        
        
  
        GEvent.addListener(marker, "click", function() {
        	  displayInfoWin(id)
        });
 		 
	 
       // Effect.Grow(markerid);
      return marker;   
       
   }

  

// -----------
// aligns infowin
// -----------
function setInfoWinPos(){
	// var adrr = $('map').getOffsetParent();

	var infoWin = $('infowindow-general');
	var infowindowWidth = infoWin.getDimensions().width;
	var infowindowHeight = infoWin.getDimensions().height	

	var map = $('map');
	var mapDim = map.getDimensions();
	var mapWidth = map.getDimensions().width;
	var mapHeight = map.getDimensions().height;	
	var mapArr = map.positionedOffset();
	var mapXPos = mapArr[0];
	var mapYPos = mapArr[1];

	var mainArr = $('main-outer').positionedOffset();
	var mainXPos = mainArr[0]; 
	var mainYPos = mainArr[1]; // always 203
 	
 	// calculate
	var targetY = mainYPos + 50;
	var targetX = mainXPos + mapWidth - infowindowWidth - 10;
	

	//console.log(targetX);

	
	// set
	infoWin.style.position = 'absolute';
	// infoWin.style.top = targetY + "px";
	infoWin.style.top = "235px";
	infoWin.style.left = targetX + "px";
	 
 

}
   
   


// -----------
// xmldata -> bufferarray
// -----------
function fetchData(){
	if(bufferArray > bufferMaxSize){return 0;};
	// define arr
	var saveArr = new Array();
	
	// xml url 
	var url = "price_data.php?" + new Date().getTime(); 
   
		// readfile
		GDownloadUrl(url, function(data, responseCode) {
			
			// parse xml
			var airpxml = GXml.parse(data);
			
			// get elemnt
			var markers = airpxml.documentElement.getElementsByTagName("marker");
			
			// loop xml result
			for (var i = 0; i < markers.length; i++) {
				
				// empty array
				saveArr = [];
  
				// get data on each node
				saveArr[0] = markers[i].getAttribute("lat"); 
				saveArr[1] = markers[i].getAttribute("lng"); 
				saveArr[2] = markers[i].getAttribute("price"); 
				saveArr[3] = markers[i].getAttribute("id"); 
				saveArr[4] = markers[i].getAttribute("swecity"); 

				// create the point
				var point = new GLatLng(saveArr[0],saveArr[1]);
	 			
				// create marker
				// var infoText;
				var img;

				
				
				
				var mrker = createMarker(point, saveArr[2], img, saveArr[3], saveArr[4]);
				saveArr[4] = mrker;
				
 				
				// --- start of fix for first markers 
				if(  (fetched==0) ){
					var smi = new Array();
					smi[0] = saveArr[3];
					smi[1] = Date.parse(new Date());
					smi[2] = mrker;
					if(i!=1 && i!=5){
						presentArray.push(smi);	
					}
					
					// -- end of fix
				}
				
				// present in buffer?
				var isIn = inarray(saveArr[3], bufferArray, 3);
			 	
				// has been on map?
				//var hasBeen = inOneDimArray(saveArr[3], hasBeenPresentArray);
				var hasBeen = inarray(saveArr[3], presentArray, 0);
				
				// adds to buffer array if not present in buffer or has been present earlyer (dual check not nececcary eg)
				if((!isIn) && (!hasBeen) ) {
			 		// add to bufferarray(push method adds to end of array) 
			 		bufferArray.push(saveArr);
			 	}
			}
 
		})
		// alert('buffer-array:' + bufferArray.length);
	return 1;
} // func end

 
 
// -----------
// check if needle is in haystack (array on lvl -pos)
// -----------
function inarray(needle, array, pos){
 
	for (var i = 0; i < array.length; i++) {
		// alert(array[i][pos] + " = " + needle + "\n\n");
		if (array[i][pos] == needle){
			return 1;  // present, return true	
		}
	} 
	return 0; // not present, return false
}

	 
	
// -----------
// check if needle is in haystack (array on lvl -pos).. 1 dim version
// -----------
function inOneDimArray(needle, array){
 
	for (var i = 0; i < array.length; i++) {
	 
		if (array[i]  == needle){
			return 1;  // present, return true	
		}
	} 
	return 0; 
}

	 
	

	
	
// -----------
// add to map
// -> max amount to add
// -> fromArr = array to read from (usually bufferArray)
// -----------
function addToMap(amounTotAdd){
		 //console.log(bufferArray.length);


		  var bal =  bufferArray.length;
 		
 		//alert(presentArray.length);
 	 
 		var someMarkerInfo = new Array();
		
 		id="";
		marker="";
		
  		var i = 0;
  		
 		while ((i<amounTotAdd) && (i<bal)){
 			 
	
 			
			// get marker from array, and remove it
			var markerArr = bufferArray.shift();
			
			var lat = markerArr[0];
			var lng = markerArr[1];
			var price = markerArr[2];
			var id = markerArr[3]; 
			var swecity = markerArr[4]; 
			
			
			var marker = markerArr[4]; 

			// puts overlay marker on map
			map.addOverlay(marker);
			someMarkerInfo = [];

			// puts this marker in presentArray
			someMarkerInfo[0] = id;
			
			//alert('someMarkerInfo[0]: ' + someMarkerInfo[0] + ', id: ' + id);
			tstmp = Date.parse(new Date());
			someMarkerInfo[1] = tstmp;
			someMarkerInfo[2] = marker;
	 
			
			//someMarkerInfo[0] = ran_number;
			
			//var presentArrLen = presentArray.length;
				 
			//presentArray[presentArrLen+1] = someMarkerInfo;
			//alert(someMarkerInfo);
			
			// console.log(id);
			
			// adds to presentarray
			presentArray.push(someMarkerInfo);
			 
			 
			/*
			 
			presentArray[presentArray.length+1][0] = someMarkerInfo[0];
			presentArray[presentArray.length+1][1] = someMarkerInfo[1];
			presentArray[presentArray.length+1][2] = someMarkerInfo[2];
				*/
			
			/*
	
			*/
			// hack, dont know why this inarray() check is neccesarry
			// but if not, the values are duplicated... 2x 
			/*
			if(!(inarray(id, presentArray, 0))){
				
			}
			*/

			
 			i++;
 			
 			
 			
			
		
				
			
			
			
 		}
 		//console.log(presentArray);	
 		//alert("addade till present array : " + idn);
 	 
}






// -----------
// unregisters markers that has timed out
// -> from presentArray
// -> from map
// -----------
function unregisterMarker(){
	//alert(presentArray);
	i=0;
	
	// loop and remove from map, all that has timed out
	// Custom loop with cached length property: maximum full-loop performance on very large arrays!
	for (var index = 0, len = presentArray.length; index < len; ++index) {
		var item = presentArray[index];
		id = item[0];
		time = item[1];
		marker = item[2];
		
		// has been present time
		var hasBeenPresentTime = ( Date.parse(new Date()) - time ) ;
		//alert('timeOutTimeInMs: ' + timeOutTimeInMs + "\n hasBeenPresentTime: " + hasBeenPresentTime);
		
		
		// should we remove?
		//map.removeOverlay(marker);
		
		if(hasBeenPresentTime > timeOutTimeInMs){
			i++;	
	//	alert('remove id ' + id + '' );
		
			// removes in 2 different ways, but really menaning the same
			// a marker cannot be on map, having timed out, and not be att the top
			map.removeOverlay(marker);
			//presentArray.shift();
		}
		
		
	 
		 
	
 
	}
	
		//console.log(i);	 
	 // alert(m);
	
	// "i" represents amount to be removed from presentArray
	// so loop and remove
	for (var index = 0, len = presentArray.length; index < len; ++index) {
		if(index <= i){
			
		}
	}
	// alert('presentA: ' + presentArray.length + "\n" + "bufferA: " + bufferArray.length)
	
	 
	
	//alert(i);

 		// alert(item[1]);
 
 
	
}




	
// -----------
// maximize window height
// -----------
function handleResize() {
  var height = windowHeight();
  document.getElementById('map').style.height = height + 'px';
 
  //alert(bufferArray);
  // document.getElementById('sidebar').style.height = height + 'px';
}

// -----------
// get window height
// -----------
 function windowHeight() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight) {
    return self.innerHeight;
  }
  // IE 6
  if (document.documentElement && document.documentElement.clientHeight) {
   return document.documentElement.clientHeight;
  }
  // IE 5
  if (document.body) {
    return document.body.clientHeight;
  }
  // Just in case. 
  return 0;
}


 

// -----------
// function is run every x seconds, ie wrapped by setinterval
// -----------
function bigLoop(){
	  fetched = fetchData();
	if(fetched){
		// get value
			
		if(bufferArray.length>0){
			clearInterval(addLoopReferenceId); // referense to previous set interval
 			addLoopReferenceId = setInterval("addLoop()",addInterval); // resets/restarts to new time
	nrPerSec = bufferArray.length / (fetchInterval/1000);
		addInterval = Math.round(1000/nrPerSec)+300 ; // the last int is to has atleast x sek 

		} 
		// change iteration speed
			
		 // console.log('addar var: ' + addInterval  + 'sek - buffer: ' + bufferArray.length + 'presentarr: ' + presentArray.length);	
	}
	  
}



// -----------
// function is run every x seconds, 
// ie wrapped by setinterval
// adds markers to map
// -----------
function addLoop(){

	// to prevent mem overflow
	if(presentArray.length>2000){
		window.location.reload();
	}
	
		// only try to add to map from buffer, if buffer > 0 (prevents error)
	if(bufferArray.length>0){
		addToMap(1);
	}
 
}



// -----------
// function is run x times per second (wrapped by setinterval)
// unregisters markers from map
// 
// -----------
function unregisterLoop(){
	// only remove if presentArray > 0
	if(presentArray.length>0){ 
		unregisterMarker();
	}
}


// -----------
// check if variable is defined, nog used alot (if at all)
// -----------
function isDefined(variable){
	
	return (!(!(document.getElementById(variable))))

}



// -----------
// initiates the gmap
// -----------
function initiateGmap(){
	// is browser capable?
	if (GBrowserIsCompatible()) {
	 
		map = new GMap2(document.getElementById("map"));
       	map.setMapType(G_PHYSICAL_MAP);
		mapLat = 25; mapLng = 6; mapZoom = 2; 
		map.setCenter(new GLatLng(mapLat, mapLng), mapZoom);
  		
		// controls
		 
		var mapControl = new GMapTypeControl();
		map.addControl(new GLargeMapControl());
		// map.setMapType(G_PHYSICAL_MAP); 
		// map.addMapType(G_PHYSICAL_MAP);
		// map.addControl(mapControl);
		
		
		
		return 1;
		// not capable
	}else {
		return 0;
	}
}





// -----------
// initiate.. onload
// -----------
function init(){
	 
	// fit to viewport
	// handleResize(); 

	// create gmap
	var initiated = initiateGmap();
 	
	//initiated?
	if(initiated){
		fetchData();
	// interval functions, big and small.
		setInterval("bigLoop()", fetchInterval);  
		addLoopReferenceId = setInterval("addLoop()", addInterval); 	
		setInterval("unregisterLoop()", unregisterInterval); 	
		// setInterval("unregisterLoop()", unregisterInterval); 	
		
		 
	}else{
		// error mess here
	}
 
}


     
// keeps things in js file ftw
Event.observe( window, 'load', function() {
	init();
	} );
window.onresize = setInfoWinPos; // resizes when changed

