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

function validate_required(field, alerttxt)
{
	with (field)
	{
		//alert(trim(value) + " len = " + len(trim(value)))
		if (value == null || trim(value) == "")
  			{value = ""; alert(alerttxt);return false}
  		else
  			return true
	}
}

function validate_required_min(field, alerttxt, min)
{
	with (field)
	{
		//alert(Trim(value) + " len = " + len(trim(value)))
		if (value == null || trim(value) == "" || value < min)
  			{value = ""; alert(alerttxt);return false}
  		else
  			return true
	}
}

function validate_selection(field, alerttxt)
{
	for (var i = 0; i < field.length; i++)
		if (field[i].checked)
			return true
	alert(alerttxt)
	return false
}

function Delete()
{
	if (confirm("Are you sure you want to delete this data ?"))
	{
		document.getElementById("rw").value = "D"
		document.forms[0].submit()
	}
}

function updateFields()
{
	document.getElementById("rw").value = "R"
	document.forms[0].submit()
}


function isYearNB(chose)
{
	inputStr = chose.toString()
	if (inputStr.length != 4)
		return false;
	for (var i = 0; i < 4; i++)
	{
		var oneChar = inputStr.charAt(i)			
		if (oneChar < "0" || oneChar > "9")
			return false
	}
	var d = new Date()
	if ( (parseInt(inputStr) < 1969) || (parseInt(inputStr) > d.getFullYear()) )
	{
		alert("" + inputStr + " is a ridiculous value !")
		return false
	}
	return true
}

function isQty(chose)
{
	if (isInt(chose))
		return (chose > 0)
	else
		return false
}

function isInt(chose)
{
	inputStr = chose.toString()
	for (var i = 0; i < inputStr.length; i++)
	{
		var oneChar = inputStr.charAt(i)			
		if (oneChar < "0" || oneChar > "9")
			return false
	}
	return true
}

function isMoney(chose)
{
	if (isFloat(chose))
		return (chose >= 0)
	else
		return false
}

function isFloat(chose)
{
	inputStr = chose.toString()
	var decimalpt = false
	for (var i = 0; i < inputStr.length; i++)
	{
		var oneChar = inputStr.charAt(i)			
		if (!decimalpt  && (oneChar == "."))
			decimalpt = true
		else if ((oneChar == ".") && decimalpt)
			return false
		if (((oneChar < "0") || (oneChar > "9")) && (oneChar != "."))
			return false
	}
	return true
}

function implodeField(field)
{
	var impfield = ""			
	for (var i = 0; i < field.length; i++)
		if (field[i].checked)
			impfield += field[i].value + ","
	if (impfield.length > 0)
		return impfield.substr(0,impfield.length-1)
	else
		return ""
}

function selectedValue(field)
{
	if (!field.length)
		return field.value
	for (var i = 0; i < field.length; i++)
		if (field[i].checked)
			return field[i].value;
	return ""
}

function contactView()
{
	if ((id = document.getElementById("contact_id").value) >= 0)
		if (window.frameElement.name != "main")
			window.parent.location="centralContacts.php?contact_id=" + id
		else
			window.location="centralContacts.php?contact_id=" + id
}

function contactCreate()
{
	if (window.frameElement.name != "main")
		window.parent.location="centralContacts.php"
	else
		window.location="centralContacts.php"
}

function itemView(fieldname)
{
	if ((id = document.getElementById(fieldname).value) >= 0)
		if (window.frameElement.name != "main")
			window.parent.location="NBitems.php?item_id=" + id
		else
			window.location="NBitems.php?item_id=" + id
}

function itemCreate()
{
	if (window.frameElement.name != "main")
		window.parent.location="NBitems.php"
	else
		window.location="NBitems.php"
}

function deleteFile(fileid)
{
	with (document.forms[0])
	{
		removefile.value = fileid
		removefilelist.value += fileid + ","
		submit()
	}
}

function setcsv()
{
	with (document.forms[0])
	{
		csv.value = 1
		submit()
	}	
}

function validate_email(field,alerttxt)
{
	with (field)
	{
		e = trim(value)
		apos=e.indexOf("@")
		dotpos=e.lastIndexOf(".")
		//alert("dotpos = " + dotpos + " e.length = " + e.length)
		if ((apos < 1) || (dotpos - apos < 2) || ((dotpos+1) >= value.length) || (dotpos < 1))
		{
			alert(e + " : " + alerttxt)
			focus()
			return false
		}
		else 
		{
			value = e
			return true
		}
	}
}

function validate_customer()
{
	var thisform = document.forms[0]
	with (thisform)
	{
		return validate_email(email, "please enter a valid email")
	}
	return false
}

function SaveCustomer()
{
	var thisform = document.forms[0]

	with(thisform)
	{
		editflag.value = 1
		savecustomerflag.value = 1
		createcustomerflag.value = 0
		if (validate_customer())
			submit()
	}	
}

function cancelCustomerEdit(cid)
{
	var thisform = document.forms[0]

	with(thisform)
	{
		editflag.value = 0
		savecustomerflag.value = 0
		createcustomerflag.value = 0
		if (cid > 0)
			submit()
		else
			window.location = "NBWebStoreCustomers_top.php"
	}	
}

