/*
 *
 * jfunctions.js 
 *
 *
 */

//Updated March 26, 2011 - added function edit_pagebodytext() for cwsx and mds 
//Updated March 22, 2011 - updated news and create gallery browser functions [mds]
//Updated February 25, 2011 - added correct popcal function and a find child with class function [mds/cd/cw]
//Updated February 6, 2011 - updated makeBox function. ty and tx required +"px". [companiondogschool]
//Updated Sept 24, 2010 - added function to pull calendar (fnctn: pop_cal() ) [mds]
//Updated April 27, 2010 - added htmlspecialchars_decode to allow_edit_news_post() [liska]
//Updated January 31, 2010 - removed alert('err') from refresh_image() function [mds.com]
//Updated January 25, 2010 - added additional table functions - add row in table.
//Updated December 29, 2009 - further edit of Dec 28
//Updated December 28, 2009 - comment out set_ht_by_content call in refresh_image() because it does not work in IE 
//Updated December 11 2009 - changed the isURLx() function 
//Updated October 26, 2009 - moved $() function 
//Updated October 3, 2009 - added rf() function  (returns false)
//Updated October 1, 2009 - remove padding from fancy_update_box() formatting script
//Updated September 23, 2009 - added ScrollSmooth function
//Updated September 16, 2009 - AB - added checkbox_value_array()
//Updated September 13, 2009 - AB 
//


//return document.getElementById()
function $(id) {
	return document.getElementById(id);
}

//return false;
function rf() {
	return false;
}

function fileUpload(form, action_url, div_id) {
	// Create the iframe...
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","upload_iframe"+div_id);
	iframe.setAttribute("name","upload_iframe"+div_id);
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","1");
	iframe.setAttribute("class","para_medtxt");
	iframe.setAttribute("style","width: 0; height: 0; border: none; color: #444; background: pink;");
//	setAstyle(iframe,"width: 0; height: 0; border: none; color: #444; background: pink;");
	
	// Add to document...
	form.parentNode.appendChild(iframe);
	window.frames['upload_iframe'+div_id].name="upload_iframe"+div_id;
	
	iframeId = document.getElementById("upload_iframe"+div_id);
	
	// Add event...
	var eventHandler = function()  {
		
		if (iframeId.detachEvent)
			iframeId.detachEvent("onload", eventHandler);
		else
			iframeId.removeEventListener("load", eventHandler, false);
		
		// Message from server...
		if (iframeId.contentDocument) {
			content = iframeId.contentDocument.body.innerHTML;
		} else if (iframeId.contentWindow) {
			content = iframeId.contentWindow.document.body.innerHTML;
		} else if (iframeId.document) {
			content = iframeId.document.body.innerHTML;
		}
	
		document.getElementById(div_id).innerHTML = content;
	
		// Del the iframe...
		setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
	}
	
	if (iframeId.addEventListener)
		iframeId.addEventListener("load", eventHandler, true);
	if (iframeId.attachEvent)
		iframeId.attachEvent("onload", eventHandler);
	
	// Set properties of form...
	form.setAttribute("target","upload_iframe"+div_id);
	form.setAttribute("action", action_url);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	
	// Submit the form...
	form.submit();
	
	document.getElementById(div_id).innerHTML = "<span style='color: #444;'>Uploading...<img src='nav/load.gif' align='left'></span>";
}


function fileUploadToDiv(form, action_url, div_id) {
	// Create the iframe...
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","upload_iframe"+div_id);
	iframe.setAttribute("name","upload_iframe"+div_id);
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","1");
	iframe.setAttribute("class","para_medtxt");
	iframe.setAttribute("style","width: 0; height: 0; border: none; color: #444; background: pink;");
//	setAstyle(iframe,"width: 0; height: 0; border: none; color: #444; background: pink;");
	
	// Add to document...
	form.parentNode.appendChild(iframe);
	window.frames['upload_iframe'+div_id].name="upload_iframe"+div_id;
	
	iframeId = document.getElementById("upload_iframe"+div_id);
	
	// Add event...
	var eventHandler = function()  {
		
		if (iframeId.detachEvent)
			iframeId.detachEvent("onload", eventHandler);
		else
			iframeId.removeEventListener("load", eventHandler, false);
		
		// Message from server...
		if (iframeId.contentDocument) {
			content = iframeId.contentDocument.body.innerHTML;
		} else if (iframeId.contentWindow) {
			content = iframeId.contentWindow.document.body.innerHTML;
		} else if (iframeId.document) {
			content = iframeId.document.body.innerHTML;
		}
	
		document.getElementById(div_id).innerHTML = content;
	
		// Del the iframe...
		setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
	}
	
	if (iframeId.addEventListener)
		iframeId.addEventListener("load", eventHandler, true);
	if (iframeId.attachEvent)
		iframeId.attachEvent("onload", eventHandler);
	alert("asdf");
	
	getInputObjects(action_url,"upload_iframe"+div_id);
	
	alert('ffff');
/*
	// Set properties of form...
	form.setAttribute("target","upload_iframe"+div_id);
	form.setAttribute("action", action_url);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	
	// Submit the form...
	form.submit();
*/
	
	document.getElementById(div_id).innerHTML = "<span style='color: #444;'>Uploading...<img src='nav/load.gif' align='left'></span>";
}


//Call Image Browser 
function call_image_browser (pagewidth,pathroot,name_of_browser,scroll_return_to_div,imgtarg,img_sub_fld_name,cid,img_or_cid) {
	if (img_or_cid == "cid") {
		var get_cid = "&set_get_cid=y";
	} else var get_cid = "";
	
	var size_array = alertSize();
	
	//create backdrop
	var bg = document.createElement("div");
	$("pagebody").appendChild(bg);
	bg.id = "blankbg";
	setAstyle(bg,"z-index: 40000; position: fixed; top: 0; left: 0; width: "+size_array[0]+"px; height: "+size_array[1]+"px; background: #000; text-align: center;");
	setOpacity(bg,0.70);
	
	//create 
	var underlay = document.createElement("div");
	underlay.id = "browser_underlay";
	setAstyle(underlay,"z-index: 40500; position: fixed; top: 0; left: 0; width: "+size_array[0]+"px; height: "+size_array[1]+"px; text-align: center;");
	
	//create browser frame div 			
	var imgbrsr = document.createElement("div");
	$("pagebody").appendChild(underlay);
	underlay.appendChild(imgbrsr);
	imgbrsr.id = "imagebrowserframe";
	setAstyle(imgbrsr,"position: absolute; left: "+((size_array[0]-pagewidth)/2)+"px; top: 30px; height: "+(size_array[1]-60)+"px; width: "+pagewidth+"px; border: 3px solid #444; overflow: hidden; background: #ccc; z-index: 41000;");
	
	
	//top: 30px -- change so that we detect the element top instead.
	
	//create header row/div at the top to close the browser window 
	var cancel_browser_div = document.createElement("div");
	setAstyle(cancel_browser_div,"position: absolute; left: 0; top: 0px; height: 25px; width: "+(pagewidth-10)+"px; border: none; overflow: hidden; background: lightgray;");
	imgbrsr.appendChild(cancel_browser_div);
	cancel_browser_div.id = "cancelbrswr";				
	
	//cerate body of browser 
	var browser_body_div = document.createElement("div");
	setAstyle(browser_body_div,"position: absolute; left: 0; top: 26px; height: "+(size_array[1]-100)+"px; width: "+(pagewidth-10)+"px; border-top: 1px solid #444; background: transparent; overflow: scroll;");
	imgbrsr.appendChild(browser_body_div);
	browser_body_div.id = name_of_browser;

	//create p to hold cancel button 
	var cancel_p = document.createElement("p");
	cancel_browser_div.appendChild(cancel_p);
	cancel_p.className = "para_medtxt";
	setAstyle(cancel_p,"text-align: right; font-weight: bold; color: #444;");
	
	//create cancel button and append to header row 
	var cancel_link = document.createElement("a");
	cancel_link.href = "#";
	setAstyle(cancel_link,"color: #444;");
	cancel_link.onclick = function() {
								if ($(scroll_return_to_div)) {
									end_browser_and_scroll(scroll_return_to_div)
								}
								return false;		
									}
	cancel_link.appendChild(document.createTextNode("CANCEL"));
	cancel_p.appendChild(cancel_link);
	
	//scroll the user browser to the top of this browser 
	ScrollToElement("imagebrowserframe");
	
	//inset gb.php (the browser) into the frame body 
	followLink(pathroot+"galleryfiles/gb.php?cid="+cid+"&m="+imgtarg+img_sub_fld_name+"&l="+name_of_browser+"&target="+img_sub_fld_name+"&imght=100&imgalign=left&pagewidth="+(pagewidth-15)+"&recht="+(size_array[1]-50)+"&scrolltodiv="+scroll_return_to_div+get_cid,name_of_browser);
	
	
}


