var eventCache = new Array();
var targetMarker = null;    //marker variable for access in other functions
var continueChecking = true; //use to stop lookup after marker is found

function EventCache(obj, type, fn)
{
    this.obj = obj;
    this.type = type;
    this.fn = fn;
}

function addEvent(obj, type, fn)
{
	if (typeof obj.addEventListener != 'undefined')
	{
	    // Firefox
	    obj.addEventListener(type, fn, false);
    }
    else if (typeof obj.attachEvent != 'undefined')
    {
        // In IE
        var iter = "e" + type + fn;
		obj[iter] = fn;
		obj[type+fn] = function() { 
		    obj[iter]( window.event ); 
        }
		obj.attachEvent( "on"+type, fn);
    }
	else
	{
	   alert("Can't addEvent in this browser.");
	}
	
	eventCache[eventCache.length] = new EventCache(obj, type, fn);
}

function bindEvent(obj, type, targetObj, fn)
{
    var closure = fn.closure(targetObj);
    
	if(obj.addEventListener)
    {
        obj.addEventListener(type, closure, false);
    }
	else
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, closure);
    }
	
	eventCache[eventCache.length] = new EventCache(obj, type, fn);
}

function clearEvents()
{
    for (var i = 0; i < eventCache.length; i++)
    {
        var evt = eventCache[i];
        try
        {
            if (evt.obj && evt.fn)
            {
                if (evt.obj.removeEventListener)
                {
                    evt.obj.removeEventListener(evt.type, evt.fn, true);
                }
                else
                {
                    evt.obj.detachEvent("on"+evt.type, evt.fn);
                }
            }
        }
        catch (e)
        {
            alert("Error on " + i + " : " + e.message);
        }
    }
}

addEvent(window, "unload", clearEvents);

// From http://laurens.vd.oever.nl/weblog/items2005/closures/
Function.prototype.closure = function(obj)
{
    // Init object storage.
    if (!window.__objs)
    {
        window.__objs = [];
        window.__funs = [];
    }

    // For symmetry and clarity.
    var fun = this;

    // Make sure the object has an id and is stored in the object store.
    var objId = obj.__objId;
    if (!objId)
    {
        __objs[objId = obj.__objId = __objs.length] = obj;
    }

    // Make sure the function has an id and is stored in the function store.
    var funId = fun.__funId;
    if (!funId)
    {
        __funs[funId = fun.__funId = __funs.length] = fun;
    }

    // Init closure storage.
    if (!obj.__closures)
    {
        obj.__closures = [];
    }

    // See if we previously created a closure for this object/function pair.
    var closure = obj.__closures[funId];
    if (closure)
    {
        return closure;
    }
    
    // Clear references to keep them out of the closure scope.
    obj = null;
    fun = null;

    // Create the closure, store in cache and return result.
    return __objs[objId].__closures[funId] = function ()
    {
        return __funs[funId].apply(__objs[objId], arguments);
    }
}

function ShowNotImplementedYetWarning()
{
    alert('This has not been implemented yet.');
} 


function ShowOverlay()
{
    var overlaybox = document.getElementById("OverlayInfoBox");
    var gmap = document.getElementById("home");
    var options = document.getElementById("btnOptions");
    
    if (overlaybox.style.visibility == 'hidden')
    {
        overlaybox.style.visibility = 'visible';
        //map.style.width = "80%";
        gmap.style.marginLeft = "220px";
        map.checkResize();
        options.innerHTML = 'Click to hide options';
    }
    else
    {
        overlaybox.style.visibility = 'hidden';
        //map.style.width = "auto";
        gmap.style.marginLeft = "0px";
        map.checkResize();
        options.innerHTML = 'Click to show options';
    }
 
}

function QuickZoom(level, checkbox)
{
    //change the zoom level
    map.setZoom(level);
    
    //set the checkbox to checked
    var ctl = document.getElementById(checkbox);
    ctl.checked = true;
    
    switch(checkbox)
    {
        case 'chkFacilities':
            ToggleFacilities(this);
            break;        
        case 'chkAirports':
            ToggleAirports(this);
            break;        
        case 'chkMinorAirports':
            ToggleMinorAirports(this);
            break;        
        case 'chkMOAs':
            ToggleMOAs(this);
            break;        
        case 'chkSUAs':
            ToggleSUAs(this);
            break;        
        case 'chkMTRs':
            ToggleLLTRs(this);
            break;        
        case 'chkNMACs':
            ToggleNMACs(this);
            break;        
        case 'chkMACs':
            ToggleMACs(this);
            break;
        default:
            break;
    }
}

