/**
 * Copyright (c) 2007, Carl S. Yestrau
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Feature Blend nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Carl S. Yestrau ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Carl S. Yestrau BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
function FlashDetectBase(options){
	var self = this;
	var _release = "1.0";
	var options = options || {};
	self.installed = false;
	self.major = -1;
	self.minor = -1;
	self.revision = -1;
	self.revisionStr = "";
	self.activeXVersion = "";
	var activeXDetectRules = options.activeXDetectRules || [
		{
			"name":"ShockwaveFlash.ShockwaveFlash.7",
			"version":function(obj){return getActiveXVersion(obj);}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash.6",
			"version":function(obj){
//				var version = "6,-1,-1,-1";
				var version = "6,0,21";
				try{
					obj.AllowScriptAccess = "always";
					version = getActiveXVersion(obj);
				}catch(err){}
				return version;
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash",
			"version":function(obj){return getActiveXVersion(obj);}
		}
	];
	var getActiveXVersion = function(activeXObj){
		var version = -1;
		try{
			version = activeXObj.GetVariable("$version");
		}catch(err){}
		return version;
	}
	var getActiveXObject = function(name){
		var obj = -1;
		try{
			obj = new ActiveXObject(name);
		}catch(err){}
		return obj;
	}
	var parseActiveXVersion = function(str){
		var versionArray = str.split(",");
		return {
			"major":parseInt(versionArray[0].split(" ")[1]),
			"minor":parseInt(versionArray[1]),
			"revision":parseInt(versionArray[2]),
			"revisionStr":versionArray[2]
		};
	}
	var parseRevisionStrToInt = function(str){
		return parseInt(str.replace(/[a-zA-Z]/g,"")) || self.revision;
	}
	self.majorAtLeast = function(version){
		return self.major >= version;
	}
	self.DetectBase = function(){
		if(navigator.plugins && navigator.plugins.length>0){
			var type = 'application/x-shockwave-flash';
			var mimeTypes = navigator.mimeTypes;
			if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
				var desc = mimeTypes[type].enabledPlugin.description;
				var descParts = desc.split(' ');
				var majorMinor = descParts[2].split('.');
				self.major = parseInt(majorMinor[0]);
				self.minor = parseInt(majorMinor[1]); 
				self.revisionStr = descParts[3];
				self.revision = parseRevisionStrToInt(self.revisionStr);
				self.installed = true;
			}
		}else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
			var version = -1;
			for(var i=0; i<activeXDetectRules.length && version==-1; i++){
				var obj = getActiveXObject(activeXDetectRules[i].name);
				if(typeof obj == "object"){
					self.installed = true;
					version = activeXDetectRules[i].version(obj);
					if(version!=-1){
						var versionObj = parseActiveXVersion(version);
						self.major = versionObj.major;
						self.minor = versionObj.minor; 
						self.revision = versionObj.revision;
						self.revisionStr = versionObj.revisionStr;
						self.activeXVersion = version;
					}
				}
			}
		}
	}();
}
var FlashDetect = new FlashDetectBase();;
// *******************************************

function fmObjectActivate(id, movie, width, height, play, quality, bgcolor, base) {
//do: generate an object to activate

	var fm = fmObjectGetParams(id, movie, width, height, play, quality, bgcolor, base);
	return fmObjectGenerate(fm.attrs, fm.params);
}

function fmObjectActivateWrite(id, movie, width, height, play, quality, bgcolor, base) {
//do: generate an object to activate

	var fm = fmObjectGetParams(id, movie, width, height, play, quality, bgcolor, base);
	if(!FlashDetect.installed){
		document.write( "<div class=\"notice error\" style=\"width:520px;\">This website uses Flash application. <a href=\"http://www.adobe.com/go/getflash/\" target=\"_blank\">Click Here</a> to install flash in order to view the map.</div>\n");
	} else {
		document.write(fmObjectGenerate(fm.attrs, fm.params));
	}
}

function fmObjectGetParams(id, movie, width, height, play, quality, bgcolor, base) {
//do: get params and attributes

	var fm = new Object();
	fm.attrs = new Object();
	fm.params = new Object();
	
	//attributes
	fm.attrs['id'] = id;
	fm.attrs['width'] = width;
	fm.attrs['height'] = height;
	fm.attrs['type'] = 'application/x-shockwave-flash';
	fm.attrs['data'] = movie;
	if (base != "") { fm.attrs['BASE'] = base; }
	
	//parameters
	fm.params['movie'] = movie;
	if (base != "") { fm.params['BASE'] = base; }
	fm.params['play'] = play;
	fm.params['bgcolor'] = bgcolor;
	fm.params['quality'] = quality;
	fm.params['menu'] = 'false';
	fm.params['wmode'] = 'opaque';
	fm.params['allowScriptAccess'] = 'sameDomain';
	
	return fm;
}

function fmObjectGenerate(attrs, params) {
//do: generate the flash object
	
	var str = '<object ';

	for (var i in attrs) 
		str += i + '="' + attrs[i] + '" ';
	str += '>';
	
	for (var i in params) 
		str += '<param name="' + i + '" value="' + params[i] + '" />';
	str += '</object>';
	
	return str;
};
// *********************
// ** THEME functions **
// *********************

function swap(advisory) {
	var fmASMcPath = "map_mc.";

	//var fmEngine = document.fmASEngine2;
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine2;
	} else {
		fmEngine = window.document.fmASEngine2;
	}
	
	if (advisory) {
		fmEngine.swap();
	} else {
		fmEngine.swap();
	}	
	//alert("1");
}


function fmThemeLoad(theme_xml) {

	//do: load a new theme into the AS
	var fmASMcPath = "map_mc.";
	
	//var fmEngine = document.fmASEngine;
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine;
	} else {
		fmEngine = window.document.fmASEngine;
	}

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideTheme", theme_xml);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "themeLoad");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
	
}


function fmThemeLoadX(theme_xml) {

	//do: load a new theme into the AS
	var fmASMcPath = "map_mc.";
	
	//var fmEngine = window.frames["iMapProb"].document.fmASEngine;
	//var fmEngine = document.fmASEngine2;
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine2;
	} else {
		fmEngine = window.document.fmASEngine2;
	}


	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideTheme", theme_xml);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "themeLoad");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}


function fmThemeReloadAreas(areas_xml) {
	//do: reload the areas of a theme
	var fmASMcPath = "map_mc.";
	//var fmEngine = window.frames["iMapStorm"].document.fmASEngine;
	//var fmEngine = document.fmASEngine;
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine;
	} else {
		fmEngine = window.document.fmASEngine;
	}

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAreasXML", areas_xml);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "themeReloadAreas");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}




// *******************
// ** MAP functions **
// *******************

function fmInitialView() {
	//do: return the map to initial view
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "themeInitialView");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmMapBackLevel() {
	//do: return the map one level back
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "themeBackLevel");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

// ************************
// ** MAP MODE functions **
// ************************

function fmMapModeZoom() {
	//do: change the map mode to zoom mode

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "modeZoom");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmMapModeSelect() {
	//do: change the map mode to select mode

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "modeSelect");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmMapModeExportListAreas() {
	//do: return the list of areas selected

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "modeExport");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
	return fmEngine.GetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAreasSelected");
}

function fmMapModeCleanAreas() {
	//do: clean the list of areas selected

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "modeClean");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

// *********************
// ** AREAS functions **
// *********************

function fmAreaCenter(area_str) {
	//do: center the map into an area
	//var fmEngine = window.frames["iMapProb"].document.fmASEngine;
	var fmASMcPath = "map_mc.";
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine;
	} else {
		fmEngine = window.document.fmASEngine;
	}
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideArea", area_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "areaCenter");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmAreaCenterLatLon(area_str, lat, lon, scale) {
	//do: center the map into a latitude/longitude
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideArea", area_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideLat", lat);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideLon", lon);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideScale", scale);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "areaCenterLatLon");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}


function fmAreaCenterLatLonX(area_str, lat, lon, scale) {

	var fmASMcPath = "map_mc.";
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine2 = window.fmASEngine2;
	} else {
		fmEngine2 = window.document.fmASEngine2;
	}
	
	//do: center the map into a latitude/longitude
	fmEngine2.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideArea", area_str);
	fmEngine2.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideLat", lat);
	fmEngine2.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideLon", lon);
	fmEngine2.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideScale", scale);
	fmEngine2.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "areaCenterLatLon");
	fmEngine2.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmAreaZoomIn(areas_array) {
	//do: zoom in into the map (areas_str array)
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAreas", areas_array);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "areaZoomIn");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmAreaEnabled(area_str, enabled_str) {
	//do: enabled / disabled an area

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideArea", area_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideEnabled", enabled_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "areaEnabled");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmAreaColor(area_str, colorNormal, colorOver, colorPress, colorText) {
	//do: change the color of an area

	var fmASMcPath = "map_mc.";
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine;
	} else {
		fmEngine = window.document.fmASEngine;
	}
	
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideArea", area_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideColorNormal", colorNormal);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideColorOver", colorOver);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideColorPress", colorPress);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideColorText", colorText);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "areaColor");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

//********************
//** POIS FUNCTIONS **
//********************

function fmPOIsShowCategory(category_str) {
	//do: show all pois of a category (* for all categories)
	var fmASMcPath = "map_mc.";
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine;
	} else {
		fmEngine = window.document.fmASEngine;
	}
	
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideCategory", category_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "POIsShowCategory");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmPOIsHideCategory(category_str) {
	//do: hide all pois of a category (* for all categories)

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideCategory", category_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "POIsHideCategory");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmPOIAddEvent(event_str, target_str, url_str, id_str) {
	//do: add an event to a POI

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideEvent", event_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideTarget", target_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideUrl", url_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideId", id_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "POIEvent");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmReloadPOIs(pois_xml) {
	//alert('debu');
	//do: reload the pois of a theme
	var fmASMcPath = "map_mc.";
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
		fmEngine = window.fmASEngine;
	} else {
		fmEngine = window.document.fmASEngine;
	}

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideCategory", pois_xml);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "ReloadPOIs");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
	
	
}


//****************************
//** ALERT WINDOW FUNCTIONS **
//****************************

function fmShowAlert(title_str, text_str) {
	//do: show an alert window

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideTitle", title_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideText", text_str);
	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "showAlert");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

function fmHideAlert() {
	//do: hide an alert window

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "hideAlert");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
}

//*********************
//** PRINT FUNCTIONS **
//*********************

function fmPrint() {
	//do: print the current view

	fmEngine.SetVariable("_root." + fmASMcPath + "ASEngine_mc.outsideAction", "print");
	fmEngine.TCallLabel("_root." + fmASMcPath + "ASEngine_mc.outside_mc", "doAction");
};////////////////////////////////////////////////////////////////
function cdtime(container, targetdate){
	if (!document.getElementById || !document.getElementById(container)) return
		this.container=document.getElementById(container)
		this.currentTime=new Date()
		this.targetdate=new Date(targetdate)
		this.timesup=false
		this.updateTime()
	}

cdtime.prototype.updateTime=function(){
	var thisobj=this
	this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
	setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
	this.baseunit=baseunit
	this.formatresults=functionref
	this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
	if (timediff<0){ //if time is up
		this.timesup=true
		this.container.innerHTML=this.formatresults()
		return
	}
	var oneMinute=60 //minute unit in seconds
	var oneHour=60*60 //hour unit in seconds
	var oneDay=60*60*24 //day unit in seconds
	var dayfield=Math.floor(timediff/oneDay)
	var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
	var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
	var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
	if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
		hourfield=dayfield*24+hourfield
		dayfield="n/a"
	}
	else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
		minutefield=dayfield*24*60+hourfield*60+minutefield
		dayfield=hourfield="n/a"
	}
	else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
		var secondfield=timediff
		dayfield=hourfield=minutefield="n/a"
	}
		this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
		setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
	}

/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////

//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left

//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc


function formatresults(){
if (this.timesup==false){//if target date/time not yet met
	var displaystring=arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds<br / > left in the 2007 Hurricane Season"
}
else{ //else if target date/time met
	var displaystring="Hurricane Season has ended!"
}
return displaystring
}




////////////////////////////////////////////////////////////////

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) 
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

//////////////////////////////////////////////////////
function make(event_str, id_str) {
	var parts = id_str.split('/');
	//alert(parts[0]);
	if (confirm("Would you like to plot this storm?")) {
		javascript:do_ShowStorm_sajax(id_str);
	}
}



//////////////////////////////////////////////////////
function highlightCounty(xol) {
		//fmThemeReloadAreas('fm-us/counties.php');
	//fmMapModeCleanAreas();
	
	fmInitialView();
	if (confirm("This will mark the county in black on the map so you can easily locate it. Would you like to continue?")) {
	fmAreaColor(xol, '0x000000', '0x000000', '0xFFFFFF', '0xFFFFFF');
	fmAreaCenter(xol);
	}
	//alert('Working on Site');
	//fmThemeReloadAreas('fm-us/counties.php');
	//fmMapModeCleanAreas();
	
}

//////////////////////////////////////////////////////
function ZoomPoi(event_str, id_str) {
	var parts = id_str.split('/');
	fmAreaCenterLatLonX('NA', parts[0], -(parts[1]), 1500);
}

////////////////////////////////////////////////////////////////
function SwitchTab(my_class) {
 document.getElementById('frame').className=my_class;
 if (my_class == "probs") {
 	SlurpDiv('hint_probs', 'hints');
	SlurpDiv('info_probs', 'infoholder');
	//SlurpDiv('head_probs', 'data_message');
	
	 document.getElementById('world').style.visibility = "hidden";
	 document.getElementById('us').style.visibility = "visible";
	 document.getElementById('data2').style.visibility = "hidden";
	 document.getElementById('data1').style.visibility = "visible";

	 	 
	//var flash = getFlashMovieObject("fmASEngine");
	//flash.LoadMovie(0, 'fmASContainer.swf?ASConfig=fmASEngineUS.php');
	
 } // if probs
 if (my_class == "storm") {
 	SlurpDiv('hint_storm', 'hints');
	SlurpDiv('search_content_year', 'search_content');
	SlurpDiv('info_storm', 'infoholder');
	//SlurpDiv('head_storm', 'data_message');
	
	 document.getElementById('us').style.visibility = "hidden";
	 document.getElementById('world').style.visibility = "visible";
	 document.getElementById('data1').style.visibility = "hidden";
	 document.getElementById('data2').style.visibility = "visible";

	 	 
	//var flash = getFlashMovieObject("fmASEngine");
	//flash.LoadMovie(0, 'fmASContainer2.swf?ASConfig=fmASEngine.php');
	
 } // if storm	  
} // switchTab(class


////////////////////////////////////////////////////////////////
function SlurpDiv(source, target) {
	document.getElementById(target).innerHTML=document.getElementById(source).innerHTML;
} // SlurpDiv


////////////////////////////////////////////////////////////////
function SearchTab(source, tab) {
	document.getElementById('tab1').className='';
	document.getElementById('tab2').className='';
	document.getElementById('tab3').className='';
	document.getElementById('tab4').className='';
	document.getElementById('tab5').className='';
	document.getElementById(tab).className='selected';
	SlurpDiv(source, 'search_content');
}  // SearchTab


////////////////////////////////////////////////////////////////
function TrackTab(source, tab) {
	document.getElementById('tab1').className='';
	document.getElementById('tab2').className='';
	document.getElementById(tab).className='selected';
	SlurpDiv(source, 'track_content');
}  // SearchTab


////////////////////////////////////////////////////////////////
function WriteSomething(ID, sText) {
    if (document.layers) {
        var oLayer;
        oLayer = document.layers[ID].document;
        oLayer.open();
        oLayer.write(sText);
        oLayer.close();
    }
    else if (parseInt(navigator.appVersion)>=5&&navigator.appName=="Netscape") {
        document.getElementById(ID).innerHTML = sText;
    }
    else if (document.all) document.all[ID].innerHTML = sText

} //function WriteSomething(ID, sText)	



////////////////////////////////////////////////////////////////
function LoadDate(label, my_date) {
   	SlurpDiv('advisory_off', 'updates');
	WriteSomething('label_storm', label);
	my_date = '0000'+my_date;
    x_ShowProbsForDate_sajax(my_date, do_ShowProbsForDate_sajax_cb);
	LoadAdvisory(my_date, 'stop');
} //function WriteSomething(ID, sText)	


///////////////////////////////////////////////////////////////////
function do_ShowProbsForDate_sajax_cb() {

} //function do_showProbsForDate_sajax_cb(list)

////////////////////////////////////////////////////////////////
//function LoadStorm() {
   
//} //function WriteSomething(ID, sText)	





///////////////////////////////////////////////////////////////////
function do_GetProbabilityFromAdvisory_sajax(advisory_id) {
    x_GetProbabilityFromAdvisory_sajax(advisory_id, do_GetProbabilityFromAdvisory_sajax_cb);
} //do_GetProbabilityFromAdvisorya_sajax(advisory_id)



///////////////////////////////////////////////////////////////////
function do_GetProbabilityFromAdvisory_sajax_cb(list) {
    if (list == '') {
        list = 'There are no advisories for this storm or date.';
    }
    WriteSomething('data_probs', list);
} //do_GetProbabilityFromAdvisory_sajax_cb(list)


///////////////////////////////////////////////////////////////////
function MakePulldown(id, list) {

    var pulldown = document.getElementById(id);
    pulldown.options.length = 0;
    pulldown.focus();

    if (list == '') {
        pulldown.options.length = 0;
        pulldown.options[0] = new Option('No options exist for that date','');
        //do_GetAdvisoryByStorm_sajax_cb('');
        return;
    } //if (list == '')

    sList = list.split('|');
    pulldown.options[0] = new Option('Please select...','');
    //for (var i = 1; i < sList.length; i++) {
    for (var i = 0; i < sList.length; i++) {
        aOption = sList[i].split(':');
        if (aOption[1] != undefined) {
            //pulldown.options[i] = new Option(aOption[1], aOption[0]);
            pulldown.options[i+1] = new Option(aOption[1], aOption[0]);
        } //if
    } //for
    return pulldown;

} // function MakePulldown(id, list) {



///////////////////////////////////////////////////////////////////
function do_GetStormsYear_sajax(my_date) {
	
	WriteSomething('data_storm', 'Loading storms.... Please wait...');
    x_GetStormsYear_sajax(my_date, do_GetStormsYear_sajax_cb);
    //WriteSomething('title_year', mydate);
} //function do_GetStormsYear_sajax(mydate) {

///////////////////////////////////////////////////////////////////
function do_GetStormsYear_sajax_cb(list) {
    //MakePulldown('storm_select', list);
	var parts = list.split('|');
	WriteSomething('messages_storm', '<h2>Your Search Results</h2>Your search returned '+parts[0]+' storms. Click a storm for more.');
	WriteSomething('head_storm', '<ul id="lastnext" style="margin:0;padding:0;width:200px;"><li><a style="color:#FFFFFF;padding-left:50px;padding-right:50px;" href="javascript:void(0);" onclick="AllStorm();">map all storms</a></li></ul><br style="clear:both;" />');
	WriteSomething('data_storm', '');	
	eval(parts[1]);
	
	//WriteSomething('data', parts[1]);
	//WriteSomething('num_results', parts[0]+' storms found');

} //function do_GetStormsYear_sajax_cb(list)


///////////////////////////////////////////////////////////////////
// added by Anne
function do_GetStormsMonth_sajax(my_month) {
	
	WriteSomething('data_storm', 'Loading storms.... Please wait...');
    x_GetStormsMonth_sajax(my_month, do_GetStormsMonth_sajax_cb);
    //WriteSomething('title_year', my_month);
} //function do_GetStormsYear_sajax(mydate) {

///////////////////////////////////////////////////////////////////
function do_GetStormsMonth_sajax_cb(list) {
    //MakePulldown('storm_select', list);
	var parts = list.split('|');
	WriteSomething('messages_storm', '<h2>Your Search Results</h2>Your search returned '+parts[0]+' storms. Click a storm for more.');
	WriteSomething('head_storm', '<ul id="lastnext" style="margin:0;padding:0;width:200px;"><li><a style="color:#FFFFFF;padding-left:50px;padding-right:50px;" href="javascript:void(0);" onclick="AllStorm();">map all storms</a></li></ul><br style="clear:both;" />');
	WriteSomething('data_storm', '');	
	eval(parts[1]);
	
	//WriteSomething('data', parts[1]);
	//WriteSomething('num_results', parts[0]+' storms found');

} //function do_GetStormsYear_sajax_cb(list)


///////////////////////////////////////////////////////////////////
function do_GetStormsCounty_sajax(fm_id) {
	WriteSomething('data_storm', 'Loading storms.... Please wait...');
    x_GetStormsCounty_sajax(fm_id, do_GetStormsCounty_sajax_cb);
    //WriteSomething('title_year', fm_id);
} //function do_GetStormsMonth_sajax(fm_id) {

///////////////////////////////////////////////////////////////////
function do_GetStormsCounty_sajax_cb(list) {
	//alert(list);
    var parts = list.split('|');
	WriteSomething('messages_storm', '<h2>Your Search Results</h2>Your search returned '+parts[0]+' storms. Click a storm for more.');
	WriteSomething('head_storm', '<ul id="lastnext" style="margin:0;padding:0;width:200px;"><li><a style="color:#FFFFFF;padding-left:50px;padding-right:50px;" href="javascript:void(0);" onclick="AllStorm();">map all storms</a></li></ul><br style="clear:both;" />');
	WriteSomething('data_storm', '');	
	eval(parts[1]);//MakePulldown('storm_select', list)
} //function do_GetStormsMonth_sajax_cb(list)

///////////////////////////////////////////////////////////////////
// added by Anne
function do_GetStormsZip_sajax(my_zip) {
	
	WriteSomething('data_storm', 'Loading storms.... Please wait...');
    x_GetStormsZip_sajax(my_zip, do_GetStormsZip_sajax_cb);
    //WriteSomething('title_year', my_month);
} //function do_GetStormsYear_sajax(mydate) {

///////////////////////////////////////////////////////////////////
function do_GetStormsZip_sajax_cb(list) {
    //MakePulldown('storm_select', list);
	var parts = list.split('|');
	WriteSomething('messages_storm', '<h2>Your Search Results</h2>Your search returned '+parts[0]+' storms. Click a storm for more.');
	WriteSomething('head_storm', '<ul id="lastnext" style="margin:0;padding:0;width:200px;"><li><a style="color:#FFFFFF;padding-left:50px;padding-right:50px;" href="javascript:void(0);" onclick="AllStorm();">map all storms</a></li></ul><br style="clear:both;" />');
	WriteSomething('data_storm', '');	
	eval(parts[1]);
	
	//WriteSomething('data', parts[1]);
	//WriteSomething('num_results', parts[0]+' storms found');

} //function do_GetStormsYear_sajax_cb(list)

///////////////////////////////////////////////////////////////////
// added by Anne
function do_GetStormsLatLon_sajax(my_zip) {
	
	WriteSomething('data_storm', 'Loading storms.... Please wait...');
	lat = document.getElementById('lat').value;
     lon = document.getElementById('lon').value;
     x_GetStormsLatLon_sajax(lat, lon, do_GetStormsLatLon_sajax_cb);
    //WriteSomething('title_year', my_month);
} //function do_GetStormsYear_sajax(mydate) {

///////////////////////////////////////////////////////////////////
function do_GetStormsLatLon_sajax_cb(list) {
    //MakePulldown('storm_select', list);
	var parts = list.split('|');
	WriteSomething('messages_storm', '<h2>Your Search Results</h2>Your search returned '+parts[0]+' storms. Click a storm for more.');
	WriteSomething('head_storm', '<ul id="lastnext" style="margin:0;padding:0;width:200px;"><li><a style="color:#FFFFFF;padding-left:50px;padding-right:50px;" href="javascript:void(0);" onclick="AllStorm();">map all storms</a></li></ul><br style="clear:both;" />');
	WriteSomething('data_storm', '');	
	eval(parts[1]);
	
	//WriteSomething('data', parts[1]);
	//WriteSomething('num_results', parts[0]+' storms found');

} //function do_GetStormsYear_sajax_cb(list)


///////////////////////////////////////////////////////////////////
function do_ShowStorm_sajax(named) {
	var parts = named.split('/');

	SlurpDiv("advisory_active", "updates");
	WriteSomething('label_storm', parts[1]);

	do_GetAdvisoryByStorm2_sajax(named);

	x_ShowStorm_sajax(parts[0], do_ShowStorm_sajax_cb);

		//WriteSomething('panel_map_storms', '<iframe src="+map_probs.php" name="iMapProb" id="iMapProb" width="600" height="440" marginwidth="0" marginheight="0" frameborder="0"></iframe>');
	//slurp_div("bonus_flasher", "panel_map_storms");
} //function do_ShowStorm_sajax(mydate) {

///////////////////////////////////////////////////////////////////
function do_ShowStorm_sajax_cb() {
	
} //function do_ShowStorm_sajax_cb(list)



///////////////////////////////////////////////////////////////////

function do_ShowProbsForStorm_sajax(named) {
	var parts = named.split('/');
	SwitchTab('probs');
	SlurpDiv("advisory_active", "updates");
	WriteSomething('label_storm', parts[1]);
	MakePulldown('advisory_list_select', '0:Loading Forecasts...|');
	
	do_GetAdvisoryByStorm2_sajax(named);
    x_ShowProbsForStorm_sajax(parts[0], do_ShowProbsForStorm_sajax_cb);
    
	
} //function do_showProbsForStorm_sajax(mydate) {

///////////////////////////////////////////////////////////////////
function do_ShowProbsForStorm_sajax_cb() {
	NextAdv();
} //function do_showProbsForStorm_sajax_cb(list)


///////////////////////////////////////////////////////////////////
function do_GetAdvisoryByStorm2_sajax(named) {
    var parts = named.split('/');
    x_GetAdvisoryByStorm2_sajax(parts[0], do_GetAdvisoryByStorm2_sajax_cb);
} //function do_GetStormsYear_sajax(mydate) {



///////////////////////////////////////////////////////////////////
function do_GetAdvisoryByStorm2_sajax_cb(list) {
	//alert(list);
    if (list == '') {
        list = 'There are no advisories for this storm or date.';
    }
    MakePulldown('advisory_list_select', list);
	//fmThemeLoadX('fm-world/fm-world-single.php');
	NextAdv();
} //function do_GetAdvisoryStorm_sajax_cb(list)




///////////////////////////////////////////////////////////////////
function NextAdv() {
    var advisory_list_select = document.getElementById('advisory_list_select');
    if (advisory_list_select.selectedIndex < advisory_list_select.length) {
        advisory_list_select.selectedIndex += 1;
        advisory_list_select.focus();

        SwitchAdvisory(advisory_list_select.options[advisory_list_select.selectedIndex].value, '');
    }
}


///////////////////////////////////////////////////////////////////
function LastAdv() {
    var advisory_list_select = document.getElementById('advisory_list_select');
    if (advisory_list_select.selectedIndex > 0) {
        advisory_list_select.selectedIndex =  advisory_list_select.selectedIndex - 1;
        advisory_list_select.focus();
        SwitchAdvisory(advisory_list_select.options[advisory_list_select.selectedIndex].value, '');
    }
}


///////////////////////////////////////////////////////////////////
function SwitchAdvisory(this_advisory, my_date) {
	LoadAdvisory(this_advisory);
	if (my_date != "stop") {
		fmThemeLoad('fm-us/fm-us.php?advisory_id='+this_advisory);
		fmThemeLoadX('fm-world/fm-world-single.php?advisory_id='+this_advisory);
	}
}


///////////////////////////////////////////////////////////////////
function LoadAdvisory(advisory_id) {
    //do_GetStormsFromCritera_sajax(advisory_id);
    do_GetProbabilityFromAdvisory_sajax(advisory_id);
} //function LoadAdvisory(advisory_id


///////////////////////////////////////////////////////////////////
function AllStorm() {
	fmThemeLoadX('fm-world/fm-world.php');
};function call_url(url, element) {
	var req;
	var data;
	
 	var msxmlhttp = new Array(
		'Msxml2.XMLHTTP.5.0',
		'Msxml2.XMLHTTP.4.0',
		'Msxml2.XMLHTTP.3.0',
		'Msxml2.XMLHTTP',
		'Microsoft.XMLHTTP');
	for (var i = 0; i < msxmlhttp.length; i++) {
		try {
			req = new ActiveXObject(msxmlhttp[i]);
		} catch (e) {
			req = null;
		}
	}
 			
	if(!req && typeof XMLHttpRequest != "undefined")
		req = new XMLHttpRequest();
	if (!req)
		return;
	
	req.onreadystatechange = function() { 
		if(req.readyState == 4) {
			if(req.status == 200) {
				data = req.responseText.replace(/^\s*|\s*$/g,"");
				if (element) {
					document.getElementById(element).innerHTML = eval(data);
				} else {
					eval(data);
				}
			} else {
				return;
			}
		}
	};
	req.open("GET", url, true);
	req.send(null);
	return true;
}

function attach_file(p_script_url) {
	script = document.createElement('script');
	script.src = p_script_url;
	document.getElementsByTagName('head')[0].appendChild(script);
}

function make_active(tab) { 
	document.getElementById("tab1").className = ""; 
	document.getElementById("tab2").className = ""; 
	document.getElementById("tab3").className = ""; 	
	document.getElementById("tab"+tab).className = "selected"; 
	
	document.getElementById("cont_data_1").style.display = "none"; 
	document.getElementById("cont_data_2").style.display = "none"; 
	document.getElementById("cont_data_3").style.display = "none"; 	
	document.getElementById("cont_data_"+tab).style.display = "block"; 
	if (tab == 1) {
		obj_series_id_list = document.getElementById('series_id_list');
		display_series(obj_series_id_list.options[obj_series_id_list.options.selectedIndex].value);
		document.getElementById("subtabs").style.display = "none"; 
		document.getElementById("reload_btn").style.visibility = "hidden";
		document.getElementById("reload_btn2").style.visibility = "hidden";
	} 
	
	if (tab == 2) {
		document.getElementById("subtabs").style.display = "block"; 
		document.getElementById("reload_btn").style.visibility = "visible";
		document.getElementById("reload_btn2").style.visibility = "hidden";
		if (document.getElementById('link_pr_frt').className == 'selected') {
			bucket_type = 'forecast';
		} else {
			bucket_type = 'market';
		}
		call_url('refresh_map.php?type=' + bucket_type);
	}
	if (tab == 3) {
		document.getElementById("subtabs").style.display = "none";
		document.getElementById("reload_btn").style.visibility = "hidden";
		document.getElementById("reload_btn2").style.visibility = "visible";
		call_url('refresh_map_world.php');
	}	
}


function make_active_acc_tab(tab) { 
	document.getElementById("acc_tab_1").className = ""; 
	document.getElementById("acc_tab_2").className = ""; 
	document.getElementById("acc_tab_3").className = ""; 	
	document.getElementById("acc_tab_4").className = ""; 	
	document.getElementById("acc_tab_"+tab).className = "selected"; 
	
	document.getElementById("cont_acc_1").style.display = "none"; 
	document.getElementById("cont_acc_2").style.display = "none"; 
	document.getElementById("cont_acc_3").style.display = "none";
	document.getElementById("cont_acc_4").style.display = "none"; 
	document.getElementById("cont_acc_"+tab).style.display = "block"; 
}

function view_forecast_based_probs(){
	fmInitialView(); 
	fmThemeReloadAreas('fm-us/counties.php');
	fmReloadPOIs('fm-us/pois.php');
	document.getElementById('link_pr_mkt').className = '';
	document.getElementById('link_pr_frt').className = 'selected';
	call_url('refresh_map_legend.php?type=forecast');
	
}

function view_market_based_probs(){
	fmInitialView();
	fmThemeReloadAreas('fm-us/counties_markets.php');
	fmReloadPOIs('fm-us/pois.php');
	document.getElementById('link_pr_mkt').className = 'selected';
	document.getElementById('link_pr_frt').className = '';
	call_url('refresh_map_legend.php?type=market');
}

function switch_ownership_dot(_switch){
	call_url('ajax_ownership_dot.php?switch=' + _switch);
	
}
function display_series(series_id) {
	series_id = (series_id) ? series_id : '';
	obj_series_pot_container = document.getElementById('series_pot');
	obj_series_pot_container.innerHTML = '';
	obj_container = document.getElementById('prob_data');
	obj_container.innerHTML = '<br /><img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  /> <small class=""txt_gray>Loading...</small>';
	call_url('populate_opt_probabilities.php?series_id=' + series_id, '');
}

function display_option_menu(series_id) {
	series_id = (series_id) ? series_id : '';
	call_url('populate_main_opt_menu.php?series_id=' + series_id, '');
}



function display_forecast() {
	obj_forecast_data = document.getElementById('forecast_data');
	obj_forecast_data.innerHTML = '<div style="margin:10px 4px;"><img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  /> <small class=""txt_gray>Loading...</small></div>';
	obj_forecast_data_desc = document.getElementById('forecast_data_desc');
	obj_forecast_data_desc.innerHTML = '';
	call_url('populate_forecast_data.php');
}

function display_storm(named_id) {
	call_url('ajax_set_storm.php?active_storm=' + named_id);
	obj_container = document.getElementById('prob_data');
	obj_container.innerHTML = '<br /><img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  /> <small class=""txt_gray>Loading...</small>';
	call_url('populate_opt_probabilities.php');
}

function set_storm(named_id) {
	call_url('ajax_set_storm.php?active_storm=' + named_id + '&x=1');
}

function register_click(link_id) {
	link_id = (link_id) ? link_id : '';
	call_url('ajax_register_click.php?link_id=' + link_id);
}

function set_purchase(region_id) {
	//alert(region_id);
	document.form_purchaseoption1.county_id_1.options.selectedIndex = region_id;
	document.form_purchaseoption1.num_options.focus();
}

function set_order_book_purchase(region_id) {
	//alert(region_id);
	document.form_purchaseoption1.county_id.options.selectedIndex = region_id;
	document.form_purchaseoption1.num_options.focus();
}

function get_option_price(num_options, series_id, region_id) {
	if (num_options) {
		obj_container = document.getElementById('cont_current_price');
		obj_container.innerHTML = '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  />';
		call_url('populate_current_price.php?num_options=' + num_options + '&series_id=' + series_id + '&region_id=' + region_id, '');
	}
}

function get_bid_highest_price(series_id, region_id) {
	obj_container = document.getElementById('cont_bid_price');
	obj_container.innerHTML = '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  />';
	call_url('populate_order_book_price.php?type=bid&series_id=' + series_id + '&region_id=' + region_id, '');
}

function get_ask_lowest_price(series_id, region_id) {
	obj_container = document.getElementById('cont_ask_price');
	obj_container.innerHTML = '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  />';
	call_url('populate_order_book_price.php?type=ask&series_id=' + series_id + '&region_id=' + region_id, '');
}



function load_series(obj) {
	if(typeof(opt_timer) != "undefined") {
		clearTimeout(opt_timer);
	}
	series_id = obj.options[obj.selectedIndex].value;
	//alert(series_id);
	if(series_id != 0) {
		display_series(series_id);
		display_option_menu(series_id);
		call_url('populate_forecast_data.php?series_id=' + series_id);
		if (document.getElementById('link_pr_mkt').className == 'selected') {
			call_url('refresh_map_legend.php?type=market&series_id=' + series_id);
		} else {
			call_url('refresh_map_legend.php?type=forecast&series_id=' + series_id);
		}
	}
}

function refresh_map() {
	call_url('refresh_map.php');
	setTimeout("refresh_map()", timer);
}


function confirm_this(msg) {
	var res = confirm(msg);
	if(res) {
		return true;
	} else {
		return false;	
	}
}

function confirm_cancel(msg, url) {
	var res = confirm(msg);
	if(res) {
		window.location = url;
	} else {
		return false;	
	}
}


function confirm_cancel_log(msg, url) {
	var res = confirm(msg);
	if(res) {
		obj_container = document.getElementById('cont_loading');
		obj_container.innerHTML = '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  /> Canceling...';
		call_url('ajax_log_purchase_cancel.php?url=' + url);
	} else {
		return false;	
	}
}

function load_past_storm_by_year(obj) {
	year = obj.options[obj.selectedIndex].value;
	// remove existing content of the storm dropdown
	document.form_storm.named_id.options.length = 0;
	document.getElementById('loading').innerHTML = 'Populating....';

	call_url('ajax_load_past_storm_by_year.php?year=' + year);
}

function load_past_advisories_by_named_id(obj) {
	named_id = obj.options[obj.selectedIndex].value;
	obj_container = document.getElementById('block_advisories');
	obj_container.innerHTML = '<br /><img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  /> <small class=""txt_gray>Loading...</small>';
	call_url('ajax_load_past_advisories_by_named_id.php?named_id=' + named_id);
}

function display_loader(cont_loader, msg) {
	obj_container = document.getElementById(cont_loader);
	obj_container.innerHTML = '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  /> ' + msg;
}



function check_order_confirmation() {
	obj_check_box = document.getElementById('agree').checked;
	if (obj_check_box == false) {
		alert('You must agree and check the checkbox before proceeding');
		call_url('ajax_log_confirm_agree_error.php');
		return false;
	} else {
		document.getElementById('btn_submit').disabled = 'disabled';
		return true;
	}
}

function popup_calculator() {
	series_id=document.getElementById('series_id_input').value;
	county_id=document.getElementById('form_county_id').value;
	num_purchase=document.getElementById('form_num_options').value;
	 
	var currentTime = new Date()
	var hours = currentTime.getHours()
	var minutes = currentTime.getMinutes()
	var seconds = currentTime.getSeconds()

	var this_var = 'w' + hours + minutes + seconds;
	window.open('limit_price_calculator.php?series_id='+series_id+'&county_id='+county_id+'&num_purchase='+num_purchase+'',this_var,'toolbar=no,width=550,height=400');
	//this_var.focus();
}

function calculate_req_napl(napl) {
	withdrawal = document.getElementById('withdrawal_amount').value;
	req_napl_container = document.getElementById('req_napl');
	if (withdrawal > napl) {
		alert('Amount should not be greater than current net authorized purchase limit');
		req_napl_container.innerHTML = '';
		document.getElementById('withdrawal_amount').value = '';
	} else {
		req_napl = napl - withdrawal;
		req_napl_container.innerHTML =  '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  />';
		call_url('calculate_req_napl.php?napl=' + napl + '&withdrawal=' + withdrawal);

	}
}

function change_process_buttons() {
	obj_check_box = document.getElementById('agree').checked;
	if (obj_check_box == true) {
		document.getElementById('btn_quote_cancel').className = 'btn_quote_cancel_checked';
		document.getElementById('btn_submit').className = 'btn_quote_order_checked';
	} else {
		document.getElementById('btn_quote_cancel').className = 'btn_quote_cancel';
		document.getElementById('btn_submit').className = 'btn_quote_order';
	}
}

function change_bid_process_buttons() {
	obj_check_box = document.getElementById('agree').checked;
	if (obj_check_box == true) {
		document.getElementById('btn_bid_cancel').className = 'btn_bid_cancel_checked';
		document.getElementById('btn_submit').className = 'btn_place_bid_checked';
	} else {
		document.getElementById('btn_bid_cancel').className = 'btn_bid_cancel';
		document.getElementById('btn_submit').className = 'btn_place_bid';
	}
}

function change_ask_process_buttons() {
	obj_check_box = document.getElementById('agree').checked;
	if (obj_check_box == true) {
		document.getElementById('btn_ask_cancel').className = 'btn_ask_cancel_checked';
		document.getElementById('btn_submit').className = 'btn_place_ask_checked';
	} else {
		document.getElementById('btn_ask_cancel').className = 'btn_ask_cancel';
		document.getElementById('btn_submit').className = 'btn_place_ask';
	}
}

function popup_focus(file, width, height) {
	var wp=window.open(file,'LimitCalculator','toolbar=no,width=' + width + ',height=' + height);
	wp.focus();
}

// check NUMBER
function isNumber(obj,msg){
  var strTmp = obj.value;
  var ValidChars = "0123456789";

  //Check Validity
  for (i=0; i<=strTmp.length-1; i++) 
    if (ValidChars.indexOf(strTmp.charAt(i)) == -1){
	  alert(msg)
      obj.focus()
      return false;
	}
  return true;
}	

//check if empty
function notEmpty(obj,msg){   
	var mystr = ""
	len = obj.value.length
	if (len > 0){  
		for (i=0;i<len; i++){
			if(obj.value.substring(i,i+1)!=" "){ 
				mystr = mystr + obj.value.substring(i,i+1);
			}
		}	
	}
	if(mystr==""){
		alert(msg);
		if(obj.name !='rte1'){
			if(obj.name!='txt_total'){
				obj.focus();
			}
		}
		return false;
	}
 return true;	
}


function is_number_key(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
		
	return true;
}

function is_float_key(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (((charCode > 47 && charCode < 58) || charCode == 46 || charCode < 32))
		return true;
		
	return false;
}

function add_commas(str) {
	str += '';
	x = str.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


//check form_purchaseoption1
function check_form_purchaseoption1(obj){
	if(notEmpty(obj.numberofoptions,"Please enter the number of options.") == false ||
		isNumber(obj.numberofoptions,"This field must be a valid number.") == false){
		return false;
	}else{
		return true;
	}		
}

//check form_purchaseoption2
function check_form_purchaseoption2(obj){
	if(notEmpty(obj.totaldollaramount,"Please enter the total dollar amount.") == false ||
		isNumber(obj.totaldollaramount,"This field must be a valid number.") == false){
		return false;
	}else{
		return true;
	}		
}

//popup
function popup_pic(sPicURL) { 
	window.open("dsp_pic_popup.php?"+sPicURL, "ViewImage",  "resizable=1,HEIGHT=200,WIDTH=200"); 
}

function display_element(element, switch_) {
	if (switch_ == 0) {
		document.getElementById(element).style.display = 'none';
	} else {
		document.getElementById(element).style.display = 'block';
	}
}

function get_damage_threshold(region_id) {

	obj_container = document.getElementById('cont_damage_threshold');
	obj_container.innerHTML = '<img src="images/ajax-loader-sm.gif" width="18" height="18" align="absmiddle"  />';
	call_url('populate_damage_threshold.php?region_id=' + region_id, '');

}
;/**
 * addEvent written by Dean Edwards, 2005
 * with input from Tino Zijdel
 *
 * http://dean.edwards.name/weblog/2005/10/add-event/
 **/
