/*
    ------------------------
	WebserviceBroker 
	------------------------
	todo: workload etc
*/

	// --------------------------------------
	// Object
	// --------------------------------------
	// add a simple method for 
	// detecting objects
	Object.prototype.objectType = function()
	{
		var obType = String(this.constructor).match(/function\s+(\w+)/);

		if(obType) return obType[1];
		return "undefined"; // just in case...
	}

function WebServiceBroker()
{
	this.version=1.04;
	this.servicesSent=new Array();
	
	this.divId="";
	
	this.requestId=0;
	
	return this;
}
		
	
		// add Request
		WebServiceBroker.prototype.addWebServiceRequest = function( gameId, gameobjectId, area, areaSub, action, actionSub, argument, argumentSub )
		{
			// alert("addWebServiceRequest");
			// alert( gameId+"  "+ gameobjectId+"  "+ action+"  "+ actionSub+"  "+ argument +"  "+ argumentSub );
			
			var objRequest=new WebserviceRequest();
				objRequest.gameId=gameId;
				objRequest.gameobjectId=gameobjectId;
				objRequest.area=area;
				objRequest.areaSub=areaSub;
				objRequest.action=action;
				objRequest.actionSub=actionSub;
				objRequest.argument=argument;
				objRequest.argumentSub=argumentSub;
				
			// generate an url .. 
			this.addWebServiceRequestObject(objRequest);
		
			return objRequest;
		};	
		
		WebServiceBroker.prototype.addWebServiceREST = function( url )
		{
			var obj=new WebserviceRequest();
				obj.requestUrl=url;
			
			// generate an url .. 
			this.addWebServiceRequestObject(obj);
		
			// alert(url);
		
			return obj;
		};			
	
		// uses showHtmlInDiv
		WebServiceBroker.prototype.addWebServiceRequestObject=function( obj )
		{
			this.requestId++;

//			obj.webservicebrokerObj=this;
			obj.serviceId=this.requestId;
			
			// generate a div there
			divStr="<div id='request"+this.requestId+"'><a href='javascript:void()' onClick=\"showHtmlInDiv('inspectorContent',''+webservicebrokerObj.requestWithOutputTypeById("+this.requestId+",'detail'))\">Request "+this.requestId+" load</a></div>";
//			alert(divStr);
			this.addStatusRequest(divStr);
			
// special
obj.gameobjectId=actualGameObjectPositionsId;
if (obj.actionSub=="deadlimit")
{
	obj.gameobjectId=actualGameObjectDeadLimitId;
}
			
			// do Rest Request
			if (obj.requestUrl=="")
			{
				// change ! actgameobjectid
				obj.requestUrl="load.php?serviceId="+escape(obj.serviceId)+"&gameId="+escape(obj.gameId)+"&actgameobjectid="+escape(obj.gameobjectId)+"&area="+escape(obj.area)+"&areaSub="+escape(obj.areaSub)+"&action="+escape(obj.action)+"&actionSub="+escape(obj.actionSub)+"&argument="+escape(obj.argument)+"&argumentSub="+escape(obj.argumentSub)+"";
			}
			
			// alert(obj.requestUrl);

			// service sent			
			this.servicesSent[this.servicesSent.length]=obj;
			
			// do request
			obj.doRequest();
			
			return obj;
		};	
		
		WebServiceBroker.prototype.requestWithOutputType=function( obj, type )
		{
			str=obj.getWithOutputType(type);
			return ""+str;
		}
		
		// by id
		// 	requestWithOutputTypeById
		WebServiceBroker.prototype.requestWithOutputTypeById=function( requestId, type )
		{
			obj=this.getRequestObjectById(requestId);
			if (obj) return obj.getWithOutputType(type);
			return "not found";
		}
		
		
		WebServiceBroker.prototype.addStatusRequest=function( txt )
		{ 
			// alert(txt);
			// alert(''+txt);
			
			// document.writeln(txt+"  "+this.divId);
			divObj=document.getElementById(this.divId);
			if (divObj)
			{
				// document.writeln("divfound");
				divObj.innerHTML=txt+""+divObj.innerHTML;
				// document.writeln(txt);
			}
		}

		WebServiceBroker.prototype.addStatusResponse=function( txt )
		{
			divObj=document.getElementById(this.divId);
			if (divObj)
			{
				// document.writeln(txt);
				
			}
		}
		
		// searching
		WebServiceBroker.prototype.getRequestObjectById=function( serviceId, type )
		{
			for (t=0;t<this.servicesSent.length;t++)
			{
				obj=this.servicesSent[t];
				if (obj.serviceId==serviceId)
				{
					return obj;
				}
			}
			
			return null;
		}
		
		/*
			show methodes
		*/

		// setOutputDivId
		WebServiceBroker.prototype.setOutputDivId = function( divId )
		{
			// alert(divId);
			this.divId=divId;
		}
		
		/* 
			simple show functions
		*/
		// show functions ...
		WebServiceBroker.prototype.showHtmlInDiv=function( divId, strHtml )
		{
				divObj=document.getElementById(divId);
				if (divObj)
				{
					// alert(strHtml);
					divObj.innerHTML=""+strHtml;
				}

		}
		

