/*
MENU functions for javascript selectable RASP maps.

Copyright (C) 2010 Thomas Pantzer

This program is free software; you can redistribute it and/or modify it under 
the terms of the GNU General Public License as published by the Free Software 
Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY 
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with 
this program; if not, see http://www.gnu.org/licenses/.
*/

function myGetElementById(a,f)
{
	if (getElemByIdWorks > 0) {
		var e = document.getElementById(a);
		if (!e) {
			alert("myGetElementById("+a+","+f+")");
		} else {
			if (e.id == a) {
				return e;
			}
		}	
		if (debug > 0) {
			if (browserNotCompatibleMsgSent == 0) {
				// M$ ist doch zu blöd, ID und Name ist _NICHT_ das selbe, im Explorer aber schon
				browserNotCompatibleMsgSent = 1;
			}
		}	
		// work around for shitty M$ Explorer 
		te = document.getElementsByTagName("div"); // our special case: we only need to find IDs for "div"-elements
		for (k=0; k<te.length; k++) {
			if (te[k].id == a) {
				return te[k];
			}		
		}
	} else {
		// work around for old 4.8 Netscape, <DIV>s are <LAYER>s		
		te = document.layers;
//		alert("document.layers.length:"+te.length);
		for (k=0; k<te.length; k++) {		
			if (te[k].name == a) {
//				alert("te["+k+"].name:"+te[k].name);
				return te[k];
			}		
		}
	}	
	// should not get here, even with M$
	alert("M$-Explorer Bug: cant distinguish between ID and NAME attributes\nfunction:"+f+"\nelement with Id:"+a+" not found in <div> tags");		
		
	return e;
}

function map_animation()
{
	if (ctlForm.animateur.selectedIndex > 0) {
		animation_callback();	
	}	
}

function animation_callback()
{
	if (ctlForm.animateur.selectedIndex > 0) {
		if ((ctlForm.time.selectedIndex+1) < ctlForm.time.options.length) {
			ctlForm.time.selectedIndex++;
		} else {
			if (ctlForm.animateur.selectedIndex > 1) {
				if ((ctlForm.day.selectedIndex+1) < ctlForm.day.options.length) {
					ctlForm.day.selectedIndex++;
				} else {
					ctlForm.day.selectedIndex = 0;
				}
			}		
			ctlForm.time.selectedIndex = 0;
		}
		change_image();
		
		delay = ctlForm.delay.options[ctlForm.delay.selectedIndex].value;
		
		if ((ctlForm.time.selectedIndex+1) == ctlForm.time.options.length) {
			delay = eval(delay) + 2000;
		}
		window.setTimeout("animation_callback()", delay);
	} else {
		ctlForm.delay.selectedIndex = 3; 	// 5 Sekunden
	}	
}

function change_day()
{
	if (ctlForm.animateur.selectedIndex > 0) {
		ctlForm.delay.selectedIndex = 3; 	// 5 Sekunden
	}	
	init_daytimes();
	change_image();
}


function change_image(typ,arg)
{
	url = new_image_url();
	if (loadImage > 0) {
		if (divIsLayer) {
			var D = document.weathermap.document;
			D.open();
			D.writeln("<img src="+url+" width="+imageWidth+" border=0 usemap=#soundMap>");
			D.writeln("<map name=soundMap id=soundMap>");
			for (i=0; i<soundMapLength; i++) {
				document.writeln('<AREA shape="circle" coords="'+soundMapCoords[i]+'" title="'+i+'" alt="'+i+'" href="javascript:open_soundMap('+i+')">');
			}
			D.writeln("</map>");
			D.close();
		} else {
			document.images[0].src = url;
		}	
	} else {
		alert("URL:"+url);
	}	
}


function change_map()
{
	if (ctlForm.animateur.selectedIndex > 0) {
		ctlForm.delay.selectedIndex = 3; 	// default 3 Sekunden
	}	
	change_image();
}

function change_time()
{
	if (ctlForm.animateur.selectedIndex > 0) {
		ctlForm.animateur.selectedIndex = 0;
	}
	change_image();
}

