/* $Id: lc1.js,v 1.3 2009/11/25 21:09:35 pmorrill Exp $ */
//
// global variables
//
var	winRight	= 0;
var 	winBottom	= 0;
var	ctrlPanel	= null;
var	panelUrl	= '';
var	g_mod		= 0;
var	tinyMCE 	= null;
var 	logout_warn_msg	= 'Please consider saving your work: this website may log you out during this period of inactivity and your changes will be lost.';

//
// Just tell me if this is the dreaded ir 6!
//
function is_ie6() {
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
		var ieversion=new Number(RegExp.$1);
		if (ieversion<7) return true;
	}	
	return false;
}

function flagChange() { g_mod = 1; }

function popwin(url,name,width,height,options) {
	win_size();

	var x = ( width < winRight ? (winRight - width)/2 : 50 );
	var y = ( height < winBottom ? (winBottom-height)/2 : 50 );

	//
	// default options:
	//
	if ( ! options || options == '' ) options = 'scrollbars=yes,resizable=yes';

	popup = window.open(url,name,'width='+width+',height='+height+',screenx='+x+',screeny='+y+',left='+x+',top='+y+','+options);
	popup.focus();
}

function popup_window(url,name,width,height,options) {
	win_size();

	var x = ( width < winRight ? (winRight - width)/2 : 50 );
	var y = ( height < winBottom ? (winBottom-height)/2 : 50 );

	//
	// to initiate correct sub-nesting of templates, we add a parameter
	//
	var pi = new RegExp(/\?.+=/);
	if ( pi.test(url) ) var tp = '&type=pop';
	else {
		var rg = new RegExp(/\/$/);
		var tp = ( rg.test(url) ? 'index.php/pop' : '/pop' );
	}

	//
	// default options:
	//
	if ( ! options || options == '' ) options = 'scrollbars=yes,resizable=yes';

	popup = window.open(url+tp,name,'width='+width+',height='+height+',screenx='+x+',screeny='+y+',left='+x+',top='+y+','+options);
	popup.focus();
}

function close_popup() {
	if ( confirm('Any changes that you have not yet saved will be lost') ) window.close();
}

function jumpTo(list,refer) {
	location.href=refer+list.options[list.selectedIndex].value;
}

function select_checks_on_form(form,on) {
	if ( document.forms[form] ) return select_checks(document.forms[form],on);
}

function select_checks(form,on) {
	for (var i = 0; i < form.elements.length; i++) {
		var s = form.elements[i];
		if ( s.type == 'checkbox' ) { s.checked = on; }
	}
}

function select_all(on) {
	select_checks(document.theform,on);
}

function set_focus(f,e) {
	if ( f && f.elements[e] ) {
		f.elements[e].focus();
		if ( f.elements[e].select ) f.elements[e].select();
	}
}

function get_radio_value(r) {
	for (i=0; i < r.length; i++) {
		if ( r[i].checked ) return r[i].value;
	}
	return false;
}

function enable_radios(r,e) {
	for (i=0; i < r.length; i++) { r[i].disabled = e; }
}

//
// just try to get the window size
//
function win_size() {
	if ( window.innerWidth ) {
		winRight = window.innerWidth;
		winBottom = window.innerHeight;
	} else if ( document.documentElement.clientWidth ) {
		winRight = document.documentElement.clientWidth;
		winBottom = document.documentElement.clientHeight;
	} else {
		winRight = document.body.clientWidth;
		winBottom = document.body.clientHeight;
	}

	//
	// sanity
	//
	if ( !winBottom || winBottom > 800 ) winBottom = 800;
}

function control_panel(url,keep) {
	if ( ctrlPanel && panelUrl == url && keep == 0 ) { ctrlPanel.close(); ctrlPanel = null; return; }
	popup = window.open(url,'pControl','width=750,height=150,screenx=20,screeny=30,left=20,top=30,modal=yes,scrollbars=yes,resizable=yes,toolbar=no');
	popup.focus();
	panelUrl = url;
	ctrlPanel = popup;
}

function destroy_panel() {
	if ( ctrlPanel ) ctrlPanel.close();
}

function href_parent(url) {
	if ( opener ) opener.document.location.href=url;
}

