// check that all the required fields have a value
// required is an array of the form {fieldName1: fieldTitle1, fieldName2: fieldTitle2, ...}
function checkRequired(theForm, required, prefix) {
	if (!prefix) prefix = 'input';
	for(var k in required) {
		var field = theForm[prefix+'['+k+']'];
		
		if (field && !field.disabled && field.value=='') {
			alert("Please "+(field.type.match('select-') ? 'select' : 'specify')+" a "+required[k]);
			field.focus(); 
			// if the browser is Netscape 6 or IE
			if(document.all || document.getElementByID)
				field.style.background = "yellow";
			return false;
		}
		else if(!field) {
		    
		    // It could be a checkbox or a muti-select field? let's try that!
		    field = theForm[prefix+'['+k+'][]'];
		    if (field && !field.disabled) {
		        var empty = true;
		        for(var i=0; i < field.length; i++) {
                    if(field[i].checked || field[i].selected)
                        empty=false;
                }
                if (empty) {
                    alert("Please "+(field.type.match('select-') ? 'select one or more' : 'specify a')+" "+required[k]);
                    return false;
                }
		    }
		        
		}
	}

	return true;
}
// check that that the fields are of the valid format
// valid is an array of objects of the form 
// [{field:fieldName1, pattern:/pat1/, message:"display if does not match"}, 
//	{field:fieldName1, pattern:/pat2/, message:"display this if does not match"}, .. ]
function checkValid(theForm, validate, prefix) {
	if (!prefix) prefix = 'input';
	for(var i=0; i<validate.length; i++) {
		var vObj = validate[i];
		var field = theForm[prefix+'['+vObj.field+']'];
		if (field && !field.value.match(vObj.pattern)) {
			alert(vObj.message);
			field.focus(); 
			// if the browser is Netscape 6 or IE
			if(document.all || document.getElementByID) field.style.background = 'yellow';
			return false;
		}
	}

	return true;
}

function check_email(e) {
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

	for(i=0; i < e.length ;i++){
		if(ok.indexOf(e.charAt(i)) < 0){
			return (false);
		}	
	} 

	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return (-1);		
		} 
	}
}

function openWindow(sURL, sName, oFeatures, bReplace) {
	sFeatures = '';
	if (oFeatures) {
		for(var k in oFeatures) {
			if (sFeatures) sFeatures += ", ";
			sFeatures += k+"="+oFeatures[k];
		}
	}
  newwin = window.open(sURL, sName, sFeatures, bReplace);
	if (newwin) newwin.focus();
	return newwin;
}