function step_time(cursorDown)
{
	var before = ctlForm.time.selectedIndex;
	var x = ctlForm.time.selectedIndex;
	if (cursorDown == 0) {
		x++;
	} else {
		x += ctlForm.time.options.length;
		x--;
	}

	x %= ctlForm.time.options.length;
	ctlForm.time.selectedIndex = x;
	var after = ctlForm.time.selectedIndex;
	
//	alert("before:"+before+", after:"+after+", olen:"+ctlForm.time.options.length);
	
	change_image();
}

function toggle_cross(arg)
{
	var elem = myGetElementById(arg,"toggle_cross");
//		alert("toggle:"+arg);
	if (elem) {
		var style = elem.style;
		var onDisplay = "visible";
		if (divIsLayer) {
			style = elem;
			onDisplay = "show";
		}
//			alert("style.visibility:"+style.visibility);
	    if (style.visibility == onDisplay) {
			style.visibility = "hidden";
		} else {
			style.visibility = "visible";
		}
	}	
}

function sync_crosses()
{
	for (i=0; i<ctlForm.elements.length; i++) {
		var chkbx = ctlForm.elements[i];
		if (chkbx) {
			var arg = chkbx.name.split("_");	
			if (arg[0] == "iconChecker") {
				var elem = myGetElementById(arg[1],"sync_crosses");
//				alert("arg[1]:"+arg[1]);
				if (elem) {
					var style = elem.style;
					if (divIsLayer) {
						style = elem;
					}
					if (chkbx.checked) {
						style.visibility = "visible";		
					} else {
						style.visibility = "hidden";		
					}	
				}	
			}	
		}	
	}
}

function cross_blink()
{
	if (!ctlForm) {
		if (debug) {
			alert("ctlForm is NULL, late initialze()");
		}	
		initialize();
	}	
	if (ctlForm.blinker.checked) {
//		alert("into callback");
		blinker_callback();	
	}	
}

function blinker_callback()
{
	for (i=0; i<ctlForm.elements.length; i++) {
		var chkbx = ctlForm.elements[i];
		if (chkbx) {
			var arg = chkbx.name.split("_");	
			if (arg[0] == "iconChecker") {
				if (chkbx.checked) {
					toggle_cross(arg[1]);
				}	
			}	
		}	
	}
	if (ctlForm.blinker.checked) {
		window.setTimeout("blinker_callback()", 500);
	} else {
		sync_crosses();
	}	
}

function newTakeoffIcon()
{
	var choice = myGetElementById("areaUpdateSelector","newTakeoffIcon");
	return choice.options[choice.selectedIndex].value;
}

var crossPos = new Array(2);
crossPos[0] = 500;
crossPos[1] = 500;

var lastChangedIcon = "";

function newCrossPos(degLat, degLon, iname)
{
	rotate(deg2rad(fLon*(degLon-sLn)));	
	
	var xrot = parseInt(Pr[0] + (rStart + fLat*(eLt-degLat))*vRot[0]);
	var yrot = parseInt(Pr[1] + (rStart + fLat*(eLt-degLat))*vRot[1]);
	crossPos[0] = xrot -CursorSize -leftShift -x_offset;
	crossPos[1] = yrot -CursorSize -upShift -y_offset;

	if (maintaining > 0) {
		if (ctlForm.show.checked) {
			alert("move "+iname+" to point("+crossPos[0] + "," + crossPos[1]+")");
		}	
		if (ctlForm.showSound.checked) {
			x = crossPos[0] + CursorSize + leftShift;
			y = crossPos[1] + CursorSize + upShift;
			alert("soundMapCoords[soundMapIdx++]=\""+x+","+y+",10\";");
		}	
	}
	elem = myGetElementById(iname,"newCrossPos");
	if (elem) {
		if (elem.style) {
			elem.style.left = crossPos[0] + "px";		
			elem.style.top = crossPos[1] + "px";		
//			alert("elem:"+elem+", iname:"+elem.id);
		} else {
//			alert("elem:"+elem+", iname:"+elem.name);
			elem.left = crossPos[0];
			elem.top = crossPos[1];
		}	
	}
}

