var map;
var stopicon;
var reset=false;

/*---------------------------------------------------------CreateXmlHttpRequestObject---------------------------*/
/*--function for creating object to request xml data from server--*/
function createXmlHttpRequestObject ( ){
	var xmlHttp=null ;
    
	try{
		xmlHttp = new XMLHttpRequest ( ) ;
	}catch(e){
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.3.0",
                "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");

		for(var i=0 ; i<XmlHttpVersions.length && !xmlHttp ; i++){
			try{
				xmlHttp = new ActiveXObject ( XmlHttpVersions [ i ] ) ;
			}catch(e){}
      }
	}
    
	if ( !xmlHttp )
		alert("BĹ‚Ä…d podczas tworzenia obiektu XMLHttpRequest.");
	else
		return xmlHttp ;	
}

/*--------------------------------------------------------SendRequest--------------------------*/
/*sending request to a server to obtain requested data xml data in this case
type: 0 - stops, 1 - segments*/
function sendRequest(type,nr,opt){
	var xHReq=createXmlHttpRequestObject();

	if(xHReq){   
		try{
			if(xHReq.readyState==4 || xHReq.readyState==0){
				
				if(reset==true){
					map.clearOverlays();
					reset=false;
				}
			
				var file='';
				var params='';
				if(type==0){
					file="common/stop_parser.php";
					params='city='+nr+'&stop='+opt;
				}else if(type==1){
					file="common/stop_map.php";
				}else if(type==2){
					file="common/lines_map.php";
					reset=true;
				}else if(type==3){
					if(nr==-1)
						return;
					file="common/segment_parser.php";
					params='nr='+nr;
				}else if(type==4){
					file="common/stop_selection.php";
					params='name='+nr;
				}else if(type==5){
					map.clearOverlays();
					file="common/results.php";
					reset=true;
				}
				
				xHReq.open("POST",file,true);
				xHReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xHReq.onreadystatechange = function(){
					if(xHReq.readyState==4 && xHReq.status==200 ){
						try{
							var response=xHReq.responseText ;

							if(response.indexOf("ERRNO")>=0 || response.indexOf("error: ")>=0 || response.length==0)
								throw(response.length==0 ? "Server error." : response);
							var xmlDoc=xHReq.responseXML.documentElement;
							var bounds=new GLatLngBounds();
							
							if(type==0 || type==1){
								var stops=xmlDoc.getElementsByTagName("s");
								if(stops.length<=0){
									if(opt!="- Wybierz przystanek -"){
										alert("nie znaleziono przystanku");
										map.setCenter(MAP_CENTER);
									}
								}else{
									for (var i=0;i<stops.length;i++){ 
										var lat=stops[i].getElementsByTagName("t")[0].childNodes[0].nodeValue;
										var lon=stops[i].getElementsByTagName("g")[0].childNodes[0].nodeValue;
										var point = new GLatLng(lat,lon);
										var name=stops[i].getElementsByTagName("n")[0].childNodes[0].nodeValue;
										var id=stops[i].getElementsByTagName("i")[0].childNodes[0].nodeValue;
										var info=createInfo(id,name,'Przystanek');
										var marker = createMarker(point,info);
										map.addOverlay(marker);
										
										if(type==0)
											bounds.extend(point);
									}
									if(type==0){
										map.setCenter(bounds.getCenter());
										GEvent.trigger(marker, "click");
									}
								}
							
							}else if(type==2 || type==3 || type==5){
								if(xmlDoc!=null)
									var lines=xmlDoc.getElementsByTagName('l');
									
								if(xmlDoc==null || lines.length<=0){
									if(type==3)
										alert("wybrana linia nie została znaleziona");
									else if(type==5)
										alert("nie znaleziono połączenia");
										
									return;
								}
								for(var i=0;i<lines.length;i++){
									var pts=[];
									var cps=lines[i].getElementsByTagName('c');
									for(var j=0;j<cps.length;j++){
										var lts=cps[j].getElementsByTagName('t')[0].childNodes[0].nodeValue;
										var lgs=cps[j].getElementsByTagName('g')[0].childNodes[0].nodeValue;
										pts[j]=new GLatLng(lts,lgs);

										if(type==5){
											var typeattr=cps[j].attributes.getNamedItem("t");
											if(typeattr){
												switch(typeattr.value){
													case 'b':
														var infotype='Początek podróży';
														changeIcon('begin');
														break;
													case 'c':
														var infotype='Przesiadka';
														changeIcon('change');
														break;
													case 'e':
														var infotype='Koniec podróży';
														changeIcon('end');
														break;
													case 'w':
														var infotype='Przejście piesze';
														changeIcon('walk');
														break;
													default:
														break;
												}
											}
										}else if(type==3){
											infotype='Przystanek';
										}

										var nameattr=cps[j].attributes.getNamedItem("s");
										var idattr=cps[j].attributes.getNamedItem("i");
										if(nameattr && idattr){
											var info=createInfo(idattr.value,nameattr.value,infotype);
											var marker = createMarker(pts[j],info);
											map.addOverlay(marker);
											bounds.extend(pts[j]);
										}
									}
									map.addOverlay(new GPolyline(pts,LINE_COLOR,2,1));
								}
								
								if(type!=2){
									map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
								}
								
								if(type==5){
									changeIcon('normal');
								}
							}else if(type==4){
								var html_stop_selection;
								
								if(opt==0){
									html_stop_selection='<select id="stop_selection" onChange="handleSelectedStop(this)">';
									if(FIRST_SELECTED_STOP=="default")
										html_stop_selection+='<option selected> - Wybierz przystanek - <\/option>';
								}else if(opt==1)
									html_stop_selection='<select class="combobox" id="stopfrom">';
								else if(opt==2)
									html_stop_selection='<select class="combobox" id="stopto">';
								
								var stops=xmlDoc.getElementsByTagName('n');
								for(var i=0;i<stops.length;i++){
									var name=stops[i].childNodes[0].nodeValue;
									var id=stops[i].attributes.getNamedItem('i');
									html_stop_selection+='<option value="'+id.value+'" ';
									if(FIRST_SELECTED_STOP!="default" && FIRST_SELECTED_STOP==name)
										html_stop_selection+='selected';
									html_stop_selection+='>'+name+'<\/option>';
								}
								
								html_stop_selection+='<\/select>';
								
								if(opt==0)
									document.getElementById("stopdiv").innerHTML=html_stop_selection;
								else if(opt==1)
									document.getElementById("stopfromdiv").innerHTML=html_stop_selection;
								else if(opt==2){
									document.getElementById("stoptodiv").innerHTML=html_stop_selection;
								}
							}
						}catch(e){}
					}
				}		
				xHReq.send( params ) ;
			}
		}catch(e){
			alert(e.toString());
		}
	}
}

