// common.js -- common client-side javascript routines
function DateFormat(optionalDateValue) { // use today by default
	var dt = new Date();
	if (optionalDateValue != null) dt = Date.parse(optionalDateValue);
	return dt.getMonth() + 1; + "/" + dt.getDate() + "/" + dt.getFullYear();
}
function DateAdd(days, optionalDateValue) // Optional days from today. -7=lastweek
{
	var t = new Date();
	if (optionalDateValue != null) t = Date.parse(optionalDateValue);
	j = t.getTime()/(24*60*60*1000) + days; // convert to days, add days
	t.setTime(j*(24*60*60*1000)); // convert back to miili-seconds
	return t; // Call getClientDate
}
function isDate(value) {
	if (value == '') {alert("Date is blank."); return false;}
	var dateVal = new Date(value);
	if (dateVal.getFullYear() < 1980) dateVal.setFullYear(dateVal.getFullYear() + 100);
	if (isNaN(dateVal) || dateVal < 0) {alert("Invalid date format. " + value); return false;}

	var dateArray = value.split('/');
	if (dateArray.length == 1)  dateArray = value.split('-');
	var dayOfMonth = dateArray[1];
	if (dayOfMonth != dateVal.getDate()) {alert('Invalid date ' + value + '.'); return false;}
	return true;
}
function checkDateInPast(fieldObj) {
	isDate(fieldObj.value);
	var dateVal = new Date(fieldObj.value);
	if (dateVal <= new Date()) {
		alert("Date must be in future."); 
		fieldObj.focus();
		return false;
	}

	fieldObj.value = dateVal.getMonth() + 1 + "/" + dateVal.getDate() + "/" + dateVal.getYear();
}
function deadCenter(file,name,width,height,scroll) {
	newWindow(file, width, height);
}
function newWindow(file, width, height) { // Create a new window of a given size, centered on the screen
	if (file == null || file == "") {
		alert("Filename passed is blank!");
		return;
	}
	if (width == 0 || height == 0) {
		window.open(file,"newindow","height=" + height + ",width=" + width + ",resizable=0,status=0,scrollbars=0,left=1000,top=1000");
	}
	else {
		w = window.open(file,"newindowtest","height=" + height + ",width=" + width + ",resizable=1,status=0,scrollbars=1,left=" +
			(window.screen.availWidth/2-width/2) + ",top=" + (window.screen.availHeight/2-height/2));
		w.focus();
	}
}
function moveOption(lFrom,lTo,ordered,discard)
// Move an entry from one list (lFrom) to another list (lTo). Insert the entry into
// lTo maintaining ordering if (ordered=true), else put it after the selected element
// or at the end of the list if nothing in lTo is selected. If an element to move's
// value is = discard, just remove it
{
	if (discard==null) discard=0;
	if (ordered==null) ordered=true; // optional parames
	// make sure we have everthing we need
	if (lFrom==null || lTo==null) {
		alert("moveOption: 2 pamaters required.");
		return -1;
	}
	if (lFrom.selectedIndex<0) {
		//alert("No items are selected.");
		return; // we must know which entry to move
	}
	// determine what and where we are moving from and to (which element, where to insert)
	for (var index = 0; index < lFrom.options.length; index++ )
	{
	  if ( lFrom.options[index].selected == true)
	  {
		fromPos= index; // lFrom.selectedIndex
		fromVal= lFrom.options[fromPos].value
		fromTxt= lFrom.options[fromPos].text
		if (fromVal == "") continue; // Don't move items with no values
		if (fromTxt.substring(0,3) == "(*)") fromTxt = fromTxt.substring(4,500) // strip off leading *
		toPos= lTo.length;
		if (ordered) // figure out where to insert the element to maintain ordering of lTo
		{ 
			var fromTxtUp = fromTxt.toUpperCase()
			var toUp
			for (i= 0; i<lTo.length; i++) 
			{
				toUp = lTo.options[i].text.toUpperCase()
				if (fromTxtUp < toUp) 
				{
					break;
				}
			}
			toPos= i;
		}

		var	oOption = document.createElement("OPTION");
		oOption.text = fromTxt;
		oOption.value = fromVal;
		if (toPos >= lTo.length) 
		{
			lTo.options.add(oOption, lTo.options.length);
		}
		else
		{
			lTo.options.add(oOption, toPos);
		}
		
		lFrom.remove(fromPos);

		index--;   //   Compensate for the combination of index++ and Remove
	  }
	}
//	lFrom.selectedIndex=-1;
}
//Select children of selected objects in listbox
function selectChildren( list )
{
	var selectSub = false;
	for( var i = 0; i < list.options.length; i++)
	{
		if(list.options[i].selected & list.options[i].text.indexOf("-- ") == -1)
			selectSub = true;
		else if(selectSub && list.options[i].text.indexOf("-- ") != -1)
			list.options[i].selected = true;
		else
			selectSub = false;
	}
}
function moveAll(lFrom,lTo)
{
	if (lFrom==null || lTo==null) {
		alert("moveOption: 2 pamaters required.");
		return -1;
	}
	for (var i = 0; i < lFrom.options.length; i++ )
	{
		lTo.options.length++;
		lTo.options[lTo.options.length-1].value = lFrom.options[i].value;
		lTo.options[lTo.options.length-1].text  = lFrom.options[i].text;
	}
	lFrom.options.length = 0;
}
function removeAll(dropDownOptions) {
	dropDownOptions.length = 0;
}
// This takes the values and loops over the options of a <SELECT> and highlights if it matches
function changeSelectBox(compareValue, fieldName) // used in /RMS/upload.aspx
{
	if (fieldName == null) return;
	for (i = 0; i < document.getElementById(fieldName).length; i++)
	{
		if (document.getElementById(fieldName).options[i].value == compareValue)
		{
			document.getElementById(fieldName).selectedIndex = i;
			break;
		}
	}
}
function selectAll(oList) {	// in order for all list elements to be passed to another .asp file all the
	// options/elements of the list must be selected. This requires that the
	// list be of type 'multiple' (which means more than one thing can be selected).
	if (oList == null) return;
	oList.multiple = true;
	for (var i = 0; i < oList.length; i++)
	{
		oList.options[i].selected= true;
		//if (oList.options[i].value>0) entry_cnt++; // Check if something is in the list
	}
}
function checkField (fieldObj) {
	if (fieldObj.value == '' || fieldObj.value ==  null) {
		alert('Field ' + fieldObj.name + ' is required.'); 
		fieldObj.focus();
		return false;
	}
	return true;
}
function ChangeMouse (formObj, cursor) { // mode = wait,default,move,hand,text,help or URL
	if (navigator.appName != 'Netscape') {
		//if (cursorURL != null) document.style.cursor = "url(" + cursorURL + ")";
		for (i = 0; i < formObj.all.length; i++)
		{
			if (i == 100) return;
			if (cursor.indexOf(".") == -1)
				eval('formObj.all(i).style.cursor="' + cursor + '"');
			else
				eval('formObj.all(i).style.cursor="url(' + cursor + ')"');
		}
	}
}
function addToDropDown(fieldObj, value, display) {
//	var listOption = document.createElement('OPTION');
//	listOption.value = value;
//	listOption.text = display;
//	fieldObj.add(listOption, 0);
	fieldObj.options[fieldObj.options.length] = new Option(display, value);
}
function storeCaret (textEl) {
	if (textEl.createTextRange) 
		textEl.caretPos = document.selection.createRange().duplicate();
}
function insertAtCaret (textEl, text) {
	if (textEl.createTextRange && textEl.caretPos) {
		var caretPos = textEl.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
	}
	else
		textEl.value  = text;
}
//if (typeof XMLHttpRequest != "object" && typeof XMLHttpRequest != "function") {
//	function XMLHttpRequest() {
//		alert("Using Microsoft.XMLHTTP");
//		return new ActiveXObject("Microsoft.XMLHTTP");
//	}
//}
function GetURL(url)
{        
    params = url.split("?")[1];
    url = url.split("?")[0];

    var ajax;
	var IE = false;
	if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) IE = true;
    try
    {
        // Firefox, Opera 8.0+, Safari, Chrome
        ajax = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
			ajax=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
			try
			{
	            ajax=new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e)
			{
				alert("Your browser does not support AJAX!");
				return false;
			}
        }
    }
    ajax.onreadystatechange=function()
    {
    }

    if(url.length * 1 + params.length * 1 < 2000)
    {           
        ajax.open("GET", url + "?" + params, false); // no async call so we wait for a return
		if (IE)
			ajax.send();
		else
			ajax.send(false);
		return ajax.responseText;
    }
    else
    {
        ajax.open("POST", url, false);
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajax.setRequestHeader("Content-length", params.length);
        ajax.setRequestHeader("Connection", "close");
        ajax.send(params);
        return ajax.responseText;
    }
}
function GetXmlNode(xml, nodeName)
{
	var startof = xml.indexOf("<" + nodeName + ">") + nodeName.length + 2;
	var endof = xml.indexOf("</" + nodeName + ">");
	if (endof > startof)
	{
		return xml.substr(startof, endof - startof);
	}
	else
		return "";
}

