var preEditValue 	= "";
var lastObj 		= "";
var lastQuery 		= "";
var Request 		= false;
var newValue 		= "";

function SaveEdit()
{
	var inp = document.getElementById("INLINE00");
	newValue = inp.value;
	lastObj.innerHTML = "Saved";
	MakeWebRequest("?xmlCommand=" + lastQuery + "&Value=" + escape(inp.value));
}

function MakeEdit(obj, editstr)
{
	lastQuery = editstr;
	var o = document.getElementById(obj);
	lastObj = o;
	preEditValue = o.innerHTML;
	o.innerHTML = "<INPUT ID='INLINE00' TYPE='Text' onBlur='SaveEdit();' onKeyPress='DoKey(event);' SIZE=5 Class=Inline value='" + preEditValue + "'>";

	var inp = document.getElementById("INLINE00");
	inp.focus();
	inp.select();
}

function DoKey(e)
{
	var d = document.getElementById("Debug");
	if (e.keyCode == 13)
	{
		SaveEdit();
		return false;
	}
	return true;
}

function AjaxCommand(url, dtag)
{
	$(dtag).innerHTML = "Please Wait....";
	var a = new Ajax(url, {method: 'get', evalScripts: 1, update: $(dtag)});
	a.request();
}

function AjaxComplete()
{
}

function AjaxSubmitForm(btnObject, dtag)
{
	var bof    = $(btnObject).getProperty('frm');	
	var qs     = $(bof).toQueryString();
	var url    = $(bof).action;	
	var strUrl = url;
	strUrl = strUrl.replace(/\?\?/, "?");
            		
	var a = new Ajax(strUrl + "?posted=1", {
		method      : 'post', 
		postBody    : qs,
		evalScripts : 1, 
		update      : $(dtag)
		});
		
	a.request();
	
    $(dtag).innerHTML = "Submitting Form";
}