/*
function onChangeText(button, name) {
	var theForm = button.form;
	var textarea = theForm[name];
	var content = document.getElementById(name);
	
	var size;

	if (button.value=='html') {
		size = getSize(content);
		textarea.style.width = size.width;
		textarea.style.height = size.height;
		 // must be done before content is hidden
		updateTextAreaFromContent(name);
		content.style.display = 'none';
		textarea.style.display = 'block';
	} else {
		size = getSize(textarea);
		content.style.width = size.width;
		content.style.height = size.height;
		textarea.style.display = 'none';
		content.style.display = 'block';
		// must be done after content is displayed
		if (navigator.userAgent.toLowerCase().indexOf( "safari" ) != -1) 
			setTimeout(function() { updateContentFromTextArea(name,theForm.name) }, 0); // need timeout for safari
		else
			updateContentFromTextArea(name, theForm.name);
	}

}

function getSize(obj) {
	var width, height;
	if      (obj.style.width) { width = obj.style.width; }      // use css style
	else if (obj.cols)        { width = (obj.cols * 5) + 22; }  // col width + toolbar
	else                      { width = '100%'; }               // default

	if      (obj.style.height) { height = obj.style.height; }   // use css style
	else if (obj.rows)         { height = obj.rows * 13 }       // row height
	else                       { height = '200'; }              // default

	return {width: width, height: height}
}
function updateContentFromTextArea(name, formName) {
	if (formName) field = document[formName][name];
	else field = findField(name, document);
	var content = findItem(name, document); //document.getElementById(field.name);

	if (content.contentWindow ) {
		var html = 
			'<html><head>\n'
      + '</head>\n'
      + '<body contenteditable="true" topmargin=1 leftmargin=1>'
      + field.value
      + '</body>\n'
      + '</html>\n';
		content.contentWindow.document.open();
    content.contentWindow.document.write(html);
    content.contentWindow.document.close();
		if (!content.contentWindow.document.designMode || 
			content.contentWindow.document.designMode=="off") content.contentWindow.document.designMode="on";  // needed for Firefox
	} else if (content.contentDocument) {
		content.contentDocument.body.innerHTML = field.value;
		content.contentDocument.designMode="on"; // works for Firefox
	} else {
		content.innerHTML = field.value;
	}
}
function updateTextAreaFromContent(name, formName) {
	if (formName) field = document[formName][name];
	else field = findField(name, document);
	var content = findItem(name, document);
	if (content.contentWindow ) {
		field.value = content.contentWindow.document.body.innerHTML;
	} else if (content.contentDocument) {
		field.value = content.contentDocument.body.innerHTM;
	} else {
		field.value = content.innerHTML;
	}
}

function editor_focus(editor_obj) {

  // check editor mode
  if (editor_obj.tagName.toLowerCase() == 'textarea') {         // textarea
    setTimeout(function() { editor_obj.focus(); },100);         // doesn't work all the time without delay
  }

  else {                                                        // wysiwyg

		if (editor_obj.contentWindow) {
			var editdoc = editor_obj.contentWindow.document;						// get iframe editor document object
			var editorRange = editdoc.body.createTextRange();           // editor range
			var curRange    = editdoc.selection.createRange();          // selection range
		} else {
			var editorRange = editor_obj.createTextRange();           // editor range
			var curRange    = document.selection.createRange();          // selection range
		}

    if (curRange.length == null &&                              // make sure it is not a controlRange
        !editorRange.inRange(curRange)) {                       // is selection in editor range
      editorRange.collapse();                                   // move to start of range
      editorRange.select();                                     // select
      curRange = editorRange;
    }
  }

}
//To execute command we will use javascript function execCommand. 
function editorCommand(name, command, option) {
	var editor_obj = findItem(name, document);
	var win = editor_obj.contentWindow ? editor_obj.contentWindow : window;

	//editor_focus(editor_obj);
	try {
		win.focus();
		win.document.execCommand(command, false, option);
		win.focus();
	} catch (e) { }
	}

*/

// Generic addEventListener / attachEvent function
function addEventListenerGen(sourceObject, eventName, listener) {
	if (sourceObject.addEventListener) sourceObject.addEventListener( eventName, listener, false );
	else if (sourceObject.attachEvent) sourceObject.attachEvent( 'on' + eventName, listener ) ;
	else alert("unable to add '"+eventName+"' event listener");
}

// Generic removeEventListener / detachEvent function
function removeEventListenerGen(sourceObject, eventName, listener) {
	if (sourceObject.removeEventListener) sourceObject.removeEventListener( eventName, listener, false ) ;
	else if (sourceObject.detachEvent) sourceObject.detachEvent( 'on' + eventName, listener ) ;
	else alert("unable to remove '"+eventName+"' event listener");
}

// wrap the onload function as a funcrion that calls multiple
// onload functions stored in window.onloadarr
// addOnFunction(window,'onload',function() {alert('DO IT')});
function addOnFunction(sourceObject,fname,fobj) {

	if (typeof sourceObject == "undefined") {
		alert("sourceObject is undefined");
		return;
	} else if (!typeof fobj == "function") {
		alert("not a function : "+fobj);
		return;
	}

	if (typeof sourceObject['__'+fname] == "undefined") {
		sourceObject['__'+fname] = [];

		if (typeof sourceObject[fname] == "function")
			sourceObject['__'+fname].push(sourceObject[fname]);

		sourceObject[fname] = function() {
			var a = this['__'+fname];
			var result = true;
			// call previous submit methods if they were there.
			if (typeof a != "undefined") for (var i in a) result = result && a[i]();
			return result;
		};
	}

	sourceObject['__'+fname].push(fobj);
}

// remove the function fobj from the event fname of the object fname
function removeOnFunction(sourceObject,fname,fobj) {
	var fobjStr = fobj.toString();
	if (typeof(sourceObject[fname]) != 'function') ; // do nothing
	else if (sourceObject[fname].toString() == fobjStr) {
		sourceObject[fname] = undefined;
	} else if (sourceObject['__'+fname]) {
		for (var i=0; i<sourceObject['__'+fname].length; i++) 
			if (sourceObject['__'+fname][i].toString()==fobjStr) 
				sourceObject['__'+fname].splice(i, 1);
	}
}