/*-------------------------------------------CreateInfo---------------------------------------------------------*/
function createInfo(id,name,type){
	var info='<div id="tooltip"><div id="tipmain">'+type+':<br\/>';
	
	if(STOP_NAME_AS_LINK){
		info+='<a href="'+TIMETABLE_PATH+id;
		if(TIMETABLE_WITH_EXT)
			info+='.htm';
		info+='" target="_blank">'+name+'<\/a><\/div><br\/>';
	}else{
		info+=name+'<\/div><br\/>';
		info+='<div id="tipsubmain"><a href="'+TIMETABLE_PATH+id;
		if(TIMETABLE_WITH_EXT)
			info+='.htm';
		info+='" target="_blank">';
		info+='Kliknij, aby zobaczyć rozkład jazdy<\/a><\/div>';
	}
	
	if(CHRONOLOGY_LINK_AVAILABLE){
		info+='<div id="tipsubmain"><a href="'+CHRONOLOGY_LINK+id;
		if(TIMETABLE_WITH_EXT)
			info+='.htm';
		info+='" target="_blank">';
		info+='Kliknij, aby zobaczyć odjazdy chronologiczne<\/a><\/div>';
	}
	
	if(STOP_NAME_AS_LINK){
		info+='<br\/>';
		info+='<div id="tipinfo">kliknij aby zobaczyć rozkład jazdy<\/div>'
	}
	
	info+='<hr\/>';
	info+='<div id="tipinfo">'+MANAGEMENT_INFO+'<\/div>';
	info+='<div id="tipphone"><a href="http://'+WEB_PAGE+'" target="_blank">'+WEB_PAGE+'<\/a> '+CONTACT+'<\/div><\/div>';
	return info;
}

/*-------------------------------------------handleSelectedLine-------------------------------------------------*/
/*handle selected option from listbox*/
function handleSelectedLine(opt){
	map.clearOverlays();
	sendRequest(3,opt.selectedIndex - 1,0);
}