function ClearAirportBox(control)
{

    if (control.value == 'Enter Your Airport Identifier')
    {
        control.value = '';
    }    
}

function AutoShowAirport(code)
{        
    if (code != null && code != '')
    {
        //Call function to ajax call for coordinates        
        ajax_loadXMLContent('','ajax/getairport.aspx?id=' + code);
        //Error in IE when doing it with ajax call, will try to force
        //directly
        //var apoint = new GLatLng(39.7016666666667,-104.751666666667);
        //targetMarker = apoint;
    } 
}


    
function LocateAirportByButton()
{
    
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
    
    var control = document.getElementById('txtAirport');      
    if (control.value == 'Enter Your Airport Identifier' || control.value.trim() == '')
    {
        alert('Please enter an airport identifier.');        
    }
    else
    {
        if (control.value != null && control.value.trim() != '')
        {
            //Call function to ajax call for coordinates
            ajax_loadXMLContent('','ajax/getairport.aspx?id=' + control.value.trim());
            
            //set the trimmed value back
            control.value = control.value.trim();
        }
    } 
}

function LocateAirport(e)
{
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
    
    var characterCode; //literal character code will be stored in this variable

/*    
    if(e && e.which)
    { //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which; //character code is contained in NN4's which property     
    }
    else
    {
        e = window.event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }
*/    
    
    var control = document.getElementById('txtAirport');      
    if (control.value != null && control.value.trim() != '')
    {
    
        //Call function to ajax call for coordinates
        ajax_loadXMLContent('','ajax/getairport.aspx?id=' + control.value.trim());
        
        //set the trimmed value back
        control.value = control.value.trim();
    }
 
}

function ajax_loadXMLContent(divId,pathToFile)
{
  if(enableCache && jsCache[pathToFile]){
    //document.getElementById(divId).innerHTML = jsCache[pathToFile];
    
    try
    {
        var response = jsCache[pathToFile];
        var lat = response.getElementsByTagName('lat')[0].firstChild.data;
        var lng = response.getElementsByTagName('lng')[0].firstChild.data;
        //var guid = response.getElementsByTagName('guid')[0].firstChild.data;
        //alert (lat + ',' + lng + ',' + guid);
        //Recenter map and zoom in
        var point = new GLatLng(lat, lng);
        if (point != null)
        {
            map.setCenter(point);
            map.setZoom(9); 
            
            //We must store in global var since the timeout mechanism below won't allow us
            //to pass variables as part of the declaration
            targetMarker = point;
            window.setTimeout('openMarker();', 2000);//wait at least 3 seconds before starting
        }
    }
    catch(err)
    {
        //alert('Unable to find airport specified, please try again.');
        alert('Unable to find airport specified, please try again.\nIf you were attempting to enter a four-letter ICAO identifier, just use the last three letters.');
        //alert(err.message);//for debugging error
    }   
    
    return;
  }
  
  var ajaxIndex = dynamicContent_ajaxObjects.length;
  //document.getElementById(divId).innerHTML = 'Loading content...';
  dynamicContent_ajaxObjects[ajaxIndex] = new sack();
  dynamicContent_ajaxObjects[ajaxIndex].requestFile = pathToFile;

  dynamicContent_ajaxObjects[ajaxIndex].onCompletion = 
  function(){ ajax_showContentXML(divId,ajaxIndex,pathToFile); };  

  dynamicContent_ajaxObjects[ajaxIndex].runAJAX();  
  
  
} 


