/**
* Include daemon
*/
(function() {
           var jsfiles = new Array(
			"kortasja.js",
			"lib/LMutil.js",
			"lib/ScaleBar.js",
			"lib/newLayerSwitcher.js",
			"lib/sendEmailForm.js",
			"lib/tooltip.js",
			"lib/multipleBaseLayers.js",
			"lib/leit/searchResultFormat.js",
			"lib/leit/search.js",
			"lib/leit/smoothpopup.js",
			"lib/displayTeikningar.js"
        );

        var agent = navigator.userAgent;
        var docWrite = (agent.match("MSIE") || agent.match("Safari"));
        if(docWrite) {
            var allScriptTags = new Array(jsfiles.length);
        }
        var host = "";//OpenLayers._getScriptLocation() + "lib/";    
        for (var i=0, len=jsfiles.length; i<len; i++) {
            if (docWrite) {
                allScriptTags[i] = "<script src='" + host + jsfiles[i] +
                                   "'></script>"; 
            } else {
                var s = document.createElement("script");
                s.src = host + jsfiles[i];
                var h = document.getElementsByTagName("head").length ? 
                           document.getElementsByTagName("head")[0] : 
                           document.body;
                h.appendChild(s);
            }
        }
        if (docWrite) {
            document.write(allScriptTags.join(""));
        }
    
})();



/******************************************
** Common layers 
*******************************************/
	var veitu_resolutions = new Array(0.78269675781250003, 0.39134837890625002, 0.19567418945312501, 0.097837094726562504); //Start at 1:2000 (1:2220 -  zoomlevel 9)
	var vegir_resolutions = new Array(350.37037000000001, 100.185185, 50.092592500000002, 25.046296250000001); // First four levels
	var sveitabae_resolutions = new Array(6.2615740625000003, 3.1307870312500001,
							1.5653935156250001, 0.78269675781250003, 0.39134837890625002, 0.19567418945312501, 0.097837094726562504); //
	var sveitabaeir_scales = new Array(50000, 25000, 10000, 5000, 2000, 1000, 500, 25);
	var gotuheiti_scales = new Array(5000, 2000, 1000, 500, 25);
	var vegir_scales = new Array(500000, 250000, 100000, 50000, 25000, 10000);

	var ornefni_scales = client_scales;

	if (isCustomOrnefni && client_id != 'skipulag')
	    ornefni_scales = custom_ornefni_scales;
	
	var common_layers = []
	
	if(doVegir)
	{
		var wms_vegir = new OpenLayers.Layer.WMS( "Vegir","http://212.30.228.18/geoserver2/wms",
			{layers:'postgis:vegagerd_vegir',format:'image/jpeg',transparent: true},
			 {singleTile:true,displayInLayerSwitcher:false, isBaseLayer:false,scales: vegir_scales});
		common_layers.push(wms_vegir);
	}
	
	if(doSvMaski != "")
	{
		// We need to loop through the doSvMaski valures to generate the CQL
		var arrSvfList = doSvMaski.split(',');
		var leCQL = ""
		for(i=0;i<arrSvfList.length;i++)
		{
			leCQL += "numer <> " + arrSvfList[i];
			if( i < (arrSvfList.length-1) )
				leCQL += " AND ";
		}
		var wms_svMaski = new OpenLayers.Layer.WMS("Hreppa maski","http://geoserver.loftmyndir.is/geoserver2/wms?",
			{layers: 'postgis:isl_hreppar_sjo',format:'image/png',transparent: true,CQL_FILTER:("" + leCQL +"")},
			{singleTile:true,displayInLayerSwitcher:false,isBaseLayer: false});
		common_layers.push(wms_svMaski);	
	}
	
	if(doOrnefni)
	{	
			var wms_ornefni = new OpenLayers.Layer.WMS("Örnefni &nbsp; &nbsp;",
				"http://geoserver.loftmyndir.is/geoserver2/wms",
				{layers: 'postgis:isl_ornefni,postgis:isl_sveitabaeir',format:'image/jpeg', transparent: true},
				{singleTile:true,displayInLayerSwitcher:true,isBaseLayer: false, scales: ornefni_scales});
			common_layers.push(wms_ornefni);
	}
	
	if(doGotuheiti)
	{
			var wms_gotuheiti = new OpenLayers.Layer.WMS( "Götuheiti og húsnúmer &nbsp;","http://geoserver.loftmyndir.is/geoserver2/wms",
				{layers:'postgis:lm_labelvegir,postgis:isl_husnumer',format:'image/jpeg',transparent: true},
				{singleTile:true,displayInLayerSwitcher:false,isBaseLayer: false});
			common_layers.push(wms_gotuheiti);
	}
	
	if(doWFS)
	{
		// Gather setup from client configuration
		var client_wfs = clientWFS();
		if(typeof(client_wfs) !== 'undefined') 
		{
			common_layers.push(client_wfs);
		}
		
	}