//build links for image browser initiation 
function create_image_browser (parentID,parentClassName,ia,image_id,other_args,image_array,local_id) {
	var pagewidth = ia[0];
	var root = ia[1];
	var img_brsr_name = ia[2];
	var scroll_return_to_div = ia[3];
	var imgtarg = ia[4];
	var image_id_target_field_id = ia[5];
	var cid = ia[6];
	var img_size = ia[7]
		
	clear_contents(parentID);
	$(parentID).className = parentClassName;
	$(parentID).style.paddingLeft = "4px";	
	
	//paragraph for browser link 
	make_el_dom("p","para_smltxt","",parentID,"browser_p"+local_id);
	$("browser_p"+local_id).style.marginLeft = "1em";
	
	//link for browser 
	make_el_dom("a","para_smltxt edit","Click to browse for a new image...","browser_p"+local_id,"browser_link"+local_id);
	$("browser_link"+local_id).style.cursor = "pointer";
	
	$("browser_link"+local_id).onclick = function () {
		call_image_browser(pagewidth,root,img_brsr_name,scroll_return_to_div,imgtarg,image_id_target_field_id,cid,"img");
		return false;		
	}	

	//paragraph for image 
	make_el_dom("p","para_smltxt","",parentID,"browser_p2"+local_id);
	$("browser_p2"+local_id).style.marginLeft = "1em";
	
	//image span target 
//	alert(imgtarg+image_id_target_field_id+" :span id");
	make_el_dom("span","para_smltxt","","browser_p2"+local_id,imgtarg+image_id_target_field_id);
	
	//create image  image_array(path,item_id,width,height)
	if (image_id > 0) {
		var img = document.createElement("img");
		$(imgtarg+image_id_target_field_id).appendChild(img);
		img.src = image_array[0];
		img.id = "img"+image_array[1]+"_"+local_id;
		img.style.width = image_array[2];
		img.style.height = image_array[3];
		img.align = "left";
	}
	
//	alert(img.src);
	
	//paragraph for submit button 
	make_el_dom("p","para_smltxt","",parentID,"browser_p3"+local_id);
	$("browser_p3"+local_id).style.marginLeft = "1em";
	

	//submit button
	make_el_dom("a","para_smltxt edit","Submit/Update Image","browser_p3"+local_id,"submitlink"+local_id);
	$("submitlink"+local_id).style.cursor = "pointer";
	
	//clear div
	make_el_dom("div","clear","",parentID,"clearalldiv"+local_id);
	$("clearalldiv"+local_id).style.height = "10px";
	
	
	//submit onclick: 
	$("submitlink"+local_id).onclick = function () {
		followLink("?&add_new_news_img="+local_id+"&news_img_id="+$(ia[5]).value+other_args,"pagebody");
		return false;
	}
	
	//final hidden paragraph for hidden text elements 
	make_el_dom("p","hide","",parentID,"browser_p4"+local_id);
	$("browser_p4"+local_id).style.marginLeft = "1em";
	
	make_input_el("text","browser_p4"+local_id,image_id,ia[5],ia[5]);
//	make_input_el("text","browser_p4"+local_id,image_id,ia[4]+ia[5],ia[4]+ia[5]);	
	//make_input_el(inpType,parentID,val,newID,newName) 
}

function allow_edit_newsfeed (posts,parentID,newsid,all_args,clikspanid,targ) {
	//remove br from posts
	posts = posts.replace(RegExp("<br />","gi"),"\n");
	
	posts = htmlspecialchars_decode(posts,"ENT_QUOTES");
	
	//title
	make_el_dom("p","para_medtxt smltxt_b","Change the news post:",parentID,"p_");
	
	//create textbox with post in it 
	var textbox = document.createElement('textarea');
	textbox.id = 'inp_'+clikspanid;
	$(parentID).appendChild(textbox);
	textbox.style.height = '100px';
	textbox.style.width = '250px';
	
	
	textbox.value = posts;
	textbox.onblur = function() {
		$("submit_ta_a"+newsid).onclick();
	}
	
	make_el_dom("p","para_medtxt edit","",parentID,"edit_ta_p_"+newsid);
	
	//submit button
	make_el_dom("a","para_medtxt edit","Submit/Save","edit_ta_p_"+newsid,"submit_ta_a"+newsid);
	$("submit_ta_a"+newsid).style.cursor = "pointer";
	
	//submit onclick: 
	$("submit_ta_a"+newsid).onclick = function () {
		click_to_edit_onblur("no","ntext","",all_args,targ,clikspanid,"textarea");
		//click_to_edit_onblur("no","n_comment",followto,all_args,targ,clickspanid,"textarea");		
		return false;
	}
}