function MakeWebRequest(url)
{
	Request = false;
	if (window.XMLHttpRequest)
	{
		//|   Mozilla and Safari
		Request = new XMLHttpRequest();
		if (Request.overrideMimeType) Request.overrideMimeType("text/xml");
	} else 
	if (window.ActiveXObject)
	{
		try {
			Request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try { Request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
		}
	}
	
	if (!Request)
		return "Failed to create XML";
		
	// console.log("Making AJAX Request to url:", url);
	Request.onreadystatechange = Contents;
	Request.open("POST", url, true);
	Request.send(null);
}

function VerifyDateField(strName, eField)
{
	alert('ve');
	$('eField').innerHTML = "TEST";
}

function Contents()
{
	// console.log("Contents Called, State=", Request.readyState);
	// console.log("Status=", Request.status);
	// console.log("D=", lastObj);
	if ((Request.readyState == 4) && (Request.status == 200))
	{
		lastObj.innerHTML = newValue;
	}	
}

///
///  Handle dynamic calls to edit a field

function onPopupContent(dtag, ticket)
{
	//|
	//|   This is called when a popup window is opened with a ticket.   The ticket
	//|   is passed back into a script with a given id.
	// console.log("Popup Ajax URL:", ticket);
	//console.log("Popup Ajax Div:", dtag);
	
    $(dtag).innerHTML = "Please Wait....";
    var a             = new Ajax(unescape(ticket) , {method: 'get', evalScripts: 1, update: $(dtag)});
    a.request();
}

function printDiv(dtag)
{
      	
	var a = window.open('','','scrollbars=yes,width=640,height=300');
	a.document.open("text/html");
	a.document.write('<html><head><style type="text/css">#frame{background-image:none;background-color:#FFFFFF;}</style>');
	a.document.write('<link rel=Stylesheet href="Print.css" />');
	a.document.write('</head><body style="padding-left:20px;background-image:none;background-color:#FFFFFF;">');
	a.document.write(document.getElementById(dtag).innerHTML);
	a.document.write('</body></html>');
	a.document.close();
	a.print();
	a.close();
}


///
///  Function to Manage popup Windows

var movedwin = 0;
var startmoveX;
var startmoveY;
var oldleft;
var oldtop;
var save_onmousemove;
var save_onmouseout;
var save_onmouseup;
var save_cursor;

function rw(o)
{
    return o.offsetWidth?o.offsetWidth:o.clientWidth;
}

function rh(o)
{
    return o.offsetHeight?o.offsetHeight:o.clientHeight;
}

function ore(v)
{
    return v?v:'';
}

//|
//|  BMP - Add an element to the document
//|
function addJavascriptSrc(srcUrl) 
{
	var newdiv = document.createElement("Script");
	var divIdName = 'my'+num+'Div';
	newdiv.setAttribute("Language", "Javascript");
	newdiv.setAttribute("Src", srcUrl);
	document.body.appendChild(newdiv);
}

function consume (ev) 
{
    if (!ev) ev         = window.event;
    if (ev.stopPropagation) 
	{
        ev.stopPropagation();
        ev.preventDefault();
	} else if (ev.cancelBubble) {
        ev.cancelBubble = true;
        ev.returnValue  = false;
	}
};

function getMouseX(ev) 
{                                                             
    if (!ev)ev       = window.event;
    return (ev.pageX?ev.pageX:(ev.x+document.body.scrollLeft));   
}
                                                                                    
function getMouseY(ev) 
{                                                             
    if (!ev)ev       = window.event;
    return (ev.pageY?ev.pageY:(ev.y+document.body.scrollTop));     
}

function hide_element(dtag)
{
	var o = document.getElementById(dtag);
	o.style.visibility = 'hidden';
}

function window_show(winid, evTag)
{
	// console.log("evtag=", evTag);
	
	win                                  = document.getElementById(winid);
	winTable                             = document.getElementById("popup" + winid);
	if(!win.style.left) win.style.left   = rw(document.body)/2-rw(win)/2+'px';
//	if(!win.style.top) win.style.top     = rh(document.body)/2-rh(win)/2+'px';
win.style.top = "100px";
	win.style.visibility                 = 'visible';
//	win.style.overflow               = (rw(win_4)>parseInt(win_2.style.width) || rh(win_4)>parseInt(win_2.style.height))?'scroll':'hidden';
	document.onmousemove                 = ore(save_onmousemove);
	document.onmouseout                  = ore(save_onmouseout);
	document.onmouseup                   = ore(save_onmouseup);
	document.body.style.cursor           = ore(save_cursor);
	
	if (evTag != '')
	{
		onPopupContent("inside" + winid, evTag);
	}
}

function window_hide(winid)
{
    document.getElementById(winid).style.visibility = 'hidden';
    document.onmousemove                            = ore(save_onmousemove);
    document.onmouseout                             = ore(save_onmouseout);
    document.onmouseup                              = ore(save_onmouseup);
    document.body.style.cursor                      = ore(save_cursor);
}

function window_startmove(winid, e)
{
    startmoveX                   = getMouseX(e);
    startmoveY                   = getMouseY(e);
    save_onmousemove             = document.onmousemove;
    save_onmouseout              = document.onmouseout;
    save_onmouseup               = document.onmouseup;
    save_cursor                  = document.body.style.cursor;
    document.onmousemove         = window_move;
    document.onmouseout          = null;
    document.onmouseup           = window_stopmove;
    document.body.style.cursor   = 'move';
    movedwin                     = document.getElementById(winid);
    oldleft                      = parseInt(movedwin.style.left);
    oldtop                       = parseInt(movedwin.style.top);
    consume(e);
	return false;
}

function window_move(e)
{
    if (movedwin)
    {
        X                           = getMouseX(e);
        Y                           = getMouseY(e);
        newleft                     = oldleft+X-startmoveX;
        newtop                      = oldtop+Y-startmoveY;
        newleft                     = Math.max(0               , newleft);
        newtop                      = Math.max(0               , newtop);
        newleft                     = Math.min(rw(document.body)-rw(movedwin),newleft);
        newtop                      = Math.min(rh(document.body)-rh(movedwin),newtop);
        movedwin.style.left         = newleft+'px';
        movedwin.style.top          = newtop+'px';
        consume(e);
        return false;
};
}

function window_stopmove(e)
{
    if (movedwin)
    {
        movedwin                    = 0;
        document.onmousemove        = ore(save_onmousemove);
        document.onmouseout         = ore(save_onmouseout);
        document.onmouseup          = ore(save_onmouseup);
        document.body.style.cursor  = ore(save_cursor);
        consume(e);
        return false;
	}
}

/**
This function is a generic function that will pass the contents of a field through
a validator function and then set the error condition if it's not right.
*/
function ValidateField(fieldName, verifyFunction, errorMessage)
{
	var retVal = false;
	// console.log("Checking fieldName= " + fieldName + ", verifyFunction=" + verifyFunction + ",");

	eval("retVal = " + verifyFunction + "('" + $(fieldName).value + "', '" + fieldName + "');");
	// console.log("Return Value=", retVal);

    if (retVal)
    {
    	$('error' + fieldName).setOpacity(0);
        $('error' + fieldName).innerHTML = "";
        $('opt' + fieldName).innerHTML   = '<img src=form_okay.gif width=13 height=13/>';
    	$(fieldName).removeClass("trContainsError");
        return true;
	} else {
        $('error' + fieldName).setOpacity(1);		
        $('error' + fieldName).innerHTML = errorMessage;
        $(fieldName).addClass("trContainsError");
        $('opt' + fieldName).innerHTML   = '<img src=form_error.gif width=13 height=13/>';              
        return false;        
	}
	
	// console.log("GOT=", retVal);
}

/**
Checks to see if a username is strong
*/
function isNotEmpty(val)
{
	if (val.test(".")) return true;
	return false;	
}

function isStrongUsername(val)
{
	if (val.test("....") && val.test("[a-zA-Z0-9]") && (!val.test("[^a-zA-Z0-9\_]")))
		return true;
	return false;
}

function isStrongPassword(val)
{
    if (val.test("....") && val.test("[a-zA-Z]") && val.test("[0-9\.-_!@#$%^&*]"))
        return true;
    return false;
}

function isWeakPhone(val)
{
	if (val.test("[a-zA-Z]")) return false;
	if (val.test("[0-9][0-9][0-9]")) return true;
	return false;	
}

function isStrongCurrency(num, reformatTag)
{
	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num))	return false;
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num % 100;
	num = Math.floor(num/100).toString();
	if (cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
		
	$(reformatTag).value = (((sign)?'':'-') + '$' + num + '.' + cents);
	return true;
}