function EditCustomer()
{
	var thisform = document.forms[0]

	with(thisform)
	{
		editflag.value = 1
		savecustomerflag.value = 0
		createcustomerflag.value = 0
		submit()
	}	
}

function CreateCustomer()
{
	var thisform = document.forms[0]

	with(thisform)
	{
		editflag.value = 1
		savecustomerflag.value = 0
		createcustomerflag.value = 1
		submit()
	}	

}

function DeleteCustomer()
{
	if (confirm("Are you sure you want to permanently delete this customer ?"))
	{
		var thisform = document.forms[0]

		with(thisform)
		{
			editflag.value = 1
			savecustomerflag.value = 0
			createcustomerflag.value = 0
			deletecustomerflag.value = 1
			submit()
		}
	}
}

function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

//	document.URLForm.F2.value = encoded;
	return encoded;
}

function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   //var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
//   document.URLForm.F1.value = plaintext;
   return plaintext;
}

function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}

//req.onreadystatechange = function () { processRequest(idx); }

AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        } else {
            return true;
        }
    },

    loaded : function(id) {
        var i = document.getElementById(id);
        if (i.contentDocument) {
            var d = i.contentDocument;
        } else if (i.contentWindow) {
            var d = i.contentWindow.document;
        } else {
            var d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }

        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }

}

var xmlHttp = null;
var webpagedisplay = 'webpagedisplay';
var ajaxseparation = "ajaxseparation";
var separ = "¨";
function WSfireQuery(query, statechange)
{
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	} 
	with(document.forms[0])
	{
		var url="../../../../NBwebsiteAJAX.php";
		//var encodewsurl = URLEncode(wsurl.value);
		url += "?q="+query;
		url += "&sid="+Math.random();
		//alert(url);
		xmlHttp.onreadystatechange=function() {WSstateChanged(statechange);};
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}	
}

function getWindowheight() 
{ 
	var windowheight = 0; 
	if (typeof(window.innerheight) == 'number')
	{ 
		windowheight = window.innerheight; 
	} 
	else 
	{ 
		if (document.documentelement && document.documentelement.clientheight) 
		{ 
			windowheight = document.documentelement.clientheight; 
		} 
		else 
		{ 
			if (document.body && document.body.clientheight) 
			{ 
				windowheight = document.body.clientheight;
			} 
		} 
	} 
	return windowheight; 
} 

function WSstateChanged(task)
{
	if (xmlHttp.readyState==4)
	{ 
		var scriptResult = xmlHttp.responseText;
		var reg = new RegExp(ajaxseparation, "g");
		var tableau = scriptResult.split(reg);
		if (task == webpagedisplay)
		{
			var pagetitle = document.getElementById("pagetitle");
			var pagetext = document.getElementById("pagetext");
			var mainframe = document.getElementById("mainframe");
			pagetitle.innerHTML = tableau[0];
			pagetext.innerHTML = tableau[1];
//			mainframe.style.height = '900px'; 
//alert(tableau[1])
			//firefox bullshit
//			mainframe.style.height = (pagetext.offsetHeight+pagetitle.offsetHeight+50) + 'px'; 
//alert(mainframe.style.height);
        } 
	}
}

String.prototype.htmlEntities = function()
{
  /*var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é',
                         'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
                         'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
                         'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
                         'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
                         'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<',
                         '>','¢','£','¤','¥','¦','§','¨','©','ª','«',
                         '¬','®','¯','°','±','²','³','´','µ','¶',
                         '·','¸','¹','º','»','¼','½','¾');

  var entities = new Array ('amp','agrave','aacute','acirc','atilde','auml','aring',
                            'aelig','ccedil','egrave','eacute','ecirc','euml','igrave',
                            'iacute','icirc','iuml','eth','ntilde','ograve','oacute',
                            'ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc',
                            'uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc',
                            'Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute',
                            'Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde',
                            'Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave',
                            'Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig',
                            'lt','gt','cent','pound','curren','yen','brvbar','sect','uml',
                            'copy','ordf','laquo','not','shy','reg','macr','deg','plusmn',
                            'sup2','sup3','acute','micro','para','middot','cedil','sup1',
                            'ordm','raquo','frac14','frac12','frac34');*/
var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é',
                         'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
                         'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
                         'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
                         'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
                         'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß',
                         '¢','£','¤','¥','¦','§','¨','©','ª','«',
                         '¬','®','¯','°','±','²','³','´','µ','¶',
                         '·','¸','¹','º','»','¼','½','¾');

  var entities = new Array ('amp','agrave','aacute','acirc','atilde','auml','aring',
                            'aelig','ccedil','egrave','eacute','ecirc','euml','igrave',
                            'iacute','icirc','iuml','eth','ntilde','ograve','oacute',
                            'ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc',
                            'uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc',
                            'Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute',
                            'Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde',
                            'Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave',
                            'Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig',
                            'cent','pound','curren','yen','brvbar','sect','uml',
                            'copy','ordf','laquo','not','shy','reg','macr','deg','plusmn',
                            'sup2','sup3','acute','micro','para','middot','cedil','sup1',
                            'ordm','raquo','frac14','frac12','frac34');

  newString = this;
  for (var i = 0; i < chars.length; i++)
  {
    myRegExp = new RegExp();
    myRegExp.compile(chars[i],'g')
    newString = newString.replace (myRegExp, '&' + entities[i] + ';');
  }
  return newString;
}