<!--
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 (e2) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	return xmlHttp;
}

function popupPage(url,name,w,h){		
	myleft=(screen.width)?(screen.width-w)/2:100;
	mytop=(screen.height)?(screen.height-h)/2:100;
	properties = "width="+w+",height="+h+",scrollbars=no,menubar=no,toolbar=no,status=no, top="+mytop+",left="+myleft;
	window.open(url,name,properties);
}

function toggleEditor(id) {
	if (tinyMCE.getInstanceById(id) === null) {
		tinyMCE.execCommand('mceAddControl', false, id);
	} else {
		tinyMCE.execCommand('mceRemoveControl', false, id);
	}
}

function setCheckboxes(form, name, do_check)
{
	for (i = 0; i < form.elements.length; i++) {
		if ((name != "" && form.elements[i].id.indexOf(name) != -1) || (name == "" && form.elements[i].checked == true))
		 	form.elements[i].checked = do_check;
		else if (name == "" && form.elements[i].checked == false)
		 	form.elements[i].checked = do_check;
	}
}

function setCheckboxesCol(form, name, val, do_check)
{
	for (i = 0; i < form.elements.length; i++) {
		if ((name != "" && form.elements[i].id.indexOf(name) != -1 && form.elements[i].value == val) || (name == "" && form.elements[i].checked == true))
		 	form.elements[i].checked = do_check;
		else if (name == "" && form.elements[i].checked == false && form.elements[i].value == val) 
		 	form.elements[i].checked = do_check;
	}
}

function confirmMassAction(form) {
	var action = form.MassAction.options[form.MassAction.selectedIndex].text;
	
	if (action == "No Action")
		return false;
		
	return confirm("Are you sure you want to perform the action \""+action+"\" to all checked rows?");
}

function starRating (rating, field) {
	document.getElementById(field).value = rating;
	
}

function seteventoptiondesc(value) {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 
	var url = "events_options_GetDesc.php";
	 
	url = url + "?sid=" + Math.random();
	
	url = url + "&OptionID="+value;
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			if (xmlHttp.responseText != "" && xmlHttp.responseText != "none") {
			 document.getElementById("OptionDesc").innerHTML = xmlHttp.responseText;
			 document.getElementById("OptionDesc").style.display = "block";
			} else {
			 document.getElementById("OptionDesc").innerHTML = "";
			 document.getElementById("OptionDesc").style.display = "none";
			}
		}
	}
	
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function submitenter (myfield, e) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	if (keycode == 13) {
	   myfield.form.submit();
	   return false;
   }
	else
   	return true;
}

function suggestBlockOption(optionid) {
	var str = escape(document.getElementById("OptionSuggest_"+optionid).value);		
	
	if (str.length == 0) { 
		document.getElementById("blockoptionResults_"+optionid).innerHTML = "";
		document.getElementById("blockoptionResults_"+optionid).style.border = "0px";	
		document.getElementById("blockoptionResults_"+optionid).style.display = "none";
		return;
	}	

	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 

	var url = "pages_blocks_Suggest.php";
	url = url + "?OptionID=" + optionid;
	url = url + "&keyword=" + str;
	url = url + "&sid=" + Math.random();
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			var result = document.getElementById("blockoptionResults_"+optionid).innerHTML = xmlHttp.responseText;

			if (result.length > 0) {
				document.getElementById("blockoptionResults_"+optionid).style.border = "1px solid #333333";			
				document.getElementById("blockoptionResults_"+optionid).style.display = "block";
			}
			else {
				document.getElementById("blockoptionResults_"+optionid).style.border = "0px";	
				document.getElementById("blockoptionResults_"+optionid).style.display = "none";
			}
		}
	}	

	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function setBlockOption(optionid, value, text) {
	document.getElementById("BlockOptions["+optionid+"]").value = value;
	document.getElementById("blockoptionDisplay_"+optionid).innerHTML = text + " (Update to confirm)";			
	document.getElementById("OptionSuggest_"+optionid).value = text;
	document.getElementById("blockoptionResults_"+optionid).innerHTML = "";
	document.getElementById("blockoptionResults_"+optionid).style.border = "0px";	
	document.getElementById("blockoptionResults_"+optionid).style.display = "none";		
	suggestBlockOptionClose(optionid);
}

function suggestBlockOptionClose (optionid) {
	document.getElementById("blockoptionResults_"+optionid).innerHTML = "";
	document.getElementById("blockoptionResults_"+optionid).style.border = "0px";	
	document.getElementById("blockoptionResults_"+optionid).style.display = "none";	
}

function suggestUser () {
	var str = escape(document.getElementById("UserSearch").value);		

	if (str.length == 0) { 
		document.getElementById("userResults").innerHTML = "";
		document.getElementById("userResults").style.border = "0px";	
		document.getElementById("userResults").style.display = "none";
		return;
	}	

	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 

	var url = "users_Suggest.php";
	url = url + "?keyword=" + str;
	url = url + "&sid=" + Math.random();

	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			var result = document.getElementById("userResults").innerHTML = xmlHttp.responseText;

			if (result.length > 0) {
				document.getElementById("userResults").style.border = "1px solid #333333";			
				document.getElementById("userResults").style.display = "block";
			}
			else {
				document.getElementById("userResults").style.border = "0px";	
				document.getElementById("userResults").style.display = "none";
			}
		}
	}	

	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function setUser (id, name, fname, lname, email) {
	if (document.getElementById("UserID") != null)
		document.getElementById("UserID").value = id;
	if (document.getElementById("UserName") != null)
		document.getElementById("UserName").value = name;
	if (document.getElementById("UserFirstName") != null)
		document.getElementById("UserFirstName").value = fname;
	if (document.getElementById("UserLastName") != null)
		document.getElementById("UserLastName").value = lname;
	if (document.getElementById("UserFullName") != null)
		document.getElementById("UserFullName").value = fname+" "+lname;
	if (document.getElementById("UserEmail") != null)
		document.getElementById("UserEmail").value = email;
		
	document.getElementById("UserSearch").value = "";
	document.getElementById("userResults").innerHTML = "";
	document.getElementById("userResults").style.border = "0px";	
	document.getElementById("userResults").style.display = "none";
}

function suggestUserClose () {
	document.getElementById("userResults").innerHTML = "";
	document.getElementById("userResults").style.border = "0px";	
	document.getElementById("userResults").style.display = "none";
	document.getElementById("userResults").style.display = "none";	
}

function suggestCity () {
	var str = escape(document.getElementById("SearchCity").value);		

	if (str.length == 0) { 
		document.getElementById("cityResults").innerHTML = "";
		document.getElementById("cityResults").style.border = "0px";	
		document.getElementById("cityResults").style.display = "none";
		return;
	}	

	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 

	var url = siteLink+"admin/locations_SuggestCity.php";
	url = url + "?keyword=" + str;
	url = url + "&sid=" + Math.random();

	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			var result = document.getElementById("cityResults").innerHTML = xmlHttp.responseText;

			if (result.length > 0) {
				document.getElementById("cityResults").style.border = "1px solid #333333";			
				document.getElementById("cityResults").style.display = "block";
			}
			else {
				document.getElementById("cityResults").style.border = "0px";	
				document.getElementById("cityResults").style.display = "none";
			}
		}
	}	

	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function setCity (city, state, zip) {	
	document.getElementById("SearchCity").value = city;
	document.getElementById("SearchZip").value = zip;

	document.getElementById("cityResults").innerHTML = "";
	document.getElementById("cityResults").style.border = "0px";
	document.getElementById("cityResults").style.display = "none";	

	setState(state);
}

function setState (state) {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 

	var url = siteLink+"admin/locations_SetState.php";
	url = url + "?selected=" + state;
	url = url + "&sid=" + Math.random();

	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			document.getElementById("stateResults").innerHTML = xmlHttp.responseText;
			document.searchForm.submit();
		}
	}

	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function suggestCityClose () {
	document.getElementById("cityResults").innerHTML = "";
	document.getElementById("cityResults").style.border = "0px";	
	document.getElementById("cityResults").style.display = "none";
	document.getElementById("cityResults").style.display = "none";	
}

function suggestFacebookAccount (type) {
	var str = escape(document.getElementById("AccountSearch").value);		

	if (str.length == 0) { 
		document.getElementById("accountResults").innerHTML = "";
		document.getElementById("accountResults").style.border = "0px";	
		document.getElementById("accountResults").style.display = "none";
		return;
	}	

	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 

	var url = siteLink+"social/facebook/getUser.php";
	if (type == "pages")
		url = siteLink+"social/facebook/getPage.php";
		
	url = url + "?keyword=" + str;
	url = url + "&sid=" + Math.random();

	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			var result = document.getElementById("accountResults").innerHTML = xmlHttp.responseText;

			if (result.length > 0) {
				document.getElementById("accountResults").style.border = "1px solid #333333";			
				document.getElementById("accountResults").style.display = "block";
			}
			else {
				document.getElementById("accountResults").style.border = "0px";	
				document.getElementById("accountResults").style.display = "none";
			}
		}
	}	

	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function setFacebookAccount (id, name) {
	if (document.getElementById("AccountUser") != null)
		document.getElementById("AccountUser").value = id;
	if (document.getElementById("AccountName") != null)
		document.getElementById("AccountName").value = name;
		
	document.getElementById("AccountSearch").value = "";
	document.getElementById("accountResults").innerHTML = "";
	document.getElementById("accountResults").style.border = "0px";	
	document.getElementById("accountResults").style.display = "none";
}

function suggestAccountClose () {
	document.getElementById("accountResults").innerHTML = "";
	document.getElementById("accountResults").style.border = "0px";	
	document.getElementById("accountResults").style.display = "none";
	document.getElementById("accountResults").style.display = "none";	
}

function suggestOver (div_value) {
	div_value.className = "suggest_link_over";
}

function suggestOut (div_value) {
	div_value.className = "suggest_link";
}

function getNameFromTitle(name, title) {
	var myTitle = document.getElementById(title).value;
	myTitle = myTitle.toLowerCase();
	myTitle = myTitle.replace(/[^a-zA-Z0-9_ ]/g, "");
	myTitle = myTitle.replace(/\s/g, "_");	
	document.getElementById(name).value = myTitle;
}

function getNameFromFields(name, f1, f2) {
	var myTitle = document.getElementById(f1).value+" "+document.getElementById(f2).value;
	myTitle = myTitle.toLowerCase();
	myTitle = myTitle.replace(/\s/g, "_");
	myTitle = myTitle.replace(/[^a-zA-Z0-9_]/g, "");	
	document.getElementById(name).value = myTitle;
}


function getDescFromTitle(name, title) {
	var myTitle = document.getElementById(title).value;
	
	document.getElementById(name).value = myTitle;
}

function copyField(from, to) {
	var html = document.getElementById(from).value;
	var tmp = html.replace(/(<([^>]+)>)/ig,"");	
	document.getElementById(to).value = tmp;
}

function setCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; 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 setFontSize(elmnt, type, defaultSize, size) {
	var minsize = 8;
	var maxsize = 30;
	var normsize = 12;
	var mysize = (elmnt.style.fontSize ? parseInt(elmnt.style.fontSize.replace("px","")) : defaultSize);
	
	 if (size == 0) {
		var initsize = getCookie("textsizestyle_"+type);
		size = initsize ? parseInt(initsize) : mysize;
	}
	else if (size == -1) {
		size = defaultSize;
	}
	  
	if (size > maxsize) {
		size = maxsize;
	} 
	else if (size < minsize) {
		size = minsize;
	}
	
	setCookie("textsizestyle_"+type, size, 365);
	elmnt.style.fontSize = size+"px";
}

function increaseFontSize() {
	for (var i = 0; i < sizeElmnts.length; i++) {
		var p = document.getElementsByTagName(sizeElmnts[i]);
		for (var j = 0; j < p.length; j++) {
			var size = (p[j].style.fontSize ? parseInt(p[j].style.fontSize.replace("px","")) : sizeDefaults[i]);
			setFontSize(p[j], sizeElmnts[i], sizeDefaults[i], size+1);
		}
	}
}

function decreaseFontSize() {
	for (var i = 0; i < sizeElmnts.length; i++) {
		var p = document.getElementsByTagName(sizeElmnts[i]);
		for (var j = 0; j < p.length; j++) {
			var size = (p[j].style.fontSize ? parseInt(p[j].style.fontSize.replace("px","")) : sizeDefaults[i]);
			setFontSize(p[j], sizeElmnts[i], sizeDefaults[i], size-1);
		}
	}
}

function resetFontSize() {
	for (var i = 0; i < sizeElmnts.length; i++) {
		var p = document.getElementsByTagName(sizeElmnts[i]);
		for (var j = 0; j < p.length; j++) {
			setFontSize(p[j], sizeElmnts[i], sizeDefaults[i], -1);
		}
	}
}

function initFontSize() {
	for (var i = 0; i < sizeElmnts.length; i++) {
		var p = document.getElementsByTagName(sizeElmnts[i]);
		for (var j = 0; j < p.length; j++) {
			setFontSize(p[j], sizeElmnts[i], sizeDefaults[i], 0);
		}
	}
}

function changeTemplateLink() {
	var sb = document.getElementById("PageTemplate").value;
	var pt = document.getElementById("previewTemplate");
	pt.href = siteLink+"page_template.php?template="+sb+"&mode=live";
}

function countChars(textbox, textbox2, display) {
	var text = document.getElementById(textbox).value;
	var text2 = document.getElementById(textbox2).value;
	
	var characters = text.length;
	if (text2 != "")
		characters = characters + text2.length + 1;
		
	if (characters > 140)
		document.getElementById(display).innerHTML = "<span class=\"copyred\">Total Characters: "+characters+" / 140</span>";
	else
		document.getElementById(display).innerHTML = "<span class=\"copygrey\">Total Characters: "+characters+" / 140</span>";
}


function countChars2(textbox, display) {
	var text = document.getElementById(textbox).value;
	
	var characters = text.length;
		
	if (characters > 140)
		document.getElementById(display).innerHTML = "<span class=\"copyred\">Total Characters: "+characters+" / 140</span>";
	else
		document.getElementById(display).innerHTML = "<span class=\"copygrey\">Total Characters: "+characters+" / 140</span>";
}

function writeFlash(p) {
	writeEmbed(
		'D27CDB6E-AE6D-11cf-96B8-444553540000',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
		'application/x-shockwave-flash',
		p
	);
}

function writeShockWave(p) {
	writeEmbed(
		'166B1BCA-3F9C-11CF-8075-444553540000',
		'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
		'application/x-director',
		p
	);
}

function writeQuickTime(p) {
	writeEmbed(
		'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
		'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
		'video/quicktime',
		p
	);
}

function writeRealMedia(p) {
	writeEmbed(
		'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
		'audio/x-pn-realaudio-plugin',
		p
	);
}

function writeWindowsMedia(p) {
	p.url = p.src;
	writeEmbed(
		'6BF52A52-394A-11D3-B153-00C04F79FAA6',
		'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
		'application/x-mplayer2',
		p
	);
}

function writeEmbed(cls, cb, mt, p) {
	var h = '', n;
	h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
	h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
	h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
	h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
	h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
	h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
	h += '>';

	for (n in p)
		h += '<param name="' + n + '" value="' + p[n] + '">';

	h += '<embed type="' + mt + '"';

	for (n in p)
		h += n + '="' + p[n] + '" ';

	h += '></embed></object>';

	document.write(h);
}

function stopRKey(evt) {
  evt = evt || window.event;
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if (node.id != "SearchKeywords" && node.id != "SearchKeywordsMain" && evt.keyCode == 13 && (node.type == "text" || node.type == "password")) {return false;}
}
document.onkeypress = stopRKey;

// Image Functions
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];}
}

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_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function calcImgDimensions(fileID, h_w) {
	if (document.getElementById("fileLock_"+fileID).checked) {
		var oldw = parseInt(document.getElementById("fileWidthOld_"+fileID).value);
		var oldh = parseInt(document.getElementById("fileHeightOld_"+fileID).value);
		var w = parseInt(document.getElementById("fileWidth_"+fileID).value);
		var h = parseInt(document.getElementById("fileHeight_"+fileID).value);
		if (h_w == "height") {
			if (document.getElementById("fileHeight_"+fileID).value.length > 0)
				document.getElementById("fileWidth_"+fileID).value = ""+Math.round((h / oldh) * oldw);
			else
				document.getElementById("fileWidth_"+fileID).value = ""+0;
		}
		else if (h_w == "width") {
			if (document.getElementById("fileWidth_"+fileID).value.length > 0)
				document.getElementById("fileHeight_"+fileID).value = ""+Math.round((w / oldw) * oldh);
			else
				document.getElementById("fileHeight_"+fileID).value = ""+0;
		}
		
	}	
}

function popupImg(url,name,maxW,maxH){
	var windowW = parseInt(document.getElementById("MainImageWidth").value);
	var windowH = parseInt(document.getElementById("MainImageHeight").value);
	
	if (windowW > maxW || windowH > maxH) {
		if (windowW > maxW || windowH > maxH) {
			if (windowH > windowW) {
				windowW = Math.round((maxH / windowH) * windowW);
				windowH = maxH;
			}
			else {
				windowH = Math.round((maxW / windowW) * windowH);
				windowW = maxW;
			}
		}
	}
	windowW = windowW + 10;
	winndowH = windowH + 10;
	
	var sr = document.getElementById(url).src;
	sr = sr.substring(0, sr.indexOf('&'));
	
	sr = sr + "&w="+windowW+"&h="+windowH;
	
	myleft=(screen.width)?(screen.width-windowW)/2:100;
	mytop=(screen.height)?(screen.height-windowH)/2:100;
	properties = "width="+windowW+",height="+windowH+",scrollbars=no,menubar=no,toolbar=no,status=no, top="+mytop+",left="+myleft;
	
	window.open(sr,name,properties);
}

function setPopup(w, h, src){
	if (document.getElementById("MainImageWidth") != null)
		document.getElementById("MainImageWidth").value = ""+w;
	if (document.getElementById("MainImageHeight") != null)
		document.getElementById("MainImageHeight").value = ""+h;
	
	if (document.getElementById("modalmain") != null) {
		document.getElementById("modalmain").href = src;
	}
}