function SetCookie(cookieName,cookieValue)
	{
		 var today = new Date();
		 var expire = new Date();
		 expire.setTime(today.getTime() + 3600000*24*365);
		 document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ";path=/";
	}
function GetCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}   

function ShowDiv(divid) {
	document.getElementById(divid).style.display = "";
}

function HideDiv(divid) {
	document.getElementById(divid).style.display = "none";
}

function ToggleDiv(divid) {
	if (document.getElementById(divid).style.display == "none")
		ShowDiv(divid);
	else
		HideDiv(divid);
}

function toggleDashBoardDiv(divid,div)	
{
	if (document.getElementById(divid).style.display == "none")
	{
		document.getElementById(div).className = "dashboardtitle";
		ShowDiv(divid);
	}
	else
	{
		document.getElementById(div).className = "dashboardtitle_hidden";
		HideDiv(divid);
	}
}

function checkEmail( fieldObj )
{
	if (fieldObj == null) return true;
	if (fieldObj.value.indexOf(" ") > -1 || fieldObj.value.indexOf("/") > -1)
	{
		alert("Email address can not contain a space or /. Separate multiple emails with a comma."); 	
		fieldObj.focus(); 
		fieldObj.select(); 
		return false;
	}
	var email = stripSpaces(fieldObj.value);
	if (email == "") return true;
	email = email.toLowerCase();
	if (email.indexOf("@") == -1 || email.indexOf(".") == -1)
	{
		alert("Email address must contain a @ and a ."); 	
		fieldObj.focus(); 
		fieldObj.select(); 
		return false;
	}
	email = email.replace(";", ",");

	var last5 = email.substring(email.length-5,email.length);
	var last4 = email.substring(email.length-4,email.length);
	var last3 = email.substring(email.length-3,email.length);
	
	var valid5 = ".aero,.coop,.info,.name";
	var valid4 = ".com,.edu,.biz,.net,.org,.mil,.gov,.pro";
	var valid3 = ".ca,.jp,.ru,.uk,.us,.ws,.au,.cx,.ie,.it,.ms,.nu,.nz,.pr,.to,.tv,.tw,.vi,.ar,.de";

	if (valid5.indexOf(last5) > -1 || valid4.indexOf(last4) > -1 || valid3.indexOf(last3) > -1)
	{
		fieldObj.value = email;
		return true;
	}
	else
	{
		alert("Your email: " + email + " does not end in a valid extension such as .com. Please re-type.\n If you are sure this is valid, email webmaster@mystateusa.com"); 	
		fieldObj.focus(); 
		fieldObj.select(); 
		return false;	
	}
}

