var GetChaturl = "getChatData.php";
var SendChaturl = "inc/sendAddressData.php";
var SendBewertungUrl = "inc/setBewertung.php";
var SendEmailUrl = "inc/sendafriend.php";
var lastID = -1; //initial value will be replaced by the latest known id

window.onload = initJavaScript;

function initJavaScript() {
	//document.forms['newdata'].elements['name'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
	//checkStatus(''); //sets the initial value and state of the input comment
	//checkName(); //checks the initial value of the input name
	//receiveChatText(); //initiates the first data query
}

//initiates the first data query
function receiveChatText() {
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
  	//sid = document.forms['chatForm'].elements['sid'].value;
		//limit = document.forms['chatForm'].elements['limit'].value;
  	httpReceiveChat.open("GET",GetChaturl + '?lastID=' + lastID + '&sid=' + sid +  '&limit=' + limit + '&rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveChat.onreadystatechange = handlehHttpReceiveChat; 
  	httpReceiveChat.send(null);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat() {
  var counter = 0;
  if (httpReceiveChat.readyState == 4) {
    results = httpReceiveChat.responseText.split('---'); //the fields are seperated by ---
    if (results.length > 2) {
	    for(i=0;i < (results.length-1);i=i+4) { //goes through the result one message at a time
	    	counter = insertNewContent(results[i+1],results[i+2], results[i+3], counter); //inserts the new content into the page
	    	// weil desc im select nicht die größte ID zurückliefert
	    	//alert(results[results.length-5]);

	    	if (results[i+0] > lastID) {
	    		lastID = results[i+0];
				}
     }
	  
	  
	//child=document.getElementById("outputList").lastChild;
	//document.getElementById("outputList").parentNode.removeChild(child);
	  
	//var element = document.getElementById("outputList");
  //element = element.getElementsByTagName("li");
	//alert(element.removeChild(element.parentNode));
		limit = document.forms['chatForm'].elements['limit'].value;
		if (counter == limit) {
			document.getElementById("outputList").removeChild(document.getElementById("wirdgeladen"));
		}
	//document.getElementById("outputList").removeChild(document.getElementById("outputList").lastChild);
	
	
	//document.getElementsByTagName("li")(document.getElementById("outputList"));
	
	//element.removeChild(element.lastChild);
 	//element.removeChild(element.lastChild);
    
    }
    setTimeout('receiveChatText();',9000); //executes the next data query in 9 seconds
  }
}

//inserts the new content into the page
function insertNewContent(liName,liText, liDatum, counter) {
		
	insertO = document.getElementById("outputList");
	oLi = document.createElement('li');
	if (counter%2) {
	oLi.setAttribute('className','tdcolor2'); //for IE's sake
	oLi.setAttribute('class','tdcolor2'); //for IE's sake
	}
	
	oSpan = document.createElement('span');
	oSpan.setAttribute('className','name'); //for IE's sake
	oSpan.setAttribute('class','name');
	
	oSpanDatum = document.createElement('span');
	oSpanDatum.setAttribute('className','datum'); //for IE's sake
	oSpanDatum.setAttribute('class','datum');
	
	oSpanText = document.createElement('span');
	oSpanText.setAttribute('className','text'); //for IE's sake
	oSpanText.setAttribute('class','text');
	
	oName = document.createTextNode(liName);
	oText = document.createTextNode("");
	oDatum = document.createTextNode(liDatum);
	oSpanText.innerHTML = liText;

	oSpan.appendChild(oName);
	oSpanDatum.appendChild(oDatum);
	oSpanText.appendChild(oText);
	
	oLi.appendChild(oSpan);
	oLi.appendChild(oSpanText);
	oLi.appendChild(oSpanDatum);
	insertO.insertBefore(oLi, insertO.firstChild);
	counter++;
	return counter;
}

function sendEmail() {
	var id 				= document.forms['newdata'].elements['id'].value;
	var anemail 	= document.forms['newdata'].elements['anemail'].value;
	var vonemail	= document.forms['newdata'].elements['vonemail'].value;
	
	document.forms['newdata'].elements['anemail'].disabled = true;
	document.forms['newdata'].elements['vonemail'].disabled = true;
	
	document.all.versenden.innerHTML = "Deine eMail wurde verschickt!";
	
	
	param = 'a='+ anemail + '&v=' + vonemail + '&i=' +id;
	httpSendChat.open("POST", SendEmailUrl, true);
	httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
						
	httpSendChat.onreadystatechange = handlehHttpSendChatClean;
	httpSendChat.send(param);
		
	
}

function sendeBewertung() {
	
	var id = document.forms['newdata'].elements['id'].value;
	
	if (document.forms['newdata'].elements['bewertung'][4].checked) {
		currentBewertung = 1;
	}
	
	if (document.forms['newdata'].elements['bewertung'][3].checked) {
		currentBewertung = 2;
	}
	
	if (document.forms['newdata'].elements['bewertung'][2].checked) {
		currentBewertung = 3;
	}
	
	if (document.forms['newdata'].elements['bewertung'][1].checked) {
		currentBewertung = 4;
	}
	
	if (document.forms['newdata'].elements['bewertung'][0].checked) {
		currentBewertung = 5;
	}
	
		  
   if (currentBewertung != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
								
		document.forms['newdata'].elements['bewertung'][0].disabled = true;
		document.forms['newdata'].elements['bewertung'][1].disabled = true;
		document.forms['newdata'].elements['bewertung'][2].disabled = true;
		document.forms['newdata'].elements['bewertung'][3].disabled = true;
		document.forms['newdata'].elements['bewertung'][4].disabled = true;
		document.all.bewerten.innerHTML = "Deine Stimme wurde gez&auml;hlt!";
		
		param = 'b='+ currentBewertung + '&i=' +id;
 								
		httpSendChat.open("POST", SendBewertungUrl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
							
		httpSendChat.onreadystatechange = handlehHttpSendChatClean;
		httpSendChat.send(param);
		
						
		}
}

//stores a new comment on the server
function sendComment() {

//currentName			 = document.forms['newdata'].elements['name'].value;
	var currentName			 = document.forms['newdata'].elements['name'].value;
	var currentTitel		 = document.forms['newdata'].elements['titel'].value;
	var currentPLZ			 = document.forms['newdata'].elements['plz'].value;
	var currentOrt			 = document.forms['newdata'].elements['ort'].value;
	var currentStrasse	 = document.forms['newdata'].elements['strasse'].value;
	var currentKommentar = document.forms['newdata'].elements['kommentar'].value;
	var currentLat					 = document.forms['newdata'].elements['lat'].value;
	var currentLng					 = document.forms['newdata'].elements['lng'].value;
	var ready = false;
	var currentBewertung = "";
	
	var currentFarbe = "";
	
	if (document.forms['newdata'].elements['farbe'][0].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][0].value;
	}
	
	if (document.forms['newdata'].elements['farbe'][1].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][1].value;
	}
	
	if (document.forms['newdata'].elements['farbe'][2].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][2].value;
	}

	if (document.forms['newdata'].elements['farbe'][3].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][3].value;
	}
	
		if (document.forms['newdata'].elements['farbe'][4].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][4].value;
	}
	
		if (document.forms['newdata'].elements['farbe'][5].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][5].value;
	}
	
	if (document.forms['newdata'].elements['farbe'][6].checked) {
		currentFarbe = document.forms['newdata'].elements['farbe'][6].value;
	}
	
	if (!currentName || !currentTitel || !currentOrt || !currentStrasse || !currentKommentar || !currentFarbe) {
		alert("Bitte fülle alle Felder aus.");
		return false;
	}

	
  var address = currentPLZ + " " + currentOrt + ", " + currentStrasse; 

      if (geocoder) {
         geocoder.getLatLng(
          address + ", Germany",
          function(point) {
            if (!point) {
              alert(address + " wurde nicht gefunden. Bitte überprüfen Sie die Schreibweise.");
              
            } else {
														
							if (currentLat == "" && currentLng == "") {
								currentLat 	= point.lat();
								currentLng	= point.lng();
							}
             		
             /*for (i in point) {
             	alert(i +"= " + point[i]);
            	}
            	*/
			

             
            	document.forms['newdata'].elements['name'].value 			= "Daten werden gesendet...";
							document.forms['newdata'].elements['titel'].value 		= "Daten werden gesendet...";
							document.forms['newdata'].elements['plz'].value 			= "Daten werden gesendet...";
							document.forms['newdata'].elements['ort'].value 			= "Daten werden gesendet...";
							document.forms['newdata'].elements['strasse'].value 	= "Daten werden gesendet...";
							document.forms['newdata'].elements['kommentar'].value = "Daten werden gesendet...";
              
              
              if (currentName != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
								
									currentName			 = escape(currentName);
									currentTitel		 = escape(currentTitel);
									currentPLZ			 = escape(currentPLZ);
									currentOrt			 = escape(currentOrt);
									currentStrasse	 = escape(currentStrasse);
									currentKommentar = escape(currentKommentar);
								
								param = 'n='+ currentName+'&t='+ currentTitel +'&p='+ currentPLZ +'&o='+ currentOrt +'&s=' +currentStrasse +'&k=' + currentKommentar +'&lat=' +currentLat +'&lng=' +currentLng +'&b=' +currentBewertung +'&f=' +currentFarbe;
 								
								httpSendChat.open("POST", SendChaturl, true);
								httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
							
						  	httpSendChat.onreadystatechange = handlehHttpSendChat;
						  	httpSendChat.send(param);
						
								//setTimeout('map.setCenter(point, 13);',1000);
						              
							} else {
								//setTimeout('sendComment();',1000);
							}
              
            }
            
          }

        );
      }
   

	//document.getElementById("submit").style.visibility = "hidden";
	
	//document.forms['chatForm'].elements['submit'].value = "Daten werden gesendet..."
	//document.forms['chatForm'].elements['submit'].disabled = true;
	//document.forms['chatForm'].elements['chatbarText'].style = "disabled";
	
	
}