// Item Options
function getitemoptions (blockid, itemid, optionid, nextoptionid, value) {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 
	
	var url = siteLink+"getitemoptions.php";
	url = url + "?sid=" + Math.random();	
	url = url + "&blockid="+blockid;
	url = url + "&itemid="+itemid;
	url = url + "&optionid="+optionid;
	url = url + "&nextoptionid="+nextoptionid;
	url = url + "&value="+escape(value);
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			if (nextoptionid > 0) {
				if (document.getElementById("optionselect_"+nextoptionid) != null)
					document.getElementById("optionselect_"+nextoptionid).innerHTML = xmlHttp.responseText;
					
				if (document.getElementById("myitemprice_"+itemid) != null)
					document.getElementById("myitemprice_"+itemid).style.display = "none";
				if (document.getElementById("myitemsaleprice_"+itemid) != null)
					document.getElementById("myitemsaleprice_"+itemid).style.display = "none";
				if (document.getElementById("myitemorigprice_"+itemid) != null)
					document.getElementById("myitemorigprice_"+itemid).style.display = "none";
				if (document.getElementById("myitemqtymsg_"+itemid) != null)
					document.getElementById("myitemqtymsg_"+itemid).style.display = "none";
				if (document.getElementById("addtocart_"+itemid) != null)
					document.getElementById("addtocartoff_"+itemid).style.display = "inline";
				if (document.getElementById("addtocart_"+itemid) != null)
					document.getElementById("addtocart_"+itemid).style.display = "none";
				
				if (document.getElementById("NextOption_"+nextoptionid) != null) {
					var nextnext = document.getElementById("NextOption_"+nextoptionid).value;
					if (nextnext > 0)
						getitemoptions(blockid, itemid, nextoptionid, nextnext, '');
				}
			}
			else {
				showoptionprice(blockid, itemid, value);
			}
		}
	}
	
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function showoptionprice (blockid, itemid, value) {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 
	
	var url = siteLink+"showoptionprice.php";
	 
	url = url + "?sid=" + Math.random();
	
	url = url + "&blockid="+blockid;
	url = url + "&itemid="+itemid;
	url = url + "&value="+escape(value);
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			if (value != "") {
				if (document.getElementById("ItemOptions_"+itemid) != null)
					document.getElementById("ItemOptions_"+itemid).value = xmlHttp.responseXML.documentElement.getElementsByTagName("options")[0].childNodes[0].nodeValue;
				
				var myprice = xmlHttp.responseXML.documentElement.getElementsByTagName("price")[0].childNodes[0].nodeValue;
				var mysaleprice = xmlHttp.responseXML.documentElement.getElementsByTagName("saleprice")[0].childNodes[0].nodeValue;
				var myqty = parseInt(xmlHttp.responseXML.documentElement.getElementsByTagName("qty")[0].childNodes[0].nodeValue);
				var myqtymsg = "";
				if (xmlHttp.responseXML.documentElement.getElementsByTagName("qtymsg")[0].childNodes[0] != null)
					myqtymsg = xmlHttp.responseXML.documentElement.getElementsByTagName("qtymsg")[0].childNodes[0].nodeValue;
				
				if (mysaleprice == "none") {
					if (myprice != "0") {
						if (document.getElementById("myitemprice_"+itemid) != null) {
							document.getElementById("myitemprice_"+itemid).innerHTML = myprice;
							document.getElementById("myitemprice_"+itemid).style.display = "inline";
						}
					}
					else if (document.getElementById("myitemprice_"+itemid) != null) {					
						document.getElementById("myitemprice_"+itemid).style.display = "none";
					}
					
					if (document.getElementById("myitemsaleprice_"+itemid) != null)
						document.getElementById("myitemsaleprice_"+itemid).style.display = "none";
					if (document.getElementById("myitemorigprice_"+itemid) != null)
						document.getElementById("myitemorigprice_"+itemid).style.display = "none";		
					
					if (myqtymsg != "" && document.getElementById("myitemqtymsg_"+itemid) != null) {					
						document.getElementById("myitemqtymsg_"+itemid).innerHTML = myqtymsg;
						document.getElementById("myitemqtymsg_"+itemid).style.display = "inline";
					}
				}
				else {
					if (document.getElementById("myitemorigprice_"+itemid) != null)
						document.getElementById("myitemorigprice_"+itemid).innerHTML = "(Orig. "+ myprice + ")";
					if (document.getElementById("myitemsaleprice_"+itemid) != null)
						document.getElementById("myitemsaleprice_"+itemid).innerHTML = "SALE "+ mysaleprice;
					if (document.getElementById("myitemprice_"+itemid) != null)
						document.getElementById("myitemprice_"+itemid).style.display = "none";
					if (document.getElementById("myitemsaleprice_"+itemid) != null)
					document.getElementById("myitemsaleprice_"+itemid).style.display = "inline";
					if (document.getElementById("myitemorigprice_"+itemid) != null)
						document.getElementById("myitemorigprice_"+itemid).style.display = "inline";
					
					if (myqtymsg != "" && document.getElementById("myitemqtymsg_"+itemid) != null) {
						document.getElementById("myitemqtymsg_"+itemid).innerHTML = myqtymsg;
						document.getElementById("myitemqtymsg_"+itemid).style.display = "inline";
					}
				}
				
				if (myqty > 0) {
					if (document.getElementById("addtocart_"+itemid) != null)					
						document.getElementById("addtocart_"+itemid).style.display = "inline";
					if (document.getElementById("addtocartoff_"+itemid) != null)					
						document.getElementById("addtocartoff_"+itemid).style.display = "none";
				} else {
					if (document.getElementById("addtocart_"+itemid) != null)					
						document.getElementById("addtocart_"+itemid).style.display = "none";
					if (document.getElementById("addtocartoff_"+itemid) != null)					
						document.getElementById("addtocartoff_"+itemid).style.display = "inline";
				}
			}
			else {
				var defaultprice = "";
				var defaultsaleprice = "";
				if (document.getElementById("defaultsaleprice_"+itemid) != null)					
					defaultsaleprice = document.getElementById("defaultsaleprice_"+itemid).value;
				if (document.getElementById("defaultprice_"+itemid) != null)					
					defaultprice = document.getElementById("defaultprice_"+itemid).value;
				
				if (defaultsaleprice != "") {
					if (document.getElementById("myitemsaleprice_"+itemid) != null)	{				
						document.getElementById("myitemsaleprice_"+itemid).innerHTML = defaultsaleprice;
						document.getElementById("myitemsaleprice_"+itemid).style.display = "inline";
					}
				
					if (document.getElementById("myitemorig	price_"+itemid) != null) {				
						document.getElementById("myitemorigprice_"+itemid).innerHTML = defaultprice;
						document.getElementById("myitemorigprice_"+itemid).style.display = "inline";
					}
					
					if (document.getElementById("myitemprice_"+itemid) != null)					
						document.getElementById("myitemprice_"+itemid).style.display = "none";
				}
				else {
					if (document.getElementById("myitemprice_"+itemid) != null)	{				
						document.getElementById("myitemprice_"+itemid).innerHTML = defaultprice;
						document.getElementById("myitemprice_"+itemid).style.display = "inline";
					}
					
					if (document.getElementById("myitemsaleprice_"+itemid) != null)					
						document.getElementById("myitemsaleprice_"+itemid).style.display = "none";
					if (document.getElementById("myitemorigprice_"+itemid) != null)					
						document.getElementById("myitemorigprice_"+itemid).style.display = "none";
				}
				
				if (document.getElementById("addtocart_"+itemid) != null)					
					document.getElementById("addtocart_"+itemid).style.display = "none";
				if (document.getElementById("addtocartoff_"+itemid) != null)					
					document.getElementById("addtocartoff_"+itemid).style.display = "inline";
				if (document.getElementById("myitemqtymsg_"+itemid) != null)					
					document.getElementById("myitemqtymsg_"+itemid).style.display = "none";
			}
		}
	}	
	
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

// Google Maps
function GMapIt(id, lat, lon, title, text, zoom) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(id));
		map.setCenter(new GLatLng(lat, lon), zoom);
		map.setUIToDefault();
		
		function createMarker(point, index) {	
			var markerOptions = { title: title };
			var infoOptions = { maxWidth: 175 };
			var marker = new GMarker(point, markerOptions);
			
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(text, infoOptions);
			});
			
			return marker;
		}
		
		var latlng = new GLatLng(lat, lon);
		var mymarker = createMarker(latlng, 0);
		map.addOverlay(mymarker);
	}
}

function GMapIt2(id, lat, lon, title, text, zoom, maplink, dirlink) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(id));
		map.setCenter(new GLatLng(lat, lon), zoom);
		map.setUIToDefault();
		
		function createMarker(point, index) {	
			var markerOptions = { title: title };
			var infoOptions = { maxWidth: 175 };
			var marker = new GMarker(point, markerOptions);
			text += "<br /><br /><a href=\""+maplink+"\" target=\"_blank\">View Larger Map</a>";
			text += " - <a href=\""+dirlink+"\" target=\"_blank\">Get Directions</a>";
			
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(text, infoOptions);
			});
			
			return marker;
		}
		
		var latlng = new GLatLng(lat, lon);
		var mymarker = createMarker(latlng, 0);
		map.addOverlay(mymarker);
	}
}

// File Attachments/Uploads
function newFileUpload () {
	 if (document.getElementById("total_files") != null)
	 	var totFiles = parseInt(document.getElementById("total_files").value);
	else
	 	var totFiles = 0;
	
	 if (document.getElementById("max_files") != null)
	 	var maxFiles = parseInt(document.getElementById("max_files").value);
	else
	 	var maxFiles = 10;
	
	 var upFiles = parseInt(document.getElementById("files_working").value);
	 var uploadDir = document.getElementById("dirName").value;
	
	if (totFiles >= maxFiles) {
		var plural = "";
		if (maxFiles > 1)
			plural = "s";
		alert("You may not attach more than "+maxFiles+" file"+plural+".");
	}
	else if (upFiles != 0) {
		alert("You may only upload one file at a time.  Please wait.");
	}
	else {
		 var tbl = document.getElementById("newFileTable");
		 if (tbl == null)
		 	return;
		 
		 var tblBody = tbl.tBodies[0];
		 var newNode = tblBody.rows[0].cloneNode(true);
		 
		 newNode.id = "newFileUpRow";
		 newNode.getElementsByTagName('td')[0].innerHTML = "Upload File &nbsp;&nbsp;";
		 newNode.getElementsByTagName('td')[1].innerHTML = "<form enctype=\"multipart/form-data\" action=\"files_UpFile.php\" method=\"post\" target=\"iframe_file\" name=\"uploadForm\" id=\"uploadForm\"><input type=\"file\" name=\"upNewFile\" id=\"upNewFile\" /> &nbsp;&nbsp; <img src=\"images/btn-upload.jpg\" alt=\"upload\" width=\"115\" height=\"29\" id=\"fileUp\" onclick=\"uploadNewFile()\" align=\"top\" /><input type=\"hidden\" name=\"uploadDir\" id=\"uploadDir\" value=\""+uploadDir+"\" /></form>";
		newNode.getElementsByTagName('td')[2].innerHTML = "<img src=\"images/check.png\" alt=\"ok\" width=\"22\" height=\"22\" id=\"fileOK\" onclick=\"newFileSelect()\" style=\"display:none\" />&nbsp;&nbsp;<img src=\"images/delete.png\" alt=\"cancel\" width=\"22\" height=\"22\" onclick=\"newFileCancel()\" id=\"fileCancel\" />";
		
		tblBody.replaceChild(newNode, tblBody.rows[0]);
	}
}

function newFileUploadOnly () {
	 if (document.getElementById("total_files") != null)
	 	var totFiles = parseInt(document.getElementById("total_files").value);
	else
	 	var totFiles = 0;
	
	 if (document.getElementById("max_files") != null)
	 	var maxFiles = parseInt(document.getElementById("max_files").value);
	else
	 	var maxFiles = 10;
	 var upFiles = parseInt(document.getElementById("files_working").value);
	 var uploadDir = document.getElementById("dirName").value;
	
	if (totFiles >= maxFiles) {
		var plural = "";
		if (maxFiles > 1)
			plural = "s";
		alert("You may not attach more than "+maxFiles+" file"+plural+".");
	}
	else if (upFiles != 0) {
		alert("You may only upload one file at a time.  Please wait.");
	}
	else {
		 var tbl = document.getElementById("newFileTable");
		 if (tbl == null)
		 	return;
		 
		 var tblBody = tbl.tBodies[0];
		 var newNode = tblBody.rows[0].cloneNode(true);
		 
		 newNode.id = "newFileUpRow";
		 newNode.getElementsByTagName('td')[0].innerHTML = "Upload File &nbsp;&nbsp;";
		 newNode.getElementsByTagName('td')[1].innerHTML = "<form enctype=\"multipart/form-data\" action=\"files_Upload.php\" method=\"post\" target=\"iframe_file\" name=\"uploadForm\" id=\"uploadForm\"><input type=\"file\" name=\"upNewFile\" id=\"upNewFile\" /> &nbsp;&nbsp; <img src=\"images/btn-upload.jpg\" alt=\"upload\" width=\"115\" height=\"29\" id=\"fileUp\" onclick=\"uploadNewFileOnly()\" align=\"top\" /><input type=\"hidden\" name=\"uploadDir\" id=\"uploadDir\" value=\""+uploadDir+"\" /></form>";
		newNode.getElementsByTagName('td')[2].innerHTML = "&nbsp;";
		
		tblBody.replaceChild(newNode, tblBody.rows[0]);
	}
}