function findItem(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(d.getElementById) x=d.getElementById(n); 
  if(!x && !(x=d[n])&&d.all) x=d.all[n];
	if(!x) x=findField(n, d);
	return x;
}

function findField(n, d) { //v4.01
  var i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	return x;
}

function callFun (obj, fName, defVal) {
	var fobj = obj[fName];
	return (typeof(fobj) == 'function') ? fobj() : defVal;
}

// call the iLayer documents doSubmit function (if it exists) 
// then cancel this submit and wait for the iLayer to finish submitting before
// removing this function and re-submitting the form.
function onILayerSubmit(form, fobj, iLayer) { 
	var doc = iLayer.contentDocument || iLayer.contentWindow.document;
	if (typeof(doc.doSubmit) != 'function') return true; // no doSubmit on the document
	else if (!doc.doSubmit()) return false; // doSubmit returned false

  // set an interval to wait for the iLayer to finish submitting
	var limit = 50;
	var interval = setInterval(
		function () { 
			var doc = iLayer.contentWindow ? iLayer.contentWindow.document : iLayer.contentDocument;	
			if (--limit < 0 || (doc && doc.body)) {
				// when the iLayer document and document.body exist (or the interval has passed)
				// clear the interval
				clearInterval(interval);
				// remove this (caller) onsubmit function
				removeOnFunction(form,'onsubmit',fobj);
				// re-submit the onsubmit
				if (typeof(form.onsubmit) != 'function') ; // do nothing
				else if (!form.onsubmit()) return; // onsubmit canceled

				// submit the form
				form.submit();
			}
		}, 
		100);

	return false;	
}



function getWidth(obj) {
	if (!obj) {
		theWidth = 0;
  } else if (obj.offsetWidth && (obj.offsetWidth > 0)) {
		theWidth = obj.offsetWidth;
	} else if (obj.scrollWidth && (obj.scrollWidth > 0)) {
		theWidth = obj.scrollWidth;
	} else if (obj.clientWidth && (obj.clientWidth > 0)) {
		theWidth = obj.clientWidth;
	}
	return theWidth;
}
function getHeight(obj) {
	if (!obj) {
		theHeight = 0;
  } else if (obj.offsetHeight && (obj.offsetHeight > 0)) {
		theHeight = obj.offsetHeight;
	} else if (obj.scrollHeight && (obj.scrollHeight > 0)) {
		theHeight = obj.scrollHeight;
	} else if (obj.clientHeight && (obj.clientHeight > 0)) {
		theHeight = obj.clientHeight;
	}
	return theHeight;
}

function windowWidth(win) {
	if (!win) win = window;
	if (win.innerWidth && (win.innerWidth > 0)) {
		theWidth = win.innerWidth;
	} else if (win.document.documentElement.clientWidth && (win.document.documentElement.clientWidth > 0)) {
		theWidth = win.document.documentElement.clientWidth;
	} else {
		theWidth = win.document.body.clientWidth;
	}
	return theWidth;
}
function windowHeight(win) {
	if (!win) win = window;
	if (win.innerHeight && (win.innerHeight > 0)) {
		theHeight = win.innerHeight;
	} else if (win.document.documentElement.clientHeight && (win.document.documentElement.clientHeight > 0)) {
		theHeight = win.document.documentElement.clientHeight;
	} else {
		theHeight = win.document.body.clientHeight;
	}
	return theHeight;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function getInnerHTML(id, doc) {
	if (!doc) doc = document;
	if (doc.getElementById) { return doc.getElementById(id).innerHTML; }
	else if (doc.all) { return doc.all[id].innerHTML; }
	else if (doc.layers) { return doc.layers[id].innerHTML; }
}
function setInnerHTML(id, html, doc) {
	if (!doc) doc = document;
	if (doc.getElementById) { doc.getElementById(id).innerHTML = html; }
	else if (doc.all) { doc.all[id].innerHTML = html; }
	else if (doc.layers) { doc.layers[id].innerHTML = html; }
}
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	if (expiredays==null || expiredays==0) expiredays=1;
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

// escape regular expression metacharacters like $ or . 
RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