function allow_edit_news_post (posts,parentID,newsid,all_args,clikspanid,targ) {
	//remove br from posts
	posts = posts.replace(RegExp("<br />","gi"),"\n");
	
	posts = htmlspecialchars_decode(posts,"ENT_QUOTES");
	
	//title
	make_el_dom("p","para_medtxt smltxt_b","Change the news post:",parentID,"p_");
	
	//create textbox with post in it 
	var textbox = document.createElement('textarea');
	textbox.id = 'inp_'+clikspanid;
	$(parentID).appendChild(textbox);
	textbox.style.height = '100px';
	textbox.style.width = '250px';
	
	
	textbox.value = posts;
	textbox.onblur = function() {
		$("submit_ta_a"+newsid).onclick();
	}
	
	make_el_dom("p","para_medtxt edit","",parentID,"edit_ta_p_"+newsid);
	
	//submit button
	make_el_dom("a","para_medtxt edit","Submit/Save","edit_ta_p_"+newsid,"submit_ta_a"+newsid);
	$("submit_ta_a"+newsid).style.cursor = "pointer";
	
	//submit onclick: 
	$("submit_ta_a"+newsid).onclick = function () {
		click_to_edit_onblur("no","n_comment","",all_args,targ,clikspanid,"textarea");
		//click_to_edit_onblur("no","n_comment",followto,all_args,targ,clickspanid,"textarea");		
		return false;
	}
}