function newFileSelect (selfile) {
	 if (document.getElementById("total_files") != null)
	 	var totFiles = parseInt(document.getElementById("total_files").value);
	else
	 	var totFiles = 0;
	
	 if (document.getElementById("max_files") != null)
	 	var maxFiles = parseInt(document.getElementById("max_files").value);
	else
	 	var maxFiles = 10;
	
	if (totFiles >= maxFiles) {
		var plural = "";
		if (maxFiles > 1)
			plural = "s";
		alert("You may not attach more than "+maxFiles+" file"+plural+".");
	}
	else {
		 var tblBody = document.getElementById("newFileTable").tBodies[0];
		 var newNode = tblBody.rows[0].cloneNode(true);
		 
		 filePreview = "<div id=\"filePreview\" style=\"display:none;z-index:150;\"></div> <img src=\"images/zoom.png\" alt=\"preview\" width=\"22\" height=\"22\" id=\"preview\" onmouseover=\"previewFile()\" onmouseout=\"previewFileClose()\" style=\"display:none;\" \>&nbsp;&nbsp;";
		 
		 newNode.id = "newFileSelRow";
		 newNode.getElementsByTagName('td')[0].innerHTML = "Select File &nbsp;&nbsp;";
		 newNode.getElementsByTagName('td')[1].innerHTML = "<div id=\"selNewFileDiv\"><select name=\"selNewFile\" id=\"selNewFile\" onchange=\"checkFileSelect(this.value)\"></select></div>";	
		 newNode.getElementsByTagName('td')[2].innerHTML = filePreview + "<img src=\"images/check.png\" alt=\"ok\" width=\"22\" height=\"22\" id=\"fileOK\" style=\"display: none\" onclick=\"addNewFile()\" />&nbsp;&nbsp;<img src=\"images/delete.png\" alt=\"cancel\" width=\"22\" height=\"22\" onclick=\"newFileCancel()\" id=\"fileCancel\" />";
		
		tblBody.replaceChild(newNode, tblBody.rows[0]);
		
	 	var uploadDir = document.getElementById("dirName").value;
		showFilesInDir(uploadDir, selfile);
		
		if (selfile != "-1" && selfile.length > 0  && selfile != "none")		
			document.getElementById("fileOK").style.display = "inline";
	}
}

function newFileCancel () {
	 var tblBody = document.getElementById("newFileTable").tBodies[0];
	 var newNode = tblBody.rows[0].cloneNode(true);
	 
	 newNode.id = "newFileRow";
	 newNode.getElementsByTagName('td')[0].innerHTML = "Attach File &nbsp;&nbsp;";
	 newNode.getElementsByTagName('td')[1].innerHTML = "<input type=\"image\" class=\"button\" id=\"uploadFile\" name=\"uploadFile\" src=\"images/btn-uploadnewfile.jpg\" width=\"196\" height=\"28\" align=\"middle\" alt=\"Upload New File\" onclick=\"newFileUpload();return false;\" /> &nbsp;or&nbsp; <input type=\"image\" class=\"button\" id=\"selectFile\" name=\"selectFile\"  src=\"images/btn-selectexistingfile.jpg\" width=\"196\" height=\"28\ alt=\"Choose Existing File\" align=\"middle\" onclick=\"newFileSelect('');return false;\" />";	
	 newNode.getElementsByTagName('td')[2].innerHTML = "&nbsp;";
	
	tblBody.replaceChild(newNode, tblBody.rows[0]);
}

function showFilesInDir(dir, selfile) {	
	var xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 
	
	var fileTypes = "all";
	if (document.getElementById("file_types") != null)
		fileTypes = document.getElementById("file_types").value;
	
	var url = "files_GetDir.php";
	url = url + "?sid=" + Math.random();
	url = url + "&fileTypes=" + fileTypes;
	
	if (dir.length > 0) {
		url = url + "&dir=" + dir;
	}
	
	if (selfile.length > 0) {
		url = url + "&file=" + selfile;
	}
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			document.getElementById("selNewFileDiv").innerHTML = "<select name=\"selNewFile\" id=\"selNewFile\" onchange=\"checkFileSelect(this.value)\">"+xmlHttp.responseText+"</select>";	
		}
	}
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function checkFileSelect(file) {	
	if (file != "-1")	{	
		document.getElementById("fileOK").style.display = "inline";
		
		 var ext = "";
		 var imgPreview = ""
		 if (file.lastIndexOf(".") != -1) {
			ext = file.substr(file.lastIndexOf("."), file.length);
			if (ext == ".gif" || ext == ".jpg" || ext == ".png") {
				document.getElementById("preview").style.display = "inline";
			}
		 }
		 else {
			document.getElementById("preview").style.display = "none";
		 }
	}
	else {
		document.getElementById("fileOK").style.display = "none";
	}
}

function previewFile() {
	var file = document.getElementById("selNewFile").value;
	var ext = "";
	if (file.lastIndexOf(".") != -1 )
		ext = file.substr(file.lastIndexOf("."), file.length); 
	
	if (file != "-1" && (ext == ".gif" || ext == ".jpg" || ext == ".png")) {
	 	var uploadDir = document.getElementById("dirName").value;	
		document.getElementById("filePreview").innerHTML = "<img src=\"../phpThumb/phpThumb.php?src=../uploads/"+uploadDir+"/"+file+"&w=100\" />";
		document.getElementById("filePreview").style.display = "inline";
	}
}

function previewFileClose() {	
	document.getElementById("filePreview").innerHTML = "";
	document.getElementById("filePreview").style.display = "none";	
}

function uploadNewFile() {
	if (document.getElementById("upNewFile").value == "")
		return;		
	
	var upFiles = parseInt(document.getElementById("files_working").value);
	if (upFiles != 0) {
		alert("You may only upload one file at a time.  Please wait.");
	}
	else {		  
	 var tblBody = document.getElementById("newFileTable").tBodies[0];
	 var newNode = tblBody.rows[0].cloneNode(true);
	 
	 newNode.id = "fileWaitRow";
	 newNode.getElementsByTagName('td')[0].innerHTML = "Uploading... &nbsp;&nbsp;";
	 newNode.getElementsByTagName('td')[1].innerHTML = "<img src=\"images/progress.gif\" alt=\"uploading\" width=\"190\" height=\"14\" id=\"fileWait\" />";
	newNode.getElementsByTagName('td')[2].innerHTML = "<img src=\"images/check.png\" alt=\"ok\" width=\"22\" height=\"22\" id=\"fileOK\" onclick=\"newFileSelect()\" style=\"display:none\" />&nbsp;&nbsp;<img src=\"images/delete.png\" alt=\"cancel\" width=\"22\" height=\"22\" onclick=\"newFileCancel()\" id=\"fileCancel\" />";
		
        document.uploadForm.submit();
		tblBody.replaceChild(newNode, tblBody.rows[0]);
      }
}

function uploadNewFileOnly() {
	if (document.getElementById("upNewFile").value == "")
		return;
	
	var upFiles = parseInt(document.getElementById("files_working").value);
	if (upFiles != 0) {
		alert("You may only upload one file at a time.  Please wait.");
	}
	else {		  
	 var tblBody = document.getElementById("newFileTable").tBodies[0];
	 var newNode = tblBody.rows[0].cloneNode(true);
	 
	 newNode.id = "fileWaitRow";
	 newNode.getElementsByTagName('td')[0].innerHTML = "Uploading... &nbsp;&nbsp;";
	 newNode.getElementsByTagName('td')[1].innerHTML = "<img src=\"images/progress.gif\" alt=\"uploading\" width=\"190\" height=\"14\" id=\"fileWait\" />";
	newNode.getElementsByTagName('td')[2].innerHTML = "<img src=\"images/delete.png\" alt=\"cancel\" width=\"22\" height=\"22\" onclick=\"newFileUploadOnly()\" id=\"fileCancel\" />";
		
        document.uploadForm.submit();
		tblBody.replaceChild(newNode, tblBody.rows[0]);
      }
}

function fileDone (file) {
	newFileSelect(file);
	
	var upFiles = parseInt(document.getElementById("files_working").value);
	document.getElementById("files_working").value = 0;
}

function fileDoneUploadOnly (file) {
	newFileUploadOnly();
	
	var upFiles = parseInt(document.getElementById("files_working").value);
	document.getElementById("files_working").value = 0;
}

function addNewFile() {
	var file = document.getElementById("selNewFile").value;
	 var recordID = document.getElementById("recordID").value;
	 var dirName = document.getElementById("dirName").value;
	 var tableName = document.getElementById("tableName").value;
	var recordField = document.getElementById("record_field").value;
	
	var fileTypes = "all";
	if (document.getElementById("file_types") != null)
		fileTypes = document.getElementById("file_types").value;
	
	 var totFiles = parseInt(document.getElementById("total_files").value);
	 var maxFiles = parseInt(document.getElementById("max_files").value);
	
	if (totFiles >= maxFiles) {
		var plural = "";
		if (maxFiles > 1)
			plural = "s";
		alert("You may not attach more than "+maxFiles+" file"+plural+".");
	}	
	else if (file != "-1" && file != "") {
		var xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null) {
			alert ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "files_AddFileDB.php";
		url = url + "?sid=" + Math.random();
		url = url + "&tableName="+tableName;
		url = url + "&dirName="+dirName;
		url = url + "&file=" + file;
		url = url + "&recordID=" + recordID;
		url = url + "&recordField="+recordField;
		url = url + "&fileTypes=" + fileTypes;
		
		var label = file.substr(0, file.lastIndexOf("."));
		url = url + "&fileLabel="+label;
		
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4) {
				var newfile = parseInt(xmlHttp.responseText);
				
				if (newfile > 0)
					getAttachments(newfile);	
				else if (newfile == -1)
					alert("Wrong file type.  Please try another file.");
				else
					alert("Cannot attach the file.  Please try another file.");
					
				newFileCancel();
			}
		}
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
	document.getElementById("total_files").value = totFiles+1;
}

function getAttachments(fileid) {	
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	}
	
	var recordID = document.getElementById("recordID").value;
	var dirName = document.getElementById("dirName").value;
	var tableName = document.getElementById("tableName").value;
	var formName = document.getElementById("formName").value;
	var recordField = document.getElementById("record_field").value;
	
	var listType = "columns";
	if (document.getElementById("file_list_type") != null)
		listType = document.getElementById("file_list_type").value;
	
	var fileTypes = "all";
	if (document.getElementById("file_types") != null)
		fileTypes = document.getElementById("file_types").value;
	
	var numFields = -1;
	if (document.getElementById("num_file_fields") != null)
		numFields = parseInt(document.getElementById("num_file_fields").value);
		
	var fileFields = "";
	var fileTitles = "";
	var fileRequired = "";
	var sep = "";
	if (numFields > 1) {
		var i;
		for (i = 1; i <= numFields; i++) {
			fileFields = fileFields + sep + document.getElementById("file_field_"+i).value;
			fileTitles = fileTitles + sep + document.getElementById("file_title_"+i).value;
			fileRequired = fileRequired + sep + document.getElementById("file_required_"+i).value;
			sep = "[NF]";
		}
	} else if (numFields == 1) {
		fileFields = document.getElementById("file_field").value;
		fileTitles = document.getElementById("file_title").value;
		fileRequired = document.getElementById("file_required").value;
	} else if (numFields == 0) {
		fileFields = "none";
		fileTitles = "none";
		fileRequired = "none";
	} else {
		newFileUploadOnly();
		return;
	}
	
	var url = "files_GetAttachments.php";
	if (listType == "rows")
		url = "files_GetAttachments2.php";	
	
	url = url + "?sid=" + Math.random();
	url = url + "&tableName="+tableName;
	url = url + "&formName="+formName;
	url = url + "&recordID=" + recordID;
	url = url + "&recordField="+recordField;
	url = url + "&fileFields=" + fileFields;
	url = url + "&fileTitles=" + fileTitles;
	url = url + "&fileRequired=" + fileRequired;
	url = url + "&fileTypes=" + fileTypes;
	
	if (fileid > 0)
		url = url + "&newFile=" + fileid;
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			document.getElementById("myFileAttachments").innerHTML = xmlHttp.responseText;
		}
	}
	
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function deleteAttachment(fileID) {	
	if (confirm("Are you sure you want to detach this file?")) {
		xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null) {
			alert ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "files_DeleteFileDB.php";
		var tableName = document.getElementById("tableName").value;
		var recordField = document.getElementById("record_field").value;
		var numFields = parseInt(document.getElementById("num_file_fields").value);
		
		var fileFields = "";
		var sep = "";
		if (numFields > 1) {
			for (var i = 1; i <= numFields; i++) {
				fileFields += sep + document.getElementById("file_field_"+i).value;
				sep = "[NF]";
			}
		} else if (numFields == 1) {
			fileFields = document.getElementById("file_field").value;
		} else if (numFields == 0) {
			fileFields = "none";
		} 
		 
		url = url + "?sid=" + Math.random();
		
		if (fileID != "-1") { 
			url = url + "&fileID="+fileID;
			url = url + "&tableName="+tableName;
			url = url + "&recordField="+recordField;
			url = url + "&fileFields="+fileFields;			
		}
		
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4) {
				 getAttachments(0);		
			}
		}
		
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
}

