/* Event Functions */

// Add an event to the obj given
// event_name refers to the event trigger, without the "on", like click or mouseover
// func_name refers to the function callback when event is triggered
function addEvent(obj,event_name,func_name){
	if (obj.attachEvent){
		obj.attachEvent("on"+event_name, func_name);
	}else if(obj.addEventListener){
		obj.addEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = func_name;
	}
}

// Removes an event from the object
function removeEvent(obj,event_name,func_name){
	if (obj.detachEvent){
		obj.detachEvent("on"+event_name,func_name);
	}else if(obj.removeEventListener){
		obj.removeEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = null;
	}
}

// Stop an event from bubbling up the event DOM
function stopEvent(evt){
	evt = evt || window.event;
	if (evt.stopPropagation){
		evt.stopPropagation();
		evt.preventDefault();
	}else if(typeof evt.cancelBubble != "undefined"){
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	return false;
}

// Get the obj that starts the event
function getElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.currentTarget;
	}
}
// Get the obj that triggers off the event
function getTargetElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.target;
	}
}
// For IE only, stops the obj from being selected
function stopSelect(obj){
	if (typeof obj.onselectstart != 'undefined'){
		addEvent(obj,"selectstart",function(){ return false;});
	}
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function getCaretEnd(obj){
	if(typeof obj.selectionEnd != "undefined"){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}

		try{
			Lp.setEndPoint("EndToEnd",M);
		}catch(e){
			return -1;
		}finally{
			var rb=Lp.text.length;
			if(rb>obj.value.length){
				return -1;
			}
			return rb;
		}
		/*
		Lp.setEndPoint("EndToEnd",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;*/
	}
}
// Get the start position of the caret in the object
function getCaretStart(obj){
	if(typeof obj.selectionStart != "undefined"){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}

		try{
			Lp.setEndPoint("EndToEnd",M);
		}catch(e){
			return -1;
		}finally{
			var rb=Lp.text.length;
			if(rb>obj.value.length){
				return -1;
			}
			return rb;
		}
	}
}
// sets the caret position to l in the object
function setCaret(obj,l){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(l,l);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',l);
		m.collapse();
		m.select();
	}
}
// sets the caret selection from s to e in the object
function setSelection(obj,s,e){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(s,e);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',s);
		m.moveEnd('character',e);
		m.select();
	}
}

/*    Escape function   */
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
/*String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}*/
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
/* --- Escape --- */

/* Offset position from top of the screen */
function findPos(obj) {
	if (!obj) return ;
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function findPosSize(obj) {
	if (!obj) return ;
	var curleft = curtop = 0;
	var width = obj.offsetWidth;
	var height = obj.offsetHeight;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop,width,height];
}