// gameId, gameobjectId, action, actionSub, argument, argumentSub

function WebserviceRequest()
{
	// broker
	this.webservicebrokerObj;
	
	// status
	this.serviceId=-1; 
	
	this.gameId=-1; 

	this.gameobjectId=-1; 
	
	this.area="";
	this.areaSub="";

	this.action="";
	this.actionSub="";
	
	this.attributeId=-1; // not used
	this.attributeArgument=-1;  // not used

	this.requestUrl=""; 
	
	this.initTimeObject=new Date();

	this.startTimeService;
	
	// answer ..
	this.answerHTML="";
	this.answer="";
	
	this.endTimeService;
	
	// loaded function
}
	WebserviceRequest.prototype.getWithOutputType=function( type )
	{
		str=	"<br>id: "+this.serviceId;	
		str=str+"<br>actionSub: "+this.actionSub;	
		str=str+"<br>actionSub: "+this.actionSub;	
		str=str+"<br>answerHTML: "+this.answerHTML.substring(0,100)+"...";	

		return str;
	}
	
	WebserviceRequest.prototype.doRequest=function(  )
	{
		siteUrl=this.requestUrl; // "index.php";
		this.startTimeService=new Date();
			
			var xmlHttpReq = false; 
			var self = this; 
			// Mozilla/Safari 
		   if (window.XMLHttpRequest) { 
				self.xmlHttpReq = new XMLHttpRequest(); 
			} 
			// IE 
			else if (window.ActiveXObject) { 
				self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
			} 
			//self.xmlHttpReq.open('POST', siteUrl, true); 
			self.xmlHttpReq.open('GET', siteUrl, true); 
			
			self.xmlHttpReq.setRequestHeader('Content-Type', 'text/html'); 
			
			self.xmlHttpReq.onreadystatechange =  
							function()  
							{ 
								if (self.xmlHttpReq.readyState == 4) 
								{ 
									// contentLoaded(self.xmlHttpReq.responseText); 
									// alert("test");
									self.requestDone( self, self.xmlHttpReq.responseText);
								} 
							} 
			self.xmlHttpReq.send(siteUrl); 
	}

	

	WebserviceRequest.prototype.requestDone=function(  webserviceRequest, requestAnswerText  )
	{
		// alert("load");
		// document.writeln("---"+requestAnswer);
		// alert("---"+webserviceRequest.serviceId+"  "+requestAnswerText);
		
//	 alert("WebserviceBroker "+webserviceRequest.action+" "+webserviceRequest.actionSub+"\n"+webserviceRequest.requestUrl+"\n"+requestAnswerText);        

		if (true)
		{
			divObj=document.getElementById("webservicelog");
			if (divObj)  
			{
				// webserviceRequest.requestUrl
				// divObj.innerHTML="request "+webserviceRequest.action+" "+webserviceRequest.actionSub+"<br>answer: "+requestAnswerText+"<br>"+divObj.innerHTML;
				// divObj.innerHTML="request "+webserviceRequest.action+" "+webserviceRequest.actionSub+"<br><br>"+divObj.innerHTML;
			}
		}	
		
	
		
		// split in javascript
		requestAnswerText=""+requestAnswerText;
		arr=requestAnswerText.split("\n");
		for (t=0;t<arr.length;t++)
		{
			// alert(t+"  "+arr[t]);
			strLine=arr[t];
			// split now ;
			
			// if (webserviceRequest.actionSub=="countryhighscore") alert(strLine);
			
			arrValues=strLine.split(";");
		
			// get last ...
			
			// only one?
			if (t==0) 
			if (arrValues.length==1) {  
				actualGameObjectPositionsId=arrValues[0];  
				if (webserviceRequest.actionSub=="deadlimit")
				{
					actualGameObjectDeadLimitId=arrValues[0];  
				}
			}
			
				// clear it ..
			if (t==0) 	
			if (webserviceRequest.actionSub=="deadbodylast")
			{
				divObj=document.getElementById("deadbodylast");
				if (divObj)
				{
						divObj.innerHTML=" <a href='map.php'>+++ fraqs + "+arrValues[0]+" +++  incoming +</a> ";
				}
			}
			
			if (webserviceRequest.actionSub=="countryhighscore")
			{
				if (t>0)
				{
					divObj=document.getElementById("countryhighscore");	
					if (divObj)
					{
						divObj.innerHTML=divObj.innerHTML+"<a href='map.php'>+ "+arrValues[2]+" + "+arrValues[11]+" +</a><br>";
					}
				}
				if (t>7) 
				{
					divObj.innerHTML=divObj.innerHTML+"+ ... +";
					break;
				}
			}
			
			// alert("got you "+webserviceRequest.action);
			
			// webserviceRequest
			if (webserviceRequest.action=="get")
			{
				if (webserviceRequest.actionSub=="locations")
				{
					// insert a marker here
					if (arrValues.length>1)
					{
						var lat=arrValues[7];
						var lng=arrValues[8];
				
						// use array with objects for this?
				
						// ok add gmarkers
						// map.setCenter(new GLatLng(lat, lng), 1);
						map.setCenter(new GLatLng(ownPositionLat, ownPositionLng), 2);
 						// map.panTo(new GLatLng(ownPositionLat, ownPositionLng), 1);
 						
 
						centerPoint=map.getCenter();
						
						var myIcon = new GIcon();
						myIcon.image = 'imgs/image.png';
						//myIcon.printImage = 'imgs/printImage.gif';
						//myIcon.mozPrintImage = 'imgs/mozPrintImage.gif';
						myIcon.iconSize = new GSize(45,71);
						// myIcon.shadow = 'imgs/shadow.png';
						//myIcon.transparent = 'imgs/transparent.png';
						myIcon.shadowSize = new GSize(81,71);
						//myIcon.printShadow = 'imgs/printShadow.gif';
						myIcon.iconAnchor = new GPoint(23,71);
						myIcon.infoWindowAnchor = new GPoint(23,0);
						myIcon.imageMap = [25,3,26,4,28,5,44,6,44,7,43,8,43,9,42,10,42,11,42,12,42,13,41,14,40,15,39,16,39,17,39,18,39,19,39,20,40,21,40,22,40,23,40,24,40,25,40,26,37,27,31,28,31,29,31,30,31,31,31,32,31,33,31,34,31,35,31,36,31,37,31,38,31,39,32,40,32,41,32,42,32,43,32,44,32,45,32,46,32,47,32,48,32,49,32,50,32,51,33,52,33,53,33,54,33,55,33,56,33,57,33,58,33,59,33,60,33,61,33,62,33,63,33,64,33,65,33,66,34,67,33,68,26,69,25,70,19,70,18,69,18,68,19,67,13,66,13,65,13,64,13,63,14,62,14,61,14,60,14,59,14,58,14,57,14,56,14,55,14,54,15,53,15,52,15,51,15,50,15,49,15,48,15,47,15,46,15,45,16,44,16,43,16,42,0,41,0,40,1,39,1,38,2,37,3,36,4,35,5,34,6,33,7,32,8,31,9,30,10,29,11,28,12,27,11,26,11,25,12,24,13,23,14,22,14,21,14,20,14,19,16,18,17,17,16,16,15,15,15,14,20,13,18,12,16,11,16,10,16,9,17,8,17,7,18,6,18,5,18,4,19,3];						

						var latlng = new GLatLng(lat,
											  lng);
						// map.addOverlay(new GMarker(latlng));


						  markerOptions = { icon:myIcon };
  						  var marker = new GMarker(latlng, markerOptions);
  						  map.addOverlay(marker);
  						  
  						 // var htmlText=""+arrValues[2]+"("+arrValues[3]+")"+" ("+lat+"/"+lng+")";
  						  
						   // show infos there ...
						   // GEvent.addListener(marker, "click", function() { alert("You clicked the map."); });
						   GEvent.addListener(marker, "click", function (latlng) { if (latlng) { /* alert("You clicked the map."+latlng); */ map.setZoom(7);  map.panTo(latlng);   } });
//						   GEvent.addListener(marker,"mouseover", function(latlng) {  marker.openInfoWindowHtml("hallo here i am "+htmlText); });  
							/*
								GEvent.addListener(marker, "click", function() {
							    marker.openInfoWindowHtml("Marker <b>" + t + "</b>");
								  });
							  */
          
					}
					
				
				} // locations
				
				// deadlimit
				if (webserviceRequest.actionSub=="deadlimit")
				{
					if (arrValues.length>1)
					{
						// add a corps in logdiv
						divObj=document.getElementById("deadlog");
						if (divObj)
						{
							// divObj.innerHTML=" "+arrValues[10]+" killed person in "+arrValues[2]+" ("+arrValues[3]+")  ["+arrValues[7]+"/"+arrValues[8]+"] <br>"+divObj.innerHTML;
							divObj.innerHTML=" "+arrValues[10]+" <a href='javascript:void()' onClick=\" map.setZoom(7); map.panTo(new GLatLng("+arrValues[7]+","+arrValues[8]+")); \">"+arrValues[3]+" ("+arrValues[2]+")</a><!-- <br> -->"+divObj.innerHTML;
						
							var textLimit=3000;
							if (divObj.innerHTML.length>textLimit) 
							{
								divObj.innerHTML=divObj.innerHTML.substring(0,textLimit)+"[...]";
							}
						}
					}
					/*
					else
					{
						divObj=document.getElementById("deadlog");
						if (divObj)  
						{
							divObj.innerHTML=divObj.innerHTML."no new deads "; // +webserviceRequest.requestUrl+"<br>"+divObj.innerHTML;
						}
						
					}
					*/
				}
				
				// deadbodylast
				if (webserviceRequest.actionSub=="deadbodylast")
				{
					if (arrValues.length>1)
					{
						// add a corps in logdiv
						divObj=document.getElementById("deadbodylast");
						if (divObj)
						{
							// divObj.innerHTML=" "+arrValues[10]+" killed person in "+arrValues[2]+" ("+arrValues[3]+")  ["+arrValues[7]+"/"+arrValues[8]+"] <br>"+divObj.innerHTML;
							divObj.innerHTML=divObj.innerHTML+" <a href='map.php?lat="+arrValues[7]+"&lng="+arrValues[8]+"'>"+arrValues[2]+"+++ "+arrValues[3]+" +++ "+arrValues[10]+" +++ </a>";
						
//							divObj.innerHTML=divObj.innerHTML.substring(0,textLimit)+" +++ "+arrValues[10]+" +++ ";

						}
					}
					/*
					else
					{
						divObj=document.getElementById("deadlog");
						if (divObj)  
						{
							divObj.innerHTML=divObj.innerHTML."no new deads "; // +webserviceRequest.requestUrl+"<br>"+divObj.innerHTML;
						}
						
					}
					*/
				}
			
			}
		}

			
			/*
			divObj=document.getElementById("service");
			if (divObj)
			{
				divObj.innerHTML=divObj.innerHTML+"<br>  - ";
			}
			*/
			
		
		// different requests and do special things !
		// alert(""+webserviceRequest.area);
		if (webserviceRequest.isRequestWithArea("user","position"))
		{
			// alert("test");
			/*
			divObj=document.getElementById("service");
			if (divObj)
			{
				divObj.innerHTML=divObj.innerHTML+"<br> set user - ";
			}
			*/
		}


/*		
		// setup
		if (webserviceRequest.isRequestWithArea("setup","users")) // ("setup","users","get","list"))
		{
			// set it to this list 
			// new list
			
			// reset list 
			// add again all
			// alert("hallo");
			if (requestAnswerText!="")
			{
				divObj=document.getElementById("list");
				if (divObj)
				{
					// is there a gamestart?
					// gamestatus: start ...
					if (requestAnswerText.indexOf("<!-- game.status:started -->")!=-1)
					{
						// just a second
						alert("game started\ngo to your aircraft!");
						
						// go on 
						document.location.href='game.php';	
					}
				
					divObj.innerHTML=requestAnswerText;
					// divObj.innerHTML+"<br><script>alert('abc');</script>**<b>"+requestAnswerText+"";
				}			
			}
		}

		// user/team		
		if (webserviceRequest.isRequestWithArea("game","users"))
		{
			if (requestAnswerText!="")
			{
				divObj=document.getElementById("list");
				if (divObj)
				{
					// is there a gamestart?
					// gamestatus: start ...
					if (requestAnswerText.indexOf("<!-- game.status:started ____-->")!=-1)
					{
						// just a second
						alert("game started\ngo to your aircraft!");
						
						// go on 
						document.location.href='game.php';	
					}
				
					divObj.innerHTML=requestAnswerText;
					// divObj.innerHTML+"<br><script>alert('abc');</script>**<b>"+requestAnswerText+"";
				}
				else
				{
					alert("could not find!");
				}
			}
		}
		
		// 
		
		// document.writeln("--"+request);
		
		divObj=document.getElementById("request"+webserviceRequest.serviceId);
		if (divObj)
		{
			webserviceRequest.endTimeService=new Date();
			
			divObj.innerHTML=divObj.innerHTML+"  ("+webserviceRequest.requestUrl+") ";
			divObj.innerHTML=divObj.innerHTML+" done ";
			divObj.innerHTML=divObj.innerHTML+(webserviceRequest.getTotalMilliseconds( webserviceRequest.endTimeService )-webserviceRequest.getTotalMilliseconds(webserviceRequest.startTimeService))+" ms";
		
			// answer
			webserviceRequest.answerHTML=requestAnswerText;
			
			// parse this to object .. 
			// parse it ... ! ...
			
		}
		
		*/
		
	}
				// isRequestWith
				WebserviceRequest.prototype.isRequestWithAreaAction=function(  area,areaSub,action,actionSub  )
				{
//					alert("   "+this.area);
					if (this.area==area)
					{
						if (this.areaSub==areaSub)
						{
							if (this.action==action)
							{
								if (this.actionSub=actionSub)
								{
									return true;
								}
							}
						}
					}
					
					return false;
				}	

				// isRequestWith
				WebserviceRequest.prototype.isRequestWithArea=function(  area,areaSub  )
				{
//					alert("   "+this.area);
					if (this.area==area)
					{
						if (this.areaSub==areaSub)
						{
							return true;
						}
					}
					
					return false;
				}	

	WebserviceRequest.prototype.getTotalMilliseconds=function(  dateObj  )
	{
		total=dateObj.getHours()*3600*1000+dateObj.getMinutes()*60*1000+dateObj.getSeconds()*1000+dateObj.getMilliseconds();
		return total;
	}	

	
	