function openKCFinder2(field) {
    window.KCFinder = {
        callBack: function(url) {
            window.KCFinder = null;
            if (url != "") KCAddNewFile(url);
        }
    };
	
	var totFiles = parseInt(document.getElementById("total_files").value);
	var maxFiles = parseInt(document.getElementById("max_files").value);
	
	if (totFiles >= maxFiles) {
		var plural = "";
		if (maxFiles > 1)
			plural = "s";
		alert("You may not attach more than "+maxFiles+" file"+plural+".");
	}	
	else {
		var dir = "files";
		if (document.getElementById("dirName") != null)
			dir += "/" + document.getElementById("dirName").value;
			
		window.open('../kcfinder/browse.php?type=files&opener=custom&dir='+dir, 'kcfinder_textbox',
			'status=0, toolbar=0, location=0, menubar=0, directories=0, ' +
			'resizable=1, scrollbars=0, width=900, height=600'
		);
	}
}

function openKCFinderTxt(field, dir) {
    window.KCFinder = {
        callBack: function(url) {
            window.KCFinder = null;
			var relLink = siteLink.substr(siteLink.indexOf('/', 7));
			url = url.replace(relLink, '');			
            var txt = document.getElementById(field);
			txt.value = url;
		}
    };
	
	if (dir != "")
		dir = "files/" + dir;
	else
		dir = "files";
			
	window.open('../kcfinder/browse.php?type=files&opener=custom&dir='+dir, 'kcfinder_textbox',
		'status=0, toolbar=0, location=0, menubar=0, directories=0, ' +
		'resizable=1, scrollbars=0, width=900, height=600'
	);
	
	// Selected file: <input type="text" readonly="readonly" onclick="openKCFinderTxt(this), '')" value="Click here and select a file double clicking on it" style="width:600px;cursor:pointer" />
 

}

function openKCFinderImg(div, dir) {
    window.KCFinder = {
        callBack: function(url) {
            window.KCFinder = null;
            div.innerHTML = '<div style="margin:5px">Loading...</div>';
            var img = new Image();
            img.src = url;
            img.onload = function() {
                div.innerHTML = '<img id="img" src="' + url + '" />';
                var img = document.getElementById('img');
                var o_w = img.offsetWidth;
                var o_h = img.offsetHeight;
                var f_w = div.offsetWidth;
                var f_h = div.offsetHeight;
                if ((o_w > f_w) || (o_h > f_h)) {
                    if ((f_w / f_h) > (o_w / o_h))
                        f_w = parseInt((o_w * f_h) / o_h);
                    else if ((f_w / f_h) < (o_w / o_h))
                        f_h = parseInt((o_h * f_w) / o_w);
                    img.style.width = f_w + "px";
                    img.style.height = f_h + "px";
                } else {
                    f_w = o_w;
                    f_h = o_h;
                }
                img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
                img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
                img.style.visibility = "visible";
            }
        }
    };
	
	if (dir != "")
		dir = "files/" + dir;
	else
		dir = "files";
			
	window.open('../kcfinder/browse.php?type=files&opener=custom&dir='+dir, 'kcfinder_image',
		'status=0, toolbar=0, location=0, menubar=0, directories=0, ' +
		'resizable=1, scrollbars=0, width=900, height=600'
	);
	
	// <div class="KCImage" onclick="openKCFinderImg(this, '')"><div style="margin:5px">Click here to choose an image</div></div>
}

function openKCFinderCombo(div, dir, field) {
    window.KCFinder = {
        callBack: function(url) {
            window.KCFinder = null;
			var relLink = siteLink.substr(siteLink.indexOf('/', 7));
			url = url.replace(relLink, '');			
            var txt = document.getElementById(field);
			txt.value = url;
			url = siteLink + url;			

            div.innerHTML = '<div style="margin:5px">Loading...</div>';
            var img = new Image();
            img.src = url;
            img.onload = function() {
                div.innerHTML = '<img id="KCImg_' + field + '" src="' + url + '" />';
                var img = document.getElementById('KCImg_' + field);
                var o_w = img.offsetWidth;
                var o_h = img.offsetHeight;
                var f_w = div.offsetWidth;
                var f_h = div.offsetHeight;
                if ((o_w > f_w) || (o_h > f_h)) {
                    if ((f_w / f_h) > (o_w / o_h))
                        f_w = parseInt((o_w * f_h) / o_h);
                    else if ((f_w / f_h) < (o_w / o_h))
                        f_h = parseInt((o_h * f_w) / o_w);
                    img.style.width = f_w + "px";
                    img.style.height = f_h + "px";
                } else {
                    f_w = o_w;
                    f_h = o_h;
                }
                img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
                img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
                div.style.paddingLeft = 0 + 'px';
                div.style.paddingTop = 0 + 'px';
                img.style.visibility = "visible";
            }
        }
    };
	
	if (dir != "")
		dir = "files/" + dir;
	else
		dir = "files";
			
	window.open('../kcfinder/browse.php?type=files&opener=custom&dir='+dir, 'kcfinder_image',
		'status=0, toolbar=0, location=0, menubar=0, directories=0, ' +
		'resizable=1, scrollbars=0, width=900, height=600'
	);
	
	// <div class="KCImage" onclick="openKCFinderImg(this, '')"><div style="margin:5px">Click here to choose an image</div></div>
}

function loadKCFinderCombo(field) {
	var div = document.getElementById('KC_' + field);
	var txt = document.getElementById(field);
	var url = txt.value;
	
	if (url == "") {
		div.innerHTML = '<div style="margin:5px">Click here to choose an image</div>';
		return;
	}
	url = siteLink + url;
	
    div.innerHTML = '<div style="margin:5px">Loading...</div>';
    var img = new Image();
    img.src = url;
    img.onload = function() {
    	div.innerHTML = '<img id="KCImg_' + field + '" src="' + url + '" />';
        var img = document.getElementById('KCImg_' + field);
        var o_w = img.offsetWidth;
        var o_h = img.offsetHeight;
        var f_w = div.offsetWidth;
        var f_h = div.offsetHeight;
		if ((o_w > f_w) || (o_h > f_h)) {
			if ((f_w / f_h) > (o_w / o_h))
				f_w = parseInt((o_w * f_h) / o_h);
			else if ((f_w / f_h) < (o_w / o_h))
				f_h = parseInt((o_h * f_w) / o_w);
			img.style.width = f_w + "px";
			img.style.height = f_h + "px";
		} else {
			f_w = o_w;
			f_h = o_h;
		}
		img.style.marginLeft = parseInt((div.offsetWidth - f_w) / 2) + 'px';
		img.style.marginTop = parseInt((div.offsetHeight - f_h) / 2) + 'px';
		div.style.paddingLeft = 0 + 'px';
		div.style.paddingTop = 0 + 'px';
		img.style.visibility = "visible";
	}
}

function unloadKCFinderCombo(field) {
	var div = document.getElementById('KC_' + field);
	var txt = document.getElementById(field);
	txt.value = '';
	div.innerHTML = '<div style="margin:5px">Click here to choose an image</div>';
	
}

function KCAddNewFile(file) {
	var recordID = document.getElementById("recordID").value;
	var tableName = document.getElementById("tableName").value;
	var recordField = document.getElementById("record_field").value;
	
	var fileTypes = "all";
	if (document.getElementById("file_types") != null)
		fileTypes = document.getElementById("file_types").value;
	
	 var totFiles = parseInt(document.getElementById("total_files").value);
	 var maxFiles = parseInt(document.getElementById("max_files").value);
	
	if (totFiles >= maxFiles) {
		var plural = "";
		if (maxFiles > 1)
			plural = "s";
		alert("You may not attach more than "+maxFiles+" file"+plural+".");
	}	
	else if (file != "") {
		var xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null) {
			alert ("Your browser does not support AJAX!");
			return;
		} 
		
		var url = "files_KCAddFileDB.php";
		url = url + "?sid=" + Math.random();
		url = url + "&tableName="+tableName;
		url = url + "&file=" + file;
		url = url + "&recordID=" + recordID;
		url = url + "&recordField="+recordField;
		url = url + "&fileTypes=" + fileTypes;
		
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4) {
				var newfile = parseInt(xmlHttp.responseText);
				
				if (newfile > 0) {
					getAttachments(newfile);	
				}
				else {
					document.getElementById("total_files").value = totFiles;
					if (newfile == -1)
						alert("Wrong file type.  Please try another file.");
					else
						alert("Cannot attach the file.  Please try another file.");
				}
			}
		}
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
		
		document.getElementById("total_files").value = totFiles+1;
	}
	else {
		alert("Cannot attach the file.  Please try another file.");
	}
}

// Validation
function WAAddError(formElement,errorMsg,focusIt,stopIt)  {
  if (document.WAFV_Error)  {
	  document.WAFV_Error += "\n" + errorMsg;
  }
  else  {
    document.WAFV_Error = errorMsg;
  }
  if (!document.WAFV_InvalidArray)  {
    document.WAFV_InvalidArray = new Array();
  }
  document.WAFV_InvalidArray[document.WAFV_InvalidArray.length] = formElement;
  if (focusIt && !document.WAFV_Focus)  {
	document.WAFV_Focus = focusIt;
  }
  if (stopIt == 1)  {
	document.WAFV_Stop = true;
  }
  else if (stopIt == 2)  {
	formElement.WAFV_Continue = true;
  }
  else if (stopIt == 3)  {
	formElement.WAFV_Stop = true;
	formElement.WAFV_Continue = false;
  }
}

