/**
 * Application: Church Organizer
 * Script: /javascript/library.js
 * Author: DW
 * Summary: Main JS Library
 */
//Browser compatability
if(document.all && !document.getElementById) {
    document.getElementById = function(id) {
         return document.all[id];
    }
}
function opensubset(url,rows) {
	if (url) {
		top.subset.document.location.href = '/organizer/scripts/frameset/loading.htm';
		top.subset.document.location.href = url;
	}
	if (!rows) rows = '50%,50%';
	top.document.getElementById('mainset').rows = rows;
}
function closesubset() {
	top.document.getElementById('mainset').rows = "*,0";
	closeaddset();
}
function closeoptions() {
	top.document.getElementById('actionset').rows = "*,0";
	top.options.document.location.href = '/organizer/scripts/frameset/blank.htm';
	//top.actions.document.body.scroll = 'no';
}
function openoptions() {
	top.document.getElementById('actionset').rows = "50%,50%";
	//top.actions.document.body.scroll = 'auto';
}
function openaddset(url,cols) {
	if (url) {
		top.addset.document.location.href = '/organizer/scripts/frameset/loading.htm';
		top.addset.document.location.href = url;
	}
	if (!cols) cols = '50%,50%';
	top.document.getElementById('serviceset').cols = cols;
}
function closeaddset() {
	top.document.getElementById('serviceset').cols = "*,0";
}
function isdefined(variable) {
	return (typeof(window[variable]) == "undefined")?  false: true;
}
function calendarpop(pCtrl,pFormat,pShowTime,pTimeMode) {
	if (pFormat==undefined) pFormat = 'mmddyyyy';
	if (pShowTime==undefined) pShowTime = false;
	if (pTimeMode==undefined) pTimeMode = 12;
	if (!isdefined('winCal')) document.write('<script language="javascript" type="text/javascript" src="/organizer/javascript/datetimepicker.js"></script>');
	document.write ("<a href=\"javascript:NewCal('"+pCtrl+"','"+pFormat+"',"+pShowTime+","+pTimeMode+")\"><img src=\"/organizer/images/calendar-tiny.gif\" border=\"0\" alt=\"Pick a date\"></a>");
}
function blankall(main) {
	if (main) top.main.document.location.href = '/organizer/scripts/frameset/loading.htm';
	top.options.document.location.href = '/organizer/scripts/frameset/loading.htm';
	top.subset.document.location.href = '/organizer/scripts/frameset/loading.htm';
	top.addset.document.location.href = '/organizer/scripts/frameset/loading.htm';
	closeoptions();
	closesubset();
}
function help(hid) {
	if (page==undefined) page = '';
	else page = 'page.php?id='+hid;
	var win = window.open('http://help.worshiporganizer.com/'+page,'wohelp','left=100,top=50,height=400,width=700,scrollbars=yes,resizable=yes,location=no,menubar=no,status=no,toolbar=yes');
	//var win = window.open('http://www.worshiporganizer.com/help/'+page,'wohelp','left=100,top=50,height=400,width=700,scrollbars=yes,resizable=yes,location=no,menubar=no,status=no,toolbar=yes');
	win.focus();
}
// Tabs
var tabdivs = new Array();
var tabcells = new Array();
var tablabels = new Array();
var tabpics = new Array();
var tabselected = 0;
var tabcookie = '';
var tabnum = 0;
function tabbar(tabs,cookiepre) {
	if (cookiepre==undefined) {
		cookiepre = document.location.href;
		if (cookiepre.indexOf('?')>0) cookiepre = cookiepre.substr(0,cookiepre.indexOf('?'));
		cookiepre = cookiepre.split('/');
		cookiepre = cookiepre[cookiepre.length-1];
		cookiepre= cookiepre.substr(0,cookiepre.length-4);
	}
	tabcookie = 'tab-'+cookiepre;
	tabnum = 0;
	document.write('<table cellpadding="0" cellspacing="0" height="100%" width="100%" id="tabtable"><tr height="1%"><td class="nopad">');
	document.write('<table cellpadding="0" cellspacing="0" height="1" width="100%"><tr valign="center">');
	for (tab in tabs) {
		document.write('<td id="tabcell"><table cellpadding="0"><tr valign="center"><td style="padding:1px"><img src="/organizer/images/icons/'+tabs[tab]+'"></td><td class="nopad" nowrap>'+tab+' &nbsp;</td></tr></table></td><td class="tabspacer">&nbsp;</td>');
	}
	document.write('<td class="tabspacer" width="99%" align="right" id="messagecell" nowrap>&nbsp;</td></tr></table></td></tr>');
}
function tabcontents() {
	if (tabnum>0) document.write('</td></tr></table></td></tr>');
	document.write('<tr valign="top"><td class="tabcell" id="tabdiv""><table height="100%" width="100%" cellspacing="0" cellpadding="0"><tr valign="top"><td style="padding:0px">');
	tabnum++;
}
function collecttabs(notab) {
	document.write('</td></tr></table>');
	for (j=0; j<2; j++) {
		if (j==0) tags = document.getElementsByTagName('TD');
		else tags = document.getElementsByTagName('TABLE');
		for (i=0; i<tags.length; i++) {
			el = tags[i];
			if (el.id=='tabcell') {
				el.onclick = new Function('tabclick('+tabcells.length+')');
				tabcells[tabcells.length] = el;
				tablabels[tablabels.length] = el.lastChild.lastChild.lastChild.lastChild;
				tabpics[tabpics.length] = el.lastChild.lastChild.lastChild.firstChild.firstChild;
			} else if (el.id=='tabdiv') {
				tabdivs[tabdivs.length] = el;
			}
		}
	}
	if (GetCookie(tabcookie)!='' && GetCookie(tabcookie)<tabcells.length && notab==undefined) tabclick(GetCookie(tabcookie));
	else tabclick(0);
}
function tabclick(id) {
	for (i=0; i<tabdivs.length; i++) {
		if (i==id) {
			tabdivs[i].parentNode.style.display = '';
			tabcells[i].className = 'tabSelected';
			tablabels[i].className = 'tablSelected';
			tabpics[i].className = 'tabpSelected';
		}
		else {
			tabdivs[i].parentNode.style.display = 'none';
			tabcells[i].className = 'tabUnselected';
			tablabels[i].className = 'tablUnselected';
			tabpics[i].className = 'tabpUnselected';
		}
	}
	tabselected = id;
	SetCookie(tabcookie,id);
}
// Draw button bar
function buttonbar(btns,idpre) {
	// Receives associative array of buttons
	btnstr = '<table cellpadding="0" cellspacing="0"><tr>';
	var action, target;
	for (var i=0; i<btns.length; i++) {
		if (typeof(btns[i])=='string') {
			// Label
			btnstr += '<td nowrap>'+btns[i]+'</td>';
		} else {
			btns[i]['title'] = btns[i].label;
			
			if (btns[i]['target']==undefined) target = '';
			else target = ' target="'+btns[i]['target']+'"';
			// Look for hotkeys
			if (btns[i]['hotkey']!=undefined) {
				if (btns[i]['label'].indexOf(btns[i]['hotkey'])>-1) btns[i]['label'] = btns[i]['label'].replace(btns[i]['hotkey'],'<u>'+btns[i]['hotkey']+'</u>');
				else if (btns[i]['label']!=undefined) btns[i]['label'] = btns[i]['label']+' ('+btns[i]['hotkey']+')';
				if (btns[i]['link']!=undefined) hotKeys[btns[i]['hotkey']] = "document.location.href='"+btns[i]['link']+"'";
				else hotKeys[btns[i]['hotkey']] = btns[i]['action'];
				btns[i]['title'] += ' (Hotkey: Control+Shift+'+btns[i]['hotkey']+')';
			}
			
			if (btns[i]['link']!=undefined) action = btns[i]['link'];
			else action = 'javascript:'+btns[i]['action'];
			btnstr += '<td align="right" class="nopad">';
			if (btns[i]['icon'].substring(0,1)=='<') btnstr += btns[i]['icon'];
			else {
				btnstr += '<a href="'+action+'"'+target+'><img border="0" src="/organizer/images/icons/'+btns[i]['icon']+'" title="'+btns[i]['title']+'"';
				if (idpre!=undefined) btnstr += ' id="'+idpre+i+'a"';
				btnstr += '></a>';
			}
			btnstr += '</td><td nowrap';
			if (i<btns.length-1) btnstr += ' style="padding-right:8px"';
			btnstr += '><a href="'+action+'"'+target+' class="button" title="'+btns[i]['title']+'"';
			if (idpre!=undefined) btnstr += ' id="'+idpre+i+'b"';
			btnstr += '>'+btns[i]['label']+'</a></td>';
		}
	}
	btnstr += '</tr></table>';
	return btnstr;
}
function message(value,color) {
	// Set message element
	if (value=='') value = '&nbsp;';
	//if (color==undefined) color = '#332B9E';
	if (value.toLowerCase().substr(0,7)=='error: ') color = '#FF0000';
	else if (color==undefined) color = '#0A8A00';
	document.getElementById('messagecell').style.color = color;
	document.getElementById('messagecell').innerHTML = value;
}
function printwin(url) {
	window.open(url,'','top=50,left=50,height=500,width=700,location=0,resizable=1,menubar=0,toolbar=0,status=0,scrollbars=1');
}
function SetCookie(cookieName,cookieValue) {
	//Supports deleting
	if (cookieValue=='') {
		var expire = new Date();
		expire.setTime(expire.getTime() - 3600000*24*7);
		document.cookie = cookieName+"=;expires="+expire.toGMTString();
	}
	else document.cookie = cookieName+"="+escape(cookieValue);
}
function GetCookie(cookieName) {
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return "";
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length;
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
function Dec2Hex(Decimal) {
	var hexChars = "0123456789ABCDEF";
	var a = Decimal % 16;
	var b = (Decimal - a)/16;
	return "" + hexChars.charAt(b) + hexChars.charAt(a);
}
function colorval (color) {
	if (color=='') return color;
	else if (color.length==7) return color.toUpperCase();
	else {
		// Strip out extra info
		var re = new RegExp (' ', 'gi') ;
		color = color.replace(re,'').replace(')','(').split('(')[1];
		var ca = color.split(',');
		ca[0] = Dec2Hex(ca[0]);
		ca[1] = Dec2Hex(ca[1]);
		ca[2] = Dec2Hex(ca[2]);
		return '#'+ca[0]+ca[1]+ca[2];
	}
}
function dotip(id,text) {
	var te = document.getElementById(id);
	if (te!=null) te.title = text;
}
function download() {
	window.document.location.href = window.document.location.href + '&downloadrpt=1';
}
var html_table_row_color = '';
function table_rowcolor() {
	if (html_table_row_color=='#DCE8FC') html_table_row_color='#FFFFFF';
	else html_table_row_color='#DCE8FC';
	return html_table_row_color;
}
var html_table_num = 0;
var html_table_last_group_color = '';
var reorderIDs = new Array();
var tableResizable = new Array();
var tableDataGetMore = new Array(); // Store full table data so we can build pageBy
function drawtable(data,stronly,moreid,morepages,fixedheight,width,expandgroups,nowrap,resizable) {
	if (data.length==1) return '';

	if (stronly==undefined) stronly = 0;
	if (moreid==undefined) moreid = '';
	if (fixedheight==undefined) fixedheight = 0;
	if (width==undefined) width = '';
	if (resizable==undefined) resizable = 0;
	
	// Keep track of table being resizable so when we add more data we can adjust accordingly
	

	// sortedby is an index
	var tbl = '';
	if (fixedheight>0) {
		tbl += '<table cellpadding="0" cellspacing="0"';
		if (width!='') tbl += ' width="'+width+'"';
		tbl += '><tr><td class="nopad"><div id="tablediv'+html_table_num+'" style="';
		tbl += 'height:'+fixedheight+';overflow-y:auto;width:111%">';
	}
	tbl += '<table id="table'+html_table_num+'" cellpadding="0" cellspacing="0" class="songtable" style="clear:left"';
	if (width!='') tbl += ' width="'+width+'"';
	tbl += '><thead><tr height="15" bgcolor="#F8F8F8" valign="bottom">';
	var fldname;
	var reorder = 0;
	var skipcol = -1;
	if (data[0][0]=='drag:') {
		skipcol = 0;
		reorder = 1;
		reorderIDs[html_table_num] = new Array();
	} else if (data[0].length>1 && data[0][1]=='drag:') {
		skipcol = 1;
		reorder = 1;
		reorderIDs[html_table_num] = new Array();
	}
	for (i=0; i<data[0].length; i++) {
		if (i!=skipcol) {
		fldname= data[0][i];
		if (fldname=='' || fldname=='groupby:' || fldname=='drag:') fldname = '&nbsp;';
		if (fldname!='drag:') {
			tbl += '<th class="songtable2" nowrap><table cellpadding="0" cellspacing="0"><tr><td class="nopad" nowrap>'+fldname+'</td></tr></table></th>';
			if (i<data[0].length-1 && data[0][i].substring(0,8)!='groupby:') tbl += '<th class="songtable"><img src="/organizer/images/1px.gif" width="2"></th>';
		}
		} // i!=skipcol
	}
	tbl += '</tr></thead><tbody>';
	html_table_row_color = '';
	html_table_last_group_color = '';
	var row_bgcolor = '';
	var display_none = '';
	var row_id = '';
	var grouplabel;
	var newdata, after;
	for (i=1; i<data.length; i++) {
		tbl += '<tr valign="top"';

		if (!expandgroups && data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='*' || data[i][0].substring(8,9)=='#' || data[i][0].substring(8,9)=='')) html_table_row_color = html_table_last_group_color;
		row_bgcolor = table_rowcolor();
		if (!expandgroups && data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='*' || data[i][0].substring(8,9)=='#' || data[i][0].substring(8,9)=='')) html_table_last_group_color = html_table_row_color;

		// Check for groupby id
		if (data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='-' || data[i][0].substring(8,9)=='_')) {
			row_id = ' id="rowgroup_'+html_table_num+'_'+data[i][0].substring(9)+'"';
			if (!expandgroups) display_none = ';display:none';
		} else if (data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='*' || data[i][0].substring(8,9)=='#' || data[i][0].substring(8,9)=='')) {
			row_id = ' id="rowgroup"';
			display_none = '';
		} else {
			row_id = '';
			display_none = '';
		}

		tbl += ' style="background-color:'+row_bgcolor+display_none+'"'+row_id+
				' onclick="rowsel(this,\''+html_table_row_color+'\')">';
		if (expandgroups) groupexp = 'groupcol';
		else groupexp= 'groupexp';
		grouplabel = 0;
		for (j=0; j<data[i].length; j++) {
			if (j!=skipcol) {
			newdata = data[i].slice();
			dt = newdata[j];
			cls = 'songtable2';
			if (dt.substring(0,8)=='groupby:') {
				if (dt.substring(8,9)=='#') grouplabel = 1;
				//if (dt.substring(8,9)=='#') window.status = grouplabel;

				if (dt.substring(8)=='') dt = '';
				else if (dt.substring(8,9)=='*' || dt.substring(8,9)=='#') dt = '<a href="javascript:collapsetablegroup('+html_table_num+',\''+dt.substring(9)+'\')"><img border="0" src="/organizer/images/'+groupexp+'.gif" id="rowgroupimg_'+html_table_num+'_'+data[i][0].substring(9)+'"></a>';
				else if (dt.substring(8,9)=='_') dt = '<img src="/organizer/images/L.png">';
				else dt = '<img src="/organizer/images/I-table.png">';
				cls = 'nopad';
			}

			tbl += '<td class="'+cls+'"';
			if (nowrap) tbl += ' noWrap';

			if (dt.substring(0,5)=='html:') {
				tbl += ' '+dt.substring(5,dt.indexOf('|'));
				dt = dt.substring(dt.indexOf('|')+1);
			}
			if (dt.substring(0,6)=='after:') {
				after = ' '+dt.substring(6,dt.indexOf('|'));
				dt = dt.substring(dt.indexOf('|')+1);
			} else after = '';

			if (reorder && j==(skipcol+1) && !grouplabel) tbl += ' id="dragid'+data[i][skipcol]+'" onmouseover="drag_mover(this)" onmouseout="drag_mout(this)" onmouseup="drag_mup(this)" onselectstart="return false;"';

			if (dt=='') dt = '&nbsp;';
			tbl += '>';
			tbl += dt;
			tbl += '</td>';
			if (j<data[i].length-1 && data[i][j].substring(0,8)!='groupby:') {
				tbl += '<td align="right"';
				if (reorder && j==(skipcol+1) && !grouplabel) {
					tbl += ' id="dragid'+data[i][skipcol]+'" onmousedown="drag_start(this)" onmouseover="drag_mover(this)" onmouseout="drag_mout(this)" onmouseup="drag_mup(this)" class="draghandle" onselectstart="return false;"';
					reorderIDs[html_table_num][reorderIDs[html_table_num].length] = 'dragid'+data[i][skipcol];
				} else tbl += ' class="songtable"';
				if (after=='' && reorder && j==(skipcol+1) && !grouplabel) tbl += ' style="width:7"';
				else if (after=='') tbl += ' style="width:2"';
				tbl += '>';
				if (after!='') tbl += after;
				else tbl += '&nbsp;';
				tbl += '</td>';
			}
			} // j!=skipcol
		}
		tbl += '</tr>';
		// Draw each row - faster display
		if (!stronly) {
			document.write(tbl);
			tbl = '';
		}
	}
	if (reorder) {
		// Need to add groupby column!
		tbl += '<tr bgcolor="#D6D3CE" valign="center">';
		if (skipcol==1) tbl += '<td></td>';
		tbl += '<td onmouseover="drag_mover(this)" onmouseout="drag_mout(this)" onmouseup="drag_mup(this)">' +
				'<img src="/organizer/images/1px.gif"></td><td id="dragid-1" class="draghandle" onmouseover="drag_mover(this)" onmouseout="drag_mout(this)" onmouseup="drag_mup(this)"><img src="/organizer/images/1px.gif"></td><td colspan="'+(2*data[0].length-1)+'"></td></tr>';
		reorderIDs[html_table_num][reorderIDs[html_table_num].length] = 'dragid-1';
	}
	tbl += '</tbody></table>';
	if (moreid!='') {
		data.shift();
		tableDataGetMore[html_table_num] = new Array();
		tableDataGetMore[html_table_num]['p1'] = data;

		// Comment out Get All Data for now... might cause problems for users trying to load imported data, thousands of songs
		// Build table of page numbers
		var pagediv = '<div id="table_page_numbers_'+html_table_num+'"';
		pagediv += '>';
		for (i=1; i<=morepages; i++) {
			pagediv += '<div align="center" class="pagenum';
			if (i==1) pagediv += ' pagenum-sel';
			pagediv += '"';
			if(navigator.appVersion.indexOf('MSIE')>0) pagediv += ' style="width:18"';
			pagediv += ' onclick="getmoredata('+html_table_num+",'"+moreid+"',"+i+","+expandgroups+','+nowrap+',0)" title="Page '+i+' of '+morepages+'">'+i+'</div>';
		}
		pagediv += '</div>';
		if(navigator.appVersion.indexOf('MSIE')>0) pagediv += '<div style="height:1"></div>';
		// We have to use a hidden table to re-draw rows b/c of IE - very buggy when adding rows to a table, insertAdjacentHTML and innerHTML both bombed
		pagediv += '<div id="get_more_temp_table_'+html_table_num+'" style="display:none"></div>';
		tbl = pagediv+'<div style="clear:left">'+tbl+'</div>';
		//tbl += '<div id="moredata'+html_table_num+'">'+buttonbar(
		//	[
		//		{'label':'Get More Rows','icon':'forward_16.gif','action':'getmoredata('+html_table_num+',\''+moreid+'\',2,'+expandgroups+','+nowrap+',0)'} /*,
		//		{'label':'Get All Remaining Rows','icon':'forward_16.gif','action':'getmoredata('+html_table_num+',\''+moreid+'\','+expandgroups+','+nowrap+',1)'}*/
		//	]
		//)+'</div>';
		
	}
	if (reorder) {
		tbl += '<script type="text/javascript">drag_init();</script>';
	}
	if (fixedheight) tbl += '</div></td></tr></table>';
	html_table_num++;
	if (stronly) return tbl;
	else {
		document.write(tbl);
		if (resizable) $(document).ready(function() {makeColumnsResizable(html_table_num-1);});
	}
}
// Assume we'll only do this with one table!!
function getElementX(el){
  var posX = 0;
  while(el != null){
    posX += el.offsetLeft;
    el = el.offsetParent;
  }
  return posX;
}
var activeDragColumn = -1;
function mouseOverColumn(evt) {
	if (activeDragColumn<0) return;
	var rows = document.getElementById('table0').rows;
	if (rows.length<2) return;
	var cwidth = getX(evt) - getElementX(rows[1].cells[activeDragColumn-1].firstChild) - rows[0].cells[activeDragColumn].firstChild.clientWidth;
	var minwidth = rows[0].cells[activeDragColumn-1].firstChild.clientWidth;
	if (cwidth<minwidth) return;
	
	// Loop through each row, setting width of divs
	for (i=1; i<rows.length; i++) {
		//rows[i].cells[activeDragColumn-1].firstChild.style.width = '100px';
		rows[i].cells[activeDragColumn-1].firstChild.style.width = cwidth;
		//rows[i].cells[activeDragColumn-1].firstChild.innerHTML = cwidth;
	}
	// Set first row column width
	rows[0].cells[activeDragColumn-1].width = cwidth;
}	
// Make a table that's already been drawn resizable
var tableCellWidths = new Array();
var tableCellHeights = new Array();
function makeColumnsResizable(table_num) {
	// Get array of columns widths
	var rows = document.getElementById('table'+table_num).rows;
	var newdiv, cell;
	tableCellWidths[table_num] = new Array();
	tableCellHeights[table_num] = new Array();
	for (i=0; i<rows[0].cells.length; i++) {
		if (rows[0].cells[i].className=='songtable2') {
			tableCellWidths[table_num][i] = rows[0].cells[i].offsetWidth;
			tableCellHeights[table_num][i] = rows[0].cells[i].offsetHeight;
		}
	}
	//return;
	// Add resizing handles to first row
	for (j=0; j<rows[0].cells.length; j++) {
		cell = rows[0].cells[j];
		if (cell.className=='songtable') {
			//cell.style.textAlign = 'right';
			cell.innerHTML = '<div align="right"><img style="cursor:move;-moz-user-select:none" onmousedown="activeDragColumn='+j+'" src="/organizer/images/draghandle.gif" title="Resize Column" onselectstart="return false;" ondragstart="return false;"></div>';
		}
	}
	for (i=1; i<rows.length; i++) {
		for (j=0; j<rows[i].cells.length-1; j++) {
			cell = rows[i].cells[j];
			if (cell.className=='songtable2') {
				newdiv = document.createElement('DIV');
				newdiv.style.width = tableCellWidths[table_num][j]-4; // Padding
				//newdiv.style.height = tableCellHeights[table_num][j]-5;
				newdiv.style.height = 13;
				newdiv.style.overflow = 'hidden';
				newdiv.innerHTML = cell.innerHTML;
				cell.noWrap = true;
				cell.innerHTML = '';
				cell.appendChild(newdiv);
			}
		}
	}
	// Remember position of mouse event
	document.body.onmousemove = function(evt) {mouseOverColumn(evt);}
	document.body.onmouseup = function() {activeDragColumn = -1;}
}
// Functions for reordering
var drag_cell = null;
var drag_index = -1;
var drop_cell = null;
var drag_text = null;
var drag_tbl = null;
var drag_e = null;
var drag_newrow;
function drag_init() {
	document.write('<div id="drag_text" style="position:absolute;display:none"></div>');
	drag_text = document.getElementById('drag_text');
	drag_tbl = document.getElementById('table'+(html_table_num-1));
	document.body.onmouseup = function () {
		drag_cell = null;
		drag_text.style.display = 'none';
	}
	document.body.onmousemove = function(drag_e) {
		if (drag_cell==null) return;
		drag_text.style.left = getX(drag_e) + 15;
		drag_text.style.top = getY(drag_e) - 6;
		if (drag_text.style.display!='') drag_text.style.display = '';
	}
}
function drag_mover(cell) {
	if (cell.className!='draghandle') cell = cell.nextSibling; // Make sure we target the draghandle cell
	if (cell.className!='draghandle') return;
	if ( drag_cell==null || drag_cell==cell || drag_index == reorderIDs[cell.parentNode.parentNode.parentNode.id.substring(5)].in_array(cell.id)-1 ) return;
	drop_cell = cell;
	cell.style.borderTopStyle = 'solid';
	cell.style.borderTopWidth = 2;
	cell.style.borderTopColor = '#FF0000';
	cell = cell.previousSibling;
	cell.style.borderTopStyle = 'solid';
	cell.style.borderTopWidth = 2;
	cell.style.borderTopColor = '#FF0000';
}
function drag_mout(cell) {
	if (cell.className!='draghandle') cell = cell.nextSibling; // Make sure we target the draghandle cell
	if (cell.className!='draghandle') return;
	cell.style.borderTopWidth = 0;
	cell = cell.previousSibling;
	cell.style.borderTopWidth = 0;
	drop_cell = null;
}
function drag_mup(cell) {
	if (cell.className!='draghandle') cell = cell.nextSibling; // Make sure we target the draghandle cell
	if (cell.className!='draghandle') return;
	if ( drag_cell==null || drag_cell==cell || drag_index == reorderIDs[cell.parentNode.parentNode.parentNode.id.substring(5)].in_array(cell.id)-1 ) return;
	// Move rows
	document.frmReorder.Reorder_ID.value = drag_cell.id.substring(6);
	document.frmReorder.Destination_ID.value = drop_cell.id.substring(6);
	if (document.frmReorder.Reorder_ID.value!='' && document.frmReorder.Destination_ID.value!='') document.frmReorder.submit();
}
function getX(drag_e) {
	if(navigator.appVersion.indexOf('MSIE')>0) return window.event.clientX;
	else return drag_e.pageX;
}
function getY(drag_e) {
	if(navigator.appVersion.indexOf('MSIE')>0) return window.event.clientY + document.body.scrollTop;
	else return drag_e.pageY;
}
function drag_start(cell) {
	drag_cell = cell;
	drag_index = reorderIDs[cell.parentNode.parentNode.parentNode.id.substring(5)].in_array(cell.id);
	drag_text.innerHTML = cell.previousSibling.innerHTML.stripHTML();
}
function collapsetablegroup(table_num,row_id) {
	var tbl = document.getElementById('table'+table_num);
	var rows1 = tbl.rows;
	var rows2 = tbl.childNodes;
	var row;
	var img = document.getElementById('rowgroupimg_'+table_num+'_'+row_id);
	for (i=0; i<rows1.length+rows2.length; i++) {
		if (i<rows1.length) row = rows1[i];
		else row = rows2[i-rows1.length];
		if (row.id == 'rowgroup_'+table_num+'_'+row_id) {
			if (img.src.indexOf('groupcol')>0) row.style.display = 'none';
			else row.style.display = '';
		}
	}
	if (img.src.indexOf('groupcol')>0) img.src = '/organizer/images/groupexp.gif';
	else img.src = '/organizer/images/groupcol.gif';
}
function getmoredata(table_num,tid,pagenum,expandgroups,nowrap,all) {
	if (tableDataGetMore[table_num]['p'+pagenum]!=undefined) {
		processmoredata(table_num,'',pagenum,expandgroups,nowrap);
		return;
	}

	if (all && !confirm("Are you sure you want to get all remaining rows?\nThis could take a long time!")) return;

	// Get data via xmlhttp
	// We need to re-declare b/c IE is buggy
	if (!window.ActiveXObject) xmlHttp = new XMLHttpRequest();
	else xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState != 4 )  return; // Not yet finished
		else if (xmlHttp.status == 200 ) {
			stopLoader(); // Stop ajax loader
			processmoredata(table_num,xmlHttp.responseText,pagenum,expandgroups,nowrap);
		} else alert('Unspecified error getting table data.');
	}
	xmlHttp.open("POST","/organizer/scripts/general/xmlhttp.php?action=getmoredata&tid="+tid+'&page='+pagenum+'&all='+all,1);
	xmlHttp.setRequestHeader('Set-Cookie','PHPSESSID='+GetCookie('PHPSESSID'));
	// Start ajax loader
	startLoader();
	xmlHttp.send('');
}
function processmoredata(table_num,rawdata,pagenum,expandgroups,nowrap) {
	// query by tid and page xmlhttp should delete data afterwards
	var table = document.getElementById('table'+table_num);
	var firstcell = 0;

	var moredata = 1;
	// Mark the page we're on
	var pagesel = document.getElementById('table_page_numbers_'+table_num);
	var clsname = '';
	for (i=0; i<pagesel.childNodes.length; i++) {
		clsname = 'pagenum';
		if (i==pagenum-1) clsname += ' pagenum-sel';
		pagesel.childNodes[i].className = clsname;
	}
	if (tableDataGetMore[table_num]['p'+pagenum]!=undefined) data = tableDataGetMore[table_num]['p'+pagenum];
	else {
		rawdata = rawdata.split("\n");
		if (rawdata[rawdata.length-1]=='<!-- END OF DATA -->') {
			moredata = 0;
			rawdata.length = rawdata.length - 1; // Remove last item
		}
		rawdata = "data = new Array(\n"+rawdata.join("\n")+");";
		// eval() code into array data()
		eval(rawdata);
		tableDataGetMore[table_num]['p'+pagenum] = data;
	}

	if (data.length==0) {
		alert('Error: No data found. Please try again by refreshing this page.');
		return;
	}
	// Loop through rows and get last row color
	/*var rows1 = table.rows;
	var rows2 = table.childNodes;*/
	/*
	for (i=0; i<rows1.length+rows2.length; i++) {
		if (i<rows1.length) row = rows1[i];
		else row = rows2[i-rows1.length];
		if (row.tagName=='TR') html_table_row_color = colorval(row.style.backgroundColor);
		if (row.id=='rowgroup') html_table_last_group_color = colorval(row.style.backgroundColor);
	}
	*/
	html_table_row_color = '';
	html_table_last_group_color = '';
	
	// Remove existing data
	while (table.rows.length>1) table.deleteRow(1);
	
	var temp_table_div, temp_table;
	temp_table_div = document.getElementById('get_more_temp_table_'+table_num);
	
	var row_bgcolor = '';
	var row_id = '';
	var display_none = '';
	var tbl = '';
	var after;
	if (expandgroups) groupexp = 'groupcol';
	else groupexp= 'groupexp';
	for (i=0; i<data.length; i++) {
		tbl += '<tr valign="top"';
		if (!expandgroups && data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='*' || dt.substring(8,9)=='#' || data[i][0].substring(8,9)=='')) html_table_row_color = html_table_last_group_color;
		row_bgcolor = table_rowcolor();
		if (!expandgroups && data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='*' || dt.substring(8,9)=='#' || data[i][0].substring(8,9)=='')) html_table_last_group_color = html_table_row_color;

		// Check for groupby id
		if (data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='-' || data[i][0].substring(8,9)=='_')) {
			row_id = 'rowgroup_'+table_num+'_'+data[i][0].substring(9);
			if (!expandgroups) display_none = ';display:none';
		} else if (data[i][0].substring(0,8)=='groupby:' && (data[i][0].substring(8,9)=='*' || dt.substring(8,9)=='#' || data[i][0].substring(8,9)=='') ) {
			row_id = 'rowgroup';
			display_none = '';
		} else {
			row_id = '';
			display_none = '';
		}

		tbl += ' style="background-color:'+row_bgcolor+display_none+'"'+row_id+
				' onclick="rowsel(this,\''+html_table_row_color+'\')">';

		for (j=0; j<data[i].length; j++) {
			tbl += '<td';
			if (j==0 && !firstcell) {
				tbl += ' id="firstcell'+table_num+'"';
				firstcell = 1;
			}
			dt = data[i][j];
			cls = 'songtable2';
			if (dt.substring(0,8)=='groupby:') {
				if (dt.substring(8)=='') dt = '';
				else if (dt.substring(8,9)=='*' || dt.substring(8,9)=='#') dt = '<a href="javascript:collapsetablegroup('+table_num+',\''+dt.substring(9)+'\')"><img border="0" src="/organizer/images/'+groupexp+'.gif" id="rowgroupimg_'+table_num+'_'+data[i][0].substring(9)+'"></a>';
				else if (dt.substring(8,9)=='_') dt = '<img src="/organizer/images/L.png">';
				else dt = '<img src="/organizer/images/I.png">';
				cls = 'nopad';
			}
			tbl += ' class="'+cls+'"'
			if (nowrap) tbl += ' noWrap';

			if (dt.substring(0,5)=='html:') {
				tbl += ' '+dt.substring(5,dt.indexOf('|'));
				dt = dt.substring(dt.indexOf('|')+1);
			}
			if (dt.substring(0,6)=='after:') {
				after = ' '+dt.substring(6,dt.indexOf('|'));
				dt = dt.substring(dt.indexOf('|')+1);
			} else after = '';

			if (dt=='') dt = '&nbsp;';
			
			// Check for resizable
			if (tableCellWidths[table_num]!=undefined) {
				//dt = '<div style="width:'+(tableCellWidths[table_num][j]-4)+';height:'+(tableCellHeights[table_num][j]-5)+';overflow:hidden">'+dt+'</div>';
				dt = '<div style="width:'+(tableCellWidths[table_num][j]-4)+';height:13;overflow:hidden">'+dt+'</div>';
			}
			
			tbl += '>'+dt+'</td>';

			if (j<data[i].length-1 && data[i][j].substring(0,8)!='groupby:') {
				tbl += '<td class="songtable" align="right">';
				if (after!='') tbl += after;
				else tbl += '<img src="/organizer/images/1px.gif" width="2">';
				tbl += '</td>';
			}
		}
		tbl += '</tr>';
		// For non-IE.  See IE below (it's buggy)
		if(navigator.appVersion.indexOf('MSIE')<=0) {
			table.insertAdjacentHTML('beforeEnd',tbl);
			tbl = '';
		}
	}
	var temp_row;
	if(navigator.appVersion.indexOf('MSIE')>0) {
		// IE is really buggy with adding rows to a table, so we need a workaround
		temp_table_div.innerHTML = '<table>'+tbl+'</table>';
		temp_table = temp_table_div.firstChild;
		// Copy rows from temp table to real table
		while (temp_table.tBodies[0].rows.length>0) {
			//temp_row = temp_table.tBodies[0].rows[i].cloneNode();
			//alert();
			//table.tBodies[0].insertBefore(temp_table.childNodes[0].rows[i]);
			table.tBodies[0].insertBefore(temp_table.tBodies[0].rows[0]);
		}
	}
	//if (!moredata) document.getElementById('moredata'+table_num).style.display = 'none';

	///var firstc = document.getElementById('firstcell'+table_num);
	//firstc.scrollIntoView();
	//firstc.id = '';

	//stopLoader(); // Stop ajax loader
}
function rowsel(row,oColor) {
	if (colorval(row.style.backgroundColor)==oColor) {
		if (oColor=='#EDF3FE') row.style.backgroundColor = '#FFCCCC';
		else row.style.backgroundColor = '#FFFFCC';
	}
	else row.style.backgroundColor = oColor;
}
function sorttable(fld) {
	document.frmSort.sort.value = fld;
	document.frmSort.submit();
}
function wizard(src) {
	top.iconbar.wizardwindow = window.open('/organizer/wizard.php?w='+src,'wizard','left=100,top=50,height=300,width=500,scrollbars=no,resizable=yes,location=no,menubar=no,status=no,toolbar=no');
	top.iconbar.wizardwindow.focus();
}
function missingfields(frm,arr) {
	flds = '';
	for (key in arr) {
		if (frm.elements[key].value=='') {
			if (flds!='') flds += ', ';
			flds += arr[key];
		}
	}
	if (flds!='') {
		alert("Error: Please fill out the following fields:\n"+flds);
		return 1;
	} else return 0;
}
function parsexmlhttp(obj) {
	var arr = new Array();
	var data = xmlHttp.responseText.split('&');
	for (var i=0; i<data.length; i++) {
		dat = data[i]; dat = dat.split('=');
		arr[unescape(dat[0])] = unescape(dat[1]);
	}
	return arr;
}
// Convert a Javascript date to mm/dd/yyyy
function mmddyy(dt) {
 if (dt==undefined) dt = new Date();
 return (dt.getMonth()+1) + '/' + dt.getDate() + '/' + dt.getFullYear();
}
// Convert a Javascript datetime to mm/dd/yyyy H:i:s
function datetime(dt) {
 if (dt==undefined) dt = new Date();
 var tm = dt.toString().split(' ');
 tm = tm[4].split(':');
 return mmddyy(dt)+' '+tm[0]+':'+tm[1];
}
// Portal Header
function portalHeader(txt,img) {
	var str = '<table cellpadding="0" cellspacing="0" width="100%"><tr height="17" class="portalblock" valign="top">'+
			'<td class="nopad"><img src="/organizer/images/tab-left.gif"></td><td class="nopad">';
	if (img!=undefined) str += '<img src="/organizer/images/'+img+'" style="margin-top:1">';
	else str += '<img src="/organizer/images/1px.gif" width="3">';
	str += '</td><td class="portalblock" width="99%">'+txt+'</td>'+
			'<td class="nopad"><img src="/organizer/images/tab-right.gif" width="10"></td></tr></table>';
	document.write(str);
}