function nl2br (str, is_xhtml) {
	//replace all instances of <Br> with \n
    breakTag = '<br />';
    if (typeof is_xhtml != 'undefined' && !is_xhtml) {
        breakTag = '<br>';
    }
    return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

var checkflag = "false";
function check(FormName,FieldName) {
	//field = document.getElementById(elemid);
	//do not use
	var field = document.forms[FormName].elements[FieldName];
	
	if (checkflag == "false") {
	  for (i = 0; i < field.length; i++) {
		field[i].checked = true;
	  }
	  checkflag = "true";
	  return "Uncheck all"; }
	else {
	  for (i = 0; i < field.length; i++) {
	  field[i].checked = "false"; }
	  checkflag = "false";
	  return "Check all"; 
	}
}

function unhideDiv(showifclassname,hideifclassname,divid) {
	if ($(divid).className == hideifclassname) {
		$(divid).className = showifclassname;
	} else {
		$(divid).className = hideifclassname;
	}
}


menu_status = new Array(); 
function showHide(theid){
    if (document.getElementById) {
    var switch_id = document.getElementById(theid);

        if(menu_status[theid] != 'show') {
           switch_id.className = 'show';
           menu_status[theid] = 'show';
        }else{
           switch_id.className = 'hide';
           menu_status[theid] = 'hide';
        }
    }
}


function chg_show_hide(check_element,check_txt,other_element,other_txt,parent) {
	var chkel;
	var parent_el = $(parent);
	if (chkel = document.getElementById(check_element)) {
		var spanTxt = document.createTextNode(other_txt);		
		var newSpan = document.createElement("span");
		newSpan.id = other_element;
		parent_el.removeChild(chkel);
		parent_el.appendChild(newSpan);
		newSpan.appendChild(spanTxt);

	} else {
		var spanTxt = document.createTextNode(check_txt);
		var newSpan = document.createElement("span");
		newSpan.id = check_element;
		parent_el.removeChild($(other_element));
		parent_el.appendChild(newSpan);
		newSpan.appendChild(spanTxt);

	}
}

function fancy_update_box(elID) {
	$(elID).style.border = "1px solid orange";
	$(elID).style.background = "lightyellow";
	$(elID).style.color = "red";

/* //these do not work with Rounded Corners
	$(elID).style.padding = ".1em";
	$(elID).style.paddingLeft = ".4em";
	$(elID).style.paddingRight = ".4em";
*/
	
}

function setTEmptyEl(id,timeout) {
	//call timed function to delete children of element and also the style 
	var t = setTimeout("empty_element('"+id+"')",timeout);
}

function clearContentsEl(id,timeout) {
	//call timed function to delete children of element. PRESERVE Style 
	var t = setTimeout("clear_contents('"+id+"')",timeout);
}

function setTimer_delEl(id,timeout) {
	//call timed function to delete children of element and also the style 
	var t = setTimeout("rem_el('"+id+"')",timeout);
}

function empty_element(id) {
	//delete all children of element and remove STYLE 
	var el = $(id);
	setAstyle(el," ");
	delete_children_of(id);
}

function clear_contents(id) {
	//delete all children of element 
//	var el = $(id);
	delete_children_of(id);
}

function delete_children_of(id) {
	var el;
	if (el = $(id)) {
		if ( el.hasChildNodes() ) {
			while ( el.childNodes.length >= 1 ) {
				el.removeChild( el.firstChild );       
			} 
		}
	}
}

function set_ht_by_content (id_elem) {
	var el = $(id_elem);
	el.trueHeight = el.scrollHeight;
	var th = el.scrollHeight;
	el.style.height = th+"px";
	el.style.overflow='hidden';
//	alert("set_ht_by_content: "+th+" trueHeight:"+el.trueHeight) //alerts 180 or so, true height of DIV
}					

function set_ht_by_content_plus (id_elem,addHt,minHt) {
	var el = $(id_elem);
	el.trueHeight = el.scrollHeight;
	var th = el.scrollHeight;
	var fHt = (th+addHt);
	if (fHt < minHt) {
		fHt = (minHt+addHt+addHt);
	}
	el.style.height = (fHt)+"px";
	el.style.overflow='hidden';
//	alert("set_ht_by_content: "+th+" trueHeight:"+el.trueHeight+" finalHeight:"+fHt) //alerts 180 or so, true height of DIV
}					


function set_ht_by_content_ht (oversize_el,set_el,add_ht,minht) {
	
	var el = $(set_el);
	var xht = $(oversize_el).scrollHeight;
	if (xht == 0) {
		xht = $(oversize_el).offsetHeight;
	}
/*
	if (xht == 0) {
		xht = $(oversize_el).clientHeight;
	}
*/
	var sh = xht;
	xht = (xht+add_ht);
	el.trueHeight = xht;
	if (xht < minht) {
		xht = minht;
	}
	el.style.height = xht+"px";
	el.style.overflow = 'hidden';
//	alert("by ht: "+xht+"  "+xht+"px   before: "+sh+"\n"+"oversize_el: "+oversize_el+" sethtof:"+set_el);
}

function change_value(target,newvalue) {
	var obx = document.getElementById(target);
	obx.value = newvalue;
}

function show_email(name,emailHost) {
	document.write("<a href=" + "mailto:" + name + "@" + emailHost+ ">" + name + "@" + emailHost + "</a>");
}

function get_if_exists(idElem) {
	if (document.getElementById("opt_title")) {
		var val = document.getElementById("opt_title").value;
	} else val = "";
	return val;
}

function addslash(str) {
	//str = str.replace(/\'/g,'asd&amp;quot;&#39;');
	str=str.replace(/\'/g,'\\\'');	
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
//alert(str);
	return str;
}

function make_single_quote(str) {
	regexp = new RegExp("\'","gi");
	str = str.replace(regexp,"&#039;");
	return str;	
}

function addslashes(str) {
	str = str.replace(/\'/g,'&#39;');
//	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');

	return str;
}

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function ScrollSmooth(theE){
	//increment scroll bar 15 times until reaching the target element
	var currY;
	if (currY = window.pageYOffset) {
		//nothing
	} else {
		currY = document.body.scrollTop;
	}
	var posArray = new Array();
	posArray = ElementPagePosition(theE);
	var selectedPosX = posArray[0];
	var selectedPosY = posArray[1];
	
	var diff = (currY-selectedPosY);
	var incr = diff/15;
	var currPos = currY;
	for (i=0; i<15; i++) {
		currPos = currPos - incr;
		window.scrollTo(selectedPosX,currPos);
	//	alert(currPos+"  trg:"+selectedPosY+"  "+incr+"  "+i);
	}
	return;
}

function ScrollToElement(theE){
	//scroll to element with ID...
/*
	theElement = $(theE);
	var selectedPosX = 0;
	var selectedPosY = 0;
	while(theElement != null){
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
*/
	var posArray = new Array();
	posArray = ElementPagePosition(theE);
	var selectedPosX = posArray[0];
	var selectedPosY = posArray[1];	
	window.scrollTo(selectedPosX,selectedPosY);
}

function ElementPagePosition(theE) {
	theElement = $(theE);
	var selectedPosX = 0;
	var selectedPosY = 0;
	while(theElement != null){
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
	return Array(selectedPosX,selectedPosY);
}

function refresh_image(img_id,target_id,filename,alignimg,ht,wt,targinput,scrolltodiv) {
	var targetnode = $(target_id);
	if ( targetnode.hasChildNodes() ) {
		while ( targetnode.childNodes.length >= 1 ) {
			targetnode.removeChild( targetnode.firstChild );
		}
	}

	var gis = new Image();
	gis.src = filename;
	var h = gis.height;
	var w = gis.width;
			//	alert(h+"h   w"+w);
	if ( (h>0) && (w>0) ) {
		var xyratio = (h/w);
		var newH = wt*xyratio;
	} else {
//		alert("err");
		var newH = wt/1.5;
	}
	if ( $("block"+targinput) ) {
		var block = $("block"+targinput);
		block.style.height = (newH+10)+"px";
	}
	
	targetnode.style.height = newH+"px";
	
	if ($(scrolltodiv)) {
		var scrollto = $(scrolltodiv);
		var st_ht = scrollto.offsetHeight;
//		scrollto.style.height = (st_ht+newH-0)+"px";
	}
	
	var images = document.createElement('img');
	images.src = filename;
	targetnode.appendChild(images);
	images.align = alignimg;
	images.border = '0';
	images.style.height = newH+"px";
	images.style.width = wt+"px";
	images.height = newH;
	images.width = wt;
	images.style.position = "relative";
//	alert("h:"+newH+"  wt"+wt);
	if ($("browser_box"+targinput)) {
		//this is not compatible with IE
		set_ht_by_content_plus("browser_box"+targinput,5,newH);
		set_ht_by_content_plus("browser_box"+targinput,5,newH);
	}
		

}

function detect_optional() {
	//for inserting custom lines in the itinerary
	var val = document.getElementById("endday").value;
	var spannode = document.getElementById("opttitle");
	var spaninput = document.getElementById("opttitle_text");
	if (val > 899) {
		//spaninput.removeChild(document.getElementById("opttitle_text").firstChild);
		
		var spantxt = document.createTextNode(" Enter optional title: ");
		spannode.removeChild(document.getElementById("opttitle").firstChild);
		spannode.appendChild(spantxt);
		
		spaninput.removeChild(document.getElementById("opttitle_text").firstChild);
		
		newfield = document.createElement("input");
		spaninput.appendChild(newfield);
		newfield.name = "opt_title";
		newfield.id = "opt_title";
		newfield.type = "text";
		newfield.value = "(Optional)";
	} else {
		if (document.getElementById("opt_title")) {

			spaninput.removeChild(document.getElementById("opttitle_text").firstChild);			
			spannode.removeChild(document.getElementById("opttitle").firstChild);	
	
			var spantxt = document.createTextNode(" ");
			var spantxst = document.createTextNode(" ");			
			spannode.appendChild(spantxt);
			spaninput.appendChild(spantxst);
		}
	}
}

function returnHint(str,targetid,usefile,args){

	var url = usefile;

	finalElem = targetid;	
	
    if (str.length==0) { 
      document.getElementById(finalElem).innerHTML="";
      return;
    }
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
      alert ("Your browser does not support AJAX!");
      return;
    }	
    url=url+"?l="+str+"&ex="+targetid+args;
    url=url+"&xxx="+Math.random();

	//alert(" "+finalElem+" "+url+" "+str);

    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
} 


function getHint(str,idname,idrefs,userid,owner,tagonly,tagonlytarget) {
	var extra = idname;
	var pos = idname.indexOf("?");
	var tags_qry = "";
	var extra_start = "";
	var extra_end = "";
	
	finalElem = idrefs;

	if (pos > -1) {
		extra = idname.substring(pos+1);
		idname = idname.substring(0,pos);  
	}
	var url = "js/get"+idname;
	
	if (tagonly == 'y') {
		var pos_tags = extra.indexOf('&tags=');
		
		//change tags to include value in target field if tagonly=y
		var t = extra.substring(pos_tags+6);
		var pos_next_ampersand = t.indexOf("&");
		if (pos_next_ampersand > -1) {
			extra_start = extra.substring(0,pos_tags);
			extra_end = extra.substring(pos_next_ampersand+1);
		} else {
			extra_start = extra.substring(0,pos_tags); 
		}
		current_tags = document.getElementById(tagonlytarget).value;
		if ( current_tags.length > 0 ) {
			tags_qry = "&tags="+current_tags;
		}
		extra = extra_start+extra_end;	
	}
	
	url = url+".php";
	
    if (str.length==0) { 
      document.getElementById(finalElem).innerHTML="";
      return;
    }
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
      alert ("Your browser does not support AJAX!");
      return;
    }

    url=url+"?l="+str+extra+"&user_id="+userid+"&owner="+owner+"&ex="+idname+"&idrefs="+idrefs+"&tagonly="+tagonly+"&tagonlytarget="+tagonlytarget+tags_qry;
    url=url+"&xxx="+Math.random();
    
	//alert(" "+finalElem+" "+url+" "+str);

    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
} 

function check_date_format(dateval) {
	//make sure date was entered as yyyy-mm-dd and that the correct number of days in a month have been entered. No 31 in Feb.
	/*
	// String format yyyy-mm-dd
	var rgx = /(\d{4})-(\d{2})-(\d{2})/;
	var s = '1997-02-13';
	var m = s.match(rgx);
	
	// m[1] is year '1999'
	// m[2] is month '02'
	// m[3] is day '13'
	*/
	var err = "";
	var bool = true;
	var dateval = dateval.replace('/','-');
		//dateval.replace(/\//gi,'-');
	var arr = new Array();
	var numdigits;
	var numdays;
	
	arr = dateval.split('-');
	if (arr.length != 3) {
		bool = false;
		alert(dateval+" Enter your dates as YYYY-MM-DD.");
		return bool;
	}
	var i = 0;
	for (i=0; i<arr.length; i++) {
		var arrtxt = "";	
		numdigits = 2;
		switch (i) {
			case 0:
				numdigits = 4;
				minnumdays = 1000;
				numdays = 9999;		
			break;
			case 1:
				numdigits = 2;
				numdays = 12;		
				minnumdays = 0;	
				if (parseInt(arr[1],10) > numdays) {
					alert(dateval+" There are only 12 months in a year.");
					bool = false;
					return bool;
				}
				//arr[1] = parseInt(arr[1]);
			break;
			case 2:
				numdigits = 2;
				minnumdays = 0;							
				if ((parseInt(arr[1],10) < 12) && (parseInt(arr[1],10) > 1)) {
					var tempmth = parseInt(arr[1]) + 1;
					var tempdate = new Date();
					tempdate.setDate(1);
					tempdate.setMonth(tempmth-1);
					tempdate.setFullYear(parseInt(arr[0],10));
					tempdate.setHours(0,0,0,0);
					var d = Date.parse(tempdate) - (1000*60*60*24);
					tempdate.setTime(d);
					numdays = parseInt(tempdate.getDate(),10);
				} else { 
					numdays = 31;
				}
				if (parseInt(arr[2],10) > numdays) {
					bool = false;
					alert(dateval+" You entered more days than there are in a month.");
					return bool;
				}
				//arr[2] = parseInt(arr[2]);
			break;
		} //end switch
		arrtxt = arr[i];
//		alert(arrtxt);
		if (   ( ((i == 0) && (arrtxt.length == numdigits)) || ( (arrtxt.length <= numdigits) && (arrtxt.length > 0 ) ) )  ) {
			if (arr[i] == parseInt(arr[i],10)) {
				if (parseInt(arr[i],10) <= numdays) {
					if (parseInt(arr[i],10) > minnumdays) {
						//true
						var d = new Date();
						d.setDate(parseInt(arr[2],10));
						d.setMonth(parseInt(arr[1],10)-1);
						d.setFullYear(parseInt(arr[0],10));
						d.setHours(1,0,0,0);
					} else {
						bool = false;
						err = "Entry is less than the minimum number of days ("+i+")";
					}
				} else {
					bool = false;
					err = "Entry is more than the max number of days ("+i+")";
				}
			} else {
				bool = false;
				err = "Entry is non-numeric ("+i+").";
			}
		} else {
			bool = false;
			err = "Wrong number of digits ("+i+" "+arrtxt.length+" "+numdigits+")";
			//alert(dateval+" "+err+" Date must be entered as YYYY-MM-DD");
			//return bool;
		}
		if (bool == false) {
			bool = false;
			alert(dateval+" "+err+" Date must be entered as YYYY-MM-DD");
			return bool;			
		}
	} //end for
//	alert(d);
	if (bool == false) return bool;
	else return d;
}

function get_tag_by_name_js(ell,divtarget) {
	followLink('../js/get_tag_by_name.php?l='+ell,divtarget);
	
}

function confirmbox(url,ref,message) {
	var r=confirm(message)
	if (r==true) {
		followLink(url,ref);
	}
}

function add_new_items(item,title) {
	
}

function show_or_hide(check_element,display_id) {
	if (document.getElementById(check_element)) {
		var spanTxt = document.createTextNode("Hide");
	} else {
		var spanTxt = document.createTextNode("Show");
	}
	var newSpan = document.getElementById(display_id);
	newSpan.removeChild(document.getElementById(display_id).firstChild);
	newSpan.appendChild(spanTxt);
}

function showHideWithText(check_element,id_of_showhide) {
	var hiddendiv = $(check_element);
	if (hiddendiv.className == "show") {
		var spanTxt = document.createTextNode("Show");
		hiddendiv.className = "hide";
	} else {
		var spanTxt = document.createTextNode("Hide");
		hiddendiv.className = "show";
	}
	var newSpan = document.getElementById(id_of_showhide);
	newSpan.removeChild(document.getElementById(id_of_showhide).firstChild);
	newSpan.appendChild(spanTxt);
}


function setCheckFlag(itemid) {
	var flag = document.getElementByID(itemid).checked.value;
	alert(itemid + "  "+flag);
	if (flag == "false") {
		document.getElementByID(itemid).checked = true;
	}
	else {
		document.getElementByID(itemid).checked = false;
	}
	
}

function multipleSetByName(elname,attr,val) {
	var elems = new Array;
	if (!document.getElementsByName(elname)) return;
	elems = document.getElementsByName(elname);
	for (i=0; i < elems.length; i++) {
		elems[i].setAttribute(attr,val);
	}
}

function multipleSetBGByName(elname,val) {
	var elems = document.getElementsByName(elname);
	for (i=0; i < elems.length; i++) {
		elems[i].style.background = val;
	}
}


function multipleUnsetBGByName(elname,checkval,color1,color2,chk1,chk2) {
	if (!document.getElementsByName(elname)) 
		return;
	var elems = document.getElementsByName(elname);
//	alert(elems.length);
	var childs,childone,textx;
		
	for (i=0; i < elems.length; i++) {
//		elems[i].style.background = "lightgreen";
		childs = elems[i].firstChild;
		while (childs.id != checkval) {
			childs = get_nextSibling(childs);
		}
//		if (childs.id == checkval)
//			textx += childs.id+" "+childs.firstChild.firstChild.nodeValue+" "+i+"| ";
		if (childs.firstChild.firstChild.nodeType == '3') {
			if (childs.firstChild.firstChild.nodeValue == chk1.toUpperCase()) {
				elems[i].style.background = color1;
			} else elems[i].style.background = color2;
		} else return;
	}
//	alert(textx);	
}

function check_selected(chkdboxname,toChkPreName,boolval) {
	var a = new Array();	
	var elem = document.getElementsByName(chkdboxname);
	if (!elem) return false;
	for (i = 0; i < elem.length; i++) {
		if (elem[i].checked == true) {		
			var elname = ""+toChkPreName+elem[i].value+"";
			document.getElementById(elname).checked = boolval;
		}
	}
}

function checkboxes_to_array(delimiter,chkboxname,args,target,filez) {
	followLink(filez+"?"+args+"&"+chkboxname+"="+delimit_text(chkboxname,delimiter),target);
}

function checkbox_to_array(delimiter,hiddenid1,hiddenid2,chkboxname,hiddenid2value,formname,args,target,filez) {
	if (document.getElementById(hiddenid1).value = delimit_text(chkboxname,delimiter)) {
		if (hiddenid2 != "none") 
			document.getElementById(hiddenid2).value = hiddenid2value;
		if (formname != "none") {
			document.formname.submit();
		} else {
			followLink(filez+"?"+args+"&"+hiddenid1+"="+$(hiddenid1).value+"&"+hiddenid2+"="+$(hiddenid2).value,target);
		}
	} else return false;
}

function checkbox_value_array(chkbox_id) {
	//resturn array of checkbox values
	var a = new Array();
	var elem = document.getElementsByName(chkbox_id);
	if (!elem)
		return false;
	for (i=0; i < elem.length; i++) {
		if (elem[i].checked == true) {
			a.push(elem[i].value);
		}
	}

	return Array(a,a.length);

}


function delimit_text(el,d) {
	//turn an array into a string separated by 
	var a = new Array();
	var elem = document.getElementsByName(el);
	if (!elem)
		return false;
	for (i=0; i < elem.length; i++) {
		if (elem[i].checked == true) {
			a.push(elem[i].value);
		}
	}
	if (a.length > 0) {
		return a.join(d);
	} else {
		alert("Nothing has been checked off.");
		return false;
	}
}

function multipleStyleByName(elname,attr,val) {
	var elems = new Array;
	if (!document.getElementsByName(elname)) return;
	elems = document.getElementsByName(elname);
	for (i=0; i < elems.length; i++) {
		elems[i].style.setAttribute(attr,val);
	}
}

function get_child_with_className_of(parent_id,class_name) {
	//get child of parent with class name = class_name
	//used to make menu pop in IE for cwsx.
	var children = document.getElementById(parent_id).childNodes;
	for(j=0; j<children.length; j++) {
		if (children[j].className == class_name) {
/* 			alert(children[j].className+" "+class_name); */
			return children[j];
		}
	}
}

function get_firstChild(n) {
	y=n.firstChild;
	while (y.nodeType!=1) {
		y=y.nextSibling;
	}
	return y;
}


function get_nextSibling(n) {
	y = n.nextSibling;
	while (y.nodeType!=1) {
		y=y.nextSibling;
  }
return y;
}

function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	//USE THIS FUNCTION ALWAYS
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

function new_el(eltype,newid,parentel) {
/* functio ndoes not work*/
	var x;
	var l = document.createElement(eltype);
	l.id = newid;
	if (x = $(parentel)) x.appendChild(l);
}

function setAttributes (object, attributeName, attributeValue)
{
	var attributeNode = document.createAttribute (attributeName);
	attributeNode.value = attributeValue;
	object.setAttributeNode (attributeNode);
} // end setAttribute method

function createNewElements (type,newID) {
	var newE = document.createElement(type);
	newE.id = newID;
}

function get_coords(event) {
	x=event.clientX;
	y=event.clientY;
	return Array(x,y);
}

function nums_only (combined) {
//	alert(combined);
	var ValidChars = "0123456789.";
	var falsechar = 0;
	var isNumber=true;
	var Char;
	for (i = 0; i < combined.length && isNumber == true; i++) {
		char = combined.charAt(i);
		if (ValidChars.indexOf(char) == -1) {
			isNumber = false;
			falsechar = (i);
			break;
		}
	}
	return combined.substring(0,falsechar);	
}

function setOpacity( element, alphaa ) {

	element.style.filter="alpha(opacity:"+(alphaa*100)+")";
	element.style.KHTMLOpacity=alphaa;
	element.style.MozOpacity=alphaa;
	element.style.opacity=alphaa;
/*
	var style = element.style;
	
	if( style.MozOpacity != undefined ) { //Moz and older
		style.MozOpacity = alpha;
	}
	else if( style.filter != undefined ) { //IE
		//style.filter = "alpha(opacity=0)";
		//element.filters.alpha.opacity = ( alpha * 100 );
	}
	else if( style.opacity != undefined ) { //Opera
		style.opacity = alpha;
	}*/
}

function hover_div(x,y,newname,whereto,tie_to_div,bg,event,trigger_div) {
	//create a div with a bg image at a location near the location of the element that triggered the event
	
	//no need for x,y
	
	//get top and left coordinates of element that triggered the event
	//targ = event.currentTarget;
	targ = $(trigger_div);
	ty = parseInt(nums_only(targ.style.top))+parseInt(y);
	tx = parseInt(nums_only(targ.style.left)) + parseInt(x); //x-190 y-145
	var tie_to = $(tie_to_div);
	var w = "215";
	var h = "191";
	
	if ($(newname)) {
		//delete element 
		rem_el(newname);
	}
	

	var hoverdiv = document.createElement("div");
	hoverdiv.id = newname;
	hoverdiv.style.position = "absolute";
	hoverdiv.style.border = "0px solid red";

	hoverdiv.style.background = bg;
	hoverdiv.style.left = tx;
	hoverdiv.style.top = ty;
	hoverdiv.style.height = h;
	hoverdiv.style.width = w;
	setOpacity(hoverdiv,0.95);
	hoverdiv.style.zIndex = "9";
	tie_to.appendChild(hoverdiv);

	hoverdiv.style.zIndex = '9';
	hoverdiv.onmouseover = function () {
		remoteTimeout(hoverdiv.id);
	}
	hoverdiv.onmouseout = function () {
		remoteSetTimeout(hoverdiv.id);
	}	
			
	var infodiv = document.createElement("div");
	infodiv.style.top = "10";
	infodiv.style.left = "10";	
	infodiv.style.width = "170px";
	infodiv.style.height = "170px";
	infodiv.style.zIndex = "11";
	infodiv.style.position = "absolute";
	infodiv.id = "div"+newname;
	hoverdiv.appendChild(infodiv);
	
	var s_load = document.createElement("span");
	s_load.id = "load";
	s_load.style.top = "15";
	s_load.style.left = "15";
	s_load.style.position = "relative";
	hoverdiv.appendChild(s_load);
	
	followLink_no_load_div(whereto,"div"+newname);
}

function show_edit_hover(x,y,right_left,trigger_el,newname,message) {
	//shorten substring to fit in box
	//message = message.substring(0,8);
	
	trigger = document.getElementById(trigger_el);
	
	//create a div with a bg image at a location near the location of the element that triggered the event
	var hoverdiv = document.createElement("div");
	hoverdiv.id = newname;
	hoverdiv.style.position = "absolute";
	if (right_left == "right") {
		hoverdiv.style.right = x;
	} else {
		hoverdiv.style.left = x;
	}
	hoverdiv.style.background = "url(../nav/edit4.gif)";
	hoverdiv.style.top = y;
	hoverdiv.style.height = "40px";
	hoverdiv.style.width = "100px";
	hoverdiv.style.zIndex = "15";
	hoverdiv.style.border = "0px solid black";
	setOpacity(hoverdiv,0.85);	
	
	trigger.appendChild(hoverdiv);	
	hoverdiv.style.zIndex = "15";

	var editspan = document.createElement("p");
	editspan.className = "para_smltxt";
	editspan.style.left = "35px";

	editspan.style.position = "absolute";
	editspan.style.top = "5px";
	editspan.style.height = "32px";
	editspan.style.width = "60px";
	editspan.style.overflow = "hidden";
	editspan.style.color = "#444";
	editspan.style.border = "0px solid lightblue";		
	var edittxt = document.createTextNode(message);

	hoverdiv.appendChild(editspan);
	editspan.appendChild(edittxt);	
}


function remove_el(el) {
	//legacy function
	rem_el(el);
}

function rem_el(el) {
	if (temp = $(el)) {
		temp.parentNode.removeChild(temp);
	}
}

function no_blank(str) {
	if (!str) {
		str = " ";
	}
	return str;
}


function insertBlankTableRow(gTableId,plusOneRow,numColSpans,newrowID,currentrowID,newcelldivID) {
	//gTableId: tbody id
	//position: direction to place new row (-1 or +1)
	//spans - columns to span; newrowname: id for new row; currentrow: currentrow id; whereto: pathname of target; queryargs: queries.
//	var nSpanId = currentrow+newrowname+position;
	
	rindx = document.getElementById(currentrowID);
	//alert(rindx.rowIndex);	
	lineno = rindx.rowIndex+plusOneRow;
	
	createTableRow(gTableId,lineno,numColSpans,newcelldivID,newrowID);
}

function createTableRow (gTableId,lineNo,spans,newcelldivID,newrowID) {
	
	rem_el(newcelldivID);
	rem_el(newrowID);
   	
   	var gCell = document.createElement("td");
   	gCell.colSpan=spans;
	gCell.id = newrowID+newcelldivID;
	   	
	var newSpan = document.createElement("div");
	newSpan.id=newcelldivID;
   	var spanTxt = document.createTextNode("   ");
	newSpan.appendChild(spanTxt);
	
   	gCell.appendChild(newSpan);
   	
	var gTableB = document.getElementById(gTableId);
   	var gRow = gTableB.insertRow(lineNo);
   	
   	gRow.id = newrowID;
   	gRow.appendChild(gCell);
}



function insertTableObj(gTableId,position,spans,newrowname,currentrow,whereto,queryargs) {
	//gTableId: tbody id
	//position: direction to place new row (-1 or +1)
	//spans - columns to span; newrowname: id for new row; currentrow: currentrow id; whereto: pathname of target; queryargs: queries.
	var nSpanId = currentrow+newrowname+position;
	
	rindx = document.getElementById(currentrow);
	//alert(rindx.rowIndex);
	lineno = rindx.rowIndex+1;
	createTableX(gTableId,lineno,spans,nSpanId,newrowname);
	//whereto in case we want to use this script for another destination url
//	alert(whereto+queryargs);

	followLink(whereto+queryargs,nSpanId);	
/*
	var pos = queryargs.indexOf("&scrollto=");
	if (pos > -1) {
		var scrollto = queryargs.substring(pos+1,queryargs.length);
		pos = scrollto.indexOf("&");
		if (pos > -1) {
			scrollto = scrollto.substring(0,$pos);
		}
		scrollto = scrollto.substring((scrollto.indexOf("=")+1),scrollto.length);
		ScrollToElement(scrollto);
	}
*/
}

function createTableX (gTableId,lineNo,spans,nSpanId,temprow) {
	
	if (document.getElementById(temprow)) {
		tempChild = document.getElementById(temprow);
		TableObj = document.getElementById(gTableId);
		TableObj.removeChild(tempChild);
		return;
	}
   	
   	var gCell = document.createElement("td");
   	gCell.colSpan=spans;
	gCell.id = temprow+nSpanId;
	   	
	var newSpan = document.createElement("span");
	newSpan.id=nSpanId;
   	var spanTxt = document.createTextNode("   ");
	newSpan.appendChild(spanTxt);
	
   	gCell.appendChild(newSpan);
   	
	var gTableB = document.getElementById(gTableId);
   	var gRow = gTableB.insertRow(lineNo);
   	
   	gRow.id = temprow;
   	gRow.appendChild(gCell);

/*
When adding rows to a table:

1. Don"t ever user innerHTML (OK, you didn"t do that)

2. Don"t append rows to the table, append them to a
    tableSection element (tbody, thead or tfoot)

3. Consider using insertRow(-1) on the table or tableSection
    so the row is created and appended in one statement.
*/
}


/* ******************************************************************** */
/* ******************************************************************** */

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
    
//    window.alert( 'alertSize(IE): Width = ' + myWidth );
// 	window.alert( 'Height = ' + myHeight );
 	
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
    
//	window.alert( 'alertSize(IE): Width = ' + myWidth );
//	window.alert( 'Height = ' + myHeight );
    
  }
  return [myWidth,myHeight];
