// global flag
var isIE = false;

var MIN_TOP_OFFSET = 20;
var MIN_LEFT_OFFSET = 20;

function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		MyAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
	}
}

function elementFadeIn(element, opacity, speed) {

	if(!speed)
		speed = 1;

	if(speed <= 0)
		speed = 1;

	var is_ie = typeof(document.all) != 'undefined';
	var opacityStyle = (is_ie) ? "filter" : "opacity";
	
	percentStyle = (is_ie) ? "alpha(opacity=" + opacity + ")" : opacity/100;
	element.style[opacityStyle] = percentStyle;
	
	if(opacity == 0)
		element.style.display = '';
	
	opacity += 5;
	
	if(opacity <= 100)
		setTimeout(function(){ elementFadeIn(element, opacity, speed); }, parseInt(10 * speed), speed);
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	return [myWidth,myHeight];
}

function getMousePosition(e)
{
	var returnArray = new Array(2);
	
	var mouseX = 0;
	var mouseY = 0;

	if (!e) var e = window.event;
	
	if (e.pageX || e.pageY)
	{
		mouseX = e.pageX;
		mouseY = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		mouseX = e.clientX + document.body.scrollLeft;
		mouseY = e.clientY + document.body.scrollTop;
	}
	
	return [mouseX, mouseY];
}


function CreateConfirmationBox(e, funcConfirmationText, funcCallFunction, boxWidth, boxHeight) {
	if(!boxWidth)
		boxWidth = "300";
		
	if(!boxHeight)
		boxHeight = "100";

	myElement = document.createElement("span");
	
	myElement.innerHTML = funcConfirmationText;

	myElement.innerHTML += "<br/><br/><br/><span class=\"warning-textbutton\" onclick=\"this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); " + funcCallFunction + "\">yes, i am sure</span>";
	myElement.innerHTML += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	myElement.innerHTML += "<span class=\"warning-textbutton\" onclick=\"this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);\">no, cancel this operation</span>";
	
	myDiv = CreatePopupWindow(e, boxWidth, boxHeight, myElement, false, "warning-window");
}

function CreateImageBox(e, imageURL, image) {
	systemMessage("loading...", true);
	
	var mousePositionArray = getMousePosition(e);
	
	if(!image) {
		image = new Image();
		image.src = imageURL + "?" + (new Date).getTime();
		
		image.onload = function(){ CreateImageBoxFinish(image, mousePositionArray);}
	}
	else {
		CreateImageBoxFinish(image, mousePositionArray);
	}
}

function CreateImageBoxFinish(image, mousePositionArray) {

	image.className = "popupimage-img";
	
	myDiv = CreatePopupWindow(false, image.width, image.height, image, true, false, mousePositionArray );
	
	systemMessage("loading...", false);
}

function CreatePopupWindow(e, fWidth, fHeight, fChildElement, showCloseButton, fClassName, mousePositionArray, fTopOffset, fLeftOffset) {
	if(!fClassName)
		fClassName = "popup-window";
		
	if(!fTopOffset)
		fTopOffset = 0;

	if(!fLeftOffset)
		fLeftOffset = 0;

	if(!mousePositionArray)
		mousePositionArray = getMousePosition(e);
	var windowSizeArray = getWindowSize();
	var scrollArray = getScrollXY();
	
	var myDiv = document.createElement("div");
	myDiv.className = fClassName;
	myDiv.width = fWidth;
	myDiv.height = fHeight;
	myDiv.style.position = "absolute";
	myDiv.style.left = parseInt(mousePositionArray[0]) - (parseInt(myDiv.width) / 2) + "px";
	myDiv.style.top = parseInt(mousePositionArray[1]) - (parseInt(myDiv.height) / 2) + "px";
	
	// did the right go outside the window?
	if((parseInt(myDiv.style.left) + parseInt(myDiv.width)) > parseInt(parseInt(windowSizeArray[0]) + parseInt(scrollArray[0]) - 20))
		myDiv.style.left = parseInt(parseInt(windowSizeArray[0]) + parseInt(scrollArray[0]) - 20 - parseInt(myDiv.width)) + "px";

	// did the left go negative?
	if(parseInt(myDiv.style.left) < MIN_LEFT_OFFSET + fLeftOffset + parseInt(scrollArray[0]))
		myDiv.style.left = parseInt(MIN_LEFT_OFFSET + fLeftOffset + parseInt(scrollArray[0])) + "px";
	
		// did the bottom go outside the the window?
	if((parseInt(myDiv.style.top) + parseInt(myDiv.height)) > parseInt(parseInt(windowSizeArray[1]) + parseInt(scrollArray[1]) - 20))
		myDiv.style.top = parseInt(parseInt(windowSizeArray[1]) + parseInt(scrollArray[1]) - 20 - parseInt(myDiv.height)) + "px";
	
	// did the top go negative?
	if(parseInt(myDiv.style.top) < (MIN_TOP_OFFSET + fTopOffset + parseInt(scrollArray[1])))
		myDiv.style.top = parseInt(MIN_TOP_OFFSET + fTopOffset + parseInt(scrollArray[1])) + "px";
		
	myDiv.innerHTML = "";
	
	if(showCloseButton)
		myDiv.innerHTML = "<div class=\"popup_window_close-button\" onclick=\"this.parentNode.parentNode.removeChild(this.parentNode);\"><div class=\"popup_window_close_inner-button\"><div class=\"popup_window_close_inner_text-button\">X</div></div></div>";
	
	myDiv.appendChild(fChildElement);
	
	document.body.appendChild(myDiv);
	
	return myDiv;
}

