/*global document ActiveXObject Option XMLHttpRequest addLoadEvent alert unescape window */

/*---------------------------------------------------------------------
 * this script will call function(s) after page load
 *-------------------------------------------------------------------*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		};
	}
}

var head = document.getElementsByTagName("head")[0];

/*---------------------------------------------------------------------
 * reusable funtion to insert javascript into head of document;
 * to use, simpy call the script and insert source as the argument
 * example insertJavascript("/javascript/animatedcollapse.js");
 *-------------------------------------------------------------------*/
function insertJavascript(srcN)
{ 
    var nScript = document.createElement("script");
    nScript.setAttribute("src", srcN);
    nScript.setAttribute("type", "text/javascript");
    head.appendChild(nScript);
}

/*---------------------------------------------------------------------
 * reusable funtion to insert stylesheet into head of document;
 * to use, simpy call the script and insert href as the first argument
 * the second option is optional to describe media. If it is ommitted then
 * the media will default to screen (media="screen")
 * example insertStylesheet("/global_site/template/css/sBillboard.css", "screen,handheld");
 * or insertStylesheet("/global_site/template/css/sBillboard.css");
 *-------------------------------------------------------------------*/
function insertStylesheet(hrefN, media)
{ 
    var nStyle = document.createElement("link");
    if (media)
    {
        nStyle.setAttribute("media", media);
    }
    else
    {
        nStyle.setAttribute("media", "screen");
    }
    nStyle.setAttribute("rel", "stylesheet");
    nStyle.setAttribute("href", hrefN);
    nStyle.setAttribute("type", "text/css");
    head.appendChild(nStyle);
}

/*---------------------------------------------------------------------
 * reusable function to replace target with rel attribute for external
 * links replace target="_blank" with rel="external" this function is
 * used to keep site strict and open link in new window _blank
 *-------------------------------------------------------------------*/
function showLink(whichlink)
{
    var externalHref = whichlink.getAttribute("href");
    window.open(externalHref, "_blank");

    return false;
}

function externalLinks()
{
    if (!document.getElementsByTagName)
    {
    	return;
    }
    var anchors = document.getElementsByTagName("a");
    for ( var i = 0; i < anchors.length; i++ )
    {
        var anchor = anchors[i];
        if ( anchor.getAttribute("href") && anchor.getAttribute("rel") == "external" )
        {
            anchor.onclick = function() {
                return showLink(this);
            };
        	anchor.onkeypress = anchor.onclick;
        }
    }
}

addLoadEvent(externalLinks); // will load externalLinks function on page load

/*-----------------------------------------------------------------------------
 *  this replaces trackingwidget.js & calendarWidget.js
 *  pass index, total tabs as count, id attribute of content element
 *  and id attribute of tab element
 *---------------------------------------------------------------------------*/
function showHideTab(index, count, content_elementID, tab_elementID)
{		
	for (var i = 1; i <= count; i++)
	{
		var className = '';
		var display='none';
		
		if ( i == index )
		{ 
			display = 'block';
			className = 'active';
		}
		document.getElementById(content_elementID + i).style.display = display;
		document.getElementById(tab_elementID + i).className = className;	
	}			
}

/*-----------------------------------------------------------------------------
 *  this replaces trackingwidget.js 
 *  pass id attribute of element and tab number/index to hid tab
 *---------------------------------------------------------------------------*/
function hideTab(tab_elementID, tab_num)
{
	document.getElementById(tab_elementID + tab_num).style.display = 'none';
}

// countyselect
// JavaScript Document
var req;
function GetURL(url, handler)
{
	if ( handler === undefined )
	{
		handler = 'processReqChange';
	}
	url = url + '&rand=' + Math.random();
	// branch for native XMLHttpRequest object
	if ( window.XMLHttpRequest )
	{
		req = new XMLHttpRequest();
		req.onreadystatechange = eval(handler);
		req.open("GET", url, true);
		req.send(null);
	// branch for IE/Windows ActiveX version
	} 
	else if ( window.ActiveXObject )
	{
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req)
		{
			req.onreadystatechange = eval(handler);
			req.open("GET", url, true);
			req.send();
		}
	}
}
	
function LoadCounties(path)
{
	if ( path === undefined)
	{
		path = '';
	}
	document.getElementById("county").options.length = 0;
	GetURL('/?event=mobileCounties&state_id=' + document.getElementById("state").options[document.getElementById("state").selectedIndex].value, 'processReqChangeLoadCounties');
}

function processReqChangeLoadCounties()
{   
	// only if req shows "complete"
	if ( req.readyState == 4 )
	{
		// only if "OK"
		if ( req.status == 200 )
		{
			var response = req.responseXML.documentElement;
			if ( response.getElementsByTagName('errors')[0].firstChild.data == 0 )
			{
		  		document.getElementById("county").options[0] = new Option('','');
				if ( response.getElementsByTagName('id') )
				{
					for ( var i = 0; i < response.getElementsByTagName('id').length; i++ )
					{
			  			document.getElementById("county").options[document.getElementById("county").options.length] = new Option(unescape(response.getElementsByTagName('county')[i].firstChild.data),response.getElementsByTagName('id')[i].firstChild.data);
					}
		  		}
			}
			else
			{
		  		alert(response.getElementsByTagName('errors')[0].firstChild.data);
			}
	  	} 
	  	else
	  	{
			alert("200: There was a problem retrieving the XML data:\n" + req.statusText);
	  	}
  	}
}

function alertChange()
{
	var display = 'none';
	if ( document.getElementById('alert').options[document.getElementById('alert').selectedIndex].value == 'weather')
	{
		display = 'block';
	}
	document.getElementById('weather_form_div').style.display = display;
}

function popUp(URL,h,w) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,height="+h+",width="+w+",left = 0,top = 0');");
}
$(function() {
		$.fn.aToButton = function(){
				return this.each(function() {
						var btn = document.createElement('button');
						$(btn).html($(this).html())
							.attr('href', $(this).attr('href') || '')
							.attr('class', $(this).attr('class') || '')
							.attr('title', $(this).attr('title') || '')
							.bind('click', function(e) {
									location.href = $(this).attr('href');
									return false;
							});
						$(this).replaceWith(btn);
				});
		};
});