/** ********** Search JavaScript ************* **/

// Skķtamix til aš tryggja aš leitin endi ekki upp į Hofsjökli ķ fyrsta smelli
//parent.map.panTo( new parent.OpenLayers.LonLat( 517886.32431, 491785.815 ) );


// Here we need to define a parameter array to hold parameters for links in search results
var linkParameters = new Array() ;

function searchResultsCallback()
{
	currPage = 1;
	displayResults();
}

function formatResultTable( sType)
{
	switch (sType)
	{
		case "vegir":
			format_usvegir();
			break;
		case "ornefni":
			format_ornefni();
			break;
		case "vegbutar":
			format_vegbutar();
			break;
		case "heimilisfong":
			format_heimilisfong();
			break;
		case "heimilisfongSkaga":
			format_heimilisfong();
			break;
		case "heimilisfongDala":
			format_heimilisfong();
			break;
		case "heimilisfongSkutu":
			format_heimilisfong();
			break;
		case "heimilisfongBorgarf":
			format_heimilisfong();
			break;	
		case "heimilisfongBorgarb":
			format_heimilisfong();
			break;	
		case "heimilisfongSkorrad":
			format_heimilisfong();
			break;
		case "heimilisfongHval":
			format_heimilisfong();
			break;
		case "heimilisfongHvera":
			format_heimilisfong();
			break;
		case "heimilisfongVogar":
			format_heimilisfong();
			break;
		case "heimilisfongDjupa":
			format_heimilisfong();
			break;
		case "heimilisfongAkureyri":
			format_heimilisfong();
			break;
		case "heimilisfongArborg":
			format_heimilisfong();
			break;
		case "ni_plontur_isl":
			format_ni_plontur_isl();
			break;
		case "ni_plontur_lat":
			format_ni_plontur_lat();
			break;
		case "ni_plontur_reitir":
			format_ni_plontur_reitir();	
			break;
		case "lmi_ornefni_leit":
			format_lmi_ornefni_leit();		
			break;
		case "landsnet_kks_leit":
			format_landsnet_kks_leit();		
			break;
		case "poi1":
			format_poi1();		
			break;
		default:
			alert("default_format")
			break;
	}
}