function getElement(elementid) {
	try {
		if (document.getElementById) {
			return document.getElementById(elementid);
		}

		if (document.all) {
			return document.all[elementid];
		}
	} catch(e) { showmessage(e.message); }
}

function getNodeValue(obj,tag)
{
	return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}

function trim(str){
   return str.replace(/^\s*|\s*$/g,"");
}

function matchAreacode(str) {
	return str.match(/^\d{3}$/);
}

function matchZipcode(str) {
	return str.match(/^(\d{5}-\d{4})|(\d{5})$/);
}

function systemMessage(funcMessage, funcDisplay) {

	getElement("system-message").innerHTML = funcMessage;
	
	if( funcDisplay )
		getElement("system-message").style.display = "block";
	else
		getElement("system-message").style.display = "none";
}

function pageMessage(funcMessage, funcDisplay, funcBackgroundColor, funcColor) {

	pageMessageElement = getElement("page-message");
	
	if(funcBackgroundColor)
		pageMessageElement.style.backgroundColor = funcBackgroundColor;

	if(funcColor)		
		pageMessageElement.style.color = funcColor;
		
	pageMessageElement.innerHTML = funcMessage;
	
	if( funcDisplay )
		pageMessageElement.style.display = "block";
	else
		pageMessageElement.style.display = "none";
}

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn( optionalParameter0 ) {
	var xmlhttp, bComplete = false;
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); isIE = true; }
	catch (e) { 
		try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); isIE = true; }
		catch (e) { 
			try { xmlhttp = new XMLHttpRequest(); }
			catch (e) { xmlhttp = false; }
		}
	}
	if (!xmlhttp) return null;
	
	this.connect = function(sURL, sMethod, sVars, fnDone) {
		if (!xmlhttp) return false;
		bComplete = false;
		sMethod = sMethod.toUpperCase();

		sVars += "&xconndtunique" + (new Date).getTime() + "&";

		try {
			if (sMethod == "GET")
			{
				xmlhttp.open(sMethod, sURL+"?"+sVars, true);
				sVars = "";
			}
			else
				if (sMethod == "POST")
				{
					xmlhttp.open(sMethod, sURL, true);
					xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
					xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				}      
				else
				{
					xmlhttp.open("POST", sURL, true);
				}
				
			xmlhttp.onreadystatechange = function(){
				if (xmlhttp.readyState == 4 && !bComplete)
				{
					bComplete = true;
					if( optionalParameter0 )
						fnDone(xmlhttp, optionalParameter0);
					else
					fnDone(xmlhttp);
				}
			};
		xmlhttp.send(sVars);
		}
		catch(z) { return false; }
		return true;
	};
	return this;
}


function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method 
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided 
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            return result.firstChild.nodeValue;    		
        }
    } else {
        return "n/a";
    }
}

// mozXPath [http://km0ti0n.blunted.co.uk/mozxpath/] km0ti0n@gmail.com
// Code licensed under Creative Commons Attribution-ShareAlike License 
// http://creativecommons.org/licenses/by-sa/2.5/
if( document.implementation.hasFeature("XPath", "3.0") )
{
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; } 

		var oNSResolver = this.createNSResolver(this.documentElement)
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++)
		{
			aResult[i] =  aItems.snapshotItem(i);
		}
		
		return aResult;
	}
	XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; } 

		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 )
		{
			return xItems[0];
		}
		else
		{
			return null;
		}
	}

	Element.prototype.selectNodes = function(cXPathString)
	{
		if(this.ownerDocument.selectNodes)
		{
			return this.ownerDocument.selectNodes(cXPathString, this);
		}
		else{throw "For XML Elements Only";}
	}

	Element.prototype.selectSingleNode = function(cXPathString)
	{	
		if(this.ownerDocument.selectSingleNode)
		{
			return this.ownerDocument.selectSingleNode(cXPathString, this);
		}
		else{throw "For XML Elements Only";}
	}

}

function get_random(ceiling, floor)
{
	if(!floor)
		floor = 0;
		
    var ranNum = floor + (Math.round(Math.random()) * ceiling);
    
    return ranNum;
}

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

function Debug(message, dontReport) {
	if(debug == true ){
		if(!dontReport) {
			getElement("debug").style.display = "block";
			getElement("debug").value += message + "\n";
		}
	}
}