function curTop(obj){
	toreturn = 0;
	while(obj){
		if(obj.scrollTop) toreturn -= obj.scrollTop;
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj){
	toreturn = 0;
	while(obj){
		if(obj.scrollLeft) toreturn -= obj.scrollLeft;
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}

function getPopupTop(active_obj, popup_height){
	var nTop_obj = curTop(active_obj);
	var nTop = nTop_obj + active_obj.offsetHeight;
	//nTop += get_scrollTop();
	if(nTop + popup_height > get_scrollTop() + parseInt(document.body.clientTop + document.body.clientHeight)){
		nTop = nTop_obj - popup_height - 5 ;
	}
	return (nTop) + 'px';
}



function get_scrollTop(){
	var SF = (navigator.userAgent.indexOf("Safari") > -1)  ? 1 : 0;
	var nValue = 0;

	if (!SF && document.documentElement && typeof(document.documentElement.scrollTop)!='undefined'){
		nValue = document.documentElement.scrollTop;
	} else if(typeof(document.body.scrollTop)!='undefined') {
		nValue = document.body.scrollTop;
	} else if(self && typeof(self.pageYOffset)!='undefined') {
		nValue = self.pageYOffset;
	}

	return nValue;
}


/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}
function isObject(o) {
	return (typeof(o)=="object");
}
function isArray(obj) {
    return obj.constructor == Array;
} 
function isFunction(o) {
	return (typeof(o)=="function");
}
function isString(o) {
	return (typeof(o)=="string");
}
function isDate(o){
	return(typeof(o)==='date')?true:(typeof(o)==='object')?o.constructor.toString().match(/date/i)!==null:false;
}

function CSN(sValue) {
	if(isNumber(sValue)) return sValue;
	sValue = ''+sValue;
	sValue = sValue.replace(/\,/gi,'');
	sValue = sValue.replace(/\$/gi,'');
	value = parseFloat(sValue);
	return (value?value:0);
}

function FormatNumber(fValue, nDecSize) {
	var sValue='';
	nDecSize = (isNumber(nDecSize)?nDecSize:2);
	fValue = CSN(fValue);
	if (fValue){
		sValue = fValue.toFixed(nDecSize);
		return addCommas(sValue);
	}
	return sValue;
}

function HTMLFormatNumber(fValue, nDecSize, zero_caption) {
	var sValue='&nbsp';
	nDecSize = (isNumber(nDecSize)?nDecSize:2);
	fValue = CSN(fValue);
	if (fValue){
		sValue = fValue.toFixed(nDecSize);
		return addCommas(sValue);
	} else {
		if(zero_caption) sValue = zero_caption;
	}
	return sValue;
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/* Object Functions */

function urlencode(str) {
	str = escape(''+str);
	str = str.replace(/\+/g, '%2B');
	//str = str.replace(/\%\2\0/g, '+');
	str = str.replace(/\*/g, '%2A');
	str = str.replace(/\\/g, '%5C');
	//str = str.replace(/\\/g, '%2F');
	str = str.replace(/\//g, '%2F');
	str = str.replace(/\@/g, '%40');
	return str;
}

function urldecode(str) {
	str = str.replace(/\+/g, ' ');
	str = unescape(str);
	return str;
}

function replaceHTML(obj,text){
	while(el = obj.childNodes[0]){
		obj.removeChild(el);
	};
	obj.appendChild(document.createTextNode(text));
}

function HTMLEncode(str) {
	str = ''+str;
	str = str.replace(/&/g, "&amp;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	str = str.replace(/\"/g, "&quot;");
	str = str.replace(/\n/g, "<br />");
	return str;
} 

function GetAddress(Street, City, State, Zip, Phone, Fax, URL, Email) {
	var ret = Street;
	var Phone = Phone || '';
	var Fax = Fax || '';
	var URL = URL || '';
	var Email = Email || '';
	
	if((City+State+Zip).length){
		if (ret.length) ret += "\n";
		ret += City+', '+State+' '+Zip;
	}
	if((Phone+Fax).length){
		if (ret.length) ret += "\n";
		ret += (Phone.length? 'TEL: '+Phone: '')+(Phone.length>0 && Fax.length>0? '    ':'')+(Fax.length? 'FAX: '+Fax: '');
	}
	if(URL.length){
		if (ret.length) ret += "\n";
		ret += URL;
	}
	if(Email.length){
		if (ret.length) ret += "\n";
		ret += Email;
	}
	return (ret);
}

function HTMLGetAddress(Street, City, State, Zip, Phone, Fax, URL, Email) {
	return HTMLEncode(GetAddress(Street, City, State, Zip, Phone, Fax, URL, Email));
}

function getCSSRule(name) {
	for(i=0; i<document.styleSheets.length; i++){
		var css_rules = (document.styleSheets[i].cssRules) ? document.styleSheets[i].cssRules: document.styleSheets[i].rules;
		for(j=0; j<css_rules.length; j++){
			if(css_rules[i].selectorText == name) return css_rules[i];
		}
	}
	return null;
}

function addCSSRule(selector, rules){
	AddStyleSheetSet();

	if (rules.length) {
		if(document.styleSheets[0].addRule) {
			document.styleSheets[0].addRule(selector, rules);
		} else {
			document.styleSheets[0].insertRule(selector + '{' + rules + '}', 0);
		}
	}
}

function AddStyleSheetSet(){
	if (document.styleSheets.length==0){
		var cssNode = document.createElement('style');
		cssNode.type = 'text/css';
		cssNode.rel = 'stylesheet';
		cssNode.media = 'screen';
		cssNode.title = 'dynamicSheet';
		document.getElementsByTagName("head")[0].appendChild(cssNode);
	}
}


/* functions of form post. */
function GetCheckedValue(obj_elem){
	for(var i=0; i<obj_elem.length; i++) {
		if (obj_elem[i].checked) return obj_elem[i].value;
	}
	return null;
}

function SetCheckValue(obj_elem, value){
	for(var i=0; i<obj_elem.length; i++) {
		if (obj_elem[i].value==value) {
			obj_elem[i].checked=true;
			break;
		}
	}
}

function GetSelectedValue(obj_elem){
	if(obj_elem.selectedIndex>=0) {
		return parseInt(obj_elem.options[obj_elem.selectedIndex].value);
	}
	return null;
}


function FormValuesToStr(obj_form) {
	var poststr = '', elem, elem_ok, elem_value; 
	
	if (!obj_form) return '';

	for(var s=0; s<obj_form.elements.length; s++){   
		elem = obj_form.elements[s]; 
		elem_ok = false;
		switch(elem.type){
			case 'checkbox': case 'radio':
				if (elem.checked) {
					elem_value = elem.value;
					elem_ok = true;
				}
				break;
			case 'text': case 'textarea':  case 'hidden': case 'password':
				elem_value = elem.value; elem_ok=true; break;
			case 'select-one':
				elem_value = elem.options[elem.selectedIndex].value; elem_ok=true; break;
		}
		if(elem_ok){
			if(poststr.length) poststr += '&';   
			poststr += elem.name + "=" + encodeURI(elem_value);   
		}
	}   

	return poststr;
}


/* AJAX functions */
//     if (http_request.overrideMimeType) http_request.overrideMimeType('text/html');
function HttpFormPost(obj_form) {
	var poststr = '', elem, elem_ok, elem_value; 
	
	if (!obj_form) return;

	for(var s=0; s<obj_form.elements.length; s++){   
		elem = obj_form.elements[s]; 
		elem_ok = false;
		switch(elem.type){
			case 'checkbox': case 'radio':
				if (elem.checked) {
					elem_value = elem.value;
					elem_ok = true;
				}
				break;
			case 'text': case 'textarea':  case 'hidden': case 'password':
				elem_value = elem.value; elem_ok=true; break;
			case 'select-one':
				elem_value = elem.options[elem.selectedIndex].value; elem_ok=true; break;
		}
		if(elem_ok){
			if(poststr.length) poststr += '&';   
			poststr += elem.name + "=" + encodeURI(elem_value);   
		}
	}   

	HttpRequest('POST', obj_form.action, poststr);
}

function precheck_page(tag, url, obj, check_step){
	// url is nomarl url
	var check_step = check_step? check_step: 1;
	var url = UpdateQueryVariable('check', check_step, url);
	var obj_pos_size_str = '';
	if(obj){
		var obj_pos_size = findPosSize(obj); //[curleft,curtop,width,height]
		obj_pos_size_str = obj_pos_size.join('_');
	}
	HttpRequest("GET", url, "", "precheck_page_result('" + tag + "', '" + url + "', '" + obj_pos_size_str + "', '%RETURN_STRING%')", false);
}

function precheck_page_result(tag, url, obj_pos_size_str, data){
	precheck_page_result_base(tag, url, obj_pos_size_str, data);
}

function precheck_page_result_base(tag, url, obj_pos_size_str, data){
	var url = RemoveQueryVariable('check', url);
	url = RemoveQueryVariable('a', url);
	var html_popup = '';
	if(data){
		/*
			// data string structure  CHAR : 0x08 
			1-0. TAG, CHAR : 0x08
			1-1. STEP #, CHAR : 0x08
			1-2. URL   , CHAR : 0x08
			1-3. TITLE , CHAR : 0x08
			1-4. WIDTH , CHAR : 0x08
			1-5. HEIGHT , CHAR : 0x08
			2-0. DATA (others, optional)
		*/
		var items = data.split("\x7f");
		var headers = items[0].split("\x08");
		var cmd = headers[0];
		var step = headers[1];
		var url_temp = headers[2];
		url = url_temp? url_temp: url;
		var title = headers[3]? headers[3]: 'popup';
		var pos = {};
		if(obj_pos_size_str){
			pos = {};
		}
		var width = headers[4]? headers[4]: 500;
		var height = headers[5]? headers[5]: 300;
		var value = (items[1]?items[1]:'');
		var html_popup_simple = '';
		switch(cmd){
			case 'NSR': // have not security right
				url = '';
				alert('You don\'t have security right');
				break; 
			case 'NTL': // need to login
				url = '/login.html?np=' + urlencode(url);
				break;
			case 'EXT': // need to select extend menu or form and then post to url
				html_popup_simple = value;
				break;
			case 'GFM': // need to select form and then post to url
				html_popup = value;
				break;
			case 'GPW': // need to get password and then post to url
				html_popup = '<form name="frmTemp8923" action="'+url+'" method="post" onsubmit="save_data(this); return false;">'
					+'<input type="hidden" name="a" value="s" />'
					+'<ul>'
					+'<li><label>Password</label><var><input type="password" name="pwd" value="" /></var></li>'
					+'</ul>'
					+'<p class="buttons"><input type="submit" value="Submit" />'
						+'<input type="button" value="Cancel" onclick="popuplayer.Hide(\'pop_xtemp\');" /></p>'
					+'</form>';
				break;
			case 'GYN': // need to select Yes or No and then move to url(YES)
				if(!confirm(value)){
					url = '';
				}
				break;
			case 'GOK': // need to click ok button and then move to url
				alert(value);
				break;
			case 'SMG': // show message and then stay page
				url = '';
				alert(value);
				break;
			default:
		}

		if(html_popup_simple){
			//obj_pos_size_str
			var div=document.createElement("div");
			div.innerHTML = html_popup_simple;
			div.style.position = 'absolute';
			div.style.visibility = 'visible';
			div.style.display = 'block';
			document.body.appendChild(div);
		} else if(html_popup){
			var title='Popup';
			popupLayer.load('pop_xtemp', { 'iframe':'', 'imgclose':'', 'title':title, 'width':width, 
					'height':height, 'inner_html':html_popup} );
			popupLayer.show('pop_xtemp', true, true);
		} else {
			if(url) window.location.href = url;
		}
	}
}


function SetObjValue(sIDandAttr, sValue) {
	var sTag = sIDandAttr.split(".");
	switch(sTag.length) {
		case 0: break;
		case 1: document.getElementById(sTag[0]).value = sValue; alert(sValue); break;
		default: 
			var i = 0;
			var obj = document.getElementById(sTag[i]);
			for(i=1; i<sTag.length-1; i++)
				obj = obj.getAttribute(sTag[i]);
			if(sTag[i]=='value')
				obj.value = sValue;
			else 
				obj.setAttribute(sTag[i], sValue);
	}
}

function HttpRequest(sMethod, sURL, sArgs, eValStr, sync)
{
	var sText;
	var objReq;
	var sync = sync || true;

	try {	
		if (window.XMLHttpRequest)
			objReq = new XMLHttpRequest();
		else if (window.ActiveXObject)
			objReq = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {	
		objReq = new ActiveXObject("Microsoft.XMLHTTP");
	}

	objReq.onreadystatechange = function() {
		if (objReq.readyState == 4){	// Received, OK
			if(objReq.status  == 200) {
				sText = objReq.responseText;
			} else {
				sText = objReq.status  + ',Could not connect to server. please try again';
			}
			var iPos = sText.indexOf(',');
			if(iPos) {
				var ret_code = parseInt(sText.substr(0,iPos));
				if(isNaN(ret_code)) {
					ret_code = -2;
					sText = 'Please login again';
				} else {
					sText = sText.substr(iPos+1);
				}
			} else {
				var ret_code = -1;
			}
			if(ret_code){
				if(ret_code!=1) alert(ret_code + ': ' + sText);
			} else {
				//alert(eValStr.replace(/%RETURN_STRING%/gi, sText));
				//sText = sText.replace(/\\/gi, "\\\\");
				//sText = sText.replace(/\'/gi, "\\\'");
				eval(eValStr.replace(/%RETURN_STRING%/gi, addslashes(sText)));
			}
		}	
	};

	if (sMethod.toUpperCase() != "POST")
		objReq.open("GET", sURL, sync);	
	else {	
		objReq.open("POST", sURL, sync);
		objReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		objReq.setRequestHeader("Content-length", sArgs.length);
		objReq.setRequestHeader("Connection", "close");
	}
	objReq.send(sArgs);
}

	function checkEmail(email) {
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return filter.test(email);
	}


//Dependency popupLayer.js
function show_pop_update(title, width, height, use_close) {
	if(!title) title = 'Save data';
	if(!width) width = 500;
	if(!height) height = 200;
	
	if(use_close){
		popupLayer.load('pop_update', { 'iframe':'', 'title':title, 'width':width, 
				'height':height, 'inner_html':'<br><p>please wait...</p><p><img src="/image/common/ani_updating.gif"></p>'} );
	} else {
		popupLayer.load('pop_update', { 'iframe':'', 'imgclose':'', 'title':title, 'width':width, 
				'height':height, 'inner_html':'<br><p>please wait...</p><p><img src="/image/common/ani_updating.gif"></p>'} );
	}
	popupLayer.show('pop_update', true, true);
}


function hidden_update(module, type) {
	var obj_id = 'update_hidden';
	var obj_hidden_prev = document.getElementById('obj_id');
	if(obj_hidden_prev){
		document.body.removeChild(obj_hidden_prev);
	}
	var obj_hidden = document.createElement('div');
	with(obj_hidden){
		id = obj_id;
		style.display = 'none';
		frameborder=0;
		width=0;
		height=0;
		obj_hidden.innerHTML = '<iframe name="'+obj_id+'_iframe" id="'+obj_id+'_iframe" src="" '
			+'onload="hidden_update_loaded(0, \''+module+'\', \''+type+'\');" '
			+'onerror="hidden_update_loaded(1, \''+module+'\', \''+type+'\');"></iframe>';
	}
	document.body.appendChild(obj_hidden);
}

function hidden_update_loaded(code, module, type){
	if(code==1){
		if(action_completed) action_completed(module, type, 0, {'code':9999, 'mst':'', 'msg':'page load error', 'msd':''});
	}
}

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\0/g,'\\0');
	str=str.replace(/\r/g,'\\r');
	str=str.replace(/\n/g,'\\n');
	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 replace_fix_pos(str, stpos, newstr){
	return str.substr(0,stpos)+newstr+str.substr(stpos+newstr.length);
}

function cloneTableRow(or){
	var tbody = or.parentNode;
	if(tbody.rows.length){
		var nr = tbody.insertRow(-1);
		nr.className = or.className;
		for (var i=0; i<or.cells.length; i++) {
			var c = nr.insertCell(-1);
			c.innerHTML = or.cells[i].innerHTML;
		}
		return nr;
	}
	return null;
}


function ShowHideTableColumn(table, cellIndex, bShow){
	var ths = table.getElementsByTagName("th");
	var tds = table.getElementsByTagName("td");
	var bShow = bShow || false;
	var idx = 0;
	for (idx in ths){
		if (ths[idx].cellIndex == cellIndex){
			ths[idx].style.display = (bShow?'':'none');
		}
	}
	for (idx in tds){
		if(tds[idx].parentNode){
			var adjust = 0;
			switch(tds[idx].parentNode.rowIndex){
				case 1: case 2: 
					adjust =-1; break;
			}
			if (tds[idx].cellIndex == cellIndex + adjust){
				tds[idx].style.display = (bShow?'':'none');
			}
		}
	}
}

function FYN(value){
	value = value.trim();
	value = (value=='Y' || value=='y') ?'Y':'';
	return value;
}

function getObjWidth(Elem) {
	var nWidth = 0;
	var elem = (isString(Elem)) ? elem = document.getElementById(Elem): Elem;
	if(elem.clip){
		nWidth = elem.clip.width;
	} else {
		if (elem.style.pixelWidth) {
			nWidth = elem.style.pixelWidth;
		} else {
			nWidth = elem.offsetWidth;
		}
	}
	return nWidth;
}

function get_document_body(){
	return document.body;
}

function set_input_to_spreadsheet(obj_table){
	var obj = isString(obj_table) ? document.getElementById(obj_table): obj_table;
	var elms = obj.getElementsByTagName('INPUT');
	
	for(var i=0;i<elms.length;i++){
		var elm = elms[i];
		addEvent(elm,"keydown",func_input_to_spreadsheet);
	}
}

function func_input_to_spreadsheet(e){
	var keynum = e.which ? e.which: e.keyCode;
	var active_obj = e.srcElement ? e.srcElement: e.target;
	var cell_obj = active_obj.parentNode;
	var row_obj = cell_obj.parentNode;
	var tbl_obj = row_obj.parentNode.parentNode;
	var step_col = 0;
	var step_row = 0;
	var idx = 0;
	var tmp_obj = null;
	var obj_found = null;
	var do_next = true;
	var do_keyaction = true;

	if(tmp_obj =active_obj.controller){
		if(tmp_obj.run_events){
			do_next = tmp_obj.run_events(e);
		}
	}

	if(do_next!=false){
		do_keyaction = false;
		switch(keynum){
			case 37: //left
				step_col = -1;
				break;
			case 38: //up
				step_row = -1;
				break;
			case 39: //right
				step_col = 1;
				break;
			case 40: //down
				step_row = 1;
				break;
			default:
				do_keyaction = true;
		}

		if(step_col){
			idx = cell_obj.cellIndex + step_col;
			while (tmp_obj = tbl_obj.rows[row_obj.rowIndex].cells[idx]){
				if(obj_found = get_first_child_textbox(tmp_obj)) {
					obj_found.select();
					break;
				}
				idx += step_col;
			}
		}

		if(step_row){
			idx = row_obj.rowIndex + step_row;
			while (tmp_obj = tbl_obj.rows[idx]) {
				tmp_obj = tmp_obj.cells[cell_obj.cellIndex];
				if(obj_found = get_first_child_textbox(tmp_obj)) {
					obj_found.select();
					break;
				}
				idx += step_row;
			}
		}

		if (do_keyaction==false) stopEvent(e);
	}

	
	return do_keyaction;
}

function get_first_child_textbox(obj_container){
	if(obj_container){
		var elms = obj_container.getElementsByTagName('INPUT');
		for (var i=0; i<elms.length; i++) {
			if(elms[i].type == 'text'){
				return elms[i];
			}
		}
	}
	return null;
}

function debug_print(str){
	var x = document.getElementById('id_debug');
	if(x) x.value += "\n" + str;
}

function window_open(href, window_name, size_options){
	var window_options = "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1";
	window_options += (size_options ? ","+ size_options:",height=800,width=900");
	return window.open(href,window_name,window_options);
}


function createCookie(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+"="+escape(value)+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



/* site default functions */

function submit_filter(obj_form, req_l) {
	if(!obj_form) obj_form = document.getElementById('frmFilter');

	if(obj_form){
		var poststr = '';
		for(var s=0; s<obj_form.elements.length; s++){   
			elem = obj_form.elements[s]; 
			elem_ok = false;
			switch(elem.type){
				case 'checkbox': case 'radio':
					if (elem.checked) {
						elem_value = elem.value;
						elem_ok = true;
					}
					break;
				case 'text': case 'textarea':  case 'hidden': case 'password':
					elem_value = elem.value; elem_ok=true; break;
				case 'select-one':
					elem_value = elem.options[elem.selectedIndex].value; elem_ok=true; break;
			}
			if(elem_ok){
				poststr += "\x7f" + elem.name + "\x08" + encodeURI(elem_value);
			}
		}
		poststr = poststr.substr(1);
		update_filter((req_l?req_l:get_REQUEST('l')), poststr);

		window.location.replace(RemoveQueryVariable('p'));
	}
}

function RemoveQueryVariable(variable, link) {  
	return UpdateQueryVariable(variable, '', link);
}

function UpdateQueryVariable(variable, value, link) {  
	var value = '' + value;
	var link = link? link: window.location.href;
	//var href = window.location.href;
	var tags = link.split("?");
	prefix = tags[0]; 
	//var query = window.location.search.substring(1); 
	var query = (tags.length>1)?tags[1]:'';
	var vars = query.split("&");  
	var ret = '';
	var found = false;
	if(query.length){
		for (var i=0;i<vars.length;i++) {    
			var pair = vars[i].split("=");    
			if (pair[0] == variable) {
				if(value.length){
					ret += '&' + pair[0]+'='+value;
				}
				found = true;
			} else {
				ret += '&' + vars[i];
			}  
		}
	}
	if(!found && value.length>0) ret += '&' + variable+'='+value;
	return prefix + (ret?'?'+ret.substring(1):'');
}

function get_REQUEST(ji) {
	var hu = window.location.search.substring(1);
	var gy = hu.split("&");
	for (var i=0;i<gy.length;i++) {
		var ft = gy[i].split("=");
		if (ft[0] == ji) return ft[1];
	}
}

function add_filter(name, value, obj_form){
	if(!obj_form) obj_form = document.getElementById('frmFilter');
	if(obj_form){
		update_filter(get_REQUEST('l'), name+"\x08"+value);
		window.location.replace(window.location.href);
	}
}

function remove_filter(name, obj_form){
	if(!obj_form) obj_form = document.getElementById('frmFilter');
	if(obj_form){
		update_filter(get_REQUEST('l'), name+"\x08");
		window.location.replace(window.location.href);
	}
}


function update_filter(page_name, newfilter, clear_all){
	if(clear_all) eraseCookie(page_name);
	
	var qstr = readCookie(page_name);
	if(!qstr) qstr ='';

	if(newfilter.length)  {
		if (qstr.length) qstr = "\x7f" + qstr;
		var filters = newfilter.split("\x7f");
		for (var i=0; i<filters.length; i++){
			var fitem = filters[i].split("\x08");
			var iPos = qstr.indexOf("\x7f"+fitem[0]+"\x08");
			if(iPos>-1){
				var hd = qstr.substr(0,iPos);
				var iPos = qstr.indexOf("\x7f", iPos+1);
				var ft =(iPos>-1)? qstr.substr(iPos):'';
				qstr = hd + "\x7f" + filters[i] + ft;
			} else {
				qstr += "\x7f" + filters[i];
			}
		}
	}

	qstr = qstr.substr(1);
	createCookie(page_name, qstr);

	return qstr;
}

	//Disable right click script III- By Renigade (renigade@mediaone.net)
	//For full source code, visit http://www.dynamicdrive.com

function block_context(){
	var message="";
	///////////////////////////////////
	function blockIE(){
		if (document.all) {
			(message);
			return false;
		}
	}
	function blockNS(e) {
		if (document.layers||(document.getElementById&&!document.all)) {
			if (e.which==2||e.which==3) {
				(message);
				return false;
			}
		}
	}

	if (document.layers) {
		document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown=blockNS;
	} else {
		document.onmouseup=blockNS;
		document.oncontextmenu=blockIE;
	}

	document.oncontextmenu=new Function("return false");

	return this;
}

function save_form(form, code){
	hidden_update('form', 's');

	with(form){
		target="update_hidden_iframe" ;
		a.value="s";
		submit();
	}
}

/*function action_completed(module, action, result, data){
	switch(action){
		case 's': //save(0:saved, 1:error)
			break;
	}
}*/


function include(filename, start_func, interval)
{
	var interval = interval? interval: 500; // 500ms
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)

	if(typeof(start_func)!='undefined'){
		check_and_do_func(start_func, interval, 0);
	}
}


function check_and_do_func(start_func, interval, count){
	try{
		eval(start_func);
	}
	catch (e) {
		count++;
		if(count>10){
			alert('cannot load and execute ' + start_func);
		} else {
			var t=setTimeout("check_and_do_func(\"" + start_func.addslashes() + "\", " + interval + ", " + count +")",interval);
		}
	}
}

function set_date_range(type, ctr_date1, ctr_date2){
	var d = new Date();
	var ret_value = 0;
	var date1= null;
	var date2= null;
	switch(type){
		case 'all':
			break;
		case 'dc':
			date1 = new Date(d);
			date2 = date1;
			break;
		case 'dl':
			date1 = new Date(d.setDate(d.getDate()-1));
			date2 = date1;
			break;
		case 'wc':
			d.setDate(d.getDate()-d.getDay());
			date1 = new Date(d);
			date2 = new Date(d.setDate(d.getDate()+6));
			break;
		case 'wl':
			d.setDate(d.getDate()-d.getDay()-7);
			date1 = new Date(d);
			date2 = new Date(d.setDate(d.getDate()+6));
			break;
		case 'mc':
			var days = daysInMonth(d.getMonth(), d.getYear());
			date1 = new Date(d.setDate(1));
			date2 = new Date(d.setDate(days));
			break;
		case 'ml':
			d.setMonth(d.getMonth()-1);
			date1 = new Date(d.setDate(1));
			var days = daysInMonth(d.getMonth(), d.getYear());
			date2 = new Date(d.setDate(days));
			break;
		case 'yc':
			date1 = new Date(d.setFullYear(d.getFullYear(),0,1));
			date2 = new Date(d.setFullYear(d.getFullYear(),11,31));
			break;
		case 'yl':
			date1 = new Date(d.setFullYear(d.getFullYear()-1,0,1));
			date2 = new Date(d.setFullYear(d.getFullYear(),11,31));
			break;
	}

	if(set_date_value(ctr_date1, date1)) ret_value = ret_value | 1 ;
	if(set_date_value(ctr_date2, date2)) ret_value = ret_value | 2 ;

	return ret_value;
}

function daysInMonth(iMonth, iYear) {	
	return 32 - new Date(iYear, iMonth, 32).getDate();
}

function set_date_value(obj, date_value, with_time){
	var ret_valid = false;
	var obj = isObject(obj)? obj: document.getElementById(obj);
	if(date_value){
		var date_value = isDate(date_value)? date_value: Date.parse(date_value);
	}
	if(obj){
		if(date_value){
			obj.value = (date1.getMonth()+1) + '/' + date1.getDate() + '/' + date1.getYear()
				+ (with_time? date_value.getHours() + ':' + date_value.getMinutes() + ':' + date_value.getSeconds():'');
			ret_valid = true;
		} else {
			obj.value = '';
		}
	}
	return ret_valid;
}

function get_selected_tab_id(tablayout_id){
	var tablayout_id = tablayout_id? tablayout_id: 'tablayout';
	var obj_tablayout = document.getElementById(tablayout_id);
	var ret_value = '';
	if(obj_tablayout){
		var selected = obj_tablayout.getAttribute('selected_tab');
		if(selected) ret_value = selected;
	}
	return ret_value;
}

function tabbutton(tablayout_id, key){
	if(typeof eval('tabbutton_clicked') == 'function') {
		tabbutton_clicked(tablayout_id, key);
	}
}

function showtab(tablayout_id, key){
	obj_tablayout = document.getElementById(tablayout_id);
	if(obj_tablayout){
		var obj_header_group =null;
		var obj_body_group =null;
		for(var i=0; i<obj_tablayout.childNodes.length; i++){
			var node = obj_tablayout.childNodes[i];
			switch (node.className){
				case 'tablayout_header':
					obj_header_group = node.childNodes[0];
					if(obj_header_group.childNodes.length && obj_header_group.childNodes[0] && obj_header_group.childNodes[0].tagName=='UL' ){
						obj_header_group = obj_header_group.childNodes[0];
					}
					break;
				case 'tablayout_body':
					obj_body_group = node.childNodes[0];
					if(obj_body_group.childNodes.length && obj_body_group.childNodes[0] && obj_body_group.childNodes[0].tagName=='UL'){
						obj_body_group = obj_body_group.childNodes[0];
					}
					break;
			}
		}

		if(obj_header_group){
			for(var i=0; i<obj_header_group.childNodes.length; i++){
				var node = obj_header_group.childNodes[i];
				var className = 'tab_header'+(node.id == 'tab_'+key? ' selected':'');
				if(node.className != className) node.className = className;
			}
		}

		if(obj_body_group){
			for(var i=0; i<obj_body_group.childNodes.length; i++){
				var node = obj_body_group.childNodes[i];
				var className = 'tab_body'+(node.id == 'tabbody_'+key? ' selected':'');
				if(node.className != className) node.className = className;
			}
		}
		obj_tablayout.setAttribute('selected_tab', key);
	}
}


function show_image(e, width, height){
	var obj = getElement(e);
	if(width == undefined) width = 720;
	if(height == undefined) height = 600;
	if(obj){
		//src_org
		if(obj.getAttribute('src_org')==undefined){
			if(obj.childNodes.length){
				obj=obj.childNodes[0];
			}
		}

		var img_path = obj.getAttribute('src_org');
		if(img_path){
			window_open(img_path, 'image_detail_view', 'width='+width+',height='+height);
		}
	}
}


function get_window_size(type){
	switch(type){
		case 'inet_product': w=1020; h=900; break;
		default: w=800; h=900; break;
	}

	return {'w':w, 'h':h };
}


if (typeof Event == 'undefined') Event = new Object();
/*
 * Registers function +fn+ will be executed when the dom 
 * tree is loaded without waiting for images. 
 * 
 * Example:
 *
 *  Event.domReady.add(function() {
 *    ...
 *  });
 *
 */
Event.domReady = {
  add: function(fn) {
    
    //-----------------------------------------------------------
    // Already loaded?
    //-----------------------------------------------------------
    if (Event.domReady.loaded) return fn();
    
    //-----------------------------------------------------------
    // Observers
    //-----------------------------------------------------------
    var observers = Event.domReady.observers;
    if (!observers) observers = Event.domReady.observers = [];
    // Array#push is not supported by Mac IE 5
    observers[observers.length] = fn;
    
    //-----------------------------------------------------------
    // domReady function
    //-----------------------------------------------------------
    if (Event.domReady.callback) return;
    Event.domReady.callback = function() {
      if (Event.domReady.loaded) return;
      
      Event.domReady.loaded = true;
      if (Event.domReady.timer) {
        clearInterval(Event.domReady.timer);
        Event.domReady.timer = null;
      }
      
      var observers = Event.domReady.observers;
      for (var i = 0, length = observers.length; i < length; i++) {
        var fn = observers[i];
        observers[i] = null;
        fn(); // make 'this' as window
      }
      Event.domReady.callback = Event.domReady.observers = null;
    };
    
    //-----------------------------------------------------------
    // Emulates 'onDOMContentLoaded'
    //-----------------------------------------------------------
    var ie = !!(window.attachEvent && !window.opera);
    var webkit = navigator.userAgent.indexOf('AppleWebKit/') > -1;
    
    if (document.readyState && webkit) {
      
      // Apple WebKit (Safari, OmniWeb, ...)
      Event.domReady.timer = setInterval(function() {
        var state = document.readyState;
        if (state == 'loaded' || state == 'complete') {
          Event.domReady.callback();
        }
      }, 50);
      
    } else if (document.readyState && ie) {
      
      // Windows IE 
      var src = (window.location.protocol == 'https:') ? '://0' : 'javascript:void(0)';
      document.write(
        '<script type="text/javascript" defer="defer" src="' + src + '" ' + 
        'onreadystatechange="if (this.readyState == \'complete\') Event.domReady.callback();"' + 
        '><\/script>');
      
    } else {
      
      if (window.addEventListener) {
        // for Mozilla browsers, Opera 9
        document.addEventListener("DOMContentLoaded", Event.domReady.callback, false);
        // Fail safe 
        window.addEventListener("load", Event.domReady.callback, false);
      } else if (window.attachEvent) {
        window.attachEvent('onload', Event.domReady.callback);
      } else {
        // Legacy browsers (e.g. Mac IE 5)
        var fn = window.onload;
        window.onload = function() {
          Event.domReady.callback();
          if (fn) fn();
        }
      }
      
    }
    
  }
}


function setup_node_moveRow(){
	if(typeof document.getElementsByTagName("TABLE")[0].moveRow == "undefined"){
		Node.prototype.moveRow = function(){
			if(this && this.nodeName.match(/^(table|t(body|head|foot))$/i)){
				try {
					one = (!arguments[0] && arguments[0] != 0?-1:arguments[0]);
					two = (!arguments[1] && arguments[1] != 0?-1:arguments[1]);

					// Makes sure the row exists and then makes sure the insertable row isn't greater then the length
					if(!this.rows[one] || two > this.rows.length){
						var err = new Error();
						throw err;
					}

					// This is just so that it gets put in the right place.
					if(two > one)
						two = two+1;
					else if(one > two)
						one = one+1;

					newRow = this.insertRow(two);
					newRow.innerHTML = this.rows[one].innerHTML;
					this.deleteRow(one);
				} catch(e) {
				}
			}
		}
	}
}


function checkbox_click(obj){
	var obj_id = obj.getAttribute('objid');
	var elm = document.getElementById(obj_id);
	if(elm){
		var value = CSN(elm.value);
		value++;
		if(value>2) value=0; //3-state
		elm.value = value;
		obj.className = 'value_'+value;
	}
}

function get_name2underline(value){
	value = '' + value;
	value = value.trim();
	value = value.replace(' ', '_');
	return encodeURI(value);
}

function gotopage(nPage, link) {
	var page_url = UpdateQueryVariable('p', (nPage?nPage:''), link);
	window.location.replace(page_url);
}

function test_createform(){
	var form = document.forms['frmGen'];
	if(!form){
		form=document.createElement("form");
		document.body.appendChild(form);
	}
	var elm = document.createElement("input");
	with(elm){
		elm.type="hidden";
		elm.name="LHTR";
		elm.value=rid + ":"+hid;
	}
	form.appendChild(elm);
	var elm = document.createElement("input");
	with(elm){
		elm.type="hidden";
		elm.name="a";
		elm.value="d";
	}
	form.appendChild(elm);
	var elm = document.createElement("input");
	with(elm){
		elm.type="hidden";
		elm.name="id";
		elm.value=rid;
	}
	form.appendChild(elm);
	with(form){
		name = "frmGen";
		action = "/?l=forum_article";
		method = "post";
		//submit();
	}
}

function copy_to_clipboard(s){
	if(window.clipboardData){
		window.clipboardData.setData('Text',s);
	}
}

function copylink(){
	copy_to_clipboard(window.location.href);
}

function get_frame_doc(frame){
  var doc = (frame.contentWindow || frame.contentDocument);
  if (doc.document) doc = doc.document;
  return doc;
}

function get_human_filesize (value){
	var unit_list = new Array('Byte', 'KB', 'MB', 'GB', 'TB');
	value = CSN(value);
	var t_size = value;
	for(var i=unit_list.length-1; i>0; i--){
		t_size = value / Math.pow(1024, i);
		if (t_size>1) break;
	}
	return FormatNumber(t_size, (i?2:0)) + ' ' + unit_list[i];
}


function get_center_obj(o) {
	var nHeight=0, nWidth=0;
	var c = {'left':0, 'top':0};
	if(isString(o)) o = document.getElementById(o);


	nWidth = o.offsetWidth;
	nHeight = o.offsetHeight;

	if (nWidth==0 && o.style.width!='' ) nWidth = parseInt(o.style.width);
	if (nHeight==0 && o.style.height!='' ) nHeight = parseInt(o.style.height);

	if (nWidth==0) nWidth = o.scrollWidth;
	if (nHeight==0 ) nHeight = o.scrollHeight;

	c.top = get_body_scrollTop() + (get_viewport_height() - nHeight) / 2;
	c.left = get_body_scrollLeft() + (get_viewport_width() - nWidth) / 2;
	return c;
}

function get_body_scrollTop(){
	if (document.documentElement && document.documentElement.scrollTop && document.documentElement.scrollTop>0) {
		return document.documentElement.scrollTop;
	}
	if (document.body && document.body.scrollTop) {
		return document.body.scrollTop;
	}
	return null;
}

function get_body_scrollLeft(){
	if (document.documentElement && document.documentElement.scrollLeft && document.documentElement.scrollLeft>0) {
		return document.documentElement.scrollLeft;
	}
	if (document.body && document.body.scrollLeft) {
		return document.body.scrollLeft;
	}
	return null;
}

function get_doc_width() {
	var width = 0;
	var body = document.body;
	if (document.documentElement && (!document.compatMode || document.compatMode=="CSS1Compat")) {
		var rightMargin = parseInt(body.getAttribute('marginRight'),10) || 0;
		var leftMargin = parseInt(body.getAttribute('marginLeft'), 10) || 0;
		width = Math.max(body.offsetWidth + leftMargin + rightMargin, document.documentElement.clientWidth);
	}
	else {
		width =  Math.max(body.clientWidth, body.scrollWidth);
	}
	if (isNaN(width) || width==0) {
		//width = body.innerWidth;
	}

	return width;
}
	
function get_doc_height() {
	var body = document.body;
	var innerHeight = (body.innerHeight)&&!isNaN(body.innerHeight)?body.innerHeight:0;
	if (document.documentElement && (!document.compatMode || document.compatMode=="CSS1Compat")) {
		var topMargin = parseInt(body.getAttribute('marginTop')) || 0;
		var bottomMargin = parseInt(body.getAttribute('marginBottom')) || 0;
		if(isNaN(topMargin)) topMargin =10;
		if(isNaN(bottomMargin)) bottomMargin =10;
		return Math.max(body.offsetHeight + topMargin + bottomMargin, document.documentElement.clientHeight, document.documentElement.scrollHeight);
	}
	return Math.max(body.scrollHeight, body.clientHeight);
}

function get_viewport_width() {
	if (document.documentElement && (!document.compatMode || document.compatMode=="CSS1Compat")) {
		return document.documentElement.clientWidth;
	}
	else if (document.compatMode && document.body) {
		return document.body.clientWidth;
	}
	return document.innerWidth;
}
	
function get_viewport_height() {
	if (!window.opera && document.documentElement && (!document.compatMode || document.compatMode=="CSS1Compat")) {
		return document.documentElement.clientHeight;
	}
	else if (document.compatMode && !window.opera && document.body) {
		return document.body.clientHeight;
	}
	return document.innerHeight;
}


function show_css_popup(title, msg, desc, buttons, height, use_back_scr){
	var height = CSN(height)? CSN(height): 120;
	var buttons = buttons? buttons: '<p class="buttons"><a href="javascript:void(0);" class="btn_ok" onclick="popupLayer.hide(\'pop_update\')"></a></p>';
	popupLayer.load('pop_update', { 'btnclose':'', 'title':title, 'width':300, 'height':height, 'inner_html':(msg + buttons), 'refresh':true } );
	popupLayer.show('pop_update', true, true);
}

function decodeHTML(e){
	var entities=[
			['&amp;','&'],
			['&nbsp;',' '],
			['<br/>','\n'],
			['<br />','\n']
	];
	var clean = e.replace(/<li>/g,"\n* <li>");
	var clean = clean.replace(/<p>/g,"\n<p>");
	var clean = clean.replace(/<[^>]*>/g,"");
	for( var i=0, limit=entities.length; i < limit; ++i){
		clean = clean.replace( new RegExp(entities[i][0],"ig"), entities[i][1]);
	}
	return clean;
}


function set_style_opacity(o, value){
	o.style['-moz-opacity'] = value;
	o.style['-khtml-opacity'] = value;
	o.style.opacity = value;
	if (typeof(o.style.filter)!='undefined') {
		o.style.filter = "alpha(opacity=" + value*100 + ")";
	}
}


function get_available_id(){
	var idx =0;
	var hd = 'tmp_o_';
	while(document.getElementById(hd + (++idx))){
	}
	return hd + idx;
}


/* convert select to CSS Layer */
    function selectReplacement(obj) {
      // append a class to the select
      obj.className += ' replaced';
      // create list for styling
      var wrapper = document.createElement('div');
	  wrapper.className='selectReplacement_wrapper';
      var ul = document.createElement('ul');
      ul.className =(obj.className?obj.className+' ':'')+'selectReplacement';
      var opts = obj.options;
      for (var i=0; i<opts.length; i++) {
        var selectedOpt;
        if (opts[i].selected) {
          selectedOpt = i;
          break;
        } else {
          selectedOpt = 0;
        }
      }
      for (var i=0; i<opts.length; i++) {
        var li = document.createElement('li');
        var li_w = document.createElement('div');
        var txt = document.createTextNode(opts[i].text);
        li_w.appendChild(txt);
        li.appendChild(li_w);
        li.selIndex = opts[i].index;
        li.selectID = obj.id;
        li.onclick = function() {
          selectMe(this);
        }
        if (i == selectedOpt) {
          li.className = 'selected';
          li.onclick = function() {
			selectOpen(this);
            this.onclick = function() {
              selectMe(this);
            }
          }
        }
        if (window.attachEvent) {
          li.onmouseover = function() {
            this.className += ' hover';
          }
          li.onmouseout = function() {
            this.className = 
              this.className.replace(new RegExp(" hover\\b"), '');
          }
        }
        ul.appendChild(li);
      }
      // add the input and the ul
	  wrapper.appendChild(ul)
      obj.parentNode.appendChild(wrapper);
    }

    function selectMe(obj) {
      var lis = obj.parentNode.getElementsByTagName('li');
      for (var i=0; i<lis.length; i++) {
        if (lis[i] != obj) { // not the selected list item
          lis[i].className='';
          lis[i].onclick = function() {
            selectMe(this);
          }
       } else {
          setVal(obj.selectID, obj.selIndex);
          obj.className='selected';
          obj.parentNode.className = 
            obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
          obj.onclick = function() {
			  selectOpen(obj);
            this.onclick = function() {
              selectMe(this);
            }
          }
        }
      }
    }

	function selectOpen(obj){
		obj.parentNode.className += ' selectOpen';
		obj.parentNode.scrollTop=obj.offsetTop;
	}


    function setVal(objID, selIndex) {
		var obj = document.getElementById(objID);
		obj.selectedIndex = selIndex;
    }

    function replaceSelects(obj) {
		var obj = obj?obj:document;
		var s = obj.getElementsByTagName('select');
		for (var i=0; i<s.length; i++) {
			selectReplacement(s[i]);
		}
		document.onmouseup = selectsClear;
    }

	function selectsClear(){
		var objs = document.getElementsByTagName('select');
		for(var i=0; i<objs.length; i++){
			selectClear(objs[i]);
		}
	}

	function selectClear(obj){
		if(obj.className.indexOf(' replaced')>-1){
			for(var i=0; i<obj.parentNode.childNodes.length; i++){
				var objX = obj.parentNode.childNodes[i];
				if(objX.className == 'selectReplacement_wrapper'){
					if(objX.childNodes[0].className.indexOf(' selectOpen')>-1){
						var lis = objX.childNodes[0].getElementsByTagName('li');
						for(var j=0; j<lis.length; j++){
							if(lis[j].className == 'selected'){
								selectMe(lis[j]);
								break;
							}
						}
					}
				}
			}
		}
	}

    function closeSel(obj) {
      // close the ul
    }


    function checkboxReplacement(obj) {
		// append a class to the select
		obj.className += ' replaced';
		// create list for styling
		var wrapper = document.createElement('div');
		wrapper.className='checkboxReplacement_wrapper';
		var box = document.createElement('a');
		box.checkboxID = obj.id;
		box.href = 'javascript:;';
		box.className =(obj.className?obj.className+' ':'')+'checkboxReplacement';
		var span = document.createElement('span');
		span.className = obj.checked?'checked':'unchecked';
		box.appendChild(span);
        obj.onchange = function() {
			span.className = this.checked?'checked':'unchecked';
        }
        box.onclick = function() {
			checkboxClick(this);
        }
        box.onkeypress = function(e) {
			var e=window.event?window.event:e;
			checkboxKeypress(e, this);
        }
		wrapper.appendChild(box)
		obj.parentNode.appendChild(wrapper);
    }

	function checkboxKeypress(e, obj){
		var keynum = e.which ? e.which: e.keyCode;	
		if (keynum==32) {
			checkboxClick(obj);
			return false;
		}
	}

    function checkboxClick(obj) {
		var box = document.getElementById(obj.checkboxID);
		var chk = obj.childNodes[0];
		box.checked = !box.checked;
		chk.className = box.checked?'checked':'unchecked';
    }

    function replaceCheckboxes(obj) {
		var obj = obj?obj:document;
		var s = obj.getElementsByTagName('input');
		for (var i=0; i<s.length; i++) {
			if (s[i].type=='checkbox'){
				checkboxReplacement(s[i]);
			}
		}
    }


	function evt_focus(obj){
		if(obj.defaultValue==obj.value){
			obj.value = "";
			obj.style.color = "";
		}
	}
	
	function evt_blur(obj){
		if(obj.value==""){
			obj.value = obj.defaultValue;
			obj.style.color = "#aaaaaa";
		}
	}

	var Browser = { 
		name:''  , 
		ver:'' , 
		init: function(){
			var ver = 999; // we assume a sane browser    
			if (navigator.appVersion.indexOf("MSIE") != -1){
				this.name = 'IE';
				ver = parseFloat(navigator.appVersion.split("MSIE")[1]);    
			}
			this.ver = ver;
		}
	}

	Browser.init();