function isWeakCompanyName(val)
{
	var regex = /[a-zA-Z0-9]/;
	var result = regex.test(val);
	if (result) return true;
    return false;    
}

function isWeakName(val)
{
	var regex = /^[a-zA-Z0-9]{3,20} [a-zA-Z0-9]+/;
	var result = regex.test(val);
	if (result) return true;
    return false;    
}

function isStrongEmail(val)
{
	if (val == "") return false;

	var regex;
	regex = /^(([a-z0-9!#$%&*+-=?^_`{|}~][a-z0-9!#$%&*+-=?^_`{|}~.]*[a-z0-9!#$%&*+-=?^_`{|}~])|[a-z0-9!#$%&*+-?^_`{|}~]|("[^"]+"))[@]([-a-z0-9]+\.)+([a-z]{2}|com|net|edu|org|gov|mil|int|biz|pro|info|arpa|aero|coop|name|museum)$/;


	if (!regex.test(val))
	{
		return false;
	}
	return true;
}

function isStrongDate(val, reformatTag)
{
	//| Requires mattKruse.js is loaded for parseDate
	var pdate = parseDate(val);
	if (!pdate) return false;
//	M/d/yy		
	if (reformatTag)
	{
		$(reformatTag).value = formatDate(pdate, "MM/dd/yyyy");
	}
	return true;	
}