//
// pull another jscript file in to the global scope, but only after the file that calls
// this func has finished execution.
//
function IncludeJavaScript(jsURL,id) {
	var head = document.getElementsByTagName("head").item(0);
	if ( !head ) return;
	var s = document.createElement("script");
	if ( !s ) return;
	s.setAttribute("type", "text/javascript");
	s.setAttribute("charset", "utf-8");
	s.setAttribute("src", jsURL);
	s.setAttribute("id", id);
	head.appendChild(s);
}

//
// remove a dynamically appended child - referenced by its id
//
function RemoveJavaScript(id) {
	var head = document.getElementsByTagName("head").item(0);
	var s = document.getElementById(id);
	if ( s ) head.removeChild(s);
}

//
// send a request to our json server
//
function fire_json(host,request,params,cb) {
	if ( !cb ) cb = 'init_div';
	IncludeJavaScript(host+'/srv/json.php/'+request+'/'+params+'/'+cb,cb);
}

//
// simple test function to work against the standard srv at pmorrill.net
//
function json_test(json,out) {
	if ( out ) { fire_json('http://www.pmorrill.net','SRV_TEST','json_test'); return; }
	if ( json.Error ) { alert(json.Error); return; }
	alert(json.Info);
	RemoveJavaScript('json_test');
}

//
// initialize a div with the contents of the data structure; may cause
// chaining asynch calls here if json.Chain is passed in
//
function init_div(json) {
	if ( json.Error ) { alert(json.Error); RemoveJavaScript('init_div'); return; }
	if ( json.Alert ) alert(json.Alert);
	if ( dd = document.getElementById(json.DivId) ) dd.innerHTML = json.Content;
	else alert('No such div: '+json.DivId);
	RemoveJavaScript('init_div');
	if ( json.Chain ) fire_json('',json.Chain,json.Params);
}

//
// respond to a tab click: save current form, and pass new url into the
// script for referring; global g_mod is to signal a dirty form;
//
function tab_over(url,s,r) {
	if ( g_mod ) {
		if ( s && r ) {
			var submit = document.getElementById(s);
			var refer = document.getElementById(r);
			if ( submit && refer ) {
				refer.value = url;
				submit.click();
			} else return false;
		} else {
			if ( confirm('You have made changes to the current data form but have not saved the edits. These changes will be lost. Continue?') ) document.location.href='/'+url+(opener ? '/pop' : '');
			else return FALSE;
		}
	} else document.location.href='/'+url+(opener ? '/pop' : '');
}

//
// enable/disable a submit button based on modal checkbox
//
function set_submit(c,s) {
	var btn = document.getElementById(s);
	if ( btn ) btn.disabled = c.checked ? 0 : 1;
}

//
// force a new captcha image to be generated
//
function new_code(n) {
	var img = document.getElementById(n);
	if ( img ) img.src = '/srv/json.php/CAPTCHA/' + Math.random();
}

//
// main field validation
//
function verify_fields(flds) {
	var success = true;
	if ( tinyMCE ) tinyMCE.triggerSave();

	for ( i = 0; i < flds.length; i++ ) {
		var fld = document.getElementById(flds[i]);
		if ( fld && fld.disabled == false && validateEmpty(fld) && success ) { fld.focus(); success = false; }
		else if ( fld && fld.disabled == true ) fld.style.background = 'White';
	}
	if ( !success ) alert("At least one required field has not been filled in.");
	return success;
}

//
// validation of fields in contact_us form, or other places
// Note that tinymce editors are handled specially!
//
function validateEmpty(fld) {
	var mce = null;
	if ( fld.className == 'mceEditor' && (mce = tinyMCE.getInstanceById(fld.id)) ) fld = mce.getWin().document.body;
 	if ( fld.value.length == 0 ) { fld.style.background = 'Yellow'; return true; }
       	fld.style.background = 'White';
	return false;
}

function trim(s) { return s.replace(/^\s+|\s+$/, ''); }

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "You didn't enter a phone number.\n";
        fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    }
    return error;
}

var logout_w_timer = null;
function logout_warning(t) {
	if ( t < 5 ) return;
	logout_w_timer = setTimeout('logout_warning('+t/2+')',t/2*1000);
	alert(logout_warningi_msg);
}

//
// return an object, with some debug dump: style param
// causes return of the style object, rather than the object
// itself (though latter is checked first)
//
function get_object(str,style,d) {
	var obj = document.getElementById(str);
	if ( obj && style == 1 ) obj = document.getElementById(str).style;
	if ( d == 1 && !obj ) alert("Failed to evaluate: "+e);
	return obj;
}