function addEvent(element, type, handler) {
	// assign each event handler a unique ID
	if (!handler.$$guid) handler.$$guid = addEvent.guid++;
	// create a hash table of event types for the element
	if (!element.events) element.events = {};
	// create a hash table of event handlers for each element/event pair
	var handlers = element.events[type];
	if (!handlers) {
		handlers = element.events[type] = {};
		// store the existing event handler (if there is one)
		if (element["on" + type]) {
			handlers[0] = element["on" + type];
		}
	}
	// store the event handler in the hash table
	handlers[handler.$$guid] = handler;
	// assign a global event handler to do all the work
	element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	// delete the event handler from the hash table
	if (element.events && element.events[type]) {
		delete element.events[type][handler.$$guid];
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(window.event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

// end from Dean Edwards


/**
 * Creates an Element for insertion into the DOM tree.
 * From http://simon.incutio.com/archive/2003/06/15/javascriptWithXML
 *
 * @param element the element type to be created.
 *				e.g. ul (no angle brackets)
 **/
function createElement(element) {
	if (typeof document.createElementNS != 'undefined') {
		return document.createElementNS('http://www.w3.org/1999/xhtml', element);
	}
	if (typeof document.createElement != 'undefined') {
		return document.createElement(element);
	}
	return false;
}

/**
 * "targ" is the element which caused this function to be called
 * from http://www.quirksmode.org/js/events_properties.html
 **/
function getEventTarget(e) {
	var targ;
	if (!e) {
		e = window.event;
	}
	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;
	}
	if (targ.nodeType == 3) { // defeat Safari bug
		targ = targ.parentNode;
	}

	return targ;
}

;/**
 * Written by Neil Crosby. 
 * http://www.workingwith.me.uk/
 *
 * Use this wherever you want, but please keep this comment at the top of this file.
 *
 * Copyright (c) 2006 Neil Crosby
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal 
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
 * SOFTWARE.
 **/
var css = {
	/**
	 * Returns an array containing references to all elements
	 * of a given tag type within a certain node which have a given class
	 *
	 * @param node		the node to start from 
	 *					(e.g. document, 
	 *						  getElementById('whateverStartpointYouWant')
	 *					)
	 * @param searchClass the class we're wanting
	 *					(e.g. 'some_class')
	 * @param tag		 the tag that the found elements are allowed to be
	 *					(e.g. '*', 'div', 'li')
	 **/
	getElementsByClass : function(node, searchClass, tag) {
		var classElements = new Array();
		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
		
		
		for (var i = 0, j = 0; i < elsLen; i++) {
			if (this.elementHasClass(els[i], searchClass) ) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	},


	/**
	 * PRIVATE.  Returns an array containing all the classes applied to this
	 * element.
	 *
	 * Used internally by elementHasClass(), addClassToElement() and 
	 * removeClassFromElement().
	 **/
	privateGetClassArray: function(el) {
		return el.className.split(' '); 
	},

	/**
	 * PRIVATE.  Creates a string from an array of class names which can be used 
	 * by the className function.
	 *
	 * Used internally by addClassToElement().
	 **/
	privateCreateClassString: function(classArray) {
		return classArray.join(' ');
	},

	/**
	 * Returns true if the given element has been assigned the given class.
	 **/
	elementHasClass: function(el, classString) {
		if (!el) {
			return false;
		}
		
		var regex = new RegExp('\\b'+classString+'\\b');
		if (el.className.match(regex)) {
			return true;
		}

		return false;
	},

	/**
	 * Adds classString to the classes assigned to the element with id equal to
	 * idString.
	 **/
	addClassToId: function(idString, classString) {
		this.addClassToElement(document.getElementById(idString), classString);
	},

	/**
	 * Adds classString to the classes assigned to the given element.
	 * If the element already has the class which was to be added, then
	 * it is not added again.
	 **/
	addClassToElement: function(el, classString) {
		var classArray = this.privateGetClassArray(el);

		if (this.elementHasClass(el, classString)) {
			return; // already has element so don't need to add it
		}

		classArray.push(classString);

		el.className = this.privateCreateClassString(classArray);
	},

	/**
	 * Removes the given classString from the list of classes assigned to the
	 * element with id equal to idString
	 **/
	removeClassFromId: function(idString, classString) {
		this.removeClassFromElement(document.getElementById(idString), classString);
	},

	/**
	 * Removes the given classString from the list of classes assigned to the
	 * given element.  If the element has the same class assigned to it twice, 
	 * then only the first instance of that class is removed.
	 **/
	removeClassFromElement: function(el, classString) {
		var classArray = this.privateGetClassArray(el);

		for (x in classArray) {
			if (classString == classArray[x]) {
				classArray[x] = '';
				break;
			}
		}

		el.className = this.privateCreateClassString(classArray);
	}
};/**
*
*  Scrollable HTML table
*  http://www.webtoolkit.info/
*
**/

function ScrollableTable (tableEl, tableHeight, tableWidth) {

	this.initIEengine = function () {

		this.containerEl.style.overflowY = 'auto';
		if (this.tableEl.parentElement.clientHeight - this.tableEl.offsetHeight < 0) {
			this.tableEl.style.width = this.newWidth - this.scrollWidth +'px';
		} else {
			this.containerEl.style.overflowY = 'hidden';
			this.tableEl.style.width = this.newWidth +'px';
		}

		if (this.thead) {
			var trs = this.thead.getElementsByTagName('tr');
			for (x=0; x<trs.length; x++) {
				trs[x].style.position ='relative';
				trs[x].style.setExpression("top",  "this.parentElement.parentElement.parentElement.scrollTop + 'px'");
			}
		}

		if (this.tfoot) {
			var trs = this.tfoot.getElementsByTagName('tr');
			for (x=0; x<trs.length; x++) {
				trs[x].style.position ='relative';
				trs[x].style.setExpression("bottom",  "(this.parentElement.parentElement.offsetHeight - this.parentElement.parentElement.parentElement.clientHeight - this.parentElement.parentElement.parentElement.scrollTop) + 'px'");
			}
		}

		eval("window.attachEvent('onresize', function () { document.getElementById('" + this.tableEl.id + "').style.visibility = 'hidden'; document.getElementById('" + this.tableEl.id + "').style.visibility = 'visible'; } )");
	};


	this.initFFengine = function () {
		this.containerEl.style.overflow = 'hidden';
		this.tableEl.style.width = this.newWidth + 'px';

		var headHeight = (this.thead) ? this.thead.clientHeight : 0;
		var footHeight = (this.tfoot) ? this.tfoot.clientHeight : 0;
		var bodyHeight = this.tbody.clientHeight;
		var trs = this.tbody.getElementsByTagName('tr');
		if (bodyHeight >= (this.newHeight - (headHeight + footHeight))) {
			this.tbody.style.overflow = '-moz-scrollbars-vertical';
			for (x=0; x<trs.length; x++) {
				var tds = trs[x].getElementsByTagName('td');
				tds[tds.length-1].style.paddingRight += this.scrollWidth + 'px';
			}
		} else {
			this.tbody.style.overflow = '-moz-scrollbars-none';
		}

		var cellSpacing = (this.tableEl.offsetHeight - (this.tbody.clientHeight + headHeight + footHeight)) / 4;
		this.tbody.style.height = (this.newHeight - (headHeight + cellSpacing * 2) - (footHeight + cellSpacing * 2)) + 'px';

	};

	this.tableEl = tableEl;
	this.scrollWidth = 16;

	this.originalHeight = this.tableEl.clientHeight;
	this.originalWidth = this.tableEl.clientWidth;

	this.newHeight = parseInt(tableHeight);
	this.newWidth = tableWidth ? parseInt(tableWidth) : this.originalWidth;

	this.tableEl.style.height = 'auto';
	this.tableEl.removeAttribute('height');

	this.containerEl = this.tableEl.parentNode.insertBefore(document.createElement('div'), this.tableEl);
	this.containerEl.appendChild(this.tableEl);
	this.containerEl.style.height = this.newHeight + 'px';
	this.containerEl.style.width = this.newWidth + 'px';


	var thead = this.tableEl.getElementsByTagName('thead');
	this.thead = (thead[0]) ? thead[0] : null;

	var tfoot = this.tableEl.getElementsByTagName('tfoot');
	this.tfoot = (tfoot[0]) ? tfoot[0] : null;

	var tbody = this.tableEl.getElementsByTagName('tbody');
	this.tbody = (tbody[0]) ? tbody[0] : null;

	if (!this.tbody) return;

	if (document.all && document.getElementById && !window.opera) this.initIEengine();
	if (!document.all && document.getElementById && !window.opera) this.initFFengine();


}

;/**
*
*  Sortable HTML table
*  http://www.webtoolkit.info/
*
**/

function SortableTable (tableEl) {

	this.tbody = tableEl.getElementsByTagName('tbody');
	this.thead = tableEl.getElementsByTagName('thead');
	this.tfoot = tableEl.getElementsByTagName('tfoot');
	
	this.getInnerText = function (el) {
		if (typeof(el.textContent) != 'undefined') return el.textContent;
		if (typeof(el.innerText) != 'undefined') return el.innerText;
		if (typeof(el.innerHTML) == 'string') return el.innerHTML.replace(/<[^<>]+>/g,'');
	}

	this.getParent = function (el, pTagName) {
		if (el == null) return null;
		else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())
			return el;
		else
			return this.getParent(el.parentNode, pTagName);
	}

	this.sort = function (cell, clicked) { 
	    var column = cell.cellIndex;
	    var itm = this.getInnerText(this.tbody[0].rows[1].cells[column]);
		var sortfn = this.sortCaseInsensitive;

		// directly outside it is a td, tr, thead and table
		var td     = cell;
		var tr     = td.parentNode;
		var thead  = tr.parentNode;
		var table  = thead.parentNode;
		
		// find out what the current sort order of this column is
		var sort_link = css.getElementsByClass(td, 'sort', 'a');
		var previousSortOrder = '';
		// if sort link is clicked
		if (clicked == 1) {
			if (sort_link.length > 0) {
				previousSortOrder = sort_link[0].getAttribute('sortdir');
			}
		} else {
			previousSortOrder = this.previousSortOrder_loaded;
		}

		if (itm.match(/\d\d[-]+\d\d[-]+\d\d\d\d/)) sortfn = this.sortDate; // date format mm-dd-yyyy
		if (itm.match(/^[£$]/)) { sortfn = this.sortCurrency; }
		if (itm.replace(/^\s+|\s+$/g,"").match(/^[\d\.]+$/)) sortfn = this.sortNumeric;
		if (itm.match(/^\d?\.?\d+$/)) { sortfn = this.sortNumeric; }
		if (itm.match(/\d?\.?\d?\%+$/)) { sortfn = this.sortNumeric; }
		if (itm.match(/^[+-]?\d*\.?\d+([eE]-?\d+)?$/)) { sortfn = this.sortNumeric; }

		this.sortColumnIndex = column;
		
	    var newRows = new Array();
	    for (j = 0; j < this.tbody[0].rows.length; j++) {
			newRows[j] = this.tbody[0].rows[j];
			
			
		}
		
		if (this.sortColumnIndex == this.lastSortColumnIndex && clicked == 1) {
			newRows.reverse();
				
		} else {
			this.lastSortColumnIndex = this.sortColumnIndex;
			if (clicked == 0) {
				if (previousSortOrder == 'ASC') {
					newRows.sort(sortfn);
					newRows.reverse();
				} else {
					newRows.sort(sortfn);
				}
			} else {
				newRows.sort(sortfn);
			}
		}
		
		for (i=0; i < newRows.length; i++) {
			// set alternating color

			if(newRows[i].className != "closed" && newRows[i].className != 'my_entry' && newRows[i].className != 'trading_disabled'){
				if ((i % 2) == 0 ) {
					if(newRows[i].className == "odd"){
						newRows[i].className = newRows[i].className.replace("odd", "even");
					} else {
						newRows[i].className = "even";
					}
				} else {
					if(newRows[i].className == "even"){
						newRows[i].className = newRows[i].className.replace("even", "odd");
					} else {
						newRows[i].className = "odd";
					}
				} 
			}
			this.tbody[0].appendChild(newRows[i]);
			
		}	

		// now, give the user some feedback about which way the column is sorted
		var sort_link = css.getElementsByClass(tr, 'sort', 'a');
		for (var j = 0; j < sort_link.length; j++) {
			sort_linkParentNode = sort_link[j].parentNode;
			if (sort_linkParentNode != td){
				sort_link[j].className = 'sort';
				sort_link[j].setAttribute('sortdir','');
			}
		}
		var sort_dir;
		if (null == previousSortOrder || '' == previousSortOrder || 'DESC' == previousSortOrder) {
		
			td.childNodes[0].className = 'sort desc';
			sort_dir = 'DESC';
			td.childNodes[0].setAttribute('sortdir','ASC');
		} else {
			td.childNodes[0].className = 'sort asc';
			sort_dir = 'ASC';
			td.childNodes[0].setAttribute('sortdir','DESC');
		}
		
		if (clicked == 1) {
			call_url('ajax_remember_sort.php?column=' + column + '&sort_dir=' + sort_dir);
		}
	}
	this.row_class_replace = function(s, t, u) {
	  /*
	  **  Replace a token in a string
	  **    s  string to be processed
	  **    t  token to be found and removed
	  **    u  token to be inserted
	  **  returns new String
	  */
	  i = s.indexOf(t);
	  r = "";
	  if (i == -1) return s;
	  r += s.substring(0,i) + u;
	  if ( i + t.length < s.length)
		r += this.row_class_replace(s.substring(i + t.length, s.length), t, u);
	  return r;
	}
	this.sortCaseInsensitive = function(a,b) {
		aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]).toLowerCase();
		bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]).toLowerCase();
		if (aa==bb) return 0;
		if (aa<bb) return -1;
		return 1;
	}

	this.sortDate = function(a,b) {
		aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]);
		bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]);
		date1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
		date2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
		if (date1==date2) return 0;
		if (date1<date2) return -1;
		return 1;
	}

	this.sortNumeric = function(b,a) {
		aa = parseFloat(thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]));
		if (isNaN(aa)) aa = 0;
		bb = parseFloat(thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]));
		if (isNaN(bb)) bb = 0;
		return aa-bb;
	}
	
	this.sortCurrency = function(b,a) { 
		var aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]).replace(/[^0-9.]/g,'');
		var bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]).replace(/[^0-9.]/g,'');
		return parseFloat(aa) - parseFloat(bb);
	}
	
	// define variables
	var thisObject = this;
	var sortSection = this.thead;

	// constructor actions
	if (!(this.tbody && this.tbody[0].rows && this.tbody[0].rows.length > 0)) return;

	if (sortSection && sortSection[0].rows && sortSection[0].rows.length > 0) {
		var sortRow = sortSection[0].rows[sortSection[0].rows.length - 1];
	} else {
		return;
	}
	
	for (var i=0; i<sortRow.cells.length; i++) {
		var linkEl = createElement('a');
		linkEl.href = '#';
		linkEl.setAttribute('columnId', i);
		
		linkEl.title = 'Click to sort';
		
		// move the current contents of the cell that we're 
		// hyperlinking into the hyperlink
		var innerEls = sortRow.cells[i].childNodes;
		for (var j = 0; j < innerEls.length; j++) {
			linkEl.className = "sort";
			linkEl.appendChild(innerEls[j]);
		}
		
		// and finally add the new link back into the cell
		sortRow.cells[i].appendChild(linkEl);

		
		sortRow.cells[i].sTable = this;
		sortRow.cells[i].onclick = function () {
			this.sTable.sort(this, 1);
			return false;
		}
	}

};