function ajax_showContentXML(divId,ajaxIndex,pathToFile)
{   
    
    try
    {
        var response = dynamicContent_ajaxObjects[ajaxIndex].responseXML.documentElement;
        
        if (response != null)
        {
            var lat = response.getElementsByTagName('lat')[0].firstChild.data;
            var lng = response.getElementsByTagName('lng')[0].firstChild.data;
            
            //var guid = response.getElementsByTagName('guid')[0].firstChild.data;
            //alert (lat + ',' + lng);
            
            //Recenter map and zoom in
            if (lat != null && lng != null)
            {
                var point = new GLatLng(lat, lng);
                
                if (point != null)
                {
                    map.setCenter(point);
                    map.setZoom(9);                    
                    
                    //We must store in global var since the timeout mechanism below won't allow us
                    //to pass variables as part of the declaration
                    targetMarker = point;
                    window.setTimeout('openMarker();', 2000);//wait at least 3 seconds before starting
                }
            }
        }
        else
        {
            throw "No data";
        }
    
    }
    catch(err)
    {
        //alert('Unable to find airport specified, please try again.');
        alert('Unable to find airport specified, please try again.\nIf you were attempting to enter a four-letter ICAO identifier, just use the last three letters.');
        //alert(err.message);//for debugging error
    }
              
  
  //document.getElementById(divId).innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;
  if(enableCache){
    jsCache[pathToFile] = dynamicContent_ajaxObjects[ajaxIndex].responseXML.documentElement;
  }
  
  dynamicContent_ajaxObjects[ajaxIndex] = false;
}
function CheckForDisplayBubble()
{
    if (targetMarker != null)
    {        
        //targetMarker = null; //reset marker after found
        openMarker();
        //window.setTimeout('openMarker();', 2000);//wait at least 1 seconds before starting
        
    }
}

function openMarker()
{
    try
    {
        var point = targetMarker;
        var mymarker = null;
        if (point != null)
        {
            mymarker = FindMarkerReference(point, 1);
        }

        if (mymarker != null)
        {        
            // alert('triggering event:'+mymarker);            
            GEvent.trigger(mymarker, "click");            
        }
    }
    catch(err)
    {
    //do nothing;
    }

}

function FindMarkerReference(point,count)
{        
    var markerfound = false;    //flag used to indicate when marker is found and stop looking
    try
    {
    //try to find a facility first in case of overlap
        for(var i=0;i<facility_markers.length;i++)
        {
        //alert('array coords' + facility_markers[i].getPoint());
        //alert('are equal'+facility_markers[i].getPoint().equals(autoopenmarker));
            if (facility_markers[i].getPoint().equals(point))
            {
                //alert('found the match facility');
                markerfound = true;
                return facility_markers[i];
            }
        }
        
        for(var i=0;i<airport_markers.length;i++)
        {
        //alert('array coords' + facility_markers[i].getPoint());
        //alert('are equal'+facility_markers[i].getPoint().equals(autoopenmarker));
            if (airport_markers[i].getPoint().equals(point))
            {
                //alert('found the match airport');
                markerfound = true;
                return airport_markers[i];
            }
        }
        
    }
    catch(err)
    {
    
    }
     
    while(markerfound==false)
    {    
        //alert('attempt:'+count);
    
        if (count >=1000)
        {                                
            //return null since no marker still not found        
            return null;
        }
        
        //try to find a facility first in case of overlap
        for(var i=0;i<facility_markers.length;i++)
        {
        //alert('array coords' + facility_markers[i].getPoint());
        //alert('are equal'+facility_markers[i].getPoint().equals(autoopenmarker));
            if (facility_markers[i].getPoint().equals(point))
            {
                //alert('found the match');
                markerfound = true;
                return facility_markers[i];
            }
        }
        
        for(var i=0;i<airport_markers.length;i++)
        {
        //alert('array coords' + facility_markers[i].getPoint());
        //alert('are equal'+facility_markers[i].getPoint().equals(autoopenmarker));
            if (airport_markers[i].getPoint().equals(point))
            {
                //alert('found the match');
                markerfound = true;
                return airport_markers[i];
            }
        }
        
        count++;
    }
    
    
}


function closesplash()
{
    var popupfade =  document.getElementById('popupfade');
    var popupcontent = document.getElementById('popupsplash');
    popupfade.style.visibility = "hidden";
    popupcontent.style.visibility = "hidden";
    popupfade.style.height = "";
    popupcontent.style.height = "";
}

