var HttpRequestBaseUrl = "http://" + location.host + "/karttapalvelu/ajax/RequestHandler.asp";
var HttpRequestUrl = null;
var form = null;
var ResultsEl = null;
var InfoEl = null;
var iDefaultServiceType = "1"; // Digi
var debug = (location.search.substring(1, location.search.length).toLowerCase().indexOf("dbg=on") > -1);

// Set texts for user message.
var txt_MoreThanOneResults = "Haku tuotti useamman kuin yhden tuloksen. Paras vastaanottosuunta riippuu asuinpaikastasi.";
var txt_NoResults = "Antamillasi hakuehdoilla ei löytynyt kuntia. Kirjoita hakukenttään sen kunnan nimi, jonka kanavatiedot haluat hakea.";
var txt_StartInfo = "<b>Tervetuloa Digitan karttapalveluun!</b><p>Voit hakea karttapalvelusta asuinkuntaasi lähinnä olevan radio- ja tv-aseman kahdella tavalla. Kirjoita kunnan nimi hakukenttään ja klikkaa hakupainiketta. Vaihtoehtoisesti voit liikkua lähennä- ja loitonna-painikkeilla kartalla ja klikata kunnan nimeä. Saat näytölle luettelon kanavista, jotka lähin radio- ja tv-asema lähettää.</p><p>Mikäli asut usean kuuluvuus- ja näkyvyysalueen risteyskohdassa, karttapalvelu listaa kaikki alueella lähettävät radio- ja tv-asemat. Klikkaamalla aseman nimeä saat näytölle luettelon kanavista, jotka kyseinen radio- ja tv-asema lähettää. Täytelähettimet näkyvät listassa, mikäli niitä on alueella.</p>";
var txt_ServerError = "Palvelimella tapahtui virhe!";
var txt_Executing = "<img src=\"/karttapalvelu/ajax/executing.gif\" style=\"margin-right: 5px\">Haetaan...";

// Note that oMap object is created in karttakone.js file.
// Remember check that applet and plugin are fully loaded(oMap.bAppletReady) before calling any applet method.

window.onload = function () {

	form = document.forms[0];
	ResultsEl = document.getElementById("results");	
	InfoEl = document.getElementById("resultsInfo");
	ContractorsEl = document.getElementById("contractors");
	InitUI();
	
}

function BackToResults() {
	SearchMasts(form.elements['Municipality'].value, '', GetServiceType(form.elements['ServiceType']));
}

function DebugHttpResponse(res,RequestUrl) {
	var sHttpResInfo = "";
	var oDbgEl = document.getElementById("debug")
	
	if (oDbgEl != null) {
	
		// Add Map debug
		if (oMap.bAppletReady) oMap.debugView(oMap.oMapper.getCurrentView());
		
		// Add Http request debug.
		if (res.readyState == 4) {
			sHttpResInfo += "<b>Debug http request:</b><br>";
			sHttpResInfo += "readyState: " + res.readyState;
			sHttpResInfo += "<br>" + res.getAllResponseHeaders();
			sHttpResInfo += res.statusText + "(" + res.status + ")<br>" + RequestUrl + "<br>";
			sHttpResInfo += "<br><br>" + res.responseText.replace(/</gi, "&lt;");
		}
		else {
			sHttpResInfo = "readyState: " + res.readyState;
		}
		
		oDbgEl.innerHTML += "<br><br>" + sHttpResInfo;
	
	}
}

function GetServiceType(coll) {
	for (i=0; i < coll.length; i++) {
		if (coll[i].checked) return coll[i].value;
	}
}

function SetServiceType(coll, iValue) {
	for (i=0; i < coll.length; i++) {
		if (coll[i].value == iValue) {
			coll[i].checked = true;
		}
	}
}

function InitUI() {
	// Reset map.		
	if (oMap.bAppletReady) {
		oMap.highlightAntennaRegion(null);
		oMap.goTo('HOME');
	}
	
	// Set message layers.
	ResultsEl.style.display = "none";	
	InfoEl.style.display = "block";
	InfoEl.style.color = "black";
	InfoEl.innerHTML = txt_StartInfo;
	
	// Set form element default values.
	form.elements["Municipality"].value = "";
	form.elements["Municipality"].focus();
	form.elements["MastIdFromApplet"].value = "";
	
	var iServiceType
	iServiceType = form.elements["ServiceTypeDefault"].value;	
	SetServiceType(form.elements["ServiceType"], iServiceType);	
}