function popup_dom(what) {
	popup_window('/admin/dumpdom.php?dom='+what+'&type=popup','dViewer',700,600,'scrollbars=yes,resizable=yes');
}

function dump(theObj,nodestr) {
	var tx = '';
	var c = 0;
	if ( theObj.tagName ) {
		tx = "&nbsp;Tag: "+theObj.tagName+"&nbsp;|&nbsp;";
	}
	if ( theObj.firstChild ) {
		var ch = theObj.firstChild;
		var n = 0;
		for ( var j = 0; j < theObj.childNodes.length; j++ ) {
			ch = theObj.childNodes[j];
			if ( ch.tagName )	{ cx += " <a href=\"javascript:document.location.href='/admin/dumpdom.php?dom="+nodestr+".childNodes["+j+"]'\" >"+ch.tagName+"</a>"; n++; }
		}
		tx += "&nbsp;"+ n +" children: "+cx;
		tx += '<p />';
	}
	tx += "<table width=\"80%\" align=\"center\" bgcolor=\"#000000\" cellspacing=\"1\" cellpadding=\"2\">";
	tx += "<tr bgcolor=\"#efefde\"><td align=\"center\"><b>Property</b></td><td align=\"center\"><b>Descend</b></td></tr>";
	var props = new Array();
	for (var i in theObj) { props.push(i); }
	props.sort();
	for (var i = 0; i < props.length; i++) {
		str = props[i];
		tx += "<tr  bgcolor=\"#ffffff\"><td><a href=\"javascript:alert(eval('opener"+nodestr+'.'+str+"'))\">"+str+"</a></td><td><a href=\"javascript:document.location.href='/admin/dumpdom.php?dom="+nodestr+'.'+str+"'\">Descend</a></td></tr>";
	}
	tx+="</table>"

	return tx;
}

function goto_url(sel) {
	var s;
	if ( s = document.getElementById(sel) ) {
		var url = s.options[s.selectedIndex].value;
		document.location.href = url;
	}
}

//
// we swap in new options to the select box, if they are available;
// else we convert to a simple text box
//
function set_linked_select(master,slave,vars,val) {
	var s = document.getElementById(slave);
	if ( !s ) return;
	var par = s.parentNode;

	if ( master && s ) {
		var vs = vars[master.value];
		if ( vs ) {
			if ( s.type != 'select-one' ) {
				newSel = document.createElement('select');
				newSel.id = slave;
				newSel.name = slave;
				par.replaceChild(newSel,s);
				s = newSel;
			}
			s.options.length = 0;
			s.appendChild(create_sel_opt(0,'- Select -',val));
			for ( i=0; i<vs.length; i++ ) { s.appendChild(create_sel_opt(vs[i][0],(vs[i][1]?vs[i][1]:vs[i][0]),val)); }
		} else {
			newSel = document.createElement('input');
			newSel.size = 4;
			newSel.id = slave;
			newSel.name = slave;
			newSel.value = val;
			par.replaceChild(newSel,s);
		}
	}
}

function create_sel_opt(value,text,v) {
	var opt = document.createElement('option');
	opt.value = value;
	opt.innerHTML = text;
	if ( v == value ) opt.selected = true;
	return opt;
}

function build_tabs_orig(tabs,ct) {
	var tabd = document.getElementById(ct);
	var width = tabd.offsetWidth;
	var used = 0;
	if ( tabs ) {
		for (i = 0; i < tabs.length; i++) {
			var t = document.createElement('div');
			tabd.appendChild(t);
			if ( tabs[i][0] == '' ) {
//				t.className = 'tab_spacer';
//				t.style.width = (width - used - 10)+'px';
				break;
			}
			if ( tabs[i][1].length == 0 ) {
				t.className = 'tab_selected';
				t.innerHTML = '<div class="lpart"></div><div class="selectedLabel">'+tabs[i][0]+'</div><div class="part"></div></div>';
			} else if ( tabs[i][1] == -1 ) {
				t.className = 'tab_inactive';
			} else {
				t.className = 'tab';
				t.onclick = new Function('tab_over(\''+tabs[i][1]+'\',\'<? echo $this->form_id ?>\',\'<? echo $this->refer_id ?>\')');
				t.onmouseover = new Function('set_cursor(this,1)');
				t.onmouseout = new Function('set_cursor(this,0)');
				t.innerHTML = '<div class="lpart"></div><div class="label">'+tabs[i][0]+'</div><div class="part"></div></div>';
			}
			used += t.offsetWidth;
		}
	}
}