function stripSpaces(mystring)
{
	return mystring.split(" ").join("");
}

function checkPhone( fieldObj )
{
	if (fieldObj == null)
	{
		alert('You passed me a bad field name. It is null!');
		return false;
	}
	var n = fieldObj.value;
	if (n == "") return true;
	if (n.charAt(0) == "1") n = n.substring(1,11);
	var filteredValues = "1234567890";
	var returnString = "";
	for (var i = 0; i < n.length; i++)
	{ 	// Search through string and append only numbers to returnString.
		var c = n.charAt(i);
		if (filteredValues.indexOf(c) != -1) returnString += c;
	}
	if (returnString.length != 10)
	{
		alert(fieldObj.name + ' # must be 10 digits, including the area code.'); 
		fieldObj.focus(); 
		fieldObj.select(); 
		return false;
	}
	fieldObj.value = returnString.substring(0,3) + "-" + returnString.substring(3,6) + "-" + returnString.substring(6,10);
	return true;
}
function checkPager( fieldObj )
{
	if (fieldObj == null)
	{
		alert('You passed me a bad field name. It is null!');
		return false;
	}
	var n = fieldObj.value;
	if (n == "") return true;
	if (n.charAt(0) == "1") n = n.substring(1,11);
	var filteredValues = "1234567890";
	var returnString = "";
	for (var i = 0; i < n.length; i++)
	{ 	// Search through string and append only numbers to returnString.
		var c = n.charAt(i);
		if (filteredValues.indexOf(c) != -1) returnString += c;
	}
	if (returnString.length < 6)
	{
		alert(fieldObj.name + ' # must be at leat 7 digits.'); 
		fieldObj.focus(); 
		fieldObj.select(); 
		return false;
	}
	return true;
}
function removeLeftIfRight(leftSelect, rightSelect)
{	// Loop over all things on right-hand side. If found, remove on left 
	if (leftSelect == null) return;
	if (rightSelect == null) return;
	if (leftSelect.options == null) return;
	if (rightSelect.options == null) return;
	for (var index = 0; index < rightSelect.options.length; index++ )
	{
		for (var newindex = 0; newindex < leftSelect.options.length; newindex++ )
		{
			if (rightSelect.options[index].value == leftSelect.options[newindex].value )
			{
				leftSelect.remove(newindex);
				break; // We are assured it will only be the left once to get out of inner loop			
			}
		}
	}
}
function doClick(e1em, cellNumber) 
{
	if (cellNumber == null) cellNumber = 0;
	var innerHtml = e1em.cells[cellNumber].innerHTML;
	var startPos = innerHtml.indexOf("\"");
	if (startPos == -1) startPos = innerHtml.indexOf("=");
	
	if (startPos == -1) return; // Can't find a URL in the 1st cell so get out now

	var endPos = innerHtml.indexOf("\"", startPos+1);
	if (endPos == -1) endPos = innerHtml.indexOf("=", startPos);
	innerHtml = innerHtml.substring(startPos+1, endPos), 
	location.href = innerHtml.replace("&amp;", "&");
}
/*Useful Validation Code*/
var validateZipCode = function(zip)
{
    if(/^\d{5}(-\d{4})?$/.test(zip))return true;
    return false;
}
var validatePhoneNum = function(phoneNum)
{
    if(/((\(\d{3}\)?)|(\d{3}))([\s-./]?)(\d{3})([\s-./]?)(\d{4})/.test(phoneNum))return true;
    return false;
}
var validateEmail = function(email)
{
    if(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i.test(email)) return true;
    return false;
}
var validateNum = function(num)
{
    if(/^\d+$/.test(num)) return true;
    return false;
}
var validateState = function(state)
{
    if(/^[a-z][a-z]$/i.test(state)) return true;
    return false;
}
/*Default ValidationError Handler*/
var validationError = function(inputField,required)
{
    if(required) required = "Required Field";
    else required = "";
    
    if($(inputField).next().hasClass("validateError"))
    { 
        $(inputField).next().remove();
    }
    $(inputField).after('<span style="color:red;" class="validateError">*' + required + '</span>');
}
/*Common functions to validate fields with the specific class*/
function validateNumFields()
{
    return baseValidate("number",validateNum);
}
function validateZipFields()
{
    return baseValidate("zipCode",validateZipCode);
}
function validatePhoneFields()
{
    return baseValidate("phoneNum",validatePhoneNum);
}
function validateRequiredFields()
{
    return baseValidate("requiredField",function(){return true;});
}
function validateEmailFields()
{
    return baseValidate("validEmail",validateEmail);
}
function validateStateFields()
{
    return baseValidate("state",validateState);
}
/*The workhorse of the validate section pass in the class name you want to validate and the function you wish to validate with
You can also pass in your own error handler otherwise it defaults to validationError()*/
function baseValidate(className, validateFunction, validateError)
{
    if(!validateError) validateError = validationError;

    var isValid = true;

    $("." + className).each(function(){
        
        if($.trim(this.value) == "") {
            if($(this).hasClass("requiredField"))
            {
                validateError(this, true);
                isValid = false;
            }
        }
        else {
            if(validateFunction(this.value) == true)return true;
            else 
            {
                validateError(this);
                isValid = false;
            }
        }
    });
    return isValid;
}