function moveUp()
{	
	var nLat = parseFloat(document.ctl.degLat.value)+0.01;
	document.ctl.degLat.value = nLat.toFixed(2);
	newCrossPos(document.ctl.degLat.value, document.ctl.degLon.value, newTakeoffIcon() );
}

function moveLeft()
{	
	var nLon = parseFloat(document.ctl.degLon.value)-0.01;
	document.ctl.degLon.value = nLon.toFixed(2);
	newCrossPos(document.ctl.degLat.value, document.ctl.degLon.value, newTakeoffIcon() );
}

function moveRight()
{	
	var nLon = parseFloat(document.ctl.degLon.value)+0.01;
	document.ctl.degLon.value = nLon.toFixed(2);
	newCrossPos(document.ctl.degLat.value, document.ctl.degLon.value, newTakeoffIcon() );
}

function moveDown()
{	
	var nLat = parseFloat(document.ctl.degLat.value)-0.01;
	document.ctl.degLat.value = nLat.toFixed(2);
	newCrossPos(document.ctl.degLat.value, document.ctl.degLon.value, newTakeoffIcon() );
}

function change_location(choiceId)
{
	lastChangedIcon = choiceId;
	
	var idStr = "siteSelector_" + choiceId;
	var choice = ctlForm.elements[idStr];
	
	i = choice.selectedIndex;
	st = choice.options[i].value;
	var p1 = st.indexOf(',');
	
	var lat = st.substr(0,p1);
	var lon = st.substr(p1+1,100);

	if (ctlForm.degLat) {
		ctlForm.degLat.value = lat;
		ctlForm.degLon.value = lon;
		ctlForm.areaName.value = choice.options[i].text;
	}

	if (firstChildWorks > 0) {
		var el = myGetElementById("staticTextLayer_Area","change_location");
		el.firstChild.nodeValue = " " + choice.options[i].text;
		
		document.getElementById("staticLat").firstChild.nodeValue = " " + lat + "°N,";
		document.getElementById("staticLon").firstChild.nodeValue = "" + lon + "°E";
	}

	if (!divIsLayer) {
		for (x=0; x<ctlForm.areaUpdateSelector.options.length; x++) {
			if (ctlForm.areaUpdateSelector.options[x].value == choiceId) {
				ctlForm.areaUpdateSelector.selectedIndex = x;
			}
		}		
	}		
	newCrossPos(lat, lon, choiceId);
}

window.setTimeout("cross_blink()", 2000);


function newArea()
{
	menuName = newTakeoffIcon();  // Lupe,Kreuz,Karo,Stern,...
	idStr = "siteSelector_" + menuName;
	choice = myGetElementById(idStr,"newArea");
	var i;
	for (i=0; i<choice.options.length; i++) {
		if (choice.options[i].text == document.ctl.areaName.value) {
			return;
		}
	}				
	choice.options.length++;
	choice.options[choice.options.length-1].text = ctlForm.areaName.value;
	choice.options[choice.options.length-1].value = ctlForm.degLat.value +","+document.ctl.degLon.value;
}

function addSite()
{
	// texteingabe
	if (ctlForm.edit.checked) {
		newArea();
	}
}

function copySite()
{
	// dropDownMenu
	newArea();
}

function toggle_edit()
{
	te = document.getElementsByTagName("div"); // our special case: we only need to find IDs for "div"-elements
	for (k=0; k<te.length; k++) {
		var arg = te[k].id.split("_");
		var style = te[k].style;
		if (divIsLayer) {
			style = te[k];
		}
		if (ctlForm.edit.checked) {
			if (arg[0] == "textInputLayer") {
				style.visibility = "visible";			
			}		
			if (arg[0] == "staticTextLayer") {
				style.visibility = "hidden";			
			}		
		} else {
			if (arg[0] == "textInputLayer") {
				style.visibility = "hidden";			
			}		
			if (arg[0] == "staticTextLayer") {
				style.visibility = "visible";			
			}		
		}
	}
}

var wi = new Array(siteOptionValue.length);
var winchGroup = new Array(5);		// zur Zeit 5 verschiedene Gelaende-Icons implementiert
var soaringGroup = new Array(5);	

