// JavaScript Document

// http://www.webreference.com/programming/javascript/onloads/
function addLoadEvent(func) {
//alert("adding an onload sub");
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

// header image
addLoadEvent(function(){
var e=(document.getElementById)?document.getElementById("myTableId"):(document.all)?document.all.myTableId:(document.layers)?document.myTableId:null;
if(!e)return true;
e.style.backgroundImage="url("+backgroundImages[Math.floor(Math.random()*backgroundImages.length)]+")";
});

// The following controls the weather data display in the red nav bar
// constants
var weatherArrowNormal = "/images/arrows.gif";
var weatherArrowMouseover = "/images/arrows_ro.gif";
// variable
var weatherPos = 0;
// function to scroll through info
function nextWeatherItem() {
  var currentItem = document.getElementById("weather" + weatherPos);
  currentItem.style.visibility = "hidden";
  weatherPos = weatherPos + 1;
  var nextItem = document.getElementById("weather" + weatherPos);
  if ( nextItem == null ) {
    // start over at the beginning
    nextItem = document.getElementById("weather0");
    weatherPos = 0;
  } 
  nextItem.style.visibility = "visible";
}
// make sure we have weather info
function revealWeather() {
var nextItem = document.getElementById("weather" + weatherPos);
  if ( nextItem != null ) {
  // display next arrow
document.writeln(' <a href="javascript:nextWeatherItem();" onMouseOver="document.weatherArrow.src=weatherArrowMouseover;" onMouseOut="document.weatherArrow.src=weatherArrowNormal;"><img name="weatherArrow" src="/images/arrows.gif" alt="Weather Forecast for Alexandria" title="Weather Forecast for Alexandria" border="0" style="position: relative; top: 3px;"/></a>');
  // make current conditions visible
  nextItem.style.visibility = "visible";
}
}

//The following displays random table background images for the COA page header

var backgroundImages=new Array(7);
var bgImageProtocol = "http";
if (window.location.href.toLowerCase().indexOf("https:") == 0) {
  bgImageProtocol = "https";
}
backgroundImages[0]=bgImageProtocol + "://alexandriava.gov/images/header1_bg.jpg";
backgroundImages[1]=bgImageProtocol + "://alexandriava.gov/images/header2_bg.jpg";
backgroundImages[2]=bgImageProtocol + "://alexandriava.gov/images/header3_bg.jpg";
backgroundImages[3]=bgImageProtocol + "://alexandriava.gov/images/header4_bg.jpg";
backgroundImages[4]=bgImageProtocol + "://alexandriava.gov/images/header5_bg.jpg";
backgroundImages[5]=bgImageProtocol + "://alexandriava.gov/images/header6_bg.jpg";
backgroundImages[6]=bgImageProtocol + "://alexandriava.gov/images/header7_bg.jpg";

//Open new windows
function coa_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//The following controls jump menus

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  var newURL = selObj.options[selObj.selectedIndex].value;
  if (restore) selObj.selectedIndex=0;
  if ( newURL == "" ) {
    selObj.selectedIndex=0;
    return false;
  }
  //alert("going to \""+newURL+"\"");
  eval(targ+".location='"+newURL+"'");
}


//The following controls showing and hiding layers or hidden divs

function MM_showHideLayers() { //v9.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function coa_toggleVisibility(objname) { 
  obj = document.getElementById(objname);
  if (obj != null) {
    if (obj.style) { 
      if ( obj.style.visibility == 'visible' ) {
        obj.style.visibility = 'hidden';
      } else {
        obj.style.visibility = 'visible';
      }
    }
  }
}



//,'alexandriava\.gov/WorkArea/linkit\.aspx.*#'

// BEGIN $Id: achange.js,v 1.23 2008/10/27 16:18:24 peterw Exp peterw $
// $Revision: 1.23 $

function coa_escapeHTML(text) {
  var buffer = '';
    for (i=0; i < text.length; i++) { 
      var c = text.charAt(i);
      if ( c == '<') { buffer = buffer + '&lt;'; }
      else if ( c == '>') { buffer = buffer + '&gt;'; }
      else if ( c == '&') { buffer = buffer + '&amp;'; }
      else if ( c == '"') { buffer = buffer + '&quot;'; }
      else if ( c == "'") { buffer = buffer + '&apos;'; }
      else { buffer = buffer + c; }
    }
    return buffer;
}