/*-------------------------------------------handleSelectedStop-------------------------------------------------*/
/*handle selected option from listbox*/
function handleSelectedStop(opt){
	if(CITY_SELECTION==true){
		var city_sel=document.getElementById('city_selection');
		var city_ind=city_sel.selectedIndex;
		var city_text=city_sel.options[city_ind].text;
	}else{
		var city_text='none';
	}

	var stop_sel=document.getElementById('stop_selection');
	var stop_ind=stop_sel.selectedIndex;
	var stop_text=stop_sel.options[stop_ind].text;
	sendRequest(0,city_text,stop_text);
}

/*-------------------------------------------handleSelectedCity-------------------------------------------------*/
/*handle selected option from listbox*/
function handleSelectedCity(opt) {
	var city_sel=document.getElementById('city_selection');
	var city_ind=city_sel.selectedIndex;
	sendRequest(4,city_sel.options[city_ind].text,0);
}

function handleSelectedCityfrom(opt) {
	var city_sel=document.getElementById('cityfrom');
	var city_ind=city_sel.selectedIndex;
	sendRequest(4,city_sel.options[city_ind].text,1);
}

function handleSelectedCityto(opt) {
	var city_sel=document.getElementById('cityto');
	var city_ind=city_sel.selectedIndex;
	sendRequest(4,city_sel.options[city_ind].text,2);
}

/*--------------------------------------------createMarker--------------------------------------------------*/
/*create a marker on map and add new element to a listbox*/
function createMarker(point,html) {
	var marker = new GMarker(point,{icon: stopicon});
	GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
	return marker;
}

/*--------------------------------------------finding gps coordinates of given address--------------------------*/
function findAddress(address){
	var geo = new GClientGeocoder();
	if(!geo)
		return;
	geo.getLatLng(address,function(point){
		if (!point){ //if point not found
			alert(address + " nie został znaleziony!");
		}else{
			map.panTo(point);			//center  map
			var ikona = new GIcon();
			ikona.image='http://maps.google.com/mapfiles/kml/pal3/icon52.png';
			ikona.shadow='';
			ikona.iconSize=new GSize(32,32);
			ikona.iconAnchor=new GPoint(16,16);
			ikona.infoWindowAnchor=new GPoint(16,16);
			
			var marker = new GMarker(point,{icon: ikona, title: address});
			map.addOverlay(marker);
			
			marker.openInfoWindowHtml('<div style="font-family:arial;" ><strong>Poszukiwany adres</strong><br />'+address+'</div>');
		}
	});
}

/*-------------------------------------------report-------------------------------------------------------------*/
/*debugging function*/
function report (string){
	document.getElementById("register").innerHTML+=string;
}

var hid=1;
function hidesearch(){
	if(hid==0){
		document.getElementById("search").style.display="none";
		document.getElementById("map").style.margin="0px 0px 0px 0px";
		document.getElementById("map").style.width="1024px";
		hid=1;
	}else{
		hid=0;
		document.getElementById("search").style.display="inline";
		document.getElementById("map").style.margin="0px 0px 0px "+SEARCH_PANEL_WIDTH+"px";
		var width=1024-SEARCH_PANEL_WIDTH;
		document.getElementById("map").style.width=""+width+"px";
	}
	var center=map.getCenter();
	map.checkResize();
	map.setCenter(center);
}

function findEvents(type){
	if(type==0){
		hidesearch();
	}else if(type==1)
		document['find'].src='images/findn.jpg';
	else if(type==2)
		document['find'].src='images/findo.jpg';
	else if(type==3)
		document['find'].src='images/findc.jpg';
}

function stopsEvents(type){
	if(type==0){
		sendRequest(1,0,0);
	}else if(type==1)
		document['stops'].src='images/stopsn.jpg';
	else if(type==2)
		document['stops'].src='images/stopso.jpg';
	else if(type==3)
		document['stops'].src='images/stopsc.jpg';
}

function linesEvents(type){
	if(type==0)
		sendRequest(2,0,0);
	else if(type==1)
		document['lines'].src='images/linesn.jpg';
	else if(type==2)
		document['lines'].src='images/lineso.jpg';
	else if(type==3)
		document['lines'].src='images/linesc.jpg';
}

function clearEvents(type){
	if(type==0){
		map.clearOverlays();
	}else if(type==1)
		document['clear'].src='images/clearn.jpg';
	else if(type==2)
		document['clear'].src='images/clearo.jpg';
	else if(type==3)
		document['clear'].src='images/clearc.jpg';
}