/******************************  
* CORE functions 
*******************************/
/******************************  init AJAX  *****/
function initAjax()
{

	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Your browser does not support AJAX!");
			}
		}

	}
}
/****************************** sendAJAXRequest ****/
function sendAJAXRequest(url, callback)
{
	initAjax();
	xmlHttp.onreadystatechange = callback
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
/****************************** sendSyncAJAXRequest ****/
function sendSyncAJAXRequest(url)
{
	initAjax();
	//xmlHttp.onreadystatechange = callback;
	xmlHttp.open("GET",url,false);
	xmlHttp.send(null);
	return xmlHttp.responseText;
	//alert(xmlHttp.responseText);
}
/****************************** postAJAXRequest ****/
function postAJAXRequest(url, postdata, callback)
{
	initAjax();
	xmlHttp.onreadystatechange = callback
	xmlHttp.open("POST",url,true);
	xmlHttp.send(postdata);
}
/****************************** postAJAXRequest ****/
function postSyncAJAXRequest(url, postdata, callback)
{
	initAjax();
	//xmlHttp.onreadystatechange = callback
	xmlHttp.open("POST",url,false);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", postdata.length);
	xmlHttp.send(postdata);
}

/****************************** AJAX ENDAR **********************************/

/******************************  
*  deactivateAll 
******************************/
function deactivateAll()
{
	olControl_measureArea.deactivate()
	olControl_measureLine.deactivate()
	olControl_zoomBox.deactivate()
	olControl_dragPan.deactivate()
}
/******************************  
*  switchCommands 
******************************/
function switchCommands(command)
{
	document.getElementById("tbSelect").style.backgroundImage = selectIcon;
	document.getElementById("tbZoomBox").style.backgroundImage = zoomboxIcon;
	document.getElementById("tbDragPan").style.backgroundImage = dragpanIcon;
	document.getElementById("tbZoomOut").style.backgroundImage = zoomoutIcon;
	document.getElementById("tbMeasureLine").style.backgroundImage = measureIcon;
	document.getElementById("tbMeasureArea").style.backgroundImage = measureAreaIcon;
	document.getElementById("tbInfo").style.backgroundImage = infoIcon;
	log(command);
	
	if(typeof(customButtons) != "undefined") // Check is customButtons id fefined
		{
			
			// customButtons returns true if the button command was implemented
			if( customButtons(command) )
				return;
		}
	
	var tbDiv = document.getElementById("tb"+command);
	
	if(doWFS)
	{
		if(persistentWFS == false)
		{
			if(typeof(clientSelect) !== 'undefined') 
			{
				clientSelect.deactivate();
			}
		}
	}
	
	if(command=="ZoomBox")
	{
		deactivateAll();
		log("zoom");
		tbDiv.style.backgroundImage="url(img/LM_toolb_"+command+"_down.gif)";
		olControl_zoomBox.activate();
	}
	if(command=="DragPan")
	{
		deactivateAll();
		log("pan");
		tbDiv.style.backgroundImage="url(img/LM_toolb_"+command+"_hand_down.gif)";
		olControl_dragPan.activate();
	}
	if(command=="MeasureLine")
	{
		deactivateAll();
		tbDiv.style.backgroundImage="url(img/LM_toolb_"+command+"_down.gif)";
		if(storedFeature != null)
			storedFeature.destroy();
		log("measure")

		olControl_measureLine.activate();
	}
	if(command=="MeasureArea")
	{
		deactivateAll();
		tbDiv.style.backgroundImage="url(img/LM_toolb_"+command+"_down.gif)";
		if(storedFeature != null)
			storedFeature.destroy();
		log("measurearea")

		olControl_measureArea.activate();
	}		
	if(command == "ZoomOut")
	{
		map.zoomOut();

		document.getElementById("tbZoomBox").style.backgroundImage="url(img/LM_toolb_ZoomBox_down.gif)";
		olControl_zoomBox.activate();
				
	}
	if(command=="Overview")
	{
		// Delete markers from search
		this.markers.clearMarkers(); //parent.markers.clearMarkers();
		var labelLayer = getLayerByName("Merki");
		delLabels(labelLayer);
		
		deactivateAll();
		map.setCenter(new OpenLayers.LonLat(start_lon, start_lat), start_zoom, false, false);
		
		// Hreinsa teiknağar fitjar ef til stağar
		try
		{
			var elLayero = getLayerByName("leitVector"); // get leit vector layer
			elLayero.destroyFeatures();
		}
		catch(err)
		{
			//do nothing!
		}

		document.getElementById("tbZoomBox").style.backgroundImage="url(img/LM_toolb_ZoomBox_down.gif)";
		olControl_zoomBox.activate();		
				
	}
	if(command == "Print")
	{
		window.print();
	}
	if(command == "Info")
	{
		openHelpWindow();
	}
	if (command=="Select")
	{
		deactivateAll();
		
		tbDiv.style.backgroundImage="url(img/LM_toolb_"+command+"_down.gif)";
		 
		if( client_id == "reykjanesbaer" || client_id == "hestar")
		{
			poi_select.hover = true;
			poi_select.activate();
		}
		else
		{
			if(typeof(doClientSelectWMS) == 'undefined')
				doClientSelectWMS = false;
			
			//doClientSelectWMS = !(typeof(doClientSelectWMS) == 'undefined');
			
			if (doClientSelectWMS == true)
			{
				clientSelectWMS();
			}
			else
			{
				clientSelect.activate(); //WFS
			}
		}
	}
	else
	{
		if( client_id == "reykjanesbaer" || client_id == "hestar")
		{	if(typeof(poi_select) != 'undefined' )
				poi_select.hover = false;
		}
	}
}
var helpWin;
/******************************  
*  openHelpWindow 
******************************/
function openHelpWindow()
{
	if(helpWin == null || helpWin.closed)
		helpWin = window.open("help.asp?sv=" + getQuerystring("client"), "helpWindow", "status=0, toolbar=0, scrollbars=1, resizable=1, menubar=0, height=800, width=700")
	else
		helpWin.focus();
}
/******************************  
*  log 
******************************/
function log(message)
{
	try
		{
			console.log(message)
		}
	catch (e)
		{

		}
}
/******************************  
*  doTheFunkyBar 
******************************/
function doTheFunkyBar()
{	
	//return;
	//debugger;
	if(initcounter > 0)
	{
		//return;
	}
	//alert("init only this time");
	// Change images in panZoom stuff
	var zoombar = document.getElementById("LM_panzoombar");
	var control_id="";
	// Browser incompatability HACK
	if(zoombar.children != undefined)
		control_id = zoombar.children[5].id.split("_")[1];
	else if (zoombar.childNodes != undefined)
		control_id = zoombar.childNodes[5].id.split("_")[1];
	//var control_id=document.getElementById("LM_panzoombar").children[5].id.split("_")[1]
	
	var pzbControl = map.getControlsBy("CLASS_NAME","OpenLayers.Control.PanZoomBar")[0];
	//panup
	pzbControl.buttons[0].innerHTML = '<img  style="position: relative; width: 18px; height: 19px;" src="img/LM_panzoompanup3.png">';
	//panleft
	pzbControl.buttons[1].innerHTML = '<img  style="position: relative; width: 19px; height: 18px;" src="img/LM_panzoompanleft3.png">';
	//panright
	pzbControl.buttons[2].innerHTML = '<img  style="position: relative; width: 19px; height: 18px;" src="img/LM_panzoompanright3.png">';
	//pandown
	pzbControl.buttons[3].innerHTML = '<img  style="position: relative; width: 18px; height: 19px;" src="img/LM_panzoompandown3.png">';
	//zoomin
	pzbControl.buttons[4].innerHTML = '<img  id="LM_zoom-slider_plus" style="position: relative; width: 18px; height: 13px;" src="img/LM_zoom-plus3.png">'; // position: relative; 
	//zoomout
	pzbControl.buttons[5].innerHTML = '<img  id="LM_zoom-slider_minus" style="position: relative; width: 18px; height: 13px;" src="img/LM_zoom-minus3.png">'; // position: relative;
	
	//sliderBtn
	pzbControl.slider.innerHTML = '<img id="LM_zoom-slider_img" src="img/LM_zoom-slider3.png" style="padding:0px;margin:0px;position: relative;width: 18px; height: 11px;left: 11px;">'; 
	
	//SliderBg
	pzbControl.buttons[4].nextSibling.style.backgroundImage = "url(img/LM_zoombar_thin.png)";
	pzbControl.buttons[4].nextSibling.style.width="10px";
	pzbControl.buttons[4].nextSibling.style.left="27px";
	pzbControl.buttons[4].nextSibling.style.top="80px";
	
	// tökum panup hnappinn
	
	
	/* Geyma ağeins*/
	/*
	document.getElementById("OpenLayers_Control_PanZoomBar_"+control_id+"_panup_innerImage")	
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_panup_innerImage").src= "img/LM_panzoompanup3.png";
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panup_innerImage").css("width","18px");
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panup_innerImage").css("height","19px");
	
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_pandown_innerImage").src= "img/LM_panzoompandown3.png";
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_pandown_innerImage").css("width","18px");
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_pandown_innerImage").css("height","19px");
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_panleft_innerImage").src= "img/LM_panzoompanleft3.png";
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panleft_innerImage").css("width","19px");
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panleft_innerImage").css("height","18px");
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_panright_innerImage").src= "img/LM_panzoompanright3.png";
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panright_innerImage").css("width","19px");
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panright_innerImage").css("height","18px");
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_zoomin_innerImage").src= "img/LM_zoom-plus3.png";
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_zoomin_innerImage").css("width","18px");
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_zoomin_innerImage").css("height","13px");
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_zoomout_innerImage").src= "img/LM_zoom-minus3.png";
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_zoomout_innerImage").css("width","18px");
						$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_zoomout_innerImage").css("height","13px");
	*/					
					
	//var Map_Enum=document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_zoomin").nextSibling.id.split(".")[1];

	/*document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_OpenLayers."+Map_Enum+"_innerImage").src= "img/LM_zoom-slider3.png";
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_OpenLayers."+Map_Enum+"_innerImage").style.position="relative";
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_OpenLayers."+Map_Enum+"_innerImage").style.width="18px";
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_OpenLayers."+Map_Enum+"_innerImage").style.height="11px";
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_OpenLayers."+Map_Enum+"_innerImage").style.left="11px";
	document.getElementById("OpenLayers.Control.PanZoomBar_"+control_id+"_OpenLayers."+Map_Enum+"_innerImage").style.top="-7px";*/
	//document.getElementById("OpenLayers_Control_PanZoomBar_ZoombarOpenLayers."+Map_Enum+"").style.width="10px";
	//document.getElementById("OpenLayers_Control_PanZoomBar_ZoombarOpenLayers."+Map_Enum+"").style.left="27px";
	//document.getElementById("OpenLayers_Control_PanZoomBar_ZoombarOpenLayers."+Map_Enum+"").style.top="80px";
	//document.getElementById("OpenLayers_Control_PanZoomBar_ZoombarOpenLayers."+Map_Enum+"").style.backgroundImage = "url(img/LM_zoombar_thin.png)";
	//debugger;
	$j("#LM_panzoombar").attr('style', "").addClass('LM_PanZoomBarContainer');
	
	pzbControl.buttons[0].className="OpenLayers_Control_PanZoom_panup";
	//pzbControl.buttons[0].style[].clear();
	//debugger;
	//var panupObj = pzbControl.buttons[0].id.replace(".","\\.");
	arr = pzbControl.buttons[0].id.split(".")
	var panupObj = arr[0]+"\\\."+arr[1]+"\\\."+arr[2];
	$j("#"+panupObj).attr('style', null).addClass('OpenLayers_Control_PanZoom_panup');
	$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_pandown").attr('style', null).addClass('OpenLayers_Control_PanZoom_pandown');
	$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panleft").attr('style', null).addClass('OpenLayers_Control_PanZoom_panleft');
	$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_panright").attr('style', null).addClass('OpenLayers_Control_PanZoom_panright');
	$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_zoomin").attr('style', null).addClass('OpenLayers_Control_PanZoom_zoomin');
	$j("#OpenLayers\\.Control\\.PanZoomBar_"+control_id+"_zoomout").attr('style', null).addClass('OpenLayers_Control_PanZoom_zoomout_'+map.scales.length);
	$j("#OpenLayers_Control_PanZoomBar_ZoombarOpenLayers").attr('style', "").addClass('OpenLayers_Control_PanZoomBar_ZoombarOpenLayers');
	$j("#LM_panzoombar").append('<div id=leIsland class=leIsland onclick=switchCommands("Overview")></div>');
	
}

// Twitter sharing
function shareTwitter(title)
{
	// Get location and use tinyUrl.  
	// Needs to be synchronous to make sure tinyUrl is retrieved before sumitting to Twitter
	var url = sendSyncAJAXRequest('proxies/tinyUrl_proxy.asp?longUrl=' + escape( viewLink.div.childNodes[0] ) );
	if ( title == "" ) 
		title = "Skoda kortasja"; // Default if title is emtpy
	// Construct the url to send to the popup window
	var newWindowUrl = "http://twitter.com/home?status=" + encodeURIComponent(title) + " >> " + url;
	var W;
	w = window.open(newWindowUrl, "_blank","toolbar=0,status=0,width=626,height=436");
	return false;
}

// Facebook sharing
function shareFacebook(title)
{
	if ( title == "" ) 
		title = "Kortasjá Loftmynda"; // Default if title is emtpy
	// Construct the url to send to the popup window
	var url = sendSyncAJAXRequest('proxies/tinyUrl_proxy.asp?longUrl=' + escape( viewLink.div.childNodes[0] ) );
	window.open('http://www.facebook.com/sharer.php?u='+url+'&t='+encodeURIComponent(title),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function getLayerByName(layerName)
{
	layersLength = map.layers.length
	for (i=0; i < layersLength; i++)
	{
		if(map.layers[i].name == layerName)
			return map.layers[i];
	}
}
function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
} 

function getZoomFromScale(scale)
{
	var leZoomLevel = 0; //default
	for(i=0; i<client_scales.length;i++)
	{
		if ( client_scales[i] == scale )
		{
			leZoomLevel = i
		}
	}
	return leZoomLevel;
}

function handleMeasurements(event) {

	var measureoutstringelement = document.getElementById('output');
	var measureoutstring;
	var Units;
	var Measurement;
	var Title;
	var isArea = false;

	if( Math.round( event.measure.toFixed(3) ) == 0)
		return;  // hér vantar kannski skilaboğ				

	Title = this.title;
	Units = event.units;
	if(Units == "m")
		Measurement = event.measure.toFixed(1);
	else
		Measurement = event.measure.toFixed(3);	

	if( event.geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon" )  
	{	
		isArea = true;
		measureoutstring = "Niğurstağa mælingar: " + Measurement + " " + Units +  "2";
		Units +=  "2";
	}
	if( event.geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" )  
	{
		isArea = false;		
		measureoutstring = "Niğurstağa mælingar: " + Measurement + " " + Units;
	}		
	
	if( false ) // á ağ sjá mælingar og geyma í layer til ağ fela/sına
	{
		var drawnFeature = this.handler.layer.features[0].clone();
		drawnFeature.attributes.measurement = Measurement;
		drawnFeature.attributes.units = Units;
		drawnFeature.attributes.order = isArea;
		drawnFeature.attributes.title = Title;			
		
		vectors_measure.addFeatures([drawnFeature]); 
		vectors_measure.refresh();			
		
		var feat_point = drawnFeature.geometry.getCentroid(); 
		var textNode = new OpenLayers.Feature.Vector( 
			new OpenLayers.Geometry.Point(feat_point.x,feat_point.y), 
			{}, { 
				label: drawnFeature.attributes.measurement + ' ' + drawnFeature.attributes.units + ((drawnFeature.attributes.isarea)?'2':''), 
				fontColor: "#00F", 
				fontSize: "14px", 
				fontFamily: "Arial", 
				fontWeight: "bold", 
				labelAlign: "cm" 
			}); 
		vectors_measure.addFeatures([textNode]);
		vectors_measure.refresh();
	}
	alert(measureoutstring);
}


// ---- Automatic map resizeing ------------------------------------ //

function getWindowHeight() {
    if (window.self && self.innerHeight) {
        return self.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}
function getViewPortSize()
{
	var viewportwidth;
	var viewportheight;

	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

	if (typeof window.innerWidth != 'undefined')
	{
	  viewportwidth = window.innerWidth,
	  viewportheight = window.innerHeight
	}

	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

	else if (typeof document.documentElement != 'undefined'
	 && typeof document.documentElement.clientWidth !=
	 'undefined' && document.documentElement.clientWidth != 0)
	{
	   viewportwidth = document.documentElement.clientWidth,
	   viewportheight = document.documentElement.clientHeight
	}

	// older versions of IE

	else
	{
	   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
        return {width:viewportwidth,height:viewportheight};
}

/**onAppResize - Event handler for document.onresize that dynamically sets the height/width of the #map div (in fullscreen mode only)*/
function onAppResize()
{
	if(is_Fullscreen)
	{	
		//Calculate map size according to browser size
		viewPort = getViewPortSize()
		var height = viewPort.height;
		var width= viewPort.width;
		h_offset = $j("#map").css("top").replace("px","");
		H_CONST = 7; // for buttom margin
		W_CONST = 22; // 2x10 for margins + 1+1 for no scroll
		//debugger;
		$j("#map").css("width",(width-W_CONST)+"px").css("height",(height-h_offset-H_CONST )+"px");
		log("Map resize")
	}
	else
		return;
}

function calculateOffsetTop(element, opt_top) {
    var top = opt_top || null;
    var offset = 0;
    for (var elem = element; elem && elem != opt_top; elem = elem.offsetParent) {
        offset += elem.offsetTop;
    }
    return offset;
}

function loadjscssfile(filename, filetype)
{
	if (filetype=="js"){ //if filename is a external JavaScript file
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype=="css"){ //if filename is an external CSS file
		var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
	}
	if (typeof fileref!="undefined")
	document.getElementsByTagName("head")[0].appendChild(fileref);
}
		
var clientCSS = getQuerystring('client');
loadjscssfile("css/" + clientCSS + ".css", "css"); ////dynamically load and add this .css file