/*
  window.alert( 'alertSize(IE): Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );

*/
}

//document.onmousemove = alertCoord;
//document.onmousemove = grabCoord;
//grabCoord(arguments[0]);

function alertCoord(e) {
  var xcoord, ycoord;
  if( !e ) { e = window.event; }
  if( !e ) { return; }
  if( typeof( e.pageX ) == 'number' ) {
    xcoord = e.pageX;
    ycoord = e.pageY;
  } else if( typeof( e.clientX ) == 'number' ) {
    xcoord = e.clientX;
    ycoord = e.clientY;
    if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      xcoord += document.body.scrollLeft;
      ycoord += document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      xcoord += document.documentElement.scrollLeft;
      ycoord += document.documentElement.scrollTop;
    }
  } else { return; }
  window.alert('Mouse coordinates are ('+xcoord+','+ycoord+')');
}

function grabCoord(e) {
  var xcoord, ycoord;
  if( !e ) { e = window.event; }
  if( !e ) { return; }
  if( typeof( e.pageX ) == 'number' ) {
    xcoord = e.pageX;
    ycoord = e.pageY;
  } else if( typeof( e.clientX ) == 'number' ) {
    xcoord = e.clientX;
    ycoord = e.clientY;
    if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      xcoord += document.body.scrollLeft;
      ycoord += document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      xcoord += document.documentElement.scrollLeft;
      ycoord += document.documentElement.scrollTop;
    }
  } else { return; }
  
  return [xcoord,ycoord];
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}