function MastClickedFromApplet(sMastId) {
	form.elements["MastCount"].value = 1;
	form.elements["Municipality"].value = "";
	form.elements["MastIdFromApplet"].value = sMastId;
	GetContractors("","",sMastId);
	GetMastChannels(sMastId, "", GetServiceType(form.elements["ServiceType"]));	
} 

function MunicipalityClickedFromApplet(sMunicipalityId) {
	form.elements["Municipality"].value = "";
	SearchMasts("", sMunicipalityId, GetServiceType(form.elements["ServiceType"]));			
	GetContractors("",sMunicipalityId,"");
}

function OpenHelp() {
	window.open("Help.asp", "KarttapalveluOhje", "location=no,menubar=no,toolbar=no,scrollbars=yes,resizable=yes,height=600,width=500");
}

function ServiceTypeOnChange(oServiceType) {
	// User clicks between servicetype radiobuttons.
	//		- When there is several antenna results.
	//		- When there is already one antenna selected.

	// Municipality is missing so we suppose that user has selected some antenna from the map
	// (selecting antenna from the map will clear the municipality search field).
	if (form.elements["Municipality"].value.length == 0) {
		// Try to look if antenna id can be found from the hidden field and show antenna channels.
		var sMastId = form.elements["MastIdFromApplet"].value;
		if (sMastId.length > 0) GetMastChannels(sMastId, "", GetServiceType(form.elements["ServiceType"]));
	}
	else {
		SearchMasts(form.elements["Municipality"].value, "", GetServiceType(form.elements["ServiceType"]));
	}

}


function SelectAnalog()
{
    //check Analog service type
    
    var iServiceType = "3"; // Digi
    
    SetServiceType(form = document.forms[0].elements["ServiceType"], iServiceType);
    //ServiceTypeOnChange("Radio2");
}


function ServerError(msg) {
			
	if (!InfoEl) {
		// InfoEl missing. Create it.
		// This might be when error occurs in applet and page content is not fully available.
		var infoEl = document.createElement("div");
		var rightContent = document.getElementById("right");
		rightContent.appendChild(infoEl);
		alert("Sovelluksen virhe!");
	}
	
	// Hide possible AJAX results.
	if (ResultsEl) ResultsEl.style.display = "none";		

	// Show info layer.
	if (InfoEl) {
		InfoEl.style.display = "block";
		InfoEl.style.color = "red";
		InfoEl.innerHTML = msg;
	}
	
}



/* --------------------------------------------------------
	AJAX  calls
-------------------------------------------------------- */
function SearchMasts(sMunicipality, sMunicipalityId, iServiceType) {
	// Reset multiple results to zero.
	form.elements["MastCount"].value = 0;

	// Set message layers.
	ResultsEl.style.display = "none";
	InfoEl.style.display = "block";
	InfoEl.style.color = "black";
	InfoEl.innerHTML = txt_Executing;
	
	// Execute AJAX...
	HttpRequestUrl = HttpRequestBaseUrl + "?Action=1&Municipality=" + escape(sMunicipality) + "&MunicipalityId=" + sMunicipalityId + "&ServiceType=" + iServiceType;
	XmlHttp.get(ShowMasts, HttpRequestUrl, ResultsEl);

}

function GetMastChannels(sMastId, sMunicipality, iServiceType) {
	// Set message layers.
	ResultsEl.style.display = "none";
	InfoEl.style.display = "block";
	InfoEl.style.color = "black";
	InfoEl.innerHTML = txt_Executing;
	
	// Execute AJAX...
	HttpRequestUrl = HttpRequestBaseUrl + "?Action=2&Municipality=" + escape(sMunicipality) + "&ServiceType=" + iServiceType + "&MastId=" + escape(sMastId);
	XmlHttp.get(ShowMastChannels, HttpRequestUrl, ResultsEl);

	// Call applet and move map to mast location.
	if (oMap.bAppletReady) oMap.goToRegion(sMastId);
	
}

