var preEditValue 	= "";
var lastObj 		= "";
var lastQuery 		= "";
var newValue 		= "";
var	oScrollPos		= 0;
var allTimers		= [];
var allWindows		= [];

var roarTopRight;

//|
//|   Add functions to elements for showing and hiding.
window.addEvent('domready', function()
{
    Element.implement({
        show: function() {
            this.setStyle('display','');
        },
        hide: function() {
            this.setStyle('display','none');
        }
    });
});


function strncmp ( str1, str2, lgth )
{
    var s1 = (str1+'').substr(0, lgth);
    var s2 = (str2+'').substr(0, lgth);
    return ( ( s1 == s2 ) ? 0 : ( ( s1 > s2 ) ? 1 : -1 ) );
}

function evalMyScripts2(txt)
{
	//|  Assume txt is a page of text that may have <script> tags
	//|
	var re = /<script[^>]*>([\s\S])*?<.script>/gim;
	var ma = txt.match(re);
	if (ma != null)
	{
		for (var x=0; x<ma.length; x++)
		{
			// console.log("script %d: %s", x, ma[x]);
		}
	}
}

function evalMyScripts(txt)
{
	var x = eval("evalMyScripts2(txt);");
}

function SetLocalOpacity(elm,val)
{
    // If filters exist, then this is IE, so set the Alpha filter

    if ( elm.filters )
            elm.filters.alpha.opacity = val;

    // Otherwise use the W3C opacity property

    else    elm.style.opacity = val / 100;
}

function SaveEdit()
{
	var inp = document.getElementById("INLINE00");
	newValue = inp.value;
	lastObj.innerHTML = newValue;

	roarTopRight = new Roar({
			duration: 1500,
			position: 'upperRight'
		});

	MakeWebRequest(document.location + "?xmlCommand=" + lastQuery + "&Value=" + escape(newValue));
}

function MakeEdit(obj, editstr)
{
	lastQuery = editstr;
	var o = document.getElementById(obj);
	lastObj = o;
	preEditValue = o.innerText;
	o.innerHTML = "<INPUT ID='INLINE00' NAME='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)
{
//	document.getElementById(dtag).innerHTML = "Please Wait...";

	var theScripts = "";
	var a = new Request({
		url: url,
		method: 'get',
		evalScripts	: function(scriptText, pageText) {

			theScripts = scriptText;
		},
		onSuccess: function(responseText) {
			$(dtag).innerHTML = responseText;
			evalMyScripts(responseText);
			eval(theScripts);
		}
	}).send();
}

function AjaxComplete()
{
}

function AjaxSearchTable(txtField, qry)
{
	var searchVal = $(txtField).value;
	var col = $(txtField).style.backgroundColor;
	$(txtField).style.backgroundColor = '#eeeeee';


	var tableData = $("TableCallbackData").value;
	var qs = "search=" + escape(searchVal) + "&__tableCallbackData=" + tableData + "&qry=" + qry;
	var dtag = "DataTableMain";
	var a = new Request({
		url			: document.location.toString(),
		method 		: 'post',
		data		: qs,
		evalScripts	: function(scriptText, pageText) {
			theScripts = scriptText;
		},
		onSuccess	: function(responseText) {
			$(dtag).innerHTML = responseText;
			eval(theScripts);
			$(txtField).style.backgroundColor = col;
		}
	});

	a.send();
}

function AjaxSubmitFormUrl(btnObject, url, dtag)
{
	var bof  = $(btnObject).getAttribute("frm");
    var Form = document.getElementById(bof);
	$(bof).action = url;
	return AjaxSubmitForm(btnObject, dtag);
}

function AjaxSubmitForm(btnObject, dtag)
{
	var bof    = $(btnObject).getAttribute('frm');
    var Form = document.getElementById(bof);
    if (Form.onsubmit !=null) Form.onsubmit();

	var qs     = $(bof).toQueryString();
	var url    = $(bof).action;
	var strUrl = url;
	strUrl = strUrl.replace(/\?\?/, "?");

    var theScripts = "";
	var a = new Request({
		url			: url,
		method 		: 'post',
		data		: qs,
		evalScripts	: function(scriptText, pageText) {
			theScripts = scriptText;
		},
		onSuccess	: function(responseText) {
			$(dtag).set('html', responseText);
			evalMyScripts(responseText);
			eval(theScripts);
		}
	}).send();

    $(dtag).innerHTML = "Loading...";
    return true;
}

function MakeWebRequest(urlf)
{

	var a = new Request({
		url: urlf,
		method: 'get',
		onSuccess	: function(responseText) {
		// console.log("Got:" + responseText);
		
		}
	}).send();

}

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 = "Loading....";
	if (ticket.indexOf("?") != -1)
		ticket += "&__target=" + escape(dtag);

	var theScripts = "";
	var a = new Request(
	{
		url: unescape(ticket),
		method: 'get',
		evalScripts	: function(scriptText, pageText) {

			theScripts = scriptText;
		},
		onSuccess: function(responseText) {
			$(dtag).innerHTML = responseText;
			eval(theScripts);
			evalMyScripts(responseText);
		}
	}).send();
}

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_pos(winid, evTag, xx, yy)
{
	// console.log("evtag=", evTag);

	win                                  = document.getElementById(winid);
	winTable                             = document.getElementById("popup" + winid);
	win.style.left   					 = xx;
	win.style.top 						 = yy;
	win.style.visibility                 = 'visible';
	win.style.overflow                   = 'hidden';
	document.onmousemove                 = ore(save_onmousemove);
	document.onmouseout                  = ore(save_onmouseout);
	document.onmouseup                   = ore(save_onmouseup);
	document.body.style.cursor           = ore(save_cursor);

	oScrollPos = (document.all)?document.body.scrollTop:window.pageYOffset;
	document.body.scrollTo(0, 0);

	if (evTag != '')
	{
		onPopupContent("inside" + winid, evTag);
	}

	allWindows.push(winid);
}

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);

	oScrollPos = (document.all)?document.body.scrollTop:window.pageYOffset;
	win.style.top = oScrollPos;

	if (evTag != '')
	{
		onPopupContent("inside" + winid, evTag);
	}

	allWindows.push(winid);
}

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);
    document.body.scrollTo(0, oScrollPos);

	allWindows.pop();
}

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;
	}
}