function init_sites(start)
{
	var k = 0;	// Gelaendemenueindex
	var n = 0;

	for (i=0; i<ctlForm.elements.length; i++) {
//		alert("elements["+i+"]:"+document.ctl.elements[i].name);
		var elem = ctlForm.elements[i];
		if (elem) {
			if (elem.type == "select-one") {
				var arg = elem.name.split("_");			
				if (arg[0] == "siteSelector") {
//					alert("init_sites("+arg[0]+","+arg[1]+"); sowl:"+siteWinchOptions.length);
					iconName = arg[1];

					if ((siteWinchOption.length > 0) && (optGroupWorks > 0)) {
						if (start == 1) {
							elem.options.length = 0;

							winchGroup[k] = document.createElement('optgroup');
							winchGroup[k].label = "Winde";

							soaringGroup[k] = document.createElement('optgroup');
							soaringGroup[k].label = "Hangstart";

							elem.appendChild(winchGroup[k]);
							elem.appendChild(soaringGroup[k]);
						}	
						winchGroup[k].length = 0;
						soaringGroup[k].length = 0;
					} else {
						elem.options.length = siteOptionValue.length;
					}

					for (j=0; j<siteOptionValue.length; j++) {
						if (start == 1) {
							if ((siteWinchOption.length > 0) && (optGroupWorks > 0)) {
								var optionNeu = new Option(siteOptionText[j], siteOptionValue[j]);							
								if (j < siteWinchOption.length) {
									if (siteWinchOption[j] > 0) {
										winchGroup[k].appendChild(optionNeu);
									} else {
										soaringGroup[k].appendChild(optionNeu);
									}
								} else {
									soaringGroup[k].appendChild(optionNeu);
								}
							} else {						
								elem.options[j].text = siteOptionText[j];
								elem.options[j].value = siteOptionValue[j];		
							}	
						}	
						if (siteWinchOption.length > 0) {
							if (j < siteWinchOption.length) {
								if (siteWinchOption[j] > 0) {
									if (ctlForm.winchCheck.checked) {
										wi[n] = j;
										n++;
									}	
								} else {
									if (!(ctlForm.winchCheck.checked)) {
										wi[n] = j;
										n++;
									}	
								}	
							} else {
								if (!(ctlForm.winchCheck.checked)) {
									wi[n] = j;
									n++;
								}	
							}						
						}	
					}
					if (siteWinchOption.length > 0) {
						elem.selectedIndex = (wi[k] % siteOptionValue.length);
					} else {
						elem.selectedIndex = (k % siteOptionValue.length);
					}	
					k++;
				}
			}
		}	
	}	
}

function init_locations()
{
	for (L=0; L<ctlForm.elements.length; L++) {
		var elem = ctlForm.elements[L];
		if (elem) {
			if (elem.type == "select-one") {
				var arg = elem.name.split("_");			
				if (arg[0] == "siteSelector") {
//					alert("change_location("+iconName+");");
					change_location(arg[1]);
				}	
			}
		}
	}
}


function sync_winchareas()
{
//	alert("sync_winchareas();");
	init_sites(0);
	init_locations();
}



function initialize()
{
	ctlForm = myGetFormObj();
	init_sites(1);
	init_times(1);	// 1 ist immer gültig
	init_days();
	init_maps();
	change_image();	
	init_locations();
//	alert("wlbv:"+window.locationbar.visible);
}

function open_soundMap(idx)
{
	myDay = ctlForm.day.options[ctlForm.day.selectedIndex].value;
	myTime = ctlForm.time.options[ctlForm.time.selectedIndex].value;
	dayPrefix = dayOptionPrefix[ctlForm.day.selectedIndex];

	myHref = soundingUri(idx, myDay, myTime, dayPrefix) + mapImagePostfix;
	myTarget="_soundingWin";
		
	if (debug == 1) {
		alert("myHref:"+myHref);
	}	
	window.open(myHref,myTarget,"width=701,height=678,left=700,top=400,titlebar=no,menubar=no,toolbar=no,location=no,scrollbar=no,status=no,resizable=no");
}

function NOP() {
	// do-nothing-function
}


// var noIconFormElements = 6;