// Check for enter key
function enterKeyPressed(e) {
	if(!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if (code==13) return true;
	else return false;
}

// Ajax loader icons
function startLoader() {
	top.iconbar.document.getElementById('ajaxstatic').style.display = 'none';
	top.iconbar.document.getElementById('ajaxloader').style.display = '';
}
function stopLoader() {
	top.iconbar.document.getElementById('ajaxstatic').style.display = '';
	top.iconbar.document.getElementById('ajaxloader').style.display = 'none';
}

// Standardize DIV heights for portal blocks when they float (so they will line up vertically
function _sortDivs(a,b) {
	if (trueOffset(a,'y')<trueOffset(b,'y')) return -1;
	else if (trueOffset(a,'y')>trueOffset(b,'y')) return 1;
	else {
		if (trueOffset(a,'x')<trueOffset(b,'x')) return -1;
		else if (trueOffset(a,'x')>trueOffset(b,'x')) return 1;
		else return 0;
	}
}
function stdPortalBlockHeights() {
	var divs = document.getElementsByTagName('DIV');
	var pdivs = new Array();
	var heights = new Array();
	var maxheight = 0;
	// Build an array of portal divs and sort by yPos, xPos
	for (var i=0; i<divs.length; i++) {
		if (divs[i].className=='portalblocksub' || divs[i].className=='portalblocksub2' || divs[i].className=='portalblocksub3')
			pdivs[pdivs.length] = divs[i];
	}
	pdivs.sort(_sortDivs);
	// For each DIV, scan all other divs and take the tallest one at this yPos
	for (k=0; k<2; k++) {
	for (var i=0; i<pdivs.length; i++) {
		maxheight = 0;
		for (var j=0; j<pdivs.length; j++) {
			if (trueOffset(pdivs[i],'y')==trueOffset(pdivs[j],'y') && pdivs[j].clientHeight > maxheight) maxheight = pdivs[j].clientHeight;
		}
		if(navigator.appVersion.indexOf('MSIE')>0) pdivs[i].style.height = maxheight;
		else pdivs[i].style.height = maxheight-4;
	}
	}
}
function trueOffset(ele,dir) {
	(dir=="x") ? pos = ele.offsetLeft : pos = ele.offsetTop;
	tempEle = ele.offsetParent;
	while(tempEle != null) {
		pos += (dir=="x") ? tempEle.offsetLeft : tempEle.offsetTop;
		tempEle = tempEle.offsetParent;
	}
	return pos;
}
// Standardize generic DIV heights matching by id prefix
function stdDivHeights(idpref) {
	var divs = document.getElementsByTagName('DIV');
	var pdivs = new Array();
	var heights = new Array();
	var maxheight = 0;
	for (var i=0; i<divs.length; i++) {
		if (divs[i].id.toUpperCase().substr(0,idpref.length)==idpref.toUpperCase())
			pdivs[pdivs.length] = divs[i];
	}
	pdivs.sort(_sortDivs);
	for (k=0; k<2; k++) {
	for (var i=0; i<pdivs.length; i++) {
		maxheight = 0;
		for (var j=0; j<pdivs.length; j++) {
			if (trueOffset(pdivs[i],'y')==trueOffset(pdivs[j],'y') && pdivs[j].clientHeight > maxheight) maxheight = pdivs[j].clientHeight;
		}
		if(navigator.appVersion.indexOf('MSIE')>0) pdivs[i].style.height = maxheight+2;
		else pdivs[i].style.height = maxheight-6;
	}
	}
}

// Email someone
function email(etype,ids,subject) {
	if (subject==undefined) subject = '';
	opensubset('/organizer/scripts/people/email.php?type='+etype+'&ID='+ids+'&subject='+subject);
}

// MCE Editor
function startTinyMCE(names) {
	tinyMCE.init({
		mode : "exact",
		elements : names,
		theme : "advanced",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_buttons1 : "fullscreen,separator,bold,italic,underline",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		plugins : "table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,media,searchreplace,print,contextmenu,paste,directionality,fullscreen",
		fullscreen_new_window : true,
		fullscreen_settings : {
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,link,unlink,anchor,image,cleanup,code,|,hr,removeformat,preview,print"
		},
		content_css : "/organizer/css/tinymce_word.css",
		external_link_list_url : "example_link_list.js",
		external_image_list_url : "example_image_list.js",
		media_external_list_url : "example_media_list.js",
		paste_use_dialog : false,
		theme_advanced_resizing : true,
		theme_advanced_resize_horizontal : false,
		paste_auto_cleanup_on_paste : true,
		paste_convert_headers_to_strong : false,
		paste_strip_class_attributes : "all",
		paste_remove_spans : false,
		paste_remove_styles : false
	});
}

// Handle page hot-keys
var hotKeys = new Array();
function hotkeyrcv(e) {
	var evt, ctrl, shft, code, key;
	if (document.all) {
		evt = window.event; 
		code=evt.keyCode;
	} else {
		evt = e;
		code=evt.charCode;
	}
	if (code<48) code = code+96;
	ctrl = evt.ctrlKey;
	shft = evt.shiftKey;
	key = String.fromCharCode(code).toUpperCase();
	if (ctrl && shft && hotKeys[key]!=undefined) {
		eval(hotKeys[key]);
		evt.returnValue = false;
		evt.cancelBubble = false;
		return false;
	}
}
if (!document.all){
	window.captureEvents(Event.KEYPRESS);
	window.onkeypress=hotkeyrcv;
} else {
	document.onkeypress = hotkeyrcv;
} 

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+$/,"");
}
String.prototype.stripHTML = function() {
	return this.replace(/(<([^>]+)>)/ig,"");
}
Array.prototype.in_array = function ( obj ) {
	var len = this.length;
	for ( var x = 0 ; x <= len ; x++ ) {
		if ( this[x] == obj ) return x;
	}
	return -1;
}

if (!window.ActiveXObject) var xmlHttp = new XMLHttpRequest();
else var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