function ConditionalEval(cond, condeval)
{
	var retVal = false;
	eval("retVal = (" + cond + ");");
	if (retVal)
	{
		eval(condeval);
	}
}

function ConditionalCopy(cond, fromname, toname)
{
	var retVal = false;
	eval("retVal = (" + cond + ");");
	if (retVal)
	{
		var o1 = document.getElementById(fromname);
		var o2 = document.getElementById(toname);
		if ((o1 != null) && (o2 != null))
		{
			o2.value = o1.value;
		}
	}
}

function ConditionalDisable(cond, fieldname)
{
	var retVal = false;

	var o1 = document.getElementById(fieldname);
	if (o1 == null) return;

	eval("retVal = (" + cond + ");");
	if (retVal)
	{
		if (o1.origBack == null)
		{
			o1.origBack = o1.style.backgroundColor;
			o1.origBord = o1.style.border;
			o1.origColr = o1.style.color;
		}
		o1.style.backgroundColor = '#dddddd';
		o1.style.border = "1px solid #bbbbbb";
		o1.style.color = "#999999";
		// o1.disabled = 1;
	} else {
		// o1.disabled = 0;
		o1.style.backgroundColor = o1.origBack;
		o1.style.border = o1.origBord;
		o1.style.color = o1.origColr;
	}

	// o1.disabled = (retVal ? "disabled" : "");
}

/**
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)
    {
    	//SetLocalOpacity('error' + fieldName,0);
        $('error' + fieldName).innerHTML = "";
        $('opt' + fieldName).innerHTML   = '<img src=/Common/images/form_ok.png width=16 height=16/>';
    	// $(fieldName).removeClass("trContainsError");
        return true;
	} else {
    	// SetLocalOpacity('error' + fieldName,100);
        // alert (errorMessage);

        $('error' + fieldName).innerHTML = errorMessage;
        // $(fieldName).addClass("trContainsError");
        $('opt' + fieldName).innerHTML   = '<img src=/Common/images/form_error.png width=16 height=16/>';
        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 FormatCurrency(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

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 isSamePassword(val)
{
	var firstPass = $("password1").value;
	if (val != firstPass)
		return false;
	return true;
}

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;
}

function DeleteTableRowWithConfirm(qryValue, rowObject)
{
	AjaxCommand(document.location + "?" + qryValue, rowObject.ID);
}

function OpenNewWindow(sUrl)
{
    window.open(sUrl,'_blank');
}

function setRadioCheck(dtag, newValue)
{
	var x = 0;
	for (x=0; x<20; x++)
	{
		var s = dtag + x.toString();
		var o = document.getElementById(s);
		if (o == null) continue;
		if (o.value == newValue.toString())
			o.checked = true; else
			o.checked = false;
	}
}

var lastCountry = "";
function ReformatPhoneNumber(o)
{
	if (o == null) return false;
	var val = o.value;
	if (val == null) return false;
	val = val.replace(/[^0-9]/g, "");

	//|
	//| US Numbers
	var m;

	m = val.match(/^([2-9]..)(...)(....)(.*)/);
	if (m != null)
	{
		lastCountry = "United States of America";
		o.value = "+1 (" + m[1] + ") " + m[2] + "-" + m[3];
		if (m[4].length > 0)
			o.value += " x " + m[4];
		return true;
	}

	m = val.match(/^1([2-9]..)(...)(....)(.*)/);
	if (m != null)
	{
		lastCountry = "United States of America";
		o.value = "+1 (" + m[1] + ") " + m[2] + "-" + m[3];
		if (m[4].length > 0)
			o.value += " x " + m[4];
		return true;
	}

	//|  Saudi Arabia
	m = val.match(/^966(5[0346])(.......)(.*)/);
	if (m != null)
	{
		lastCountry = "Saudi Arabia";
		o.value = "+966 " + m[1] + " " + m[2] + " " + m[3];
		return true;
	}

	//| UAE
	m = val.match(/^971([2345679][05]{0,1})(.......)(.*)/);
	if (m != null)
	{
		lastCountry = "UAE";
		o.value = "+971 " + m[1] + " " + m[2] + " " + m[3];
		return true;
	}

	return true;
}

/**
 **
 **  Utility Functions
 **
 */

function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

    str_data += '';

    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}

function base64_decode (data)
{
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);

    return dec;
}