//
// build tabs from tabs array, and embed within the ct container
//
function build_tabs(tabs,ct) {
	var tabd = document.getElementById(ct);
	var width = tabd.offsetWidth;
	var used = 0;
	if ( tabd ) {
		var active_row = null;
		var work_row = document.createElement('div');
		work_row.setAttribute('class','tab_array');
		tabd.appendChild(work_row);
		var got_active = 0;
		for (i = 0; i < tabs.length; i++) {
			var t = document.createElement('div');
			work_row.appendChild(t);
			if ( tabs[i][0] == '' ) break;

			if ( tabs[i][1].length == 0 ) {
				t.className = 'tab_selected';
				t.innerHTML = '<div class="tab_left"></div><div class="tab_label">'+tabs[i][0]+'</div><div class="tab_right"></div></div>';
				got_active = 1;
			} else if ( tabs[i][1] == -1 ) {
				t.className = 'tab_inactive';
			} else {
				t.className = 'tab';
				t.onclick = new Function('tab_over(\''+tabs[i][1]+'\',\'<? echo $this->form_id ?>\',\'<? echo $this->refer_id ?>\')');
				t.onmouseover = new Function('set_cursor(this,1)');
				t.onmouseout = new Function('set_cursor(this,0)');
				t.innerHTML = '<div class="tab_left"></div><div class="tab_label">'+tabs[i][0]+'</div><div class="tab_right"></div></div>';
			}
			used += t.offsetWidth;
			if ( used > width ) {
//alert(used);
	//			if ( got_active ) active_row = work_row;
			//	tabd.appendChild(work_row);
				var work_row = document.createElement('div');
				work_row.setAttribute('class','tab_array');
				used = 0;
			}
		}
//		tabd.appendChild(work_row);
	}
}

function tabs_array(tabs) {
	var tabarray = [];
	var total_w = 0;
	var got_active = -1;
	for (i = 0; i < tabs.length; i++) {
		var t = document.createElement('div');
		t.setAttribute('id','tab_array_'+i);
		tabarray[i] = t;
		if ( tabs[i][0] == '' ) break;
			if ( tabs[i][1].length == 0 ) {
			t.className = 'tab_selected';
			got_active = i;
		} else if ( tabs[i][1] == -1 ) t.className = 'tab_inactive';
		else {
			t.className = 'tab';
			t.onclick = new Function('tab_over(\''+tabs[i][1]+'\',\'<? echo $this->form_id ?>\',\'<? echo $this->refer_id ?>\')');
			t.onmouseover = new Function('set_cursor(this,1)');
			t.onmouseout = new Function('set_cursor(this,0)');
		}

		t.innerHTML = '<div class="tab_left"></div><div class="tab_label">'+tabs[i][0]+'</div><div class="tab_right"></div></div>';
	}

	return {'active':got_active,'tabarray':tabarray};
}

function build_tabs2(tabs,ct,wrap) {
	if ( !wrap ) wrap = 550;
	var tabinfo = tabs_array(tabs);
	var tabd = document.getElementById(ct);
	if ( tabd ) {
		var t_width = tabd.offsetWidth;
		var row_width = 0;

		var used = 0;
		var active_row = null;
		var work_row = document.createElement('div');
		work_row.setAttribute('class','tab_array');
		tabd.appendChild(work_row);
		var got_active = 0;
		for (i = 0; i < tabinfo.tabarray.length; i++) {
			work_row.appendChild(tabinfo.tabarray[i]);
			row_width += document.getElementById('tab_array_'+i).style.width;
//alert(row_width);
			if ( row_width > wrap ) {
				work_row.removeChild(tabinfo.tabarray[i]);
			}
		}
	}
//	var work_row = document.createElement('div');
//	work_row.style.clear = 'both';
//	tabd.appendChild(work_row);
tabd.style.height = '27px';	
}

function set_cursor(d,on) {
	if ( on ) d.className = 'tab_hover';
	else d.className = 'tab';
}