// coa_getElements() -- JS function to crawl DOM and return
// an array of appropriate objects
// http://invisibleblocks.wordpress.com/2006/01/18/hacking-the-browsers-dom-for-fun/
function coa_getElements (evalFunc, node) {
   if (!node) node = document.documentElement;
   var matches = new Array();  // storage space
   if (evalFunc(node))         // if it's a match...
       matches.push(node);     // store it

   var child = node.firstChild;
   while (child) {                // search thru each child
       matches = matches.concat(coa_getElements(evalFunc, child));
       child = child.nextSibling;
   }
   return matches;
}

// coa_wrapAnchors() -- call as an onLoad function
// will edit any A tag's HREF value inside a DOM container 
// (normall a SPAN) whose ID begins with the specified prefix
// *unless* the A tag uses the special preserveClassName class
function coa_wrapAnchors(spanPrefix, linkAppBase, preserveClassName, internalRegex, containerType, siteBaseURL, noLinkRegex) {
  // how "internal" links would start
  var internalURLBase = document.URL;
  var firstPound = internalURLBase.indexOf("#");
  var fragmentToAdd = "";
  if (firstPound > 0) {
    internalURLBase = internalURLBase.substring(0,firstPound);
    fragmentToAdd = internalURLBase.substring(firstPound);
  }
  internalURLBase = internalURLBase + "#";

  // 1) find the spans that might have A tags to alter
  var spansToAlter = coa_getElements(
   function(node) {
       return ( node.nodeName == containerType &&
       		(node.id.indexOf(spanPrefix) == 0) );
   })
  for (var n = spansToAlter.length - 1; n >= 0; --n) {
    // our span name
    var spanName = spansToAlter[n].id.substring(spanPrefix.length);
    // find all the hyperlinks in/under this containerType
    var links = coa_getElements(
     function(node) {
         return node.nodeName == 'A' &&
         ((node.className == null) || (node.className.indexOf(preserveClassName) < 0) );
     }, spansToAlter[n]);
    for (var i = 0; i < links.length; ++i) {
      // the link is always absolute, already
      // calcualted by the browser; make sure it's
      // not already linking through the special URL
      if ( 
	  (links[i].href != null) && 
          (links[i].href.indexOf(internalURLBase) != 0) &&
          ( (links[i].href.indexOf("http://") == 0) || 
            (links[i].href.indexOf("https://") == 0) ||
            (links[i].href.indexOf("ftp://") == 0) ) &&
	  (links[i].href != "") ) {
        // edit the TARGET?
        if (
            (! links[i].href.match(internalRegex)) ||
            (links[i].href.lastIndexOf(".pdf") == (links[i].href.length - 4))
           ) {
//alert("href \"" + links[i].href + "\", internal regex \"" + internalRegex + "\"");

          links[i].target = "_blank";
          // add "opens in new window" text?
          var currentTitle = (links[i].title == null) ? "" : (" " + links[i].title);
          if ( currentTitle.toLowerCase().indexOf("opens in new window") < 0 ) {
              links[i].title = "(opens in new window)" + currentTitle; 
          }
        }
        // alter the HREF as needed
        var htmlContents = links[i].innerHTML;
        links[i].href = coa_wrapURL(links[i].href, linkAppBase, internalURLBase, spanName, htmlContents, i, noLinkRegex);
        links[i].innerHTML = htmlContents;
      } 
      //alert("link " + i + ": " + links[i].text + " - " + links[i].className);
    }
  }

  // 2) look for jump menus
  var selectsToAlter = coa_getElements(
   function(node) {
       return ( node.nodeName == 'SELECT' &&
       		(node.id.indexOf(spanPrefix) == 0) );
   })
  for (var n = selectsToAlter.length - 1; n >= 0; --n) {
    // our select name
    var spanName = selectsToAlter[n].id.substring(spanPrefix.length);
    // find all the OPTIONS inside this SELECT
    var options = coa_getElements(
     function(node) {
         return node.nodeName == 'OPTION';
     }, selectsToAlter[n]);
    for (var i = 0; i < options.length; ++i) {
      var firstSlash = options[i].value.indexOf("/");
      if ( firstSlash >= 0 ) {
        // looks like a URL
        if ( firstSlash == 0 ) {
          // prepend site base URL
          options[i].value = siteBaseURL + options[i].value;
        }
        // now, wrap 
        options[i].value = coa_wrapURL(options[i].value, linkAppBase, internalURLBase, spanName, options[i].innerHTML, i);
      }
    }
    // make the jump menu visible
    selectsToAlter[n].style.display = "";
  }
}