function closepopup()
{
    var popupfade =  document.getElementById('popupfade');
    var popupcontent = document.getElementById('popupcontent');
    popupfade.style.visibility = "hidden";
    popupcontent.style.visibility = "hidden";
    popupfade.style.height = "";
    popupcontent.style.height = "";
    
    //close the splash too if happen to be there
    var popupsplash = document.getElementById('popupsplash');    
    popupsplash.style.visibility = "hidden";    
    popupsplash.style.height = "";
}
function loadFacility(guid)
{
    ajax_loadContent('popupcontent','ajax/popup.aspx?guid=' + guid);
    
    var popupfade =  document.getElementById('popupfade');
    var popupcontent = document.getElementById('popupcontent');
    var realcontent_width = 800;
    var realcontent_height = 450;
    
    var myHeight=self.innerHeight;
    if(!myHeight){myHeight=document.body.clientHeight+document.documentElement.clientHeight;}
    var myWidth=self.innerWidth;if(!myWidth){myWidth=document.documentElement.clientWidth;}
    /*
    var myWidth = 0, myHeight = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
      }
    */
    
    //setup the fade background
    popupfade.style.width = document.body.parentNode.scrollWidth + 'px';
    popupfade.style.height = document.body.parentNode.scrollHeight + 200 + 'px';
    
    //popupfade.style.width = myWidth + 'px';
    //popupfade.style.height = '100%';//myHeight*2 + 'px';
    popupfade.style.top = 0;
    popupfade.style.left = 0;
    popupfade.style.visibility = "visible"; 
    
    
    //set the actual popupfade box            
    popupcontent.style.top = (50) + 'px';        
    popupcontent.style.left = (myWidth - realcontent_width)/2 + 'px';
    popupcontent.style.visibility = "visible"; 
    //document.getElementById('content_one').style
}


function getX(oNode)
{
    var x=0;
    while (oNode)
    {
        x+=oNode.offsetLeft;oNode=oNode.offsetParent;
    }
    return x;
}
    
function getY(oNode)
{
    var y=0;
    while (oNode)
    {
        y+=oNode.offsetTop;
        oNode=oNode.offsetParent;
    }
    return y;
}
function getWidth(oNode){return oNode.offsetWidth;}
function getHeight(oNode){return oNode.offsetHeight;}
    
    
function displayImage(params, item)
{
    ajax_loadContent('popupcontent',params);
    
    var popupfade =  document.getElementById('popupfade');
    var popupcontent = document.getElementById('popupcontent');
    var realcontent_width = 800;
    var realcontent_height = 450;
    
    
    //var myWidth = document.body.parentNode.scrollWidth, myHeight = document.body.parentNode.scrollHeight;
    var myHeight=self.innerHeight;
    if(!myHeight){myHeight=document.body.clientHeight+document.documentElement.clientHeight;}
    var myWidth=self.innerWidth;if(!myWidth){myWidth=document.documentElement.clientWidth;}
    
    
    popupfade.style.width = document.body.parentNode.scrollWidth + 'px';
    popupfade.style.height = document.body.parentNode.scrollHeight + 200 + 'px';
    popupfade.style.top = 0;
    popupfade.style.left = 0;
    popupfade.style.visibility = "visible"; 
    
    
    //set the actual popupfade box              
    var x = document.getElementById("popupcontent");
    var pos = null;
   
    if (window.pageYOffset)
    {
          pos = window.pageYOffset
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    {
        pos = document.documentElement.scrollTop
    }
    else if (document.body)
    {
          pos = document.body.scrollTop
    }

    
    popupcontent.style.top = pos + 50 + 'px';
    popupcontent.style.left = (myWidth - realcontent_width)/2 + 'px';
    popupcontent.style.visibility = "visible";     
    
    
}
function displaySplash(params)
{
    ajax_loadContent('popupsplash',params);
    
    var popupfade =  document.getElementById('popupfade');
    var popupcontent = document.getElementById('popupsplash');
    var realcontent_width = 651;
    var realcontent_height = 378;

    
    //var myWidth = document.body.parentNode.scrollWidth, myHeight = document.body.parentNode.scrollHeight;
    var myHeight=self.innerHeight;
    if(!myHeight){myHeight=document.body.clientHeight+document.documentElement.clientHeight;}
    var myWidth=self.innerWidth;
    if(!myWidth){myWidth=document.documentElement.clientWidth;}//+document.documentElement.clientWidth;}
    

    popupfade.style.width = document.body.scrollWidth + 'px';
    popupfade.style.height = document.body.scrollHeight + 850 + 'px';
    popupfade.style.top = 0;
    popupfade.style.left = 0;
    popupfade.style.visibility = "visible"; 
    
    
    //set the actual popupfade box              
    var x = document.getElementById("popupsplash");
    var pos = null;
   
    if (window.pageYOffset)
    {
          pos = window.pageYOffset
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    {
        pos = document.documentElement.scrollTop
    }
    else if (document.body)
    {
          pos = document.body.scrollTop
    }

    
    popupcontent.style.top = pos + 50 + 'px';
    popupcontent.style.left = (myWidth-realcontent_width)/2 + 'px';
    popupcontent.style.visibility = "visible";     
    
    
}


/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}