/*
//determine if cursor is within the box still
								
								var coords = grabCoord(arguments[0]);
								var whereE = findPos(this);
// 								alert(coords.length+\" coords:\"+coords[0]+\" | \"+coords[1]+\" element location: \"+whereE[0]+\" | \"+whereE[1]); 
								var botx = (whereE[0] + nums_only(this.style.width));
								var boty = (parseInt(whereE[0]) + parseInt(nums_only(this.style.height)));
								if ( ((coords[0] > whereE[0]) && (coords[0] < botx )) && ((coords[1] > whereE[1]) && (coords[1] < boty)) ) {
									alert(coords.length+\" coords:\"+coords[0]+\" | \"+coords[1]+\" element location: \"+whereE[0]+\" | \"+whereE[1]+\"  boxcoords: x/y: \"+botx+\"  \"+boty);
								} else {
									alert(\"not\"+boty+\"  \"+parseInt(whereE[0])+\"  \"+parseInt(nums_only($(\"thumbrow\"+".$row_count.").style.height)) );
								}
*/

function setAstyle(aElement /* object */, aDeclaration /* CSS Declaration */) {
	try {
		if (aElement) {
			//aDeclaration = aDeclaration.replace(/\s+/g,''); // remove all white spaces
			if (document.all) { // IE Hack
				aElement.style.setAttribute('cssText',aDeclaration);
				return (true);
			} else { // The clean way
				aElement.setAttribute ('style', aDeclaration);
				return (true);
			}
		}
	} catch (e) {
		return (false);
	}
}