//deals with the servers' reply to sending a comment
function handlehHttpSendChat() {
  if (httpSendChat.readyState == 4) {
  	//receiveChatText(); //refreshes the chat after a new comment has been added (this makes it more responsive)
  	if (httpSendChat.readyState == 4) {
  		document.getElementById("newdatainput").style.visibility = "hidden";
  		//document.getElementById("submit").style.visibility= "visible";
  		document.forms['newdata'].elements['name'].value			= "";
			document.forms['newdata'].elements['titel'].value			= "";
			document.forms['newdata'].elements['plz'].value 			= "";
			document.forms['newdata'].elements['ort'].value 			= "";
			document.forms['newdata'].elements['strasse'].value 	= "";
			document.forms['newdata'].elements['kommentar'].value = "";
			document.forms['newdata'].elements['lat'].value = "";
			document.forms['newdata'].elements['lng'].value = "";
  		setTheLastEntitiy();
  	}
  }
}

//deals with the servers' reply to sending a comment
function handlehHttpSendChatClean() {
  if (httpSendChat.readyState == 4) {
  	//receiveChatText(); //refreshes the chat after a new comment has been added (this makes it more responsive)
  	if (httpSendChat.readyState == 4) {
  	}
  }
}


//does clever things to the input and submit
function checkStatus(focusState) {
	currentChatText = document.forms['newdata'].elements['titel'];
	oSubmit = document.forms['newdata'].elements['submit'];
	if (currentChatText.value != '' || focusState == 'active') {
		oSubmit.disabled = false;
	} else {
		oSubmit.disabled = true;
	}
}