/*Tooltip*/
var xTooltipOffset = 5;
var yTooltipOffset = 20;
var baseSize;
var pageX;
var pageY;

try{
    $(document).ready(function(){
        
        $("body").append('<div class="floatingTooltip"><span></span></div>');
        baseSize = $(".floatingTooltip").css("width");
        
        $(document).mousemove(function(event){
            
            pageY = event.pageY;
            pageX = event.pageX;
            
            var tPosX = event.pageX + xTooltipOffset;

            var tPosY = event.pageY + yTooltipOffset;
            
            $(".floatingTooltip").css({top: tPosY, left: tPosX});
        });
        
    });
}
catch(e)
{//Making sure it doesn't throw an error if JQuery isn't defined
}
function showtip(text, tooltipSize, xTooltip, yTooltip) 
{
    if(tooltipSize) $(".floatingTooltip").css({width: tooltipSize});
    if(yTooltip){yTooltipOffset = yTooltip; $(".floatingTooltip").css({top :pageY + yTooltipOffset});};
    if(xTooltip){xTooltipOffset = xTooltip; $(".floatingTooltip").css({left:pageX + xTooltipOffset});};
    
    $(".floatingTooltip").css({display: "block"});
    $(".floatingTooltip span").html(text);
    
    if($(".floatingTooltip span").width() < $(".floatingTooltip").width() && !tooltipSize)
    {
        $(".floatingTooltip").width($(".floatingTooltip span").width());
    }
}
function hidetip()
{
    $(".floatingTooltip").css({display: "none", width: baseSize});
    $(".floatingTooltip span").text("");
    xTooltipOffset = 5;
    yTooltipOffset = 20;
}
/*End Tooltip.js*/
/*Contents of DivFrame.js*/
function objPos(obj) //finds X & Y co-ord and returns them in an array
{
	var curleft = curtop = 0;
	if(obj){
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}}
	return [curleft,curtop];
}
var canada = false;
function preview(obj,content) //previews object
{
	previewDiv = document.getElementById('previewbox');
	document.getElementById('previewcontent').innerHTML = content;
	var position = objPos(obj);
	var previewPos = objPos(previewDiv);
	
	if(previewPos[0] == position[0] && previewPos[1]-obj.offsetHeight == position[1] && previewDiv.style.display == "block"){
		hide();
	}
	else{
		previewDiv.style.display = "block";
		previewDiv.style.left = position[0]+"px";	
		previewDiv.style.top = position[1]+obj.offsetHeight+"px";
		
    }	
}
function hide()
{
    if(!canada)
    {
        if(document.getElementById('previewbox').style.display == "block") canada = true;
    }
    else
    {
	    document.getElementById('previewbox').style.display = "none";
	    canada = false;
	}   
}