/********************************/
function strip_tags(str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
 
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
  
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
 
    return str;
}

function strip_tags_basic(str) {
	return str.replace(/&lt;\/?[^&gt;]+&gt;/gi, "");
	//return $text.replace(/<\/?[^>]+>/gi, '');
}

			/********************************************/


function echeck(str) {
	if (str.length > 0) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID");
		   return false;
		}
	
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail Address");
		   return false;
		}
	
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
			alert("Invalid E-mail Address");
			return false;
		}
	
		 if (str.indexOf(at,(lat+1))!=-1){
			alert("Invalid E-mail Address");
			return false;
		 }
	
		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
			alert("Invalid E-mail Address");
			return false;
		 }
	
		 if (str.indexOf(dot,(lat+2))==-1){
			alert("Invalid E-mail Address");
			return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
			alert("Invalid E-mail Address - ensure there are no spaces.");
			return false;
		 }
	
		 return true;
	} else {
		alert('E-mail address is required.');
		return false;
	}
}

function isValidEmail(str) {
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function isURL(urlStr) {
	if (urlStr.indexOf(" ") != -1) {
		alert("Spaces are not allowed in a URL");
		return false;
	}
	if (urlStr == "" || urlStr == null) {
		return true;
	}
	urlStr=urlStr.toLowerCase();

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
	var urlPat=/^http:\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
	var matchArray=urlStr.match(urlPat);
	
	if (matchArray==null) {
		//alert("The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s");
		return false;
	}

	var user=matchArray[2];
	var domain=matchArray[3];

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			//alert("This domain contains invalid characters.");
			return false;
		}
	}
	
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i) > 127) {
			//alert("This domain name contains invalid characters.");
			return false;
		}	
	}
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat) == -1) {
			//alert("The domain name does not seem to be valid.");
			return false;
		}
	}
	return true;
} 