function coa_wrapURL(url, linkAppBase, internalURLBase, spanName, htmlContents, i, noLinkRegex) {
  if (url.match(noLinkRegex)) { return url; }
  var firstPound = url.indexOf("#");
  var fragmentToAdd = "";
  if (firstPound > 0) {
    fragmentToAdd = "&f=1" + url.substring(firstPound);
  }
  // edit the HREF?
  if (
       (url.indexOf(linkAppBase) < 0) && 
       ( (url.indexOf("http://") == 0) || (url.indexOf("https://") == 0) ) &&
       (url.indexOf(internalURLBase) != 0)
  ) {
    // need to build a fancy link; start with HREF and link count
    var newURL = linkAppBase + "?u=" + COA_plus_escape(url) +
                 "&i=" + i + "&s=" + escape(spanName);
    // pass the HTML content of the tag
    if ( htmlContents != null ) { 
      newURL = newURL + "&h=" + escape(coa_escapeHTML(htmlContents));
    }
    return newURL + fragmentToAdd;
  }
  // no need to modify URL, use what you started with
  return url;
}

function COA_plus_escape(text) {
  var newString = escape(text)
  //newString = newString.replace("%20","+");
  return newString;
}

// END $Id: achange.js,v 1.23 2008/10/27 16:18:24 peterw Exp peterw $


addLoadEvent(function(){
	var thisproto = "http";
	if (window.location.href.toLowerCase().indexOf("https:") == 0) {
		thisproto = "https";
	}
	coa_wrapAnchors('coa_',thisproto + '://www.alexandriava.gov/goto.aspx','coa_preserve_link','^https?:\\/\\/([a-z0-9]*\\.?alexandriava\\.gov|alexandria\\.granicus\\.com|egovdev\\.alexgov\\.net|localhost|localhost:[0-9]{1,6}|localhost\\.alexandriava\\.gov:[0-9]{1,6})\\/','SPAN','http://alexandriava.gov','alexandriava\.gov/WorkArea/linkit\.aspx.*#');
});

addLoadEvent(function(){
	var thisproto = "http";
	if (window.location.href.toLowerCase().indexOf("https:") == 0) {
		thisproto = "https";
	}
	coa_wrapAnchors('coa_',thisproto + '://www.alexandriava.gov/goto.aspx','coa_preserve_link','^https?:\\/\\/([a-z0-9]*\\.?alexandriava\\.gov|alexandria\\.granicus\\.com|egovdev\\.alexgov\\.net|localhost|localhost:[0-9]{1,6}|localhost\\.alexandriava\\.gov:[0-9]{1,6})\\/','DIV','http://alexandriava.gov','alexandriava\.gov/WorkArea/linkit\.aspx.*#');
});


function coa_panelAnchorHandler() {
  var internalURLBase = document.URL;
  var firstPound = internalURLBase.indexOf("?");
  var anchorName = "";
  if ((firstPound > 0) && ((internalURLBase.length - firstPound) > 4) ) {
    anchorName = internalURLBase.substring(firstPound + 1);
  }
  if ( (anchorName.indexOf("tab=") == 0) && (anchorName.length > 4) ) {
    coa_showPanel(coa_alphaNumOnly(anchorName.substr(4)));
    window.scrollTo(0,0)
  }
}
  
function coa_showPanel(panelName) {
  var spryPanelGroups = coa_getElements(
   function(node) {
       return node.nodeName == 'DIV' &&
       (node.className == "TabbedPanels");
   });
  for (var i = 0; i < spryPanelGroups.length; ++i) {
    // need the ID for this group
    var groupId = spryPanelGroups[i].id;
    if ( (groupId != null) && (groupId != '') ) {
      // anything here by that name?
      var spryPanels = coa_getElements(
        function(node) {
          return node.nodeName == 'LI' &&
         (node.className == "TabbedPanelsTab" );
      }, spryPanelGroups[i]);
      for (var n = 0; n < spryPanels.length; ++n) {
        var myHtml = coa_alphaNumOnly(coa_strip_tags(spryPanels[n].innerHTML));
        if ( (myHtml != null) && (myHtml == panelName) ) {
          // found it!
          var tp = new Spry.Widget.TabbedPanels(groupId);
          tp.showPanel(n + 1);
          return;
        }
      }
    }
  }
}