function WAValidateFE(formElement,value,errorMsg,extensions,focusIt,stopIt,required)  {
  var isValid = true;
  extensions = extensions.replace(/\s*,\s*/g,",");
  var ExtensionArr = extensions.split(",");
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    isValid = false;
    if (value.lastIndexOf(".") > 0)     {
      value = value.substring(value.lastIndexOf("."));
      for (var n=0; n<ExtensionArr.length; n++)     {
        ExtensionArr[n] = ExtensionArr[n].replace(/ /g,"");
        if (value.toLowerCase() == ExtensionArr[n].toLowerCase())     {
          isValid = true;
        }
      }
	}
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAtrimIt(theString,leaveLeft,leaveRight)  {
  if (!leaveLeft)  {
    while (theString.charAt(0) == " ")
      theString = theString.substring(1);
  }
  if (!leaveRight)  {
    while (theString.charAt(theString.length-1) == " ")
      theString = theString.substring(0,theString.length-1);
  }
  return theString;
}

function WAFV_GetValueFromInputType(formElement,inputType,trimWhite) {
  var value="";
  if (inputType == "select")  {
    if (formElement.selectedIndex != -1 && formElement.options[formElement.selectedIndex].value && formElement.options[formElement.selectedIndex].value != "") {
      value = formElement.options[formElement.selectedIndex].value;
    }
  }
  else if (inputType == "checkbox")  {
    if (formElement.length)  {
      for (var x=0; x<formElement.length ; x++)  {
        if (formElement[x].checked && formElement[x].value!="")  {
          value = formElement[x].value;
          break;
        }
      }
    }
    else if (formElement.checked)
      value = formElement.value;
  }
  else if (inputType == "radio")  {
    if (formElement.length)  {
      for (var x=0; x<formElement.length; x++)  {
        if (formElement[x].checked && formElement[x].value!="")  {
          value = formElement[x].value;
          break;
        }
      }
    }
    else if (formElement.checked)
      value = formElement.value;
  }
  else if (inputType == "radiogroup")  {
    for (var x=0; x<formElement.length; x++)  {
      if (formElement[x].checked && formElement[x].value!="")  {
        value = formElement[x].value;
        break;
      }
    }
  }
  else  {
    var value = formElement.value;
  }
  if (trimWhite)  {
    value = WAtrimIt(value);
  }
  return value;
}


function WAValidateRQ(formElement,errorMsg,focusIt,stopIt,trimWhite,inputType)  {
  var isValid = true;
  if (!document.WAFV_Stop && !formElement.WAFV_Stop)  {
    var value=WAFV_GetValueFromInputType(formElement,inputType,trimWhite);
    if (value == "")  {
	    isValid = false;
    }
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAValidateAN(formElement,value,errorMsg,allowUpper,allowLower,allowNumbers,allowSpace,extraChars,focusIt,stopIt,required)  {
  var isValid = true;
  extraChars = extraChars.replace(/&quot;/g,'"');
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) || formElement.WAFV_Continue)  {
    for (var x=0; x<value.length; x++)  {
	  var charGood = false;
	  var nextChar = value.charAt(x);
	  var charCode = value.charCodeAt(x);
	  if (allowLower)  {
	    if (charCode >= 97 && charCode <= 122)  {
		  charGood = true;
		}
	  }
	  if (allowUpper)  {
	    if (charCode >= 65 && charCode <= 90)  {
		  charGood = true;
		}
	  }
	  if (allowNumbers)  {
	    if (charCode >= 48 && charCode <= 57)  {
		  charGood = true;
		}
	  }
	  if (allowSpace)  {
	    if (nextChar == " ")  {
		  charGood = true;
		}
	  }
	  if (extraChars)  {
	    if (unescape(extraChars).indexOf(nextChar) >= 0)  {
		  charGood = true;
		}
	  }
	  if (!charGood)  {
	    isValid = false;
		x = value.length;
	  }
	}
	if (required && value=="")
	  isValid = false;
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAValidateZC(formElement,errorMsg,us5,us9,can6,uk,reformat,focusIt,stopIt,required)  {
  var value = formElement.value;
  var isValid = true;
  var allowed = "() -.\n\r";
  var hasLetters = false;
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    var newVal = "";
    var charVal = "";
    for (var x=0; x<value.length; x++)  {
      var z = value.charAt(x);
      if ((z >= "0") && (z <= "9")) {
        newVal += z;
        charVal += "N";
      }
      else  {
        if ((uk || can6) && ((z >= "a") && (z <= "z")) || ((z >= "A") && (z <= "Z"))) {
          charVal += "A";
          hasLetters = true;
        }
        else if (allowed.indexOf(z) < 0 || x==0 || x == value.length-1)  {
          isValid = false;
        }
      }
    }
    if ((uk || can6) && hasLetters)  {
      var acceptPattern = "";
      if (uk)  {
        acceptPattern += ",ANNAA,ANNNAA,AANNAA,AANNNAA,ANANAA,AANANAA,";
      }
      if (can6)  {
        acceptPattern += ",ANANAN,";
      }
      if (String(acceptPattern).indexOf(","+charVal+",") < 0)
        isValid = false;
    }
    if (!((uk && (charVal.length >= 5 &&  charVal.length <= 8)) || (us5 && newVal.length == 5) || (us9 && newVal.length == 9) || (can6 && charVal.length == 6)))  {
      isValid = false;
    }
    if (isValid && !hasLetters && (us5 || us9)) {
      if (us5) {
        isValid = (value.search(/^\d{5}$/) == 0);
      }
      if (us9 && ((us5 && !isValid) || !us5)) {
        isValid = ((value.search(/^\d{5}[-\. ]\d{4}$/) == 0) || (value.search(/^\d{9}$/) == 0));
      }
    }
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
  else  {
    if (reformat != "")  {
      if (reformat != "t")  {
        for (var x=0; x<newVal.length; x++)  {
          reformat = reformat.substring(0,reformat.indexOf("x")) + newVal.charAt(x) + reformat.substring(reformat.indexOf("x")+1);
        }
        if (reformat.indexOf("x")>=0)  {
          reformat = reformat.substring(0,reformat.indexOf("x"));
          while (reformat.charAt(reformat.length-1) == " " || reformat.charAt(reformat.length-1) == "-")
            reformat = reformat.substring(0,reformat.length-1);
          z = reformat.charAt(reformat.length-1);
        }
        if (newVal.length==6)
          reformat = reformat.replace(/-/,"");
      }
      else  {
        newVal = formElement.value;
        while (newVal.charAt(0) == " ")
          newVal = newVal.substring(1);
        while (newVal.charAt(newVal.length-1) == " ")
          newVal = newVal.substring(0,newVal.length-1);
        reformat = newVal;
      }
      formElement.value = reformat;
    }
  }
}

function WAValidatePN(formElement,errorMsg,areaCode,international,reformat,focusIt,stopIt,required)  {
  var value = formElement.value;
  var isValid = true;
  var allowed = "*() -./_\n\r+";
  var newVal = "";
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    for (var x=0; x<value.length; x++)  {
      var z = value.charAt(x);
      if ((z >= "0") && (z <= "9")) {
	    newVal += z;
	  }
	  else  {
		if (allowed.indexOf(z) < 0)  {
		  isValid = false;
		}
	  }
    }	
	if (international)  {
	  if  (newVal.length < 5)  {
	    isValid = false;
	  }
	}
	else if (newVal.length == 11)  {
	  if (newVal.charAt(0) != "1")	{
		isValid = false;
	  }
	}
	else if ((newVal.length != 10 && newVal.length != 7) || (newVal.length==7 && areaCode)) {
	  isValid = false;
	}
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
  else  {
    formElement.WAValid = true;
    if (reformat != "" && newVal != "")  {
      for (var x=0; x<newVal.length; x++)  {
	    reformat = reformat.substring(0,reformat.lastIndexOf("x")) + newVal.charAt(newVal.length-(x+1)) + reformat.substring(reformat.lastIndexOf("x")+1);
	  }
	  if (reformat.indexOf("x")>=0)  {
	    reformat = reformat.substring(reformat.lastIndexOf("x")+1);
        z = reformat.charAt(0);
	    while (((z < "0") || (z > "9")) && z != "(")  {
	      reformat = reformat.substring(1);
		  z = reformat.charAt(0);
		}
	  }
      formElement.value = reformat;
	}
  }
}

function WAValidateUR(formElement,value,errorMsg,force,reformat,focusIt,stopIt,required)  {
  var isValid = true;
  var valURL = value;
  if (valURL.indexOf("://")>=0)  {
    valURL = valURL.substring(valURL.indexOf("://")+3);
  }
  if (valURL.indexOf("?")>0)  {
    valURL = valURL.substring(0,valURL.indexOf("?"));
  }
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && valURL.replace(/\s/g, "")==""))  {
    if (force.toLowerCase() == "none")  {
      if (value.indexOf("://")>=0)
        isValid = false;
    }
    if (value.indexOf("?")!=value.lastIndexOf("?") || value.indexOf(" ") >= 0)  {
      isValid = false;
    }
    if (isValid)  {
      if (valURL.indexOf(";") >= 0 || valURL.indexOf("&") >= 0 || valURL.indexOf("=") >= 0 || valURL.indexOf(",") >= 0)  {
        isValid = false;
      }
    }
    if (isValid && force.toLowerCase() != "false" && force.toLowerCase() != "none" && isValid)  {
      force = force.replace(/\s*,\s*/g,",");
      force = force.split(",");
      isValid = false;
      for (var x=0; x<force.length; x++)  {
        if (value.toLowerCase().indexOf(force[x].toLowerCase())==0) {
          isValid = true;
          break;
        }
      }
    }
    if (isValid && required && valURL.replace(/\s*/g, "")=="")
      isValid = false;
    if (isValid && valURL.indexOf(".") < 1)
      isValid = false;
    if (isValid) {
      var tDomain = valURL;
      if (tDomain.indexOf(":") >= 0) {
        tDomain = tDomain.substring(0, tDomain.indexOf(":"));
        var tPort = valURL.substring(tDomain.length);
        if (tDomain.indexOf("/") >= 0) {
          isValid = false;
        }
        else {
          if (tPort.indexOf("/") >= 0) {
            tPort = tPort.substring(0, tPort.indexOf("/"));
          }
          if (isNaN(parseInt(tPort)) && tPort != "") {
            isValid = false;
          }
        }
      }
      if (isValid && tDomain.indexOf("/") >= 0) {
        tDomain = tDomain.substring(0, tDomain.indexOf("/"));
      }
      if (isValid) {
        var tDomainA = tDomain.split(".");
        if (tDomainA.length < 2) {
          isValid = false;
        }
        else {
          var ipMatch = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
          if (tDomain.search(ipMatch) == 0) {
            if (parseInt(tDomainA[0]) > 255 || parseInt(tDomainA[1]) > 255 || parseInt(tDomainA[2]) > 255 || parseInt(tDomainA[3]) > 255) {
              isValid = false;
            }
          }
          else {
            if (tDomainA[tDomainA.length-1].length < 2 || tDomainA[tDomainA.length-2].length < 2) {
              isValid = false;
            }
          }
        }
      }
    }

  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
  else  {
    if (reformat!="none" && String(reformat).toLowerCase() != "false")  {
      if (value.indexOf(reformat)!=0)  {
        if (value.indexOf("://")>=0)  {
          value = value.substring(value.indexOf("://")+3);
          while (value.charAt(0)=="/")
            value = value.substring(1);
        }
        formElement.value = reformat+value;
      }
    }
    else if (String(reformat).toLowerCase()=="false")  {
      if (value.indexOf("://")>=0)  {
        value = value.substring(value.indexOf("://")+3);
        while (value.charAt(0)=="/")
          value = value.substring(1);
        formElement.value = value;
      }
    }
  }
}

function WAValidateEM(formElement,value,errorMsg,focusIt,stopIt,required) {
  var isValid = true;
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var accepted = "\[^\\s\\(\\)><@,;:\\\\\\\"\\.\\[\\]\]+";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var section = "(" + accepted + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + section + "(\\." + section + ")*$");
    var domainPat = new RegExp("^" + accepted + "(\\." + accepted +")*$");
    var theMatch = value.match(emailPat);
    var acceptedPat = new RegExp("^" + accepted + "$");
    var userName = "";
    var domainName = "";
    if (theMatch==null) {
      isValid = false;
    }
    else  {
      userName = theMatch[1];
      domainName = theMatch[2];
	  var domArr = domainName.split(".");
	  var IPArray = domainName.match(ipDomainPat);
      for (x=0; x < userName.length; x++) {
        if ((userName.charCodeAt(x) > 127 && userName.charCodeAt(x) < 192) || userName.charCodeAt(x) > 255) {
          isValid = false;
        }
      }
      for (x=0; x < domainName.length; x++) {
        if ((domainName.charCodeAt(x) > 127 && domainName.charCodeAt(x) < 192) || domainName.charCodeAt(x) > 255) {
          isValid = false;
        }
      }
      if (userName.match(userPat) == null) {
        isValid = false;
      }
      if (IPArray != null) {
        for (var x=1; x<=4; x++) {
          if (IPArray[x] > 255) {
            isValid = false;
          }
        }
      }
      for (x=0; x < domArr.length; x++) {
        if (domArr[x].search(acceptedPat) == -1 || domArr[x].length == 0 || (domArr[x].length < 2 && x >= domArr.length-2)) {
          isValid = false;
        }
      }
      if (domArr[domArr.length-1].length !=2 && domArr[domArr.length-1].search(knownDomsPat) == -1) {
        isValid = false;
      }
      if (domArr.length < 2) {
        isValid = false;
      }
    }
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAValidateLE(formElement,value1,value2,errorMsg,focusIt,stopIt,required)  {
  var isValid = true;
  if (!document.WAFV_Stop && !formElement.WAFV_Stop)  {
    if (value1=="" && required)
	  isValid = false;
    if (value1 != value2 || (required && value1==""))
	  isValid = false;
  }
  if (!isValid)  {
    if (focusIt)
	  focusIt.value = "";
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAValidateRX(formElement,inputType,regExStr,errorMsg,focusIt,stopIt,required)  {
  var isValid = true;
  var value=WAFV_GetValueFromInputType(formElement,inputType,required);
  var extraArgs = regExStr.substring(regExStr.lastIndexOf("/")+1);
  regExStr = regExStr.substring(regExStr.indexOf("/")+1,regExStr.lastIndexOf("/"));
  regExStr = regExStr.replace(/&quot;/g,'"');
  var regEx = new RegExp(regExStr,extraArgs);
  if ((!document.WAFV_Stop && !formElement.WAFV_Stop) && !(!required && value==""))  {
    var theMatch = regEx.test(value);
    if (!theMatch)  {
      isValid = false;
    }
  }
  if (!isValid)  {
    WAAddError(formElement,errorMsg,focusIt,stopIt);
  }
}

function WAValidateEN(triggerElement,targetElement,enable)  {
  if (!document.WAFV_StopAlert)  { 
	document.WAFV_StopAlert = true;
    var isValid = true;
    var invalidArray = document.WAFV_InvalidArray;
    if (invalidArray)  {
      if (triggerElement == document)
	    isValid = false;
	  else  {
        for (var x=0; x<invalidArray.length && isValid; x++)  {
          if (invalidArray[x]==triggerElement)  {
	        isValid = false;
	      }
	  	  invalidArray[x].WAFV_Stop = false;
	    }
      }
    }
    if (!isValid)  {
      enable = !enable;
    }
    if (enable)  {
      targetElement.disabled = "";
	  
	  if (targetElement.className == "inputTextDisabled")
	  	targetElement.className = "inputText";	  
	  else if (targetElement.className == "inputPasswordDisabled")
	  	targetElement.className = "inputPassword";  
	  else if (targetElement.className == "inputSelectDisabled")
	  	targetElement.className = "inputSelect";
    }
    else  {
      targetElement.disabled = "disabled";
	  targetElement.disabled = "true";
	  
	  if (targetElement.className == "inputText")
	  	targetElement.className = "inputTextDisabled";	  
	  else if (targetElement.className == "inputPassword")
	  	targetElement.className = "inputPasswordDisabled";  
	  else if (targetElement.className == "inputSelect")
	  	targetElement.className = "inputSelectDisabled";
    }
    document.WAFV_Error = false;
    document.WAFV_Focus = false;
    document.WAFV_Stop = false;
    document.WAFV_InvalidArray = false;
	document.WAFV_StopAlert = false;
  }
}

function WAAlertErrors(errorHead,errorFoot,setFocus,submitForm)  { 
  if (!document.WAFV_StopAlert)  { 
	  document.WAFV_StopAlert = true;
	  if (document.WAFV_InvalidArray)  {  
	    document.WAFV_Stop = true;
        var errorMsg = document.WAFV_Error;
	    if (errorHead!="")
		  errorMsg = errorHead + "\n" + errorMsg;
		if (errorFoot!="")
		  errorMsg += "\n" + errorFoot;
		document.MM_returnValue = false;
		if (document.WAFV_Error!="")
		  alert(errorMsg.replace(/&quot;/g,'"'));
		else if (submitForm)
		  submitForm.submit();
	    if (setFocus && document.WAFV_Focus)  {
		  document.tempFocus = document.WAFV_Focus;
          setTimeout("document.tempFocus.focus();setTimeout('document.WAFV_Stop = false;document.WAFV_StopAlert = false;',1)",1); 
        }
        else {
          document.WAFV_Stop = false;
          document.WAFV_StopAlert = false;
        }
        for (var x=0; x<document.WAFV_InvalidArray.length; x++)  {
	      document.WAFV_InvalidArray[x].WAFV_Stop = false;
	    }
	  }
	  else  {
        document.WAFV_Stop = false;
        document.WAFV_StopAlert = false;
	    if (submitForm)  {
	      submitForm.submit();
	    }
	    document.MM_returnValue = true;
	  }
      document.WAFV_Focus = false;
	  document.WAFV_Error = false;
	  document.WAFV_InvalidArray = false;
  }
}
// Sortable Table
var currenttable = null;
document.onmousemove = function(ev){
    if (currenttable && currenttable.dragObject) {
		var rows = currenttable.dragObject;
        ev   = ev || window.event;
        var mousePos = currenttable.mouseCoords(ev);
		//document.getElementById("debug").innerHTML = "hey:"+mousePos.x+", "+mousePos.y;
        var y = mousePos.y - currenttable.mouseOffset.y;
        if (y != currenttable.oldY) {
            // work out if we're going up or down…
            var movingDown = y > currenttable.oldY;
            // update the old value
            currenttable.oldY = y;
            // update the style &to show we're dragging
			for (var m = 0; m < rows.length; m++) {
				var cells = rows[m].getElementsByTagName("td");
				var myclass;
				
				for (var n = 0; n <= cells.length-1; n++) {
					myclass = cells[n].className;
					if (!movingDown)
						myclass = myclass.replace(/movable/, "moveup");
					else
						myclass = myclass.replace(/movable/, "movedown");
					
	
					if (myclass.match(/subsubrow/) != null)
						myclass = myclass.replace(/subsubrow/, "subsubrowselect");
					else if (myclass.match(/subrow/) != null)
						myclass = myclass.replace(/subrow/, "subrowselect");
					else
						myclass = myclass.replace(/row/, "rowselect");
						
					myclass = myclass.replace(/selectselect/, "select");
            		cells[n].className = myclass;
				}
			}
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = currenttable.findDropTargetRow(y);
			var dragLevel = parseInt(rows[0].id.split("_")[3]);  // max level of draggables, stay below
			
			var maxlevel = parseInt(document.getElementById("MaxLevel").value);
			var firstRow = null;			
			var tableRows = table.tBodies[0].rows;			
            if (currentRow && dragLevel == maxlevel) {
				var currentLevel = parseInt(currentRow.id.split("_")[3]);
                if (movingDown && rows[0].id != currentRow.id && (dragLevel == currentLevel || dragLevel-1 == currentLevel)) {
					//if (parseInt(rows[0].id.split("_")[2]) != parseInt(currentRow.id.split("_")[2]))
//						return false;
						
                    rows[0].parentNode.insertBefore(rows[0], currentRow.nextSibling);
                } else if (!movingDown && rows[0].id != currentRow.id && (dragLevel == currentLevel || dragLevel-1 == currentLevel)) {
					var found = 0;
					var previd = 0;
					var currid = 0;
					for (var k=0; k<tableRows.length; k++) {
						currid = tableRows[k].id;
						if (found == 0 && tableRows[k].id == currentRow.id)
							found = 1;
						else if (found == 0)
							previd = tableRows[k].id;
					}
					
					if (parseInt(previd) != 0 && parseInt(previd.split("_")[3]) <= dragLevel-2)
						return false;
					
					//if (parseInt(previd) == 0 && dragLevel != 0)
//						return false;
					//if (parseInt(rows[0].id.split("_")[2]) != parseInt(currentRow.id.split("_")[2]))
//						return false;
                    rows[0].parentNode.insertBefore(rows[0], currentRow);
                }
            }
			else if (currentRow && dragLevel < maxlevel) {
				var arr2 = currentRow.id.split("_");				
				// don't drop within
				for (var j = 0; j < rows.length; j++) {
					if (currentRow.id == rows[j].id) {
						return false;
					}
				}				
				var insertpoint = null;
				var tableRows = table.tBodies[0].rows;				
				if (movingDown) {
					var found = 0;
					var previd = 0;
					var currid = 0;
					var nextid = 0;
					for (var k=0; k<tableRows.length; k++) {
						currid = tableRows[k].id;
						if (found == 0 && tableRows[k].id == currentRow.id)
							found = 1;
						else if (found == 0)
							previd = tableRows[k].id;
						else if (found == 1 && nextid == 0)
							nextid = tableRows[k].id;
					}
					//if (parseInt(arr2[1]) == 109)
//					else
//						return false;
//3_0_0, 67_3_1,  
					if (parseInt(arr2[3]) > dragLevel+1 && parseInt(nextid.split("_")[3])!= dragLevel)
						return false;
					if (parseInt(nextid) != 0 && parseInt(nextid.split("_")[3]) > arr2[3])
						return false;
					if (parseInt(nextid) != 0 && parseInt(nextid.split("_")[3]) > arr2[3])
						return false;
					if (arr2[3] != dragLevel && arr2[3] != dragLevel-1 && parseInt(nextid.split("_")[3]) == arr2[3])
						return false;
					//if (parseInt(rows[0].id.split("_")[2]) != parseInt(currentRow.id.split("_")[2]))
//							return false;
					//if (parseInt(rows[0].id.split("_")[3]) != parseInt(nextid.split("_")[3]))
//						return false;
					insertpoint = currentRow.nextSibling;
				}
				else {
					var found = 0;
					var previd = 0;
					var currid = 0;
					var nextid = 0;
					for (var k=0; k<tableRows.length; k++) {
						currid = tableRows[k].id;
						if (found == 0 && tableRows[k].id == currentRow.id)
							found = 1;
						else if (found == 0)
							previd = tableRows[k].id;
						else if (found == 1 && nextid == 0)
							nextid = tableRows[k].id;
					}
					if (parseInt(previd) == 0 && dragLevel != 0)
						return false;
					if (parseInt(arr2[3]) != dragLevel && parseInt(arr2[3]) != dragLevel-1)
						return false;
						
					
					if (previd != null && dragLevel > parseInt(previd.split("_")[3])+1)
						return false;
					//if (parseInt(rows[0].id.split("_")[2]) != parseInt(currentRow.id.split("_")[2]))
//						return false;					
					insertpoint = currentRow;
				}
				
				for (var l = 0; l < rows.length; l++) {
					rows[l].parentNode.insertBefore(rows[l], insertpoint);
				}					
			}
        }
        return false;
    }
}
// Similarly for the mouseup
document.onmouseup = function(ev){
    if (currenttable && currenttable.dragObject) {
		var droppedRows = currenttable.dragObject;
		var myclass = "";
        // If we have a dragObject, then we need to release it,
        // The row will already have been moved to the right place so we just reset stuff
		for (var i = 0; i < droppedRows.length; i++) {
			var cells = droppedRows[i].getElementsByTagName("td");				
				
			for (var j = 0; j <= cells.length-1; j++) {
				myclass = cells[j].className;
				if (myclass.match(/subsubrowselect/) != null)
					myclass = myclass.replace(/subsubrowselect/, "subsubrow");
				else if (myclass.match(/subrowselect/) != null)
					myclass = myclass.replace(/subrowselect/, "subrow");
				else
					myclass = myclass.replace(/rowselect/, "row");
				myclass = myclass.replace(/selectselect/, "select");
				myclass = myclass.replace(/moveup/, "movable");
				myclass = myclass.replace(/movedown/, "movable");
				
				cells[j].className = myclass;
				
			}
		}
		
        currenttable.dragObject  = null;
        // And then call the onDrop method in case anyone wants to do any post processing
        currenttable.onDrop(currenttable.table, droppedRows);
    }
}
/** get the source element from an event in a way that works for IE and Firefox and Safari
 * @param evt the source event for Firefox (but not IE–IE uses window.event) */
function getEventSource(evt) {
    if (window.event) {
        evt = window.event; // For IE
        return evt.srcElement;
    } else {
        return evt.target; // For Firefox
    }
}
// TABLE ROW DRAG & DROP
function TableDnD() {
    /** Keep hold of the current drag object if any */
    this.dragObject = null;
    /** The current mouse offset */
    this.mouseOffset = null;
    /** The current table */
    this.table = null;
    /** Remember the old value of Y so that we don't do too much processing */
    this.oldY = 0;
    // rest of the code goes here…
	/** Initialise the drag and drop by capturing mouse move events */
    this.init = function(table) {
        this.table = table;
        var rows = table.tBodies[0].rows; //getElementsByTagName("tr")
        for (var i=0; i<rows.length; i++) {
            // John Tarr: added to ignore rows for which the NoDrag attribute is set
            var nodrag = rows[i].getAttribute("nodrag")
            if (nodrag == null || nodrag == "undefined") { 
				// There is no NoDrag attribute so make draggable
                this.makeDraggable(rows[i]);
            }
        }
    }
	/** This function is called when you drop a row, so redefine it in your code
        to do whatever you want, for example use Ajax to update the server */
    this.onDrop = function(table, droppedRows) {
		//alert("hi");
		var rows = table.tBodies[0].rows;
		var orderStr = "";
		var sep = "";
		
		for (var i=0; i<rows.length; i++) {
			orderStr += sep + rows[i].id;
			sep = "[NF]";
		}
		reorderRows(orderStr);
    }
	/** Get the position of an element by going up the DOM tree and adding up all the offsets */
    this.getPosition = function(e){
        var left = 0;
        var top  = 0;
        while (e.offsetParent){
            left += e.offsetLeft;
            top  += e.offsetTop;
            e     = e.offsetParent;
        }
        left += e.offsetLeft;
        top  += e.offsetTop;
        return {x:left, y:top};
    }
    /** Get the mouse coordinates from the event (allowing for browser differences) */
    this.mouseCoords = function(ev) {
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    }
    /** Given a target element and a mouse event, get the mouse offset from that element.
        To do this we need the element's position and the mouse position */
    this.getMouseOffset = function(target, ev){
        ev = ev || window.event;
        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    }
	
	 /** Take an item and add an onmousedown method so that we can make it draggable */
    this.makeDraggable = function(item){
        if(!item) return;
        var self = this; // Keep the context of the TableDnd inside the function
        item.onmousedown = function(ev){
            // get the event source in a browser independent way
            var target = getEventSource(ev);
            // if it's an INPUT or a SELECT, then let the event bubble through, don't do a drag
            if (target.tagName == "INPUT" || target.tagName == "SELECT" || target.tagName == "A")
				return true;			
			var arr = item.id.split("_");
			var mydrag = new Array();
			var maxlevel = parseInt(document.getElementById("MaxLevel").value);
			var mylevel = parseInt(arr[3]);
			if (mylevel == maxlevel) {
				mydrag[0] = this;
				self.dragObject = mydrag;
			}
			else if (mylevel < maxlevel) {
				var found = 0;
				var rows = table.tBodies[0].rows;
				var newindex = 0;	
				for (var i=0; i<rows.length; i++) {
					var arr2 = rows[i].id.split("_");
				
					if (found == 0 && parseInt(arr2[3]) == mylevel && arr2[1] == arr[1]) {  // ids match; found it!
						mydrag[newindex] = rows[i];
						newindex++;
						found = 1;
					}
					else if (found == 1 && parseInt(arr2[3]) > mylevel) { // subsequent rows
						mydrag[newindex] = rows[i];
						newindex++;
					}
					else if (found == 1 && parseInt(arr2[3]) <= mylevel) {  // done!
						found = 0;
					}
				}				
				self.dragObject = mydrag;
			}
			else {
            	self.dragObject  = null;
			}
            self.mouseOffset = self.getMouseOffset(this, ev);
            return false;
        }
        item.style.cursor = "move";
    }
    /** We're only worried about the y position, we can only move rows up and down */
    this.findDropTargetRow = function(y) {
        var rows = this.table.tBodies[0].rows;
        for (var i=0; i<rows.length; i++) {

            var row = rows[i];
            // John Tarr added to ignore rows that I've added the NoDrop attribute to (Header rows)
            var nodrop = row.getAttribute("nodrop");
            if (nodrop == null || nodrop == "undefined") {  //There is no NoDrop attribute on rows I want to drag
                var rowY = this.getPosition(row).y;
                var rowHeight = parseInt(row.offsetHeight)/2;
                if (row.offsetHeight == 0) {
                    rowY = this.getPosition(row.firstChild).y;
                    rowHeight = parseInt(row.firstChild.offsetHeight)/2;
                }
                // Because we always have to insert before, we need to offset the height a bit
                if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                    // that's the row we're over
                    return row;
                }
            }
        }
        return null;
    }
}

function reorderRows (orderStr) {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Your browser does not support AJAX!");
		return;
	} 
	
	var baseurl = "menus_ReorderRows.php";
	
	var tableName = "";
	if (document.getElementById("sortTableName") != null) {
		tableName = document.getElementById("sortTableName").value;
	}
	var idCol = "";
	if (document.getElementById("IDColumnName") != null) {
		idCol = document.getElementById("IDColumnName").value;
	}
	var orderCol = "";
	if (document.getElementById("OrderColumnName") != null) {
		orderCol = document.getElementById("OrderColumnName").value;
	}
	var setParent = "false";
	if (document.getElementById("SetParent") != null) {
		setParent = document.getElementById("SetParent").value;
	}
	var maxLevel = "";
	if (document.getElementById("MaxLevel") != null) {
		maxLevel = document.getElementById("MaxLevel").value;
	}
	var parentCol = "";
	if (document.getElementById("ParentColumnName") != null) {
		parentCol = document.getElementById("ParentColumnName").value;
	}
	var levelCol = "";
	if (document.getElementById("LevelColumnName") != null) {
		levelCol = document.getElementById("LevelColumnName").value;
	}	
	var childCountCol = "";
	if (document.getElementById("ChildCountColumn") != null) {
		childCountCol = document.getElementById("ChildCountColumn").value;
	}	
	var blockTemplate = "";
	if (document.getElementById("blockTemplate") != null) {
		blockTemplate = document.getElementById("blockTemplate").value;
	}
	var menuName = "";
	if (document.getElementById("sortMenuName") != null) {
		menuName = document.getElementById("sortMenuName").value;
	}
	 
	url = "?sid=" + Math.random();
		
	if (tableName != "") { 	
		url = url + "&tableName="+tableName;	
		url = url + "&idCol="+idCol;				
		url = url + "&orderCol="+orderCol;			
		url = url + "&setParent="+setParent;					
		url = url + "&maxLevel="+maxLevel;
		
		if (setParent == "true") {
			url = url + "&parentCol="+parentCol;			
			url = url + "&levelCol="+levelCol;			
			url = url + "&childCountCol="+childCountCol;
		}
		
		if (tableName == "menus_links") {
			url = url + "&menuName="+menuName;		
			baseurl = "menus_links_ReorderRows.php";
		}
		else if (tableName == "pages_blocks_options") {
			url = url + "&blockTemplate="+blockTemplate;		
			baseurl = "pages_blocks_options_ReorderRows.php";
		}
	}	
	
	url = baseurl + url + "&orderStr="+orderStr;
	
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			 // do nothing
		}
	}
	
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

//-->