function chkstrlen(str,l,striptags,descr) {
	if (!str) {
		alert('An entry is required for: '+descr+'.');		
		return false;
	}
	if (striptags == 'y') {
		var newstr = strip_tags(str, '');
		if (newstr != str) {
			alert("Illegal characters have been removed from your entry.\n\nIt has been changed to: "+newstr);
		}
		str = newstr;		
	}
	if (str.length < l) {
		alert('Your '+descr+' is not long enough.');
		return false;
	}
	return true;
}

function isURLx(s)
{ 
//MAY NOT WORK
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}

function edit_pagebodytext(fieldnamearray,pdfid,pagetext,pagetitle) {
	//for pagebodyfields.php
	
	var pdfidfld = $(fieldnamearray[1]);
	var new_text_area = $(fieldnamearray[0]);
	var new_title_fld = $(fieldnamearray[2]);
								
	new_text_area.value = pagetext;
	pdfidfld.value = pdfid;
	new_title_fld.value = pagetitle;
}

function makeBox(trigger_div,xpos,ypos,w,h,framecolor,backcolor,txtcolor,newname) {
	
	//get top and left coordinates of element that triggered the event
	//targ = event.currentTarget;
	var targ = $(trigger_div);
	
	//get position of element of id trigger_div (targ) on page 
	var posArray = new Array();
	
	//ElementPagePosition gets the current position ON THE PAGE of the targ element. 
	//Doing this, we would be setting our new box to sit as a child of the targ at left and top of the targ's page
	//position. So, if targ is at 900,800, then the new box will be at 900,800 OF targ - not of the page.
	posArray = ElementPagePosition(trigger_div); //send element id of targ to get position
	var selectedPosX = posArray[0];
	var selectedPosY = posArray[1];

	//set intended page position of new box 
//	var tx = parseInt(selectedPosX) + parseInt(xpos); //x-190 y-145
//	var ty = parseInt(selectedPosY)+parseInt(ypos);
	var tx = parseInt(xpos); //x-190 y-145
	var ty = parseInt(ypos);
	
	var tie_to = $(trigger_div);
	
	if ($(newname)) {
		//delete element 
		rem_el(newname);
	}
	
	var hoverdiv = document.createElement("div");
	tie_to.appendChild(hoverdiv);

	hoverdiv.id = newname;
	hoverdiv.style.position = "absolute";
	hoverdiv.style.left = tx+"px";
	hoverdiv.style.top = ty+"px";
	hoverdiv.style.height = h;
	hoverdiv.style.width = w;
	hoverdiv.style.zIndex = "234";
	hoverdiv.style.border = "2px solid "+framecolor;
	hoverdiv.style.background = backcolor;
	hoverdiv.style.color = txtcolor;


	
	var closeboxline = document.createElement("p");
	hoverdiv.appendChild(closeboxline);
	closeboxline.style.textAlign = "right";
	closeboxline.className = "para_smltxt smltxt_b";
	closeboxline.style.borderBottom = "1px solid #647bad";

	
	var closebox = document.createElement("a");
	closeboxline.appendChild(closebox);
	closebox.appendChild(document.createTextNode("Close"));	
	closebox.style.cursor = "pointer";
	closebox.onclick = function() {
							rem_el(newname);
							return false;
						}



}

function pop_cal(trigger_div,target_input,otherdateid,currdate_str,xpos,ypos) {
	var framecolor = "#222";
	var backcolor = "#fff";
	var txtcolor = "#444";
	
	var w = "200";
	var h = "250";
	
	//grab another date field (if exists) and insert into the php file below for comparison. 
	//That way the start date from previous field can be the starting point for our calendar if greater than today's date 
	if ($(otherdateid)) {
		var otherdatestr = $(otherdateid).value;

	} else {
		var otherdatestr = 0;
	}

	//make box of size w,h at an offset of xpos,ypos from the location of div id trigger_div.
	makeBox(trigger_div,xpos,ypos,w,h,framecolor,backcolor,txtcolor,"newbox"+target_input);
	
	//access the php calendar file and place inside the box we created 
	followLink("includes/calendar/makecal.php?&currdate="+currdate_str+"&caltarget="+target_input+"&closecal=newbox"+target_input+"&closefunction=rem_el&otherdatestr="+otherdatestr,"newbox"+target_input);
	
}

function get_radio_value(radio_name) {
	var radiobut = new Array();
	radiobut = document.getElementsByName(radio_name);
	alert(radiobut.length);
	for (i=0; i < radiobut.length; i++) {
	   if (radiobut[i].checked == true) {
		  var rad_val = radiobut[i].value;
		}
	}
	alert(rad_val);
	return rad_val;
}

function make_el_dom(eltype,classN,textN,parentNid,ident) {
	var newEl = document.createElement(eltype);
	$(parentNid).appendChild(newEl);
	newEl.id = ident;
	newEl.className = classN;
	if (textN.length > 0) {
		newEl.appendChild(document.createTextNode(textN));
	}
	return newEl;
}

function make_el_dom_before_firstchild(eltype,classN,textN,parentID,ident) {
	var newEl = document.createElement(eltype);
	var parentEl = $(parentID);
	parentEl.insertBefore(newEl,parentEl.firstChild);
	newEl.id = ident;
	newEl.className = classN;
	if (textN.length > 0) {
		newEl.appendChild(document.createTextNode(textN));
	}
	return newEl;
}


function make_input_el(inpType,parentID,val,newID,newName) {
	//create input element 
	var vi = document.createElement("input");
	vi.type = inpType;
	$(parentID).appendChild(vi);
	vi.value = val;
	vi.id = newID;
	vi.name = newName;
	return vi;
}