function coa_strip_tags(input) {
        var tagRegexp = /\<[^\>]*\>/g;
        var newText = input.replace(tagRegexp,"");
        return newText;
}

function coa_alphaNumOnly(input) {
  var newstring = '';
  for (var i = 0; i < input.length; ++i) {
    var v = input.charCodeAt(i);
    if ( 
         ((v >= 48) && (v <= 57)) ||
         ((v >= 65) && (v <= 90)) ||
         ((v >= 97) && (v <= 122))
     ) {
       newstring = newstring + input.substr(i,1);
    }
  }
  return newstring;
}



addLoadEvent(function() {
  var controls = new Array("coa_weatherToggle", "coa_additionalTabs");
  for (var n = 0; n< controls.length; ++n) {
    var obj = document.getElementById(controls[n]);
    if ( obj != null ) {
      obj.style.display = "";
    }
  }
});

addLoadEvent(function() {
  coa_panelAnchorHandler()
});

function coa_cleanImageTitles() {
  var allImages = coa_getElements(
   function(node) {
       return ( node.nodeName == 'IMG' );
   });
  //var tagRegexp = /<[^>]*?>/g				// if raw HTML
  var tagRegexp = /\&lt\;[a-zA-Z0-9]*?\&gt\;/g		// if escaped HTML (as it should be?)
  for (var n = allImages.length - 1; n >= 0; --n) {
    var thisImage = allImages[n];
    var currentAlt = thisImage.alt;
    if ( (currentAlt != null) && (currentAlt != "") ) {
      var newAlt = currentAlt.replace(tagRegexp," ");
      thisImage.alt = newAlt;
    }
    var currentTitle = thisImage.title;
    if ( (currentTitle != null) && (currentTitle != "") ) {
      var newTitle = currentTitle.replace(tagRegexp," ");
      thisImage.title = newTitle;
    }
  }
}
//addLoadEvent(function() {
//  coa_cleanImageTitles()
//});

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*  http://www.webtoolkit.info/javascript-base64.html
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
		return output;
 
	},
 
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function coa_toggleShareBox(showone) {
	      var coa_togglebox = document.getElementsByTagName("div");
            for(var x=0; x<coa_togglebox.length; x++) {
                  name = coa_togglebox[x].getAttribute("name");
                  if (name == 'coa_togglebox') {
                        if (coa_togglebox[x].id == showone) {
                        coa_togglebox[x].style.display = ( coa_togglebox[x].style.display != 'block' ) ? 'block' : 'none';
                  }
                  else {
                        coa_togglebox[x].style.display = 'none';
                  }
            }
      }
} 

function coa_print()
{ 
	var disp_setting="toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,width=800,height=600,left=100,top=25"; 

	if ( document.getElementById("coa_content") == null ) { 
		alert("Error printing with this button!");
	}
	var content_value = document.getElementById("coa_content").innerHTML; 

	var docprint=window.open("","",disp_setting); 
	if ( docprint == null ) { 
		alert("Error printing with this button!");
	}

 	docprint.document.open(); 
 	docprint.document.write('<html><head>' + String.fromCharCode(60) + 'title>City of Alexandria, Virginia</title><link href="/print2.css" rel="stylesheet" type="text/css" /></head><body><div style="float:right;text-align:center;width:85px;border:1px solid blue;background-color:#ececec;padding:8px;font-weight:bold;"><a href="javascript:window.print();">Print This Page</a></div><div style="font-weight:bold;font-size:24px;letter-spacing:1px;padding:0 0 15px 0;"><img src="/images/cityseal-small.gif" alt="City of Alexandria, VA" align="absmiddle"> City of Alexandria, VA</div>');
 	docprint.document.write(content_value);
 	docprint.document.write('</body></html>'); 
 	docprint.document.close(); 
 	docprint.focus(); 
}

function coa_show_logout(htmlContent) {
	if ( document.cookie == null ) { return; }
	if ( document.cookie.indexOf("COA_SSO=") < 0 ) { return; }
	document.writeln(htmlContent);
}

function coa_framekiller() {
	// http://coderrr.wordpress.com/2009/06/18/anti-anti-frame-busting/
	if (top != self) {  
		top.location.replace(document.location);  
		alert('Removing unauthorized frame.'); 
	}  
}