function from10toradix(value,radix){

	function initArray() {
		this.length = initArray.arguments.length;
		for (var i = 0; i < this.length; i++)
			this[i] = initArray.arguments[i];
	}

    var retval = '';
    var ConvArray = new initArray(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F');
    var intnum;
    var tmpnum;
    var i = 0;

    intnum = parseInt(value,10);
    if (isNaN(intnum)){
        retval = 'NaN';
    }else{
        while (intnum > 0.9){
            i++;
            tmpnum = intnum;
            // cancatinate return string with new digit:
            retval = ConvArray[tmpnum % radix] + retval;  
            intnum = Math.floor(tmpnum / radix);
            if (i > 100){
                // break infinite loops
                retval = 'NaN';
                break;
            }
        }
    }
    return retval;
}

String.prototype.toCSShex = function() 
{ 
  var out, hx; 
  /* in rgb() form */ 
  if(this.indexOf('r')+1) 
  { 
    hx = this.match(/\d+/g); 
    out = '#' +
      (hx[0]*1).toString(16).replace(/^(\d)$/, '0$1') + 
      (hx[1]*1).toString(16).replace(/^(\d)$/, '0$1') + 
      (hx[2]*1).toString(16).replace(/^(\d)$/, '0$1');
  } 
  /* in #hex form */ 
  else 
  { 
    /* add #, if missing */ 
    out = this.replace(/^#?/,"#"); 
    /* expand #ABC form to #AABBCC */ 
   if(out.length==4) 
      out = out.replace(/[0-9a-f]/gi,"$&$&"); 
  } 
  
  return out.toUpperCase(); 
}



function createYahooMap(latitude, longitude, mapElement) {
	// Create a lat/lon object
	var myPoint = new YGeoPoint(latitude, latitude);
	// Create a map object
	var map = new  YMap(mapElement);
	// Add a pan control
	map.addPanControl();
	// Add a slider zoom control
	map.addZoomLong();
	// Display the map centered on a latitude and longitude
	map.drawZoomAndCenter(myPoint, 3);
	
	return map;
}

function createYahooMarker(geopoint, num) {
	var myImage = new YImage();
	myImage.src = 'http://us.i1.yimg.com/us.yimg.com/i/us/map/gr/mt_ic_c.gif';
	myImage.size = new YSize(20,20);
	myImage.offsetSmartWindow = new YCoordPoint(0,0);
	var marker = new YMarker(geopoint,myImage);
	var swtext = "Marker <b> " + num + "</b>";
	var label = "<img src=http://us.i1.yimg.com/us.yimg.com/i/us/ls/gr/" + num + ".gif>";
	marker.addLabel(label);
	YEvent.Capture(marker,EventsList.MouseClick, function() { marker.openSmartWindow(swtext) });
	
	return marker;
}

// Create a marker whose info window displays the given number.
function createGoogleMarker(point, html) {
	var marker = new GMarker(point);

	// Show this marker's index in the info window when it is clicked.
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});

	return marker;
}

function BakeCookie(name,value) {
	argv=arguments;
	argc=arguments.length;
	expires=(argc>2) ? argv[2] : null;
	path=(argc>3) ? argv[3] : null;
	domain=(argc>4) ? argv[4] : null;
	secure=(argc>5) ? argv[5] : false;
	document.cookie=name+"="+escape(value) +
		((expires === null) ? "" : ("; expires="+expires.toUTCString())) +
		((path === null) ? "" : ("; path="+path)) +
		((domain === null) ? "" : ("; domain="+domain)) +
		((secure === true) ? "; secure" : "");
}

function EatCookie(name) {
	arg=name+"=";
	alen=arg.length;
	clen=document.cookie.length;
	i=0;

	while (i<clen) {
		j=i+alen;
		if (document.cookie.substring(i,j) == arg) {
			return EatCookieVal(j);
		}
		i=document.cookie.indexOf(" ",i) + 1;
		if (i === 0) {break;}
	}
}

function EatCookieVal(offset) {
	endstr=document.cookie.indexOf(";",offset);
	if (endstr == -1) {endstr=document.cookie.length;}
		return unescape(document.cookie.substring(offset,endstr));
}

function TossCookie(name) {
	ThreeDays = 3*24*60*60*1000; //in millisecounds
	expDate=new Date();
	expDate.setTime(expDate.getTime()-ThreeDays);
	document.cookie=name+'=foobar; expires='+expDate.toGMTString();
}

function BakeSessionCookie (cookieName, cookieValue) {
	document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
}

function srcSwap( aElement, aSource ) {
	aElement.src = aSource;
}

function showElement( aElementID ) {
	getElement(aElementID).style['display'] = 'block';
}

// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
	}
	
// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
			}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
			}
		else {
			return;
			}
		var re = new RegExp(regex);
		if (!hasOptions(obj)) { return; }
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
				}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
					}
				}
			}
		}
	}
		
// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
	}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
	}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}