function displayResults()
{

	var searchType = $j("#searchDropDown option:selected").val();
	
	formatResultTable( searchType );
	
	// resdyState 4 means response complete and time to work the results
	if(xmlHttp.readyState==4)
 	{
		var numberOfResults = $j(xmlHttp.responseXML).find("row").length;
		
		if(numberOfResults == 1)
		{
			// fara beint į punktinn.
		}
		
		var strHTML = "<Table cellpadding=0 cellspacing=0 border=0 class=mainSearchTable>";
		strHTML += "<tr><td class=sTableHeaderLCorner><img src=img/clear.gif width=4 height=10 border=0></td>"; //1
		
		// Check number of displayers rows
		var noDisplayedColumns = 0; // To keep number of rows that need to be displayed in the result table
		for( i=0; i < aResultColumn.length; i++)
		{
			if(aResultColumn[i]['displayInTable'] == true)
			{
				noDisplayedColumns++;
			}
		}
		
		// Let's roll though the array to generate the header 
		var columnCounter = 0;
		for( i=0; i < aResultColumn.length; i++)
		{
			columnCounter++;
			if(aResultColumn[i]['displayInTable'] == true)
			{
				strHTML += "<td width=" + aResultColumn[i]['columnWidth'] + " class=sTableHeader>&nbsp;" + aResultColumn[i]['tableHeaderTxt'] + "</td>";
				if(columnCounter != (noDisplayedColumns-1) )
				{
					strHTML += "<td class=sTableHeaderDivider><img src=img/clear.gif width=1 height=10 border=0></td>";
				}
			}
		}
		strHTML += "<td class=sTableHeaderRCorner><img src=img/clear.gif width=4 height=10 border=0></td></tr>"; //13
		
		var totalColumns = (2 + noDisplayedColumns + noDisplayedColumns - 1); // corners + columns + dividers (columns-1)
		strHTML += "<tr><td colspan=" + totalColumns + " class=sTableBody>";  
		strHTML += "<Table width=100% cellpadding=0 cellspacing=0 border=0 class=mainSearchResultTable>";	// Table containg search Result list
		
		// Now we start working with the XML resultset
		var returnXML = xmlHttp.responseText;
		var counter = 0;		
		
		//var filter = "A";
		
		$j(xmlHttp.responseXML).find("row").each(function() 
		{
			// First we need to decide if result needs to be filtered
			// if variable filter is defined) -> do filtering
			if ( typeof(filter) !== "undefined")
			{
				if(filter != "")
				{
					if ( $j(this).find( aResultColumn[3]['SQLColumn'] ).text() != filter)
					{
						return; // Returns from each loop if row doen not fit filtering conditions
					}
				}
			}
				
			// Calculate what lines to display depending on what resultpage we're in
			var first = (currPage*noPerPage)-noPerPage;
			if ( counter >= first & counter < (first+noPerPage) )
			{
				for( i=0; i < aResultColumn.length; i++) // Loops through the columns
				{
					var rowClass = "";
					if( counter%2 == 0)
					{ rowClass = "sTableResults"; }
					else
					{ rowClass = "sTableResultsAlt"; }
			
					columnCounter++;
					
					// Add parameter if one is supplied
					if ( aResultColumn[i]['linkParameter'] )
					{
						linkParameters[counter] = $j(this).find( aResultColumn[i]['SQLColumn'] ).text();
					}
					
					if(aResultColumn[i]['displayInTable'] == true)
					{
						var isPoint = false; // We need to know if the result is a point
						var scale = 8000;
						var row = $j(this);
						var GML =  $j(this).find("boundary").text() ;
						
						var coordList = "";						
						
						if (GML == "<gml:MultiGeometry></gml:MultiGeometry>" || GML == "<gml:MultiGeometry srsName=\"EPSG:3057\"></gml:MultiGeometry>")
						{
							GML = $j(this).find("geom").text() ;
							isPoint = true;
							// Lets decide scale if info is available 
							scale = setResultScale( Number($j(this).find("staerd").text()) );
							//alert(  Number($j(this).find("staerd").text()) );
						}
						
						var pointz = GML.split("<gml:Point>");
						for (var idx = 1; idx < pointz.length ; idx++ )
						{
							var temp = pointz[idx].split("</gml:Point>");
							pointz[idx-1] = temp[0]; // put coordinates into array again but at index minus one
						}
						pointz.pop(); // remove last element since it's garbage
												
						if (pointz.length > 1){}
							//isPoint = false;
						if(GML.indexOf("Polygon") >= 0){//Here we are dealing with a polygon
							temp=GML.split("gml:coordinates>");
							temp=temp[1].split("</");
							coor = temp[0].split(" ")
							pointz.push("<gml:coordinates>"+coor[0]+"</gml:coordinates>")
							pointz.push("<gml:coordinates>"+coor[2]+"</gml:coordinates>")
						}	
												
							
						for (var j = 0; j < pointz.length ; j++ )
						{
							if (j > 0)
								coordList += ",";
							var coordCut = pointz[j].split("<gml:coordinates>");
							var coordz = coordCut[1].split("</gml:coordinates>");
							coordList += coordz[0];	
						}
						
						var colWidth = "";
						if ( aResultColumn[i]['columnWidth'] != "" )
							colWidth = "width=" + aResultColumn[i]['columnWidth'];
						strHTML += "<td " + colWidth + " class=" + rowClass + ">";
						
						// Show Link
						if ( aResultColumn[i]['showLink'] )
						{
							var linkType = aResultColumn[i]['linkType'];
							var linkText = $j(this).find( aResultColumn[i]['SQLColumn'] ).text();
							
							switch(linkType)
							{
							case 'jsFunction':
							  // Set up a javascript function to call when link is clicked
							  // The javascript function needs to be implemented elsewhere (but within the scope)
							  // i is index of the parameter array used in the function we are calling
							  strHTML	+= "<a href=# onclick=searchLinkClick('" + linkType + "'," + counter + ")>" + linkText + "</a>";
							  break;    
							case 'extLink':
							  // Set up a link to an external webpage
							  strHTML	+= "<a href=# onclick=searchLinkClick('" + linkType + "'," + counter + ")>" + linkText + "</a>";
							  break;
							default:
								// No linkType was set 
								if (!isPoint)
								{
									// If link has "showLink" = true we link to zoomToBounds script with extracted coordinates
									strHTML	+= "&nbsp;<a href=# onclick=zoomToBounds('" + coordList + "')>" + $j(this).find( aResultColumn[i]['SQLColumn'] ).text() + "</a></td>";
								}
								else
								{
									// If link has "showLink" = true we link to searchToXYscript with extracted coordinates
									strHTML	+= "&nbsp;<a href=# onclick=searchToXY(" + coordList + "," + scale + ")>";
									strHTML += $j(this).find( aResultColumn[i]['SQLColumn'] ).text() + "</a></td>";
								}
							}
						}
						else
						{
							// else just diplay the text for the column
							
							//if en need to translate
							if (aResultColumn[i]['translate'])
							{
								strHTML	+= "&nbsp;" + getTranslatedText( $j(this).find( aResultColumn[i]['SQLColumn'] ).text() ) + "</td>";
							}else
							{
								strHTML	+= "&nbsp;" + $j(this).find( aResultColumn[i]['SQLColumn'] ).text() + "</td>";
							}
						}
						
						if(columnCounter != (noDisplayedColumns-1) )
						{
							strHTML += "<td class=sTableHeaderDivider><img src=img/clear.gif width=1 height=10 border=0></td>";
						}
					}
				}
				strHTML += "</TR>";
			}	
			counter++; 
	    });	
		
		//alert (counter );
		
		//counter = 0; //reset counter 
		
		//if(numberOfResults > noPerPage)
		if(counter > noPerPage)
		{
			//Calculate number of pages to display
			//noPages = Math.ceil( numberOfResults/noPerPage );
			noPages = Math.ceil( counter/noPerPage ); 
			//alert("results: " + numberOfResults + " - no pages: " + noPages);
			strHTML += "<tr><td colspan=2><img src=img/clear.gif width=50 height=5 border=0><br>";
			if(currPage != 1)
			{
				strHTML += "&nbsp;<a href=# onclick=javascript:gotoPage(" + (currPage-1) + "); >Fyrri</a>";
			}
			for( i = 1; i <= noPages; i++)
			{
				if( i == currPage )
				{
					strHTML += "&nbsp;<b><font color=red>" + i + "</font></b>";
				}
				else
				{
					strHTML += "&nbsp;<a href=# onclick=javascript:gotoPage(" + i + "); >" + i + "</a>";
				}
			}
			if( currPage != noPages)
			{
				strHTML += "&nbsp;<a href=# onclick=javascript:gotoPage(" + (currPage+1) + "); >Nęsta</a>";
			}
			strHTML += "<br><img src=img/clear.gif width=50 height=5 border=0><br>&nbsp;Leit fyrir ''" + document.getElementById("searchText").value + "'' skilaši " + counter + " nišurstöšum</td></tr>";
		}
		counter = 0; //reset counter 
		
		if (numberOfResults == 0)
		{strHTML += "<tr><td>Ekkert fannst!</td></tr>";}
		
		strHTML += "</table>";
		strHTML += "</td></tr></table>";
		//document.getElementById("contactArea").innerHTML =  strHTML;
		$j("#contactArea").html(strHTML);
		
		//centering with css
		centerPopup();
		//load popup
		loadPopup();
	}//if readystate == 4
}


function gotoPage( pageNo )
{
	//alert( pageNo );
	currPage = pageNo;
	displayResults();
}

function setResultScale( no )
{
	switch ( no )
	{
		case 0:
			scale = 140000;
			break;
		case 1:
			scale = 70000;
			break;
		case 2:
			scale = 35000;
			break;
		case 3:
			scale = 8000;
			break;
		case 4:
			scale = 8000;
			break;
		case 5:
			scale = 4000;
			break;
		default:
			scale = 8000;
			break;
	}
	var sType = $j("#searchDropDown option:selected").val();
	if ( sType == "heimilisfong" )
	{
		scale = 500;
	}
	if ( sType == "heimilisfongSkaga" )
	{
		scale = 1000;
	}
	if ( sType == "heimilisfongAkureyri" )
	{
		scale = 1000;
	}
	
	return scale;
}

function searchLinkClick(linkType, index)
{
	if (linkType == "jsFunction")
		searchLinkActionJS( linkParameters[index] );
	if (linkType == "extLink")
		searchLinkActionURL( linkParameters[index] );
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}