function inputboxEvents(type,e){
	if(type==0){
		if(document.getElementById('inputbox').value==SEARCH_TEXT)
			document.getElementById('inputbox').value="";
	}else if(type==1){
		var keyCode = (window.Event) ? e.which : e.keyCode;
		if( keyCode == 13 )
			findAddress(document.getElementById('inputbox').value)
	}else if(type==2){
		if(document.getElementById('inputbox').value=="")
			document.getElementById('inputbox').value=SEARCH_TEXT	;
	}
	
}

function initSearch(){
	var stopf=document.getElementById('stopfrom');
	var stopfi=stopf.selectedIndex;
	var stopfv=stopf.options[stopfi].value;
	
	var stopt=document.getElementById('stopto');
	var stopti=stopt.selectedIndex;
	var stoptv=stopt.options[stopti].value;
	
	var day=document.getElementById('daytype');
	var dayi=day.selectedIndex;
	var dayv=day.options[dayi].value;
	
	var timeh=document.getElementById('timehour');
	var timehi=timeh.selectedIndex;
	
	var timem=document.getElementById('timeminute');
	var timemi=timem.selectedIndex;
	
	var maxch=document.getElementById('maxchanges');
	var maxchi=maxch.selectedIndex;
	if(maxchi==0)
		maxchv=100;
	else
		maxchv=maxchi;
		
	var spec=document.getElementById('spec');
	if(spec.checked)
		var specv=1;
	else
		var specv=0;
		
	var min=document.getElementById('mintime');
	var mini=min.selectedIndex;
	//var minv=min.options[mini].value;
	
	var sten=document.getElementsByName('stenhour');
	if(sten[1].checked)
		var stenv=1;
	else
		var stenv=0;
		
	var skm=document.getElementById('skm');
	if(skm.checked)
		var skmv=1;
	else
		var skmv=0;

	s="businfo.cgi?s1="+stopfv+"&s2="+stoptv+"&d="+dayv+"&h="+timehi+":"+timemi+"&a="+maxchv+"&t="+specv+"&z="+mini+"&p="+stenv+"&m="+skmv;
	openpopup(s);
}

function openpopup(page){
	window.open(page,"Wyszukiwarka","width=780,height=800");
	//sleep(1000);
	sendRequest(5,0,0);
}

function sleep(delay){
    var start = new Date().getTime();
    while(new Date().getTime() < start + delay);
}

function changeIcon(type){

	stopicon = new GIcon();

	switch(type){
		case 'normal':
			stopicon.image = MARKERS_PATH+"stopmarker.png";	
			break;
		case 'begin':
			stopicon.image = MARKERS_PATH+"marker_begin.png";
			break;
		case 'change':
			stopicon.image = MARKERS_PATH+"marker_change.png";
			break;
		case 'end':
			stopicon.image = MARKERS_PATH+"marker_end.png";
			break;
		case 'walk':
			stopicon.image = MARKERS_PATH+"marker_walk.png";
			break;
		default:
			stopicon.image = MARKERS_PATH+"stopmarker.png";  	
	}
	
	if(type=='normal'){
		stopicon.iconSize = NORMAL_ICON_SIZE;
		stopicon.infoWindowAnchor = NORMAL_ICON_SIZE_ANCHOR;
		stopicon.iconAnchor = NORMAL_ICON_SIZE_ANCHOR;
	}else{
		stopicon.iconSize = ACTIVITY_ICON_SIZE;
		stopicon.infoWindowAnchor = ACTIVITY_ICON_SIZE_ANCHOR;
		stopicon.iconAnchor = ACTIVITY_ICON_SIZE_ANCHOR;
	}
}

function initialize(){
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(MAP_CENTER,12);
		
		var mt = map.getMapTypes();
		// Overwrite the getMinimumResolution() and getMaximumResolution() methods
		for (var i=0; i<mt.length; i++){
			mt[i].getMinimumResolution = function(){
				return 6;
			}
			
			mt[i].getMaximumResolution = function(){
				return 16;
			}
		}
		
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());
		
		changeIcon('normal');
		
		inputboxEvents(2,null);
		sendRequest(4,FIRST_SELECTED_CITY,0);
		sendRequest(4,FIRST_SELECTED_CITY,1);
		sendRequest(4,FIRST_SELECTED_CITY,2);
	}
}