function GetContractors(sMunicipality, sMunicipalityId, sMastId) {

	// Set message layers.
	ContractorsEl.style.display = "none";
	InfoEl.style.display = "block";
	InfoEl.style.color = "black";
	InfoEl.innerHTML = txt_Executing;
	
	// Execute AJAX...
	HttpRequestUrl = HttpRequestBaseUrl + "?Action=3&Municipality=" + escape(sMunicipality) + "&MunicipalityId=" + sMunicipalityId + "&MastId="+sMastId;
	//alert(HttpRequestUrl);	
	XmlHttp.get(ShowContractors, HttpRequestUrl, ContractorsEl);

}

/* --------------------------------------------------------
	Callbacks
-------------------------------------------------------- */

function ShowContractors(res, el)
{
    // Turn off the info label.
	//InfoEl.style.display = "block";
	
	// Turn on the results label and show masts.
	el.style.display = "block";	
	//alert(res.responseText);
	el.innerHTML = res.responseText;
}

function ShowMasts(res, el) {
	var oMunicipalityList = null;
	var sMastId = null;
	var sMunicipality = null;
	var sMunicipalityId = null;
	var iMunicipalityCount = 0;
	var iMastCount = 0;

	if (res.status == 200) {

		// Turn off the info label.
		InfoEl.style.display = "none";
		
		// Turn on the results label and show masts.
		el.style.display = "block";
		el.innerHTML = res.responseText;
		
		oMunicipalityList = document.getElementById("MunicipalityList");
		
		sMunicipality = oMunicipalityList.getAttribute("Municipality");
		sMunicipalityId = oMunicipalityList.getAttribute("MunicipalityId"); 
		sMastId = oMunicipalityList.getAttribute("MastId");	
		iMunicipalityCount = oMunicipalityList.getAttribute("MunicipalityCount")
		iMastCount = oMunicipalityList.getAttribute("MastCount");
		
		// If we can get MastId then we have only one mast result.
		if (sMastId != null) {
			// Go directly to channels view if there is only one municipality and only one Mast on it.
			// This suppose to be most common case.
			GetMastChannels(sMastId, sMunicipality, GetServiceType(form.elements["ServiceType"]));
			// Call applet and move map to mast location.
			if (oMap.bAppletReady) oMap.goToRegion(sMastId);
		
		}
		else {
		
			// Flag that there was multiple results.
			form.elements["MastCount"].value = iMastCount
		
			// Make sure that there is no antenna higlight.
			if (oMap.bAppletReady) oMap.highlightAntennaRegion(null);
			
			// Set muncipality name as a search criteria.
			if (sMunicipality != null) form.elements["Municipality"].value = sMunicipality;
			
			// If we can get MunicipalityId then we have only one municipality result.			
			if (sMunicipalityId != null) {
				// If there is only one municipality result, center map to that municipality.
				if (oMap.bAppletReady) oMap.goToMunicipality(sMunicipalityId);
			}
			else {
				// Set map to whole finland.
				if (oMap.bAppletReady) oMap.goTo('HOME');
			}
			
			// Turn on the info label.
			InfoEl.style.display = "block";
			if (iMunicipalityCount >= 1) {
				// Multiple results.
				InfoEl.style.color = "black";
				InfoEl.innerHTML = txt_MoreThanOneResults;
			} else {
				// No results
				el.style.display = "none";
				InfoEl.style.color = "red";
				InfoEl.innerHTML = txt_NoResults;
			}
			
		}

	}
	else {
		ServerError(txt_ServerError);
	}

	if (debug) DebugHttpResponse(res, HttpRequestUrl);
	
}

function ShowMastChannels(res, el) {
	if (res.status == 200) {
		
		// Turn off the info label.
		InfoEl.style.display = "none";
		
		// Turn on the results label and show mast channels.
		el.style.display = "block";
		el.innerHTML = res.responseText;
		
		// Show back to results link when there was multiple results.
		if (form.elements["MastCount"].value > 1 && document.getElementById("BackToResults")) {
			document.getElementById("BackToResults").style.display = "block";
		}
		// Read municipality name to search field.
		if (form.elements["Municipality"].value.length == 0 && document.getElementById("MunicipalityName") != null) {
			form.elements["Municipality"].value = document.getElementById("MunicipalityName").innerHTML;
		}
		
	}
	else {
		ServerError(txt_ServerError);
	}
	
	if (debug) DebugHttpResponse(res, HttpRequestUrl);
		
}