//autoasigns a random name to a new user
function checkName() {
	currentName = document.forms['chatForm'].elements['name'];
	if (currentName.value == '') {
		currentName.value = 'guest_'+ Math.floor(Math.random() * 10000);
	}
}


//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

function SetSmiley(emo) {
	document.chatForm.chatbarText.value+=''+emo;document.chatForm.chatbarText.focus();
}
function leeren(feld) {
	if (feld.defaultValue==feld.value) {
		feld.value="";
	}
}


function htmlentities(str,typ) {
 /* if(typeof str=="undefined") str="";
  if(typeof typ!="number") typ=2;
  typ=Math.max(0,Math.min(3,parseInt(typ)));
  var html=new Array();
  html[38]="&amp;"; html[60]="&lt;"; html[62]="&gt;";
  if(typ==1 || typ==3) html[39]="&#039;";
  if(typ==2 || typ==3) html[34]="&quot;";
  for(var i in html) eval("str=str.replace(/"+String.fromCharCode(i)+"/g,\""+html[i]+"\");");
  var entity=new Array(
    "&nbsp;","&iexcl;","&cent;","&pound;","&curren;","&yen;","&brvbar;","&sect;",
    "&uml;","&copy;","&ordf;","&laquo;","&not;","&shy;","&reg;","&macr;",
    "&deg;","&plusmn;","&sup2;","&sup3;","&acute;","&micro;","&para;","&middot;",
    "&cedil;","&sup1;","&ordm;","&raquo;","&frac14;","&frac12;","&frac34;","&iquest;",
    "&Agrave;","&Aacute;","&Acirc;","&Atilde;","&Auml;","&Aring;","&AElig;","&Ccedil;",
    "&Egrave;","&Eacute;","&Ecirc;","&Euml;","&Igrave;","&Iacute;","&Icirc;","&Iuml;",
    "&ETH;","&Ntilde;","&Ograve;","&Oacute;","&Ocirc;","&Otilde;","&Ouml;","&times;",
    "&Oslash;","&Ugrave;","&Uacute;","&Ucirc;","&Uuml;","&Yacute;","&THORN;","&szlig;",
    "&agrave;","&aacute;","&acirc;","&atilde;","&auml;","&aring;","&aelig;","&ccedil;",
    "&egrave;","&eacute;","&ecirc;","&euml;","&igrave;","&iacute;","&icirc;","&iuml;",
    "&eth;","&ntilde;","&ograve;","&oacute;","&ocirc;","&otilde;","&ouml;","&divide;",
    "&oslash;","&ugrave;","&uacute;","&ucirc;","&uuml;","&yacute;","&thorn;","&yuml;"
    );
  for(var i in entity) eval("str=str.replace(/"+String.fromCharCode(i*1+160)+"/g,\""+entity[i]+"\");");
  */
  return str;
}


// initiates the two objects for sending and receiving data
var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();

