var PicturePath = "images/";
var request=null;
var requestProcess = null;
var NewStartVar = -1;


function Mod(a, b) { return(a-Math.floor(a/b)*b); }

function timetoupdate(){
	if(refreshi > 0){
		refreshi--;
				
		seconds = Mod(refreshi, 60);
		mins = refreshi - seconds;
		minutes = mins/60;
		if(document.getElementById("PlayDiaShow").innerHTML=="Play"){
			document.getElementById("refreshtimer").innerHTML = "Aktualisiere in: " +minutes + " Min " + seconds + " Sek";
		}
		
		
	}	
	else{
		clearInterval(myrefreshtimer);
	}
}

var refreshi=300;


function setNewAjaxRequester(){
if(window.ActiveXObject)
{ 
	request = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
	request = new XMLHttpRequest();
}
}

function setNewProcessRequester(){
if(window.ActiveXObject)
{ 
	requestProcess = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
	requestProcess = new XMLHttpRequest();
}
}

function setNewCounterRequester(){
if(window.ActiveXObject)
{ 
	counterProcess = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
	counterProcess = new 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;
}

var url = "service.php"; 
		
function handleHttpResponse() {
	
	  if (request.readyState == 4) {
	  	// alert("GETTING DATA STATE:" + request.readyState);
		//alert("Server done" + request.responseText);
		/*
		if (request.responseText.indexOf('invalid') == -1) {
   		   //alert(http.responseText);
		   // Split the comma delimited response into an array
      		results = null;
			results = request.responseText.split("|");
      		//document.getElementById('zip').value = results[0];
			count = results.length;
			i = 0;
			clearlistbox(document.forms[0].picturemenu);
		while(i < (count -1)){
			//alert("WRITING " + i);
			values = results[i].split(",");
			name = values[0];
			file = values[1];
			//alert("Name: " + name + " and File: " + file);
			document.forms[0].picturemenu.options[i] = new Option(name,file);
			i++;
		}
		*/
		var jsondatelist = request.responseText;
		var piclist;
		eval(jsondatelist);
		var i = 0;
		clearlistbox(document.forms[0].picturemenu);
		for (p in piclist) {
				document.forms[0].picturemenu.options[i] = new Option(piclist[p].time,piclist[p].file);
				i++;
		}
			isWorking = false;
			myCount = (document.forms[0].picturemenu.options.length - 1);
			
			//Test for StartDiaShow
			myStartDiaSelection = (myCount - 5);
			if(myStartDiaSelection < 0){
				myStartDiaSelection = 0;
			}
			if(StartUpDiaShow == true){
				myCount = myStartDiaSelection;
				DiaCount = myStartDiaSelection;
			}
			document.forms[0].picturemenu.options[myCount].selected = true;
			showpicture(document.forms[0].picturemenu.options[myCount].value);
    		document.forms[0].picturemenu.focus();
				
			
		
	 }
	 else{
	 	
	 }
	}


var isWorking = false;
var isWorkingProcess = false;

function updatePictureMenu(sort) {
		clearlistbox(document.forms[0].picturemenu);
		document.forms[0].picturemenu.options[0] = new Option("Lade...","");
		
	if (!isWorking) {
		//alert("Sending Request");
		//request = getHTTPObject();
		setNewAjaxRequester();
		//var zipValue = document.getElementById("zip").value;
		//alert(zipValue);
		request.open("POST","service.php", true);
    	request.onreadystatechange = handleHttpResponse;
		isWorking = true;
    	//request.send(null);
		//		?mode=getPictureMenu&value=" + sort
		request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			// Request senden
		request.send('mode=getPictureMenu&value=' + sort);
		
		
	}
	else{
		alert("Es läuft bereits eine Abfrage. Bitte warten Sie!");	
		
	}
}
	
function clearlistbox(lb){
// alert("CLEAR");
  for (var i=lb.options.length-1; i>=0; i--){
    lb.options[i] = null;
  }
  lb.selectedIndex = -1;
}


	//TODO Clean SelectMenu!!!!!!
	
	
	
	//function changesort(sorter){
				//document.forms[0].picturemenu.options[1] = new Option('Bild1','002.jpg');
	//	}
	function showpicture(picture){

		//Split Picture Values
		pic = picture.split("$");
		PicFileName = pic[0];
		PicWidth = pic[1];
		PicHeight = pic[2];
		
		//TODO Rescale Image if to BIG
				
		
		//Delete Existing Picture
		//el = document.getElementById('picture');
		//while (el.hasChildNodes()){
		//	el.removeChild(el.lastChild);
		//}
	
		//var myP = document.createElement("p");
		//myP.id = "name";
		//myP.align = "center";
		//var myText = document.createTextNode("ZeigeBild" + picture);
		//myP.appendChild(myText);
		
		//var myImg = document.createElement("img");
		//myImg.id = "mypicture";
		//myImg.src = PicturePath + PicFileName;
		//myImg.alt = "Bild";
		//myImg.height = PicHeight;
		//myImg.width = PicWidth;
		//myP.appendChild(myImg);
	
		//var Ausgabebereich = document.getElementById("picture");
		//Ausgabebereich.appendChild(myP);
		//Ausgabebereich.appendChild(myImg);
		
		myFadePic = document.getElementById("thephoto");
		//myFadePic.height = PicHeight;
		//myFadePic.width = PicWidth;
		newImage = PicturePath + PicFileName;
		initImage(newImage);
//		setOpacity(myFadePic, 0);
//		fadeIn(myFadePic,0);
		
		
		//precache next 5 images
		preloader(document.forms[0].picturemenu.selectedIndex)
}

function changeDiaStart(picid){
	NewStartVar = picid;

}

function datetimechanged(selection){
		clearlistbox(document.forms[0].sorttype);
		clearlistbox(document.forms[0].picturemenu);
		document.forms[0].sorttype.options[0] = new Option("Lade...","");
		
	if (!isWorking) {
		//	alert("Sending Request");
		//request = getHTTPObject();
		setNewAjaxRequester();
		//var zipValue = document.getElementById("zip").value;
		//alert(zipValue);
  	    request.open("GET","service.php?mode=getDateTimeList&value=" + selection, true);
    	request.onreadystatechange = handleDateTimeListReceived;
		isWorking = true;
    	request.send(null);
	}
	else{
		alert("Es läuft bereits eine Abfrage. Bitte warten Sie!");	
	}
}

function handleDateTimeListReceived(){
//Start JSON Parse
	if (request.readyState == 4) {
	  	
	  	/*if (request.responseText.indexOf('invalid') == -1) {
   		   // Split the comma delimited response into an array
      		results = null;
			results = request.responseText.split("|");
      		count = results.length;
			i = 0;
			clearlistbox(document.forms[0].sorttype);
		while(i < count){
			values = results[i].split(",");
			name = values[0];
			file = values[1];
			document.forms[0].sorttype.options[i] = new Option(name,file);
			i++;
			
		}
		
			isWorking = false;
    	updatePictureMenu(document.forms[0].sorttype.options[0].value);	
		}*/
		var jsondatelist = request.responseText;
		var datelist;
		eval(jsondatelist);
		var i = 0;
			clearlistbox(document.forms[0].sorttype);
			//document.forms[0].sorttype.options[i] = new Option("test","test2");
	
		for (p in datelist) {
				
				document.forms[0].sorttype.options[i] = new Option(datelist[p].date,datelist[p].nativedate);
				i++;
		}
		isWorking = false;
		updatePictureMenu(document.forms[0].sorttype.options[0].value);
	 }
	 else{
	 	
	 }
}
var DiaCount = 0;
function DiaShowNext(){
		if(NewStartVar > -1){
			DiaCount = NewStartVar;
			NewStartVar = -1;
		}
		
		
		if(DiaCount < document.forms[0].picturemenu.options.length){	
			nextpreload = (DiaCount + 4);
			preloader(nextpreload);
			document.forms[0].picturemenu.options[DiaCount].selected = true;
			showpicture(document.forms[0].picturemenu.options[document.forms[0].picturemenu.selectedIndex].value);
			DiaCount++;
			
		}
		else{
			//clearInterval(diashow);
			//document.getElementById("PlayDiaShow").innerHTML = "Abspielen";		
			//ShouldRefresh = true;	
			if(StartUpDiaShow == true){
				clearInterval(diashow);
				//StartRefresher
		refreshInterval = setInterval("refresher()",300000);
		
		//StartRefreshTimer
		refreshi = 300;
		myrefreshtimer = window.setInterval('timetoupdate()',1000);
				document.getElementById("PlayDiaShow").innerHTML = "Play";		
				document.getElementById("PlayDiaShow").style.backgroundColor = "";
				ShouldRefresh = true;
				StartUpDiaShow = false;
			}
			else{
				DiaCount = 0;
			}
			//document.forms[0].picturemenu.options[DiaCount].selected = true;
			//showpicture(document.forms[0].picturemenu.options[document.forms[0].picturemenu.selectedIndex].value);
		}
}

function DiaShowStart(){
		
		//PerformancePatch
		//Kill refreshtimers
		clearInterval(myrefreshtimer);
		clearInterval(refreshInterval);
		document.getElementById("refreshtimer").innerHTML = "Diashow läuft...";
		
		
		//alert("Bilder werden zwischengespeichert!");
		preloader(5);
		//alert("Speichern abgeschlossen starte DiaShow");			
		myinterval = document.getElementById("intervallselect").options[document.getElementById("intervallselect").selectedIndex].value
		//document.getElementById("interval").value
		myint = (myinterval * 1000);
		DiaCount=document.forms[0].picturemenu.selectedIndex;
		
		if(DiaCount>0){
			DiaCount++;	
		}
		else{
			DiaCount=0;
		}
		
		if(document.getElementById("PlayDiaShow").innerHTML=="Play"){
			document.getElementById("PlayDiaShow").innerHTML="Stop";
			document.getElementById("PlayDiaShow").style.backgroundColor = "FireBrick";
			// Stop Refresh of Page
			ShouldRefresh = false;
			diashow = setInterval("DiaShowNext()", myint);
		}
		else{
			ShouldRefresh = true;
			clearInterval(diashow);	
			
		
			//StartRefreshTimer
			refreshi = 300;
			myrefreshtimer = setInterval("timetoupdate()",1000);
			
			//StartRefresher
			refreshInterval = setInterval("refresher()",300000);
					
			document.getElementById("PlayDiaShow").innerHTML = "Play";
			document.getElementById("PlayDiaShow").style.backgroundColor = "";
		}		
}


function processnewfiles(){
		
		//document.getElementById("processpictures").innerHTML=" Die Aktualisierung von Daten läuft";
		
	if (!isWorkingProcess) {
		//	alert("Sending Request");
		//request = getHTTPObject();
		setNewProcessRequester();
		//var zipValue = document.getElementById("zip").value;
		//alert(zipValue);
  	    requestProcess.open("GET","process.php", true);
    	requestProcess.onreadystatechange = handleProcessPicturesFinished;
		isWorkingProcess = true;
    	requestProcess.send(null);
	}
	else{
		alert("Es läuft bereits eine Abfrage. Bitte warten Sie!");	
	}
}

function handleProcessPicturesFinished(){
	if (requestProcess.readyState == 4) {
	  	if (requestProcess.responseText.indexOf('invalid') == -1) {
   		 
			//document.getElementById("processpictures").innerHTML="";
		}
		
			isWorkingProcess = false;
    	
		
	 }
	 else{
	 	
	 }
}


function startcounter(){
		
		setNewCounterRequester();
	    counterProcess.open("GET","counter.php", true);
    	counterProcess.onreadystatechange = handleCounterFinished;
    	counterProcess.send(null);
}

function handleCounterFinished(){
	if (counterProcess.readyState == 4) {
	  	if (counterProcess.responseText.indexOf('invalid') == -1) {
 			//document.getElementById("counter").innerHTML="<p style='color:silver;'> " + counterProcess.responseText +  " Besuche dieser Seite seit 11.07.2007 12:00</p>";
		}	
		
	 }
	 else{
	 	
	 }
}


	
function preloader(i){
	max = (i+5);
	if(max >= document.forms[0].picturemenu.options.length){
		max = document.forms[0].picturemenu.options.length;
	}
	while(i < max){
		var picture = "";
		picture = document.forms[0].picturemenu.options[i].value;
		pic = picture.split("$");
		PicFileName = pic[0];
		PicWidth = pic[1];
		PicHeight = pic[2];
		myPic = new Image;
		myPic.src = PicturePath + PicFileName;
		i++;
	}
}

var StartUpDiaShow = true;
var InRegister = "no";

function startselection(){
		document.forms[0].datetime[0].checked = true;
		datetimechanged('date');
		processnewfiles();
		
		
		
		//StartRefreshTimer
		refreshi = 300;
		myrefreshtimer = setInterval("timetoupdate()",1000);
		
		//StartRefresher
		refreshInterval = setInterval("refresher()",300000);
		
		
		//TestStartDiaShow
		//alert(document.forms[0].picturemenu.selectedIndex);
		
		if(InRegister == "yes"){
			clearInterval(myrefreshtimer);
			document.getElementById("refreshtimer").innerHTML = "Registrierung läuft!";
			ShouldRefresh = false;
		}
		else{
			DiaShowStart();
		}
		//alert(document.forms[0].picturemenu.selectedIndex);
		
		//Set Counter new directly inside webcam.php
		//startcounter();
	}

function userposting()
{
	clearInterval(myrefreshtimer);
	document.getElementById("refreshtimer").innerHTML = "User Posting...";
	ShouldRefresh = false;
}

function initImage(newImage) {
imageId = 'thephoto';
image = document.getElementById(imageId);
var loadimage = document.getElementById("loadimage");
loadimage.style.display = "none";
image.height = "480";
image.src = newImage;
image.alt = newImage;
image.title = MyImageTitle;//"testimage";
//setOpacity(image, 0);
fadeIn(imageId,90);
//70
}

function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;

// IE/Win
obj.style.filter = "alpha(opacity:"+opacity+")";

// Safari<1.2, Konqueror
obj.style.KHTMLOpacity = opacity/100;

// Older Mozilla and Firefox
obj.style.MozOpacity = opacity/100;

// Safari 1.2, newer Firefox and Mozilla, CSS3
obj.style.opacity = opacity/100;
}

function fadeIn(objId,opacity) {
if (document.getElementById) {
obj = document.getElementById(objId);
if (opacity <= 100) {
setOpacity(obj, opacity);
opacity += 2;
//4
window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
}
}
}
var ShouldRefresh = true;

function refresher(){
	
	if (ShouldRefresh == true){
		//window.location.reload()		
		window.location.href = 'webcam.php';
	}
}