function hideInfoWindow()
{
	document.getElementById('overlay').style.display = "none";
	document.getElementById('infoWindow').style.display = "none";
}
/*End DivFrame*/
	
	var unFail;
	var fail;
	var validate = function(){
        
            $(".validateError").remove();
        
            var isValid = true;
                if(!validateZipFields())      isValid = false;
                if(!validatePhoneFields())    isValid = false;
                if(!validateRequiredFields()) isValid = false;
                if(!validateEmailFields())    isValid = false;
                if(!validateNumFields())      isValid = false;
                if(!validateStateFields())    isValid = false;
            return isValid;
        }
        
    $(document).ready(function(){
    
    image = new Image(0,0)
    image.src = "/images/busy1.gif";
    
    $("#provider").after("<input type='button' id='findprovider' style='font-size:10px;' value='Find Provider'/>");
    $("#findprovider").click(function(){findProvider()});
    
        fail = function(msg, closeWindow, failImage)
        {
            if($(".console, .error").length <= 1)
            {
            
            var messageImage;
            
                if(failImage)
                {
                    if(failImage == "error") imageSrc = '/edit/images/warning.png';
                    else if(failImage == "working") imageSrc = '/images/busy1.gif';
                    else imageSrc = failImage;
   
                    messageImage = '<img src="' + imageSrc + '" alt="busy" style="float:left; padding-right:8px; "/>'
                }
                
                $('<div class="console"></div>').appendTo('body');
                $('<div class="error"></div>').appendTo('body');
                $(".console").append('<div style="padding-top:12px; padding-left:22px;">' + (failImage ? messageImage : ' ') + '<div style="padding-top:9px;color:red; font-size: 14px">' + msg + '</div></div>');
                
                if(closeWindow)
                { 
                    $(".console").append('<div style="text-align:center; padding-top:5px;"><a style="color:#36C; text-decoration:underline; cursor:pointer;" onclick="unFail()" id="closeFail" value="Close Window">Close Window</a></div>');
                }
                
                $(".console").css({left:document.body.parentNode.scrollWidth/2 - $(".console").width()/2});
                $(".console").css({top:document.documentElement.scrollTop + 100});
                $(".error").css({height:document.body.parentNode.scrollHeight});
                
                $(window).resize(function(){
                
                    $(".console").css({left:document.body.parentNode.scrollWidth/2 - $(".console").width()/2});
                    $(".error").css({height:document.body.parentNode.scrollHeight});
                    
                });
                
                $(window).scroll(function(){
                
                    $(".console").css({top:document.documentElement.scrollTop + 100});
                
                });
                
                $(".console, .error").css("display", "block");
            }
        }

        unFail = function()
        {
            $(".console, .error").remove();
        }
        
        $("form").submit(function(){ validate();});
        $("input").blur(function(){ validate();});
    });