/* keeps console.log and console.assert from breaking if not using Firefox or Firebug */

try { console.assert(1); } catch(e) { console = { log: function() {}, assert: function() {} } }

sortParamsObj = {'sortID':0, 'sortDir':'Down'};

/* global list functions */

function printListHead(listType) {
	var selTable = document.getElementById(listType+'_listTable');
	if (document.getElementById(listType+'_listTableHead')) {
		//removeAllChildren(listType+'_listTableHeadRow');
		//$('#'+listType+'_listTableHeadRow').remove();
		return;
	}

	var newThead = document.createElement('thead');
	$(newThead).attr('id',listType+"_listTableHead");
	var parentEl = document.createElement('tr');
	$(parentEl).attr('id',listType+"_listTableHeadRow");

	newThead.appendChild(parentEl);
	selTable.appendChild(newThead);

	var parentEl = document.getElementById(listType+'_listTableHeadRow');
	for (var i=0; i<listObj[listType].headAry.length; i++) {
		var newEl = document.createElement('th');
		$(newEl).attr('id',listType+"_listHead"+listObj[listType].headAry[i].id);
		if (listObj[listType].headAry[i].id == 'noSort') {
			if (listObj[listType].headAry[i].label)
				$(newEl).text(listObj[listType].headAry[i].label);
		} else if (listObj[listType].headAry[i].id == 'selItem') { // checkbox
			newEl.setAttribute('style', "width:1.6em;");
			$(newEl).append(
				$(document.createElement("input"))
					.attr('type', "checkbox")
					.attr('id', listType+"_allSelChk")
					.attr('value', '-1')
					.attr('title', ilcTrans(5600,"Select All"))
					.bind('click', {'id':'all','listType':listType}, function(evt) { selItemChecked(evt); })
					.get(0)
			);
		} else {
			// if headAry contains .type use abstracted sort, otherwise use old sort
			var clickParamObj;
			if (listObj[listType].headAry[i].type) {
				clickParamObj = {'id':listObj[listType].headAry[i].id, 'type':listObj[listType].headAry[i].type, 'listType':listType};
			} else {
				clickParamObj = {'id':listObj[listType].headAry[i].id,'listType':listType};
			}
			$(newEl).append(
				$(document.createElement("a"))
					.attr('href','#none')
					.attr('title',"Sort Column")
					.bind('click', clickParamObj,function(evt) { sortList(evt);return false; })
					.html(listObj[listType].headAry[i].label)
					.get(0)
			);
		}
		if (listObj[listType].headAry[i].style)
			newEl.setAttribute('style', listObj[listType].headAry[i].style);
		if (listObj[listType].headAry[i].sort_by)
			$(newEl).addClass("sorted").addClass(listObj[listType].headAry[i].sort_by);

		parentEl.appendChild(newEl);
	}
}

function printListMsg(listType, loading, str) {
	var selTable = document.getElementById(listType+'_listTable');
	if (document.getElementById(listType+'_listTableHead')) {
		removeAllChildren(listType+'_listTableHead');
		$('#'+listType+'_listTableHead').remove();
	}

	removeAllChildren(listType+'_listTableBody');
	$('#'+listType+'_listPagination').css('display','none');
	$('#statusChangeBtns').css('display','none');

	var selTable = document.getElementById(listType+'_listTableBody');
	var newTr = document.createElement('tr');
	var newTd = document.createElement('td');
	if (loading)
		$(newTd).append(
			$(document.createElement("div")).attr('id', "loadinglist").addClass('loadingwhite').get(0)
		);
	else
		$(newTd).text(str);

	newTr.appendChild(newTd);
	selTable.appendChild(newTr);
}

function setListPagination(pageNum, listType) {
	var selListCnt = listObj[listType].itemAry.length;
	var lotSizeEl = document.getElementById(listType+'_listLotSize');
	var lotSize = lotSizeEl[lotSizeEl.selectedIndex].value;

	var pageCnt = Math.ceil(selListCnt/lotSize);

	if (isNaN(pageNum)) pageNum = eval(pageNum);
	if (pageNum < 1) pageNum = 1;
	pageNum = Math.min(pageNum, pageCnt);
	
	var startIdx = (pageNum-1) * lotSize;
	var pageListCnt = Math.min(selListCnt-startIdx, lotSize)
	var endIdx = startIdx+pageListCnt-1;

	$('#'+listType+'_listPageNumber').val(pageNum);
	$('#'+listType+'_listPageCount').text(pageCnt);
	$('#'+listType+'_listPageResults').text(ilcTrans(1937,"Results")+" "+(startIdx+1)+"-"+(endIdx+1)+" "+ilcTrans(689,"of")+" "+selListCnt+" | ");

	return [startIdx, endIdx];
}

function selItemChecked(evt) {
	var id = evt.data.id;
	var listType = evt.data.listType;
	var selAllType = evt.data.selAllType;
	var el = document.getElementById(listType+"_"+id+"SelChk");

	var msgText = '';
	var linkText = '';

	var ary = $("input[@id^='"+listType+"_'][@id$='SelChk']:not([@id*='all'])");

	if (id == 'all' && !selAllType) {
		$('#'+listType+"_"+id+"SelChk").attr('title', (el.checked ? ilcTrans(805,"Clear All") : ilcTrans(5600,"Select All")));
		// un/check all the items on the page using regExp
		for (var i=0; i<ary.length; i++) {
			ary[i].checked = (el.checked ? "checked" : '');
			if (el.checked) {
				listObj[listType].selItemObj[ary[i].value] = 1
			} else {
				delete listObj[listType].selItemObj[ary[i].value];
			}
		}

		var selectedCount = objectCount(listObj[listType].selItemObj);
		if (el.checked) {
			if (selectedCount < listObj[listType].itemAry.length) { // show message only if all are some items unselected
				msgText = ilcTrans(5703, 'All {Page Items} items on this page selected.');
				msgText = ilcTransKeyword(msgText,{'data':[['Page Items','<b>'+ary.length+'</b>']]});

				linkText = ilcTrans(5796, 'Select all {All Items} items');
				linkText = ilcTransKeyword(linkText,{'data':[['All Items','<b>'+listObj[listType].itemAry.length+'</b>']]});

				selAllType = 'select';
			}
		} else {
			if (selectedCount > 0) { // show message only if there are some items selected
				msgText = ilcTrans(5702, 'All {Page Items} items on this page deselected.');
				msgText = ilcTransKeyword(msgText,{'data':[['Page Items','<b>'+ary.length+'</b>']]});

				linkText = ilcTrans(5740, 'Deselect remaining {Remaining Items} items');
				linkText = ilcTransKeyword(linkText,{'data':[['Remaining Items','<b>'+selectedCount+'</b>']]});

				selAllType = 'deselect';
			}
		}

		// need to also call the updateOutputFormats if it's a client list
		if (listType == 'clt' && typeof(updateOutputFormats) != 'undefined') {
			updateOutputFormats($('#rptId').val());
		}
	} else if (id == 'all' && selAllType) {
		$('#'+listType+"_"+id+"SelChk").attr('title', (selAllType == 'select' ? ilcTrans(805,"Clear All") : ilcTrans(5600,"Select All")));
		$('#'+listType+"_"+id+"SelChk").attr('checked', (selAllType == 'select' ? "checked" : ''));

		// de/select all the items in the array
		for (var i=0; i<listObj[listType].itemAry.length; i++) {
			$('#'+listType+"_"+listObj[listType].itemAry[i].id+"SelChk").attr('checked', (selAllType == 'select' ? "checked" : ''));

			var val = listObj[listType].itemAry[i].id;
			if (typeof(getSelItemValue) == 'function') {
				var val= getSelItemValue(listObj[listType].itemAry, i).value;
			}

			if (selAllType == 'select') {
				listObj[listType].selItemObj[val] = 1;
			} else {
				delete listObj[listType].selItemObj[val];
			}
		}

		if (selAllType == 'select') {
			msgText = ilcTrans(5701, 'All {All Items} items selected.');
			msgText = ilcTransKeyword(msgText,{'data':[['All Items','<b>'+listObj[listType].itemAry.length+'</b>']]});

			linkText = ilcTrans(5739, 'Deselect all {All Items} items');
			linkText = ilcTransKeyword(linkText,{'data':[['All Items','<b>'+listObj[listType].itemAry.length+'</b>']]});

			selAllType = 'deselect';
		}

		// need to also call the updateOutputFormats if it's a client list
		if (listType == 'clt' && typeof(updateOutputFormats) != 'undefined') {
			updateOutputFormats($('#rptId').val());
		}
	} else {
		if (el.type == 'checkbox') {
			if (el.checked) {
				listObj[listType].selItemObj[el.value] = 1;
			} else {
				delete listObj[listType].selItemObj[el.value];
			}

			// check to see if we should un/check all
			var aryChk = $("input[@id^='"+listType+"_'][@id$='SelChk']:not([@id*='all']):checked");
			$('#'+listType+"_allSelChk")
				.attr('checked', (ary.length == aryChk.length ? 'checked' : ''))
				.attr('title', (ary.length == aryChk.length ? ilcTrans(805,"Clear All") : ilcTrans(5600,"Select All")));
		} else {
			// if radio, clear selected object first
			listObj[listType].selItemObj = {};
			listObj[listType].selItemObj[el.value] = 1;
		}
	}

	// display all items message if text has been provided
	if (msgText && typeof(getSelItemValue) == 'function') {
		var anchor = document.createElement("a");
		$(anchor)
			.attr('href', "#none")
			.attr('class', "links")
			.bind('click', {'id':'all','selAllType':selAllType,'listType':listType}, function(evt) { selItemChecked(evt); })
			.html(linkText);

		$('#'+listType+'_SelectAllMsg')
			.html(msgText+' ')
			.append($(anchor))
			.slideDown('fast');
	} else {
		$('#'+listType+'_SelectAllMsg')
			.empty()
			.hide();
	}

	if (el.type == 'checkbox') {
		var selChkCnt = 0;
		for (var i in listObj[listType].selItemObj) { selChkCnt++; }
		var s = '';
		if (selChkCnt) {
			s = ilcTrans(5434,'{Number} of {Total} selected');
			s = ilcTransKeyword(s,{'data':[['Number',selChkCnt],['Total',listObj[listType].itemAry.length]]});
		}
		$('#'+listType+'_selItemTotals').text(s);
	}
}

function changeSearch(event, listType) {
	key = (event.which) ? event.which : event.keyCode;
	if (key == 13) {
		if (listType == 'catalog') {
			catalog_clearStatusMessage();
		}
		getListItems(listType);
	}
	return true;
}

function setListLotSize(listType, size) {
	var lotSizeEl = document.getElementById(listType+'_listLotSize');
	for (var i=0; i<lotSizeEl.length; i++) {
		$(lotSizeEl.options[i]).attr('selected', (lotSizeEl.options[i].value == size ? "selected" : '') );
	}
}

function setUserPref(el) {
	if (document.getElementById('eUserId') && document.getElementById('eUserId').value) {
		var ajaxObj = new ilincAjax('setUserPrefLot', '');
		ajaxObj.addParam('eUserId', document.getElementById('eUserId').value);
		ajaxObj.addParam('lotSize', el.value);
		ajaxObj.send();
	}
}

function changePageNum(event, listType) {
	key = (event.which) ? event.which : event.keyCode;
	if (key == 13) {
		printListItems($('#'+listType+'_listPageNumber').val(), listType);
	}
	return true;
}

function movePageNum(dir, listType) {
	var pageNum = $('#'+listType+'_listPageNumber').val();
	
	switch(dir) {
		case 'first': pageNum = 1; break;
		case 'prev': pageNum--; break;
		case 'next': pageNum++; break;
		case 'last': pageNum = 'pageCnt'; break;
	}

	printListItems(pageNum, listType);
}

function sortList(evt) {
	var sortby = evt.data.id;
	var sortType = evt.data.type;
	var listType = evt.data.listType;

	var newClass = 'sorted down';

	var parentNode = document.getElementById(listType+'_listTableHeadRow');
	var elAry = parentNode.getElementsByTagName('th');
	for (var i=0; i<elAry.length; i++) {
		if (elAry[i].id == listType+'_listHead'+sortby && elAry[i].className == 'sorted down') { // currently selected, flip it
			newClass = 'sorted up';
		}
		elAry[i].className = '';
	}

	document.getElementById(listType+'_listHead'+sortby).className = newClass;
	var dir = (newClass == 'sorted up' ? 'Up' : 'Down');
	if (sortType) {
		sortParamsObj.sortID = sortby
		sortParamsObj.sortDir = dir
		listObj[listType].itemAry.sort(eval('sortByType'+sortType));
	} else {
		listObj[listType].itemAry.sort(eval('sortBy'+sortby+dir));
	}

	adjustHeadAry(listType, sortby, dir.toLowerCase());

	printListItems(1, listType);

	if (listType == 'menu') prepListStateCookie(listType);
}

function sortByNameDown(a,b) {
	var x = a.name.toLowerCase();
	var y = b.name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByNameUp(a,b) {
	var x = b.name.toLowerCase();
	var y = a.name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByNameDateDown(a,b) {
	var x = a.name.toLowerCase();
	var y = b.name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByDateintDown(a,b)));
}
function sortByNameDateUp(a,b) {
	var x = b.name.toLowerCase();
	var y = a.name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByDateintDown(a,b)));
}
function sortByDateintDown(a,b) {
	var x = a.dateint;
	var y = b.dateint;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByDateintUp(a,b) {
	var x = b.dateint;
	var y = a.dateint;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByDateint2Down(a,b) {
	var x = a.dateint2;
	var y = b.dateint2;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByDateint2Up(a,b) {
	var x = b.dateint2;
	var y = a.dateint2;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByDateint3Down(a,b) {
	var x = a.dateint3;
	var y = b.dateint3;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByDateint3Up(a,b) {
	var x = b.dateint3;
	var y = a.dateint3;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByDateint4Down(a,b) {
	var x = a.dateint4;
	var y = b.dateint4;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByTypeDown(a,b)));
}
function sortByDateint4Up(a,b) {
	var x = b.dateint4;
	var y = a.dateint4;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByTypeDown(a,b)));
}
function sortByDateint5Down(a,b) {
	var x = a.dateint5;
	var y = b.dateint5;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByTypeDown(a,b)));
}
function sortByDateint5Up(a,b) {
	var x = b.dateint5;
	var y = a.dateint5;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByTypeDown(a,b)));
}
function sortByFnameDown(a,b) {
	var x = a.fname.toLowerCase();
	var y = b.fname.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByFnameUp(a,b) {
	var x = b.fname.toLowerCase();
	var y = a.fname.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByLnameDown(a,b) {
	var x = a.lname.toLowerCase();
	var y = b.lname.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByLnameUp(a,b) {
	var x = b.lname.toLowerCase();
	var y = a.lname.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByEmailDown(a,b) {
	var x = a.email.toLowerCase();
	var y = b.email.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByEmailUp(a,b) {
	var x = b.email.toLowerCase();
	var y = a.email.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByUnameDown(a,b) {
	var x = a.user_name.toLowerCase();
	var y = b.user_name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByUnameUp(a,b) {
	var x = b.user_name.toLowerCase();
	var y = a.user_name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByTypeDown(a,b) {
	var x = a['type'].toLowerCase();
	var y = b['type'].toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByTypeUp(a,b) {
	var x = b['type'].toLowerCase();
	var y = a['type'].toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByRoleDown(a,b) {
	var x = a.e_type.toLowerCase();
	var y = b.e_type.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByRoleUp(a,b) {
	var x = b.e_type.toLowerCase();
	var y = a.e_type.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByCountDown(a,b) {
	var x = a.count;
	var y = b.count;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByCountUp(a,b) {
	var x = b.count;
	var y = a.count;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByCo2Down(a,b) {
	var x = a.co2;
	var y = b.co2;
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByCo2Up(a,b) {
	var x = b.co2;
	var y = a.co2;
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByDistanceDown(a,b) {
	var x = a.distance;
	var y = b.distance;
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortByDistanceUp(a,b) {
	var x = b.distance;
	var y = a.distance;
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortBySizeDown(a,b) {
	var x = a.size;
	var y = b.size;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortBySizeUp(a,b) {
	var x = b.size;
	var y = a.size;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByStatusDown(a,b) {
	var x = a.status.toLowerCase();
	var y = b.status.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByStatusUp(a,b) {
	var x = b.status.toLowerCase();
	var y = a.status.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByMethodDown(a,b) {
	var x = a.method.toLowerCase();
	var y = b.method.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByMethodUp(a,b) {
	var x = b.method.toLowerCase();
	var y = a.method.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortBySeatsDown(a,b) {
	var x = (isNaN(parseInt(a.seats)) ? 9999999999 : parseInt(a.seats));
	var y = (isNaN(parseInt(b.seats)) ? 9999999999 : parseInt(b.seats));
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortBySeatsUp(a,b) {
	var x = (isNaN(parseInt(b.seats)) ? 9999999999 : parseInt(b.seats));
	var y = (isNaN(parseInt(a.seats)) ? 9999999999 : parseInt(a.seats));
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByPriorityDown(a,b) {
	var x = a.priority;
	var y = b.priority;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByPriorityUp(a,b) {
	var x = b.priority;
	var y = a.priority;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByPostDateDown(a,b) {
	var x = a.postdate;
	var y = b.postdate;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByPostDateUp(a,b) {
	var x = b.postdate;
	var y = a.postdate;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByExpireDateDown(a,b) {
	var x = a.expiredate;
	var y = b.expiredate;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByExpireDateUp(a,b) {
	var x = b.expiredate;
	var y = a.expiredate;
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByStatusDispDown(a,b) {
	var x = a.statusdisp.toLowerCase();
	var y = b.statusdisp.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByStatusDispUp(a,b) {
	var x = b.statusdisp.toLowerCase();
	var y = a.statusdisp.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByOrderDown(a,b) {
	var x = (isNaN(parseFloat(a.order)) ? 9999999999 : parseFloat(a.order));
	var y = (isNaN(parseFloat(b.order)) ? 9999999999 : parseFloat(b.order));
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}
function sortByOrderUp(a,b) {
	var x = (isNaN(parseFloat(b.order)) ? 9999999999 : parseFloat(b.order));
	var y = (isNaN(parseFloat(a.order)) ? 9999999999 : parseFloat(a.order));
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByTypeAlpha(a,b) {
	var id = sortParamsObj.sortID;
	var dir = sortParamsObj.sortDir;

	if (dir == 'Down') {
		var x = a[id].toLowerCase();
		var y = b[id].toLowerCase();
	} else {
		var x = b[id].toLowerCase();
		var y = a[id].toLowerCase();
	}

	return ((x < y) ? -1 : ((x > y) ? 1 : sortByNameDown(a,b)));
}

function adjustHeadAry(listType, sortby, dir) {
	for (var i=0; i<listObj[listType].headAry.length; i++) {
		listObj[listType].headAry[i].sort_by = (listObj[listType].headAry[i].id.toLowerCase() == sortby.toLowerCase() ? dir : null);
	}
}

function removeAllChildren(parentID) {
	if (parentID) {
		var el = document.getElementById(parentID);
		if (el) {
			if (el.hasChildNodes()) {
				while (el.childNodes.length >= 1) {
					el.removeChild(el.firstChild);  
				}
			}
		}
	}
}
function replaceText(el,str,cssClass) {
	if (el != null) {
		clearText(el);
		var newNode = document.createTextNode(str);
		if (cssClass) el.className = cssClass;
		el.appendChild(newNode);
		el.style.display = "inline";
	}
}
function clearText(el) {
	if (el != null && el.childNodes) {
		for (var i = 0; i < el.childNodes.length; i++) {
			var childNode = el.childNodes[i];
			el.removeChild(childNode);
		}
	}
}

/* thickbox generic function */
function showThickbox(caption, url, width, height) {
	//console.log('showThickbox - url: ' + url);
	//console.log('protocol: ' + location.protocol + " - " + 'hostname: ' + location.hostname);
	//console.log('has protocol: ' + url.search('ttp:') > 0);

	// workaround to fix non-secure iframe 
	// and allow SSL sites to continue using SSL	
	$("body").remove("#TB_HideSelect");
	$("body").remove("#TB_overlay");
	$("body").remove("#TB_window");
	$("body").append("<iframe id='TB_HideSelect' src='"+ilcModPerlRelPath+"/lms/blank.pl'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");

	// allow clicking anywhere outside the thickbox to close it
	$("#TB_overlay")
			.bind('click',{},function() { closeThickbox();return false; })

	var sizeText = '';
	if (width && height)
		sizeText = '&width='+width + '&height=' + height;
	
	tb_show(caption, url + '&TB_iframe=true' + sizeText);
}

// redefining tb_position from thickbox to compensate for an IE6 error when the page is scrolled down
function tb_position() {
	$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});

	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	} else {
		var newMarginTop = parseInt(((TB_HEIGHT)/2))*-1 + document.documentElement.scrollTop + 'px';
		$("#TB_window").css({marginTop:newMarginTop});
	}
}

function closeThickbox() {
	tb_remove();
}


/* au type conversions */


/* form funcions */
function createForm(fId,fAction,fTarget,iObj) {
	var bAry = document.getElementsByTagName('body');
	var b = bAry[0];
	if (b) {
		var f = document.createElement('form');
		if (f) {
			f.setAttribute('name',fId);
			f.setAttribute('id',fId);
			f.setAttribute('method','post');
			f.setAttribute('action',fAction);
			f.setAttribute('target',fTarget);
			f.style.display = 'none';
			b.appendChild(f);
 
			for (iId in iObj) {
				var i = document.createElement('input');
				if (i) {
					i.setAttribute('name',iId);
					i.setAttribute('id',iId);
					i.setAttribute('type','hidden');
					i.setAttribute('value',iObj[iId]);
					f.appendChild(i);
				}
			}
		}
	}
}

function removeForm(fId) {
	var f = document.getElementById(fId);
	if (f) {
		if (f.hasChildNodes()) {
			while (f.childNodes.length > 0) {
				f.removeChild(f.firstChild);
			}
		}
 
		var bAry = document.getElementsByTagName('body');
		var b = bAry[0];
		if (b) b.removeChild(f);
	}
}
 
function openWinPost(fId,fTarget,winWidth,winHeight,scrollbars) {
	// allow full screen window if no width and height are provided
	widthHeightText = '';
	resizeText = 'resizable=yes';
	locationText = '';
	if (winWidth || winHeight) { 
		widthHeightText =  "width=" + winWidth + ",height=" + winHeight;
		//resizeText = 'resizable=no';
		winX = (screen.width - winWidth)/2;
		winY = (screen.height - winHeight)/2;
		locationText = ",screenX=" + winX + ",screenY=" + winY + ",left=" + winX + ",top=" + winY;
	}

	var win = window.open(ilcProductSuiteRelPath+'/lms/blank.pl', fTarget, widthHeightText + ",status=no,"+ resizeText +",toolbar=no,scrollbars=" + scrollbars + ",menubar=no" + locationText);
	if (win) win.focus();
	var a = window.setTimeout("document.getElementById('"+fId+"').submit();",500);
	var b = window.setTimeout("removeForm('"+fId+"');",1000);
}

function openWin(url, winName, winWidth, winHeight, scrollbars) {
	var params;

	if (winWidth && winHeight) {
		winX = (screen.width - winWidth)/2;
		winY = (screen.height - winHeight)/2;

		params = "width=" + winWidth + ",height=" + winHeight + ",status=no,resizable=yes,toolbar=no,scrollbars=" + scrollbars + ",menubar=no,screenX=" + winX + ",screenY=" + winY + ",left=" + winX + ",top=" + winY;
	} else { // open full screen
 		params  = 'width='+screen.width;
 		params += ', height='+screen.height;
 		params += ', top=0, left=0'
 		params += ', fullscreen=yes';
	}

	var win = window.open(url, winName, params);
/*
	winX = (screen.width - winWidth)/2;
	winY = (screen.height - winHeight)/2;
	var win = window.open(url, winName, "width=" + winWidth + ",height=" + winHeight + ",status=no,resizable=yes,toolbar=no,scrollbars=" + scrollbars + ",menubar=no,screenX=" + winX + ",screenY=" + winY + ",left=" + winX + ",top=" + winY);
*/
	if (win) win.focus();

	return win;
}

function viewContent(fId,fTarget) {
	var f = document.getElementById(fId);
	if (f) {
		openWin(ilcProductSuiteRelPath+'/lms/blank.pl',fTarget,640,480,'yes');
		var a = window.setTimeout("document.getElementById('"+fId+"').submit();",500);
		var b = window.setTimeout("removeForm('"+fId+"');",1000);
	}
}

/* session timeout functions */

function hide () { for (i=0; i<arguments.length; i++) {var e = document.getElementById(arguments[i]); if (e) e.style.display = "none";} }
function show () { for (i=0; i<arguments.length; i++) {var e = document.getElementById(arguments[i]); if (e) e.style.display = "";} }

function sessionTimeout(userID) {
	if (userID) {
		var ajaxObj = new ilincAjax('getUserInSession','handleUserInSession');
		ajaxObj.addParam('userID', userID);
		ajaxObj.send('get');
		return false;
	}

	warnSessionTimeout();
}

function warnSessionTimeout() {
	// Time is up, show div and start 60 second timeout
	clearSessionTimers();
	gTimer2 = setTimeout("redirectLogout()", 60000);

	// close thickbox
	tb_remove();

	window.scrollTo(0,0);
	show("sessionTimeoutDiv");
	self.focus();
}

function resetSessionTimeout(userID) {
	if (gInterval == null) return;

	//alert("resetSessionTimeout");

	clearSessionTimers();
	//gTimer2 = setTimeout("hide('sessionTimeoutDiv');", 500);
	hide("sessionTimeoutDiv");
	gTimer1 = setTimeout("sessionTimeout('"+userID+"')", gInterval);
}

function clearSessionTimers() {
	clearTimeout(gTimer1);
	gTimer1 = null;
	clearTimeout(gTimer2);
	gTimer2 = null;
}

/* session cookie functions */

function getCookie(cName) {
	if (document.cookie.length > 0) {
		var cStart = document.cookie.indexOf(cName+"=");
		if (cStart != -1) {
			cStart = cStart + cName.length + 1;
			var cEnd = document.cookie.indexOf(";", cStart);
			if (cEnd == -1)
				cEnd = document.cookie.length;

			return unescape(document.cookie.substring(cStart, cEnd));
		}
	} else {
		return "";
	}
}

function setCookie(cName, cVal, expDays, path, domain, secure) {
	var expDate = new Date();
	expDate.setDate(expDate.getDate()+expDays);
	document.cookie = cName + "=" + escape(cVal) + 
		( ( expDays ) ? ";expires=" + expDate.toUTCString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure == 1 ) ? ";secure" : "" );
}

function delCookie(cName, path, domain, secure) {
	// use same info as setCookie
	if ( getCookie(cName) ) document.cookie = cName + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT" + 
		( ( secure == 1 ) ? ";secure" : "" );
}

function cookieToObj(c,sep1,sep2) {
// so far, used to convert ilcHomeState and ilcListState cookies to js objects
	var o = new Object();

	if (c) {
		if (!sep1 && !sep2) {
			sep1 = "|";
			sep2 = ":";
		}

		var ary = c.split(sep1);
		for (var i in ary) {
			var ary2 = ary[i].split(sep2);
			if (ary2.length == 1) {
				// if it's not a name/value pair, set object's listtype property to it
				o.listtype = ary2[0];
			} else {
				o[ary2[0].toLowerCase()] = ary2[1];
			}
		}
	}

	return o;
}

function setListState(listType) {
	var sortby = '';
	var sortdir = '';

	var c = (listType == 'menu' ? getCookie('ilcHomeState') : getCookie('ilcListState'));

	if (!c) return;

	var cObj = cookieToObj(c);
	if (cObj.listtype == listType) {  // make sure it's 'act' in case we add more at some point
		if (cObj.sch) document.getElementById(listType+'_selSearch').value = cObj.sch;  // search

		if (cObj.st) {  // status
			var el = document.getElementById(listType+'_selStatus');
			for (var j=0; j<el.options.length; j++) {
				if (el.options[j].value == cObj.st)
					$(el.options[j]).attr('selected', "selected");
				else
					$(el.options[j]).attr('selected', "");
			}
		}

		if (cObj.rc) {  // recur
			var el = document.getElementById(listType+'_selRecurType');
			for (var j=0; j<el.options.length; j++) {
				if (el.options[j].value == cObj.rc)
					$(el.options[j]).attr('selected', "selected");
				else
					$(el.options[j]).attr('selected', "");
			}
		}

		if (cObj.sz) {  // lot size
			var el = document.getElementById(listType+'_listLotSize');
			for (var j=0; j<el.options.length; j++) {
				if (el.options[j].value == cObj.sz)
					$(el.options[j]).attr('selected', "selected");
				else
					$(el.options[j]).attr('selected', "");
			}
		}

		if (cObj.sb) sortby = cObj.sb;  // sortby

		if (cObj.sd) sortdir = cObj.sd;  // sortdir
	}

	return [sortby, sortdir];
}

function ilcTrans(id,str) {
	if (id == 0 || !window.strObj || !strObj[id]) return str;
	
	return strObj[id];
}

function ilcTransKeyword(str,keyObj) {
	for (var i=0; i<keyObj.data.length; i++) {
		str = str.replace(new RegExp("\{"+keyObj.data[i][0]+"\}","g"), keyObj.data[i][1]);
	}
	
	return str;
}

/* green meter functions */

function gm_getSitePersonalData(clientID,userID,isGuest,csAdmin) {
	$('#loading').css('display','block');
	var ajaxObj = new ilincAjax('gm_getSitePersonalData','gm_getSitePersonalDataCallback');
	ajaxObj.addParam('client_id',(csAdmin ? 0 : clientID));
	ajaxObj.addParam('user_id',userID);
	ajaxObj.addParam('inclUser',(isGuest || csAdmin ? 0 : 1));
	ajaxObj.addParam('unitCo2',gmUnit['co2']);
	ajaxObj.addParam('unitCo2Disp',gmUnit['co2Disp']);
	ajaxObj.addParam('unitDistance',gmUnit['distance']);
	ajaxObj.addParam('unitDistanceDisp',gmUnit['distanceDisp']);
	ajaxObj.addParam('unitCost',gmUnit['cost']);
	ajaxObj.addParam('unitCostDisp',gmUnit['costDisp']);
	ajaxObj.send();
}

function gm_getSitePersonalDataCallback(retObj) {
	if (gmUserID && !gmIsGuest && !gmCSAdmin) $('#gm_user').css('display','inline');

	gmDataObj['site']['distance'] = retObj.site.distance;
	gmDataObj['site']['co2'] = retObj.site.co2;
	gmDataObj['site']['cost'] = retObj.site.cost;
	gmDataObj['site']['gas'] = retObj.site.gas;

	if (retObj.user) {
		gmDataObj['user']['distance'] = retObj.user.distance;
		gmDataObj['user']['co2'] = retObj.user.co2;
		gmDataObj['user']['cost'] = retObj.user.cost;
		gmDataObj['user']['gas'] = retObj.user.gas;
	}

	if (!gmMode) gmMode = 'site';

	gm_modeClicked('gm_'+gmMode,imgPath,0,gmUserID);

	$('#loading').css('display','none');

	if (gmIC) gm_getListItems('gm');	
}

function gm_setUserPref(userID,modePref,displayPref) {
	if (!gmPrefInProgress) {
		gmPrefInProgress = 1;
		$('#loading').css('display','block');
		var ajaxObj = new ilincAjax('gm_setUserPref','gm_setUserPrefCallback');
		ajaxObj.addParam('user_id',userID);
		ajaxObj.addParam('mode_pref',modePref);
		ajaxObj.addParam('display_pref',displayPref);
		ajaxObj.send();
	}
}

function gm_setUserPrefCallback(retObj) {
	gmPrefInProgress = 0;
	$('#loading').css('display','none');
}

function gm_modeClicked(id,imgPath,setPref,userID) {
	var mode = '';
	if (id == 'gm_user' || id == 'gm_site') {
		mode = id.replace(/^gm_/,"");

		$('#gm_'+mode+'Img').attr('src',imgPath+'/icon_'+mode+'_on.gif');

		if (userID && !gmIsGuest && !gmCSAdmin) {
			var otherMode = (mode == 'user' ? 'site' : 'user');
			$('#gm_'+otherMode+'Img').attr('src',imgPath+'/icon_'+otherMode+'.gif');
		}

		gm_dispDigits(mode,gmSavings);

		if (setPref && mode != gmMode && !gmIC && userID && !gmIsGuest && !gmCSAdmin)
			gm_setUserPref(userID,mode,gmSavings);
	}

	return mode;
}

function gm_savingsClicked(id,userID) {
	var savings = '';
	var idAry = [ 'gm_co2', 'gm_distance', 'gm_cost' ];
	if ((id == 'gm_co2' || id == 'gm_distance' || id == 'gm_cost') && id.indexOf(gmSavings) == -1) {
		savings = id.replace(/^gm_/,"");

		for (var i in idAry) {
			if (idAry[i] == id) {
				$('#'+id).addClass('selected');
			} else {
				$('#'+idAry[i]).removeClass('selected');
			}
		}

		gm_dispDigits(gmMode,savings);

		if (savings != gmSavings && !gmIC && userID && !gmIsGuest && !gmCSAdmin)
			gm_setUserPref(userID,gmMode,savings);
	}

	return savings;
}

function gm_dispDigits(mode,savings) {
	var num = gmDataObj[mode][savings];
	if (!num) num = 0;

	$('#reverse').attr('innerHTML',gm_getDigitImgs(num > 99999999 ? 99999999 : num));
	$('#reverse').fadeIn('fast');

	var gasNum = ilcRound(gmDataObj[mode]['gas']);
	var gasNumAsStr = ilcAddCommas(gasNum.toString());
	$('#approxGas').text(gasNumAsStr);
}

function gm_getDigitImgs(num) {
	if (!num) num = 0;
	num = ilcRound(num,0);
	var numAsStr = ilcAddCommas(num.toString());
	var digitAry = numAsStr.split("");
	var html = '';
	var digitToClass = {"0":"zer","1":"one","2":"two","3":"thr","4":"fou","5":"fiv","6":"six","7":"sev","8":"eig","9":"nin"};
	var legalChars = "0123456789-,.";
	for (i in digitAry) {
		var d = digitAry[i];
		if (legalChars.indexOf(d) != -1) {
			var cls = "";
			if (d == "-") {
				cls = "das";
			} else if (d == ",") {
				cls = "comma";
			} else if (d == ".") {
				cls = "point";
			} else {
				cls = digitToClass[d];
			}
			if (cls) {
				html += '<span class="' + cls + '">' + d + '</span>\n';
			}
		}
	}
	return html;
}

function gm_doAction(retObj) {

}

function gm_userLocEnterSubmit(thisForm, e) {
	if (window.event && window.event.keyCode == 13) {
		gm_userLocSubmit();
		return false;
	} else if (e && e.which == 13) {
		gm_userLocSubmit();
		return false;
	} else {
		return true;
	}
}
function gm_userLocSubmit() {
	var form = document.gm_user_loc;

	var err = 0;
	if (!form.pref_zip.value) {
		if (form.pref_country.value) {
			if (!form.pref_region.value && form.pref_region.options.length > 1) {
				err = 1;
			}
			if (!form.pref_city.value && form.pref_region.options.length > 1) {
				err = 1;
			}
		}
	}

	if (err == 1) {
		// make sure error shows correct class
		if (!$("#error").hasClass('statuserror')) {
			$('#error').toggleClass('statusconfirm').toggleClass('statuserror');
		}

		var statusHeader = ilcTrans(5504,"Error Message");
		$('#error').html("<h3>"+statusHeader+"</h3><ul>"+ilcTrans(5869,"Please select a Country, State/Province and City or Zip Code.")+"</ul>");
		$('#error').show();
	} else {
		var ajaxObj = new ilincAjax('gm_userLocSubmit', 'gm_userLocSubmitCallback');
		ajaxObj.addParam('pref_country', form.pref_country.value);
		ajaxObj.addParam('pref_region', form.pref_region.value);
		ajaxObj.addParam('pref_city', form.pref_city.value);
		ajaxObj.addParam('pref_zip', form.pref_zip.value);
		ajaxObj.addParam('pref_loc', (form.pref_loc.checked ? 1 : 0));
		ajaxObj.addParam('gmUserID', form.user_id.value);
		ajaxObj.addParam('gmActivityID', form.activity_id.value);
		ajaxObj.send();
	}
}

function gm_userLocSubmitCallback(retObj) {
	var form = document.gm_user_loc;
	if (retObj.error != 0) {
		if (form.pref_zip)
			form.pref_zip.value = ''; // clear out zip
	
		// make sure error shows correct class
		if (!$("#error").hasClass('statuserror')) {
			$('#error').toggleClass('statusconfirm').toggleClass('statuserror');
		}

		var statusHeader = ilcTrans(5504,"Error Message");
		$('#error').html("<h3>"+statusHeader+"</h3><ul>"+retObj.error+"</ul>");
		$('#error').show();
	} else {
		parent.gmRefresh();
		parent.tb_remove();
	}
}

function gm_userLocSel(a) {
	var form = document.gm_user_loc;

	var ajaxObj = new ilincAjax('gm_userLocSel', 'gm_userLocSelCallback');
	ajaxObj.addParam('pref_country', form.pref_country.options[form.pref_country.selectedIndex].value);

	if (a == 'region') {
		ajaxObj.addParam('pref_region', form.pref_region.options[form.pref_region.selectedIndex].value);
	}

	ajaxObj.send();
}

function gm_userLocSelCallback(retObj) {
	var form = document.gm_user_loc;

	var regionAry = retObj.regionAry;
	var cityAry = retObj.cityAry;

	if ((regionAry && regionAry.length > 0) || (!regionAry && !cityAry)) {
		if (form.pref_region) {
			for(var i=form.pref_region.options.length;i>-1;--i){
				form.pref_region.options[i] = null;
			}
			form.pref_region.options[0] = new Option("","");
		}
	}

	if (regionAry && regionAry.length > 0) {	
		if (form.pref_region) {
			for(var i=0;i<=regionAry.length-1;++i){
				var optIndex = form.pref_region.options.length;
				form.pref_region.options[i+1] = new Option(regionAry[i],regionAry[i]);
			}
		}
	}

	if ((regionAry && regionAry.length > 0) || (cityAry && cityAry.length > 0) || !cityAry) {	
		if (form.pref_city) {
			for(var i=form.pref_city.options.length;i>-1;--i){
				form.pref_city.options[i] = null;
			}
			form.pref_city.options[0] = new Option("","");
		}
	}
	if (cityAry && cityAry.length > 0) {
		if (form.pref_city) {
			for(var i=0;i<=cityAry.length-1;++i){
				var optIndex = form.pref_city.options.length;
				form.pref_city.options[i+1] = new Option(cityAry[i],cityAry[i]);
			}
		}
	}
}

function gm_userLocDelPerm() {
	var form = document.gm_user_loc;

	var ajaxObj = new ilincAjax('gm_userLocDelPerm', 'gm_userLocDelPermCallback');
	ajaxObj.addParam('gmUserID', form.user_id.value);
	ajaxObj.send();
}

function gm_userLocDelPermCallback(retObj) {
	if (retObj.error != 0) {
		// make sure error shows correct class
		if (!$("#error").hasClass('statuserror')) {
			$('#error').toggleClass('statusconfirm').toggleClass('statuserror');
		}

		var statusHeader = ilcTrans(5504,"Error Message");
		$('#error').html("<h3>"+statusHeader+"</h3><ul>"+retObj.error+"</ul>");
		$('#error').show();
	} else {
		// make sure error shows correct class
		if (!$("#error").hasClass('statusconfirm')) {
			$('#error').toggleClass('statuserror').toggleClass('statusconfirm');
		}

		var statusHeader = ilcTrans(5619,"Status Message");
		$('#error').html("<h3>"+statusHeader+"</h3><ul>"+ilcTrans(5883,"Your permanent location has been cleared.")+"</ul>");
		$('#error').show();

		$('#gm_uloc_permdiv').hide();
	}
}

/* general functions */

function isEmpty(object) {
	for (var i in object) { return false; }
	return true;
}

function ilcRound(number,x) {
	// rounds number to x decimal places, defaults to 0
    x = (!x ? 0 : x);
    return Math.round(number*Math.pow(10,x))/Math.pow(10,x);
}

function ilcAddCommas(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;
}

function printSelSearch(listType) {
	var ulNode = document.getElementById(listType+'_selUList');
	var newLi = document.createElement('li');
	newLi.setAttribute('style', "margin-top:0.5em");

	var input = document.createElement('input');
	input.setAttribute('type', "text");
	input.setAttribute('id', listType+"_selSearch");
	input.setAttribute('value', ilcTrans(4466,'Search'));
	input.setAttribute('onfocus', "if(this.value==ilcTrans(4466,'Search'))this.value='';");
	input.setAttribute('onblur', "if(this.value=='')this.value=ilcTrans(4466,'Search');");
	input.setAttribute('onkeypress', "changeSearch(event,'"+listType+"');");

	newLi.appendChild(input);
	input = null;
	ulNode.appendChild(newLi);
	newLi = null;
	ulNode = null;
}

function printSelStatus(listType) {
	var ulNode = document.getElementById(listType+'_selUList');
	var newLi = document.createElement('li');
	newLi.setAttribute('style', "margin-top:0.1em");
	var sel = document.createElement('select');
	sel.setAttribute('id', listType+"_selStatus");

	var opt = document.createElement('option');
	opt.setAttribute('value', "active");
	if ( !(listType == 'rpt' && ilcCSAdmin == 1) ) {
		opt.setAttribute('selected', "selected");
	}
	opt.appendChild(document.createTextNode(ilcTrans(386,'Active')));
	sel.appendChild(opt);
	opt = null

	var opt = document.createElement('option');
	opt.setAttribute('value', "inactive");
	opt.appendChild(document.createTextNode(ilcTrans(387,'Inactive')));
	sel.appendChild(opt);
	opt = null;

	var opt = document.createElement('option');
	opt.setAttribute('value', "all");
	if (listType == 'rpt' && ilcCSAdmin == 1) {
		opt.setAttribute('selected', "selected");
	}
	opt.appendChild(document.createTextNode(ilcTrans(385,'All')));
	sel.appendChild(opt);
	opt = null;

	newLi.appendChild(sel);
	ulNode.appendChild(newLi);
	newLi = null;
	ulNode = null;
}

function createNewElement(type, attrName, attrValue) {
	var element = null;
	// Try the IE way; this fails on standards-compliant browsers
	try {
		element = document.createElement('<'+type+' '+attrName+'="'+attrValue+'">');
	} catch (e) {
	}
	if (!element || element.nodeName != type.toUpperCase()) {
		// Non-IE browser; use canonical method to create named element
		element = document.createElement(type);
		element.setAttribute(attrName, attrValue);
	}
	return element;
}

function createNamedElement(type, name) {
	var element = createNewElement(type, 'name', name);
	return element;
}

function setLoadingPos() {
	var subnavEl = $("#subnav").get(0);
	if (subnavEl) {
		var jLoading = $("#loading");
		if (jLoading.length) jLoading.css("top", parseInt(subnavEl.offsetTop+(subnavEl.offsetHeight-parseInt(jLoading.css("height")))/2)+"px");
	}
}

if (window.jQuery) $(document).ready( function() { setLoadingPos(); } );

/* ajax functions */

function ilincAjax(method, callback) {
    this.url = ilcModPerlRelPath+"/api/ajax_api.pl";
    //this.url = ilcProductSuiteRelPath+"/api/ajax_api.pl";
    this.paramsObj = new Object();
    this.paramsText = '';
    this.postData = null;
    this.sendType = 'post';

    this.addParam = ilc_ajaxAddParam;
    this.send = ilc_ajaxSend;

    this.addParam('output', 'json');
    this.addParam('cmd', method);
    this.addParam('callback', callback);

    this.addParam('clientID', ilcClientID);

	// override with selected client
	if (typeof(listObj) != 'undefined') {
		if (typeof(listObj['clt']) != 'undefined') {
			if (typeof(listObj['clt'].selItemObj) != 'undefined') {
				for (selClient in listObj['clt'].selItemObj) {
					this.paramsObj.clientID = selClient;
				}
			}
		}
	}
}

function ilc_ajaxAddParam(name, value) {
    this.paramsObj[name] = value;
}

function ilc_ajaxSend(sendType) {
    // default to post if no sendType specified
    this.sendType = ( sendType == undefined ? 'post' :  sendType );

    $.ajax({
        url: this.url,
        type: this.sendType,
        data: this.paramsObj,
        dataType: "json",
        callback: this.paramsObj['callback'],
        success: function(data){
            eval(this.callback+'(data);');
        }
    });
}

/* activity list and menu functions */

function actionAddNew(evt) {
	var listType = evt.data.listType;
	var locID = null;
	if (evt.data.activity_type == 'learnlinc') {
    	if ($('#'+listType+'_mainFoldersBtn').hasClass('selected')) { // folder tab
			var ary = $("li[@id^='columnav-item-']");
			for (var i=1; i<=ary.length; i++) {
				var el = "li#columnav-item-"+i+" a.columnav-active";

				if ($(el).length == 0) continue;

				var ary2 = ((($(el).attr('id')).split("_"))[1]).split(":");
				if (ary2[1] == 'f') { // folder selected
					var sel = ary2[2];
				}
			}
			if (sel) 
				locID = sel;
		}
	}

	var inpObj = {
		'action_activity_type': evt.data.action_activity_type,
		'activity_type': evt.data.activity_type,
		'state': evt.data.state
	}
	if (evt.data.activity_type == 'learnlinc' && locID)
		inpObj['loc_id'] = locID;
	if (evt.data.client_id != null)
		inpObj['client_id'] = evt.data.client_id;

	var w = (parent.ilcModPerlRelPath ? parent : window);
	w.createForm('activity',w.ilcModPerlRelPath+'/cm/cm_activity_main.pl','',inpObj);
	w.$('#activity').submit();
}

function actionAddNewHere(eSeriesID) {
	// also need to send sort state, so can return to home or activity list page as user left it

	var inpObj = {
		'activity_type':'learnlinc',
		'state':'add',
		'loc_id':eSeriesID
	};

	var w = (parent.ilcProductSuiteRelPath ? parent : window);
	w.createForm('activity',w.ilcProductSuiteRelPath+'/cm/cm_activity_main.pl','',inpObj);
	w.$('#activity').submit();
}

function actionMoreInfo(evt) {
	var eActId = evt.data.id;
	var listType = evt.data.listType;
	var eventType = (evt.data.eventType ? evt.data.eventType : 0);
	var ppUserName = (evt.data.ppUserName ? evt.data.ppUserName : '');
	var evtUserId = (evt.data.evtUserId ? evt.data.evtUserId: '');
	var isInternal = (evt.data.isInternal ? evt.data.isInternal : 0);
	showThickbox(ilcTrans(5607,"Session Information"), ilcModPerlRelPath+'/lms/display_info.pl?activity_id='+eActId+'&listType='+listType+'&eventType='+eventType+'&isInternal='+isInternal+'&ppUserName='+ppUserName+'&evtUserId='+evtUserId, 380, 408);
	
}

function actionInvite(evt) {
	var eActId = evt.data.id;
	createForm('sendInviteForm',ilcProductSuiteRelPath+'/lms/vc_url_popup.pl','URL',{'activity_id':eActId})
	openWinPost('sendInviteForm','URL',640,480,'yes');
	//showThickbox(ilcTrans(1123,"Send Invite"), ilcProductSuiteRelPath+'/lms/vc_url_popup.pl?activity_id='+eActId);
}

function actionEditActivity(evt) {
	var eActId = evt.data.id;
	var eBlkId = evt.data.series_id;
	var eActType = evt.data.block_type
	var eActionActType = (eActType == 'learnlinc' ? evt.data.au_type : eActType);;

	var inpObj = {
		'action_activity_type':eActionActType,
		'activity_id':eActId,
		'activity_type':eActType,
		'series_id':eBlkId,
		'state':'edit',
		'copy':(evt.data.copy == 1 ? 1 : 0)
	};
	if (ilcClientID != null && ilcClientID != 0)
		inpObj['client_id'] = ilcClientID;

	var w = (parent.ilcProductSuiteRelPath ? parent : window);
	w.createForm('activity',w.ilcProductSuiteRelPath+'/cm/cm_activity_main.pl','',inpObj);
	w.$('#activity').submit();
}

/* folder view functions
   using columnav and carousel */

var cn;

function fillFolders() {
	// clear folders
	$("#breadcrumbs").empty();
	$("#carouselList").empty();
	$("#carouselMoreInfo").empty();

	if (folderTree.ul) { // root elements on the site
		$("#carouselMoreInfo").append(
			$(document.createElement("div"))
				.text(ilcTrans(5478,"Click on an item to view its details"))
				.addClass('begin')
				.get(0)
		);

		var cn_cfg = {
			prevElement: 'columnav-prev',
			datasource: folderTree,
			paneHandler: addBreadcrumb,
			prevHandler: removeBreadcrumb,
			nextHandler: folderViewItemClicked,
			animationCompleteHandler: simNextFdrClick,
			numVisible: 2  // if > 1, addBreadcrumb needs to be aware of which pane was clicked
		};
	
		cn = new YAHOO.extension.ColumNav('columnav', cn_cfg);
		var sv_cfg = { url: location.href, modifier: 'HTML' };
	}
}

/*
// Replaced columnav's addBreadcrumb and removeBreadcrumb functions with new ones below

function addBreadcrumb(type, args, me) {
	var paneIndex = args[0];
	var pane = me.carousel.getItem(paneIndex); // see carousel documentation
                                                     // for its API
	var div = pane.getElementsByTagName('div')[0];
	var title = div.getAttribute('title');
	if (title) {
		var breadcrumbs = document.getElementById('breadcrumbs');
		if (me.carousel.cfg.getProperty('numVisible') > 1) {
			var spans = breadcrumbs.getElementsByTagName('span');
			if (spans.length >= paneIndex) {
				numToRemove = (spans.length - paneIndex) + 1;
				for (var i = 0; i < numToRemove; i++) {
					removeBreadcrumb();
				}
			}
		}
		var span = document.createElement('span');
		var sep = arguments.callee.calledOnce ? ' / ' : '';
		span.appendChild(document.createTextNode(sep + title));
		breadcrumbs.appendChild(span);
	}
	arguments.callee.calledOnce = true;
}

function removeBreadcrumb(args, type, me) {
	var breadcrumbs = document.getElementById('breadcrumbs');
	if (breadcrumbs.getElementsByTagName('span').length > 1) {
		breadcrumbs.removeChild(breadcrumbs.lastChild);
	}
}
*/

function addBreadcrumb(type, args, me) {
// Replaces columnav's addBreadCrumb above
// Uses jQuery to determine which folders have been selected
// and reconstructs breadcrumb list every time

	$("#breadcrumbs").empty();
	var num = 1;
	while ($("li#columnav-item-"+num+" a.columnav-active").length) {
		var text = $("li#columnav-item-"+num+" a.columnav-active").text();
		var sep = (num == 1 ? '' : ' / ');
		$("#breadcrumbs").append( $(document.createElement("span")).text(sep+text).get(0) );
		num++;
	}

	updateFolderPathStyle(1);
}

function removeBreadcrumb(type, args, me) {
// Replaces columnav's removeBreadcrumb above
// Uses jQuery to remove last breadcrumb item unless there is only one left

/*
console.log("type=" + type + ", args=" + args + ", me=" + me);
for (var i in args) { console.log("args[" + i + "]=" + args[i]); }
for (var a in me) { console.log("me." + a + "=" + me[a]); }
*/

	// workaround for removeBreadcrumb being called twice; revisit and fix later
	if (me.counter < 3) return false;

	if ($("#breadcrumbs span").length > 1) 
		$("#breadcrumbs span:last-child").remove();
	
	var selCount = $("a.columnav-active").length;

	if (selCount > 1) $("li#columnav-item-"+selCount+" a.columnav-active").removeClass("columnav-active");

	if (selCount) $("li#columnav-item-"+(selCount-1)+" a.columnav-active").removeClass("columnav-path");

	prepListStateCookie();
}

function updateFolderPathStyle(n) {
	var ary = $("li[@id^='columnav-item-']");
	for (var i=1; i<ary.length-n; i++) {
		$("li#columnav-item-"+i+" a.columnav-active").addClass('columnav-path');
	}
}

function showDetailsLink(evt) {
	$("#carouselMoreInfo").empty();
	var newEl = document.createElement("div");
	$(newEl).append(
		$(document.createElement("a"))
			.attr('href','#none')
			.bind('click',{'type':evt.data.type,'eID':evt.data.eID,'listType':evt.data.listType},function(evt) { showDetails(evt);return false; })
			.html(ilcTrans(5477,"Click here to view folder details"))
			.get(0)
		)
		.css('padding', "10px 10px 10px 10px")
	$("#carouselMoreInfo").append(newEl);

	$('#loadingdetails').css('display',"none");
}

function showDetailsTemp(type, eID, listType) {
	showDetails({'data':{'type':type,'eID':eID,'listType':listType}});
}

function showDetails(evt) {
	$('#loadingdetails').css('display','block');
	// cleared in display info on ready

	var url = ilcProductSuiteRelPath+'/lms/display_info.pl';
	if (evt.data.type == 'a') {
		url += '?activity_id='+evt.data.eID;
	} else if (evt.data.type == 'b') {
		url += '?series_id='+evt.data.eID;
	}
	url += '&listType='+evt.data.listType;
	var iframeHTML = '<iframe frameborder="0" style="width:100%; height:100%;" hspace="0" name="details_iframeContent" id="details_iframeContent" src="'+url+'"></iframe>';
	$("div.details").html(iframeHTML);
}

function toggleMainBtns(id, listType) {
	if (!$('#'+id).hasClass('selected')) {
		var typeAry = [ 'List','Calendar','Folders' ];
		for (var i in typeAry) {
			var jEl = $('#'+listType+'_main'+typeAry[i]+'Btn');
			var jDiv = $('#'+listType+'_main'+typeAry[i]+'View');
			if (id.indexOf(typeAry[i]) == -1) {
				jEl.removeClass('selected');
				jDiv.css('display','none');
			} else {
				jEl.addClass('selected');
				jDiv.css('display','inline');

			}
		}

		if (id.indexOf('Folders') != -1) {
			if (! ilcFoldersViewFilled) {
				if (folderTree.ul) { // root elements on the site
					fillFolders();
					ilcFoldersViewFilled = 1;
					simNextFdrClick();
				}
			}
			if (! folderTree.ul) { // no root elements
				$('#'+listType+'_mainFoldersView').css('display','none'); // hide the carousel
				$('#'+listType+'_mainListView').css('display','inline');
				printListMsg(listType, 0, ilcTrans(5631,"There are no items to display"));
			}
		}

		if (listType == 'menu')
			prepListStateCookie(listType);
		else
			if (id.indexOf('main') == 0) prepListStateCookie(listType);

		// if blank folders need to printListItems when returning to list
		if (id.indexOf('List') != -1 && !folderTree.ul)
			printListItems(1, listType);

		// show and hide elements specific to views
		if (document.getElementById(listType+'_selRecurType'))
			$('#'+listType+'_selRecurType').css('display', (id.indexOf('List') != -1 ? '' : 'none') );
		if (document.getElementById('reorderBtns'))
			$('#reorderBtns').css('display', (id.indexOf('Folder') != -1 && folderTree.ul ? 'block' : 'none') );
	}
}

/* folder view simulated click functions */

function getSelFdrIds() {
	var ary = new Array();
	var num = 1;
	while ($("li#columnav-item-"+num+" a.columnav-active").length) {
		var id = $("li#columnav-item-"+num+" a.columnav-active").attr('id');
		ary.push(id);
		num++;
	}
	var s = ary.join(",");
	s = s.replace(/:/g, ";");
	return s;
}

var simFdrIdAry = new Array();

function prepSimFdrClicks(idList) {
	idList = idList.replace(/;/g, ":");
	var idAry = idList.split(",");

	if (idAry.length) {
		simFdrIdAry = idAry.reverse();
		simFdrIdAry.push("begin");
	}
}

function simNextFdrClick() {
	if (simFdrIdAry.length) {
		var id = simFdrIdAry.pop();

		var beginFlag = 0;
		if (id == "begin") {
			beginFlag = 1;
			id = simFdrIdAry.pop();
		}

		var success = simFdrClick(id);
		if (!success) simFdrIdAry = new Array();

		if (beginFlag) setTimeout(simNextFdrClick, 200);
	}
}

function simFdrClick(id) {
	var success = 0;

	if (id) {
		var jqObj = $("#"+id.replace(/:/g, "\\:"));

		var currAnimSpeed = cn.carousel.cfg.getProperty('animationSpeed');
		cn.carousel.cfg.setProperty('animationSpeed', 0.1);

		if (jqObj && jqObj.length) {
			if (document.implementation.hasFeature("Events","2.0")) {  // W3C -- or could use 'if (document.dispatchEvent)'
				var e = document.createEvent("MouseEvents");
				e.initEvent("click",true,true);
				//e.initMouseEvent("click",true,true,window,1,1,1,1,1,false,false,false,false,0,jqObj.get(0))
				jqObj.get(0).dispatchEvent(e);
				success = 1;
			} else if (document.fireEvent) {  // IE
				jqObj.get(0).fireEvent("onclick");

				// determine listType
				var listType = '';
				var listTableId = $("table[id$='_listTable']").attr('id');
				var result = listTableId.match(/([a-z]+)_listTable/);
				if (result != null) {
					listType = result[1];
				}

				if (listType) {
					// call href functions
					var elId = jqObj.get(0).id;
					result = elId.match(/^cn(Act|Fdr)_[0-9]+\:[a-z]\:([a-z]+)/);
					if (result != null && !(listType == 'menu' && result[1] == 'Fdr')) {
						if (result[1] == 'Fdr' && listType != 'menu') {  // don't call href functions if folder on home page
							showDetailsLink({'data':{'type':'b','eID':result[2],'listType':listType}});
							updateFolderPathStyle(0);
						} else if (result[1] == 'Act') {
							showDetails({'data':{'type':'a','eID':result[2],'listType':listType}});
						}
					}
				}

				success = 1;
			}
		} else {
			var el = document.getElementById(id);
			if (el && document.createEventObject) {  // IE
				var e = document.createEventObject();
				el.fireEvent("onclick",e);
				succcess = 1;
			}
		}

		cn.carousel.cfg.setProperty('animationSpeed', currAnimSpeed);
	}

	return success;
}

/* status change functions */

function actionChStatus(newStatus, listType, confirmed, itemType) {
	var selItemList = '';

	// if no itemType specified use listType instead (itemType used on Communication page)
	itemType = (!itemType ? listType : itemType);

	// if folder view act on selected node
	if ($('#'+listType+'_mainFoldersBtn').hasClass('selected')) {
		var ary = $("li[@id^='columnav-item-']");
		var path = new Array();
		for (var i=1; i<=ary.length; i++) {
			var el = "li#columnav-item-"+i+" a.columnav-active";
			if ($(el).length == 0) continue;
			
			var sel = el;
			var ary3 = ((($(sel).attr('id')).split("_"))[1]).split(":");
			path[path.length] = ary3[0];
		}
		if (! sel) return;

		var ary2 = ((($(sel).attr('id')).split("_"))[1]).split(":");
		if (ary2[1] == 'f') {
			if (ary2[3] == 'r') { // only in/active this folder, no recurse
				if (chkChStatus(ary2[3],newStatus,0)) {
					listObj[listType].selItemObj[($(sel).attr('id')).replace(new RegExp("^cnFdr_\\d+:"), "")] = 1;
				}
			} else if ($(sel).hasClass('columnav-has-next')) { // get children
				if (chkChStatus(ary2[3],newStatus,0)) {
					listObj[listType].selItemObj[($(sel).attr('id')).replace(new RegExp("^cnFdr_\\d+:"), "")] = 1;
				}

				var objStr = "folderTree";
				for (var i=0; i<path.length; i++) {
					objStr += ".ul.li["+path[i]+"]";
				}
				var liObj = eval(objStr+".ul.li"); //children of the folder
				autoChkSelItem(liObj, newStatus, path, listType);
				
			} else { // empty folder
				if (chkChStatus(ary2[3],newStatus,0)) {
					listObj[listType].selItemObj[($(sel).attr('id')).replace(new RegExp("^cnFdr_\\d+:"), "")] = 1;
				}
			}
		} else { // activity
			if (chkChStatus(ary2[3],newStatus,0)) {
				listObj[listType].selItemObj[($(sel).attr('id')).replace(new RegExp("^cnAct_\\d+:"), "")] = 1;
			}
		}
	}

	for (var id in listObj[listType].selItemObj) {
		if (listObj[listType].selItemObj[id] == 1)
			selItemList += (selItemList != '' ? '|' : '') + id;
	}
//alert("selItemList=" + selItemList + ", newStatus=" + newStatus);
	if (selItemList && newStatus) {
		var agree = '';
		if ( (listType == 'content' || listType == 'ret') && confirmed) {
			agree = 1;
		} else {
			if (newStatus == 'purge') {
				agree = confirm (ilcTrans(3859,"Are you sure you want to PERMANENTLY delete the selected item(s) and all associated data?"));
			} else {
				agree = confirm (ilcTrans(5452,"Are you sure you want to change the status of the selected item(s)?"));
			}
		}

		if (agree) {
			$('#loading').css('display','block');
			
			var ajaxObj;
			if (listType == 'content' && newStatus != 'active' && !confirmed) {
				ajaxObj = new ilincAjax(itemType+'_confirmStatusItems', itemType+'_confirmStatusItemsCallback');
			} else {
				ajaxObj = new ilincAjax(itemType+'_chStatusItems', 'all_chStatusItemsCallback');
			}
			ajaxObj.addParam('listType', itemType);
			ajaxObj.addParam('eUserId', document.getElementById('eUserId').value);
			ajaxObj.addParam('selItemList', selItemList);
			ajaxObj.addParam('status', newStatus);
			ajaxObj.send();
		}
	}
}

function all_chStatusItemsCallback(retObj) {
	var listType = retObj.listType;

	getListItems(listType);
}

/* navigation menu functions */

function profileCheck() {
	var s = ilcTrans(4493,'Please enter the appropriate information in the required (*) fields and click the "{Submit Button}" button to gain access to this site.');
	s = ilcTransKeyword(s,{'data':[['Submit Button',ilcTrans(3228,"Submit")],['click','CLICK']] });
	window.alert(s);
}

function showSubNav(div) {
	var curDiv = "#"+div+"_sub_div";
	var divList = "#home_sub_div,#manage_sub_div,#administration_sub_div,#reports_sub_div";
	$(divList).css("display","none");
	$(curDiv).css("display","inline");
}

var curSelectedSubNav = 'home';
function resetSubNav() {
	showSubNav(curSelectedSubNav);
}

/* content list functions */

function actionAddNewContent() {
	// also need to send sort state, so can return to content list page as user left it
	// use post, esp. because IE does not retain referer unless post is used
	// also pass client_id?

	var w = (parent.ilcModPerlRelPath ? parent : window);
	w.createForm('content_add',w.ilcModPerlRelPath+'/cm/cm_content_main.pl','',{'state': 'add'});
	w.$('#content_add').submit();
}

function actionMoreInfoContent(evt) {
	var eContentId = evt.data.id;
	var eUserId = evt.data.eUserId;
	var listType = evt.data.listType;
	showThickbox(ilcTrans(5486,"Content Information"), ilcProductSuiteRelPath+'/lms/display_info.pl?content_id='+eContentId+'&user_id='+eUserId+'&listType='+listType, 380, 300);
}

function actionPreviewContent(evt) {
	var eContentID = evt.data.id;
	var contentType = evt.data.contentType;
	var submitURL = evt.data.submitURL;

	if (contentType == 'polling') {

	} else if (contentType == 'medialink') {

	} else {

	}
}

function actionEditContent(evt) {
	var eContentId = evt.data.id;
	var contentTypeId = evt.data.contentTypeId;
	var state = evt.data.state;
	
	var inpObj = {
		'content_id':eContentId,
		'content_type_id':contentTypeId,
		'state':state
	};

	var w = (parent.ilcProductSuiteRelPath ? parent : window);
	w.createForm('contentEditForm',w.ilcProductSuiteRelPath+'/cm/cm_content_main.pl','',inpObj);
	w.$('#contentEditForm').submit();
}

/* join functions */

function joinSession(aID, wodLevel, tb, noWin) {
	var usePopWin = false;

	// detect browser properties
	var browObj = detectBrowserProps();
	var browser = browObj["browser"]["name"];
	browser = browser.toLowerCase();

	var width = 440;
	//var height = 425;
	var height = 475;
	if (browser == 'ie' && !winJwsEnabled && !noWin) { // normally thickbox, but need window
		usePopWin = true;
	}

	if (tb == 0) { // always need window (currently only waitlist)
		usePopWin = true;
		width = 675;
		//height = 465;
		height = 515;
	}

	var win = -1;
	if (usePopWin) {
		var uID = '';
		if (document.getElementById('eUserId'))
			uID = document.getElementById('eUserId').value;

		win = popWinJoinSession(aID, uID, wodLevel, 0, width, height);
	} else {
		var url = ilcModPerlRelPath + "/lms/int_join.pl?activity_id=" + aID;
		if (wodLevel) {
			url += "&wod_level=" + wodLevel;
		}

		/* use jnlp */
		if (winJwsEnabled) {
			window.location = url + '&jws=1';
		} else {
			//showThickbox(ilcTrans(5545,"Join Session"), url+'&tb=1', 450, 350);
			showThickbox(ilcTrans(5545,"Join Session"), url+'&tb=1', 450, 400);
		}
	}

	return win;
}

function actionMoreInfoJoin(eActId, eUsrId, isInternal, eventType, ppUserName, eSizeByType) {
	var showTB = 1;

	if (isInternal && eSizeByType != 'async') {
		popWinJoinSession(eActId, eUsrId, '', 0, 440, 425);
	} else {
		if (eSizeByType == 'sync' && eventType) {
			var form = parent.document.menu;
			form.join_id.value = eActId;
			if (eUsrId)
				form.event_user_id.value = eUsrId;

			form.uc.value = 1;
			form.ref.value = 'event';

			form.submit();
		} else {
			var url = ilcModPerlRelPath + '/lms/vc_launch.pl?' + (eventType ? 'ref=event&' : '') + 'activity_id=' + eActId;
			if (eUsrId)
				url += '&user_id='+eUsrId;

			if (ppUserName)
				url += '&pp='+ppUserName;

			popWinJoinSession(eActId, eUsrId, '', 0, 800, 640);
		}
	}
}

function popWinJoinSession(aID, uID, wodLevel, axOnly, width, height) {
	var url = ilcModPerlRelPath + "/lms/vc_launch.pl?activity_id=" + aID + "&user_id=" + uID;
	if (wodLevel) {
		url += "&wod_level=" + wodLevel;
	}
	url += '&on_menu=1';
	if (axOnly) {
		url += '&axonly=1';
	}

	var win = openWin(url, 'JS', width, height, 0, 0);

	return win;
}

function winJwsChk(disableJava) {
	var browObj = detectBrowserProps();
// mp - allow ActiveX join with Vista
//	if (browObj["os"]["name"] == 'win' && (!disableJava || browObj["os"]["version"] == 'vista' || browObj["browser"]["name"] == 'safari') ) {
	if (browObj["os"]["name"] == 'win' && (!disableJava || browObj["browser"]["name"] == 'safari') ) {
		var manualJoinPref = getCookie('manual_join_pref');
		if (!manualJoinPref) {
			/* if manual join pref on, no need to check */
			/* if vista or safari and win, check */
			var appletCodebase = ilcCCDocsDir + '/applet';
			$('#winJavaAppletDiv').html('<applet code=javaDetectionApplet.class codebase="' + appletCodebase + '" name="winJavaDetect" width=1 height=1></applet>');

			var applet = document.winJavaDetect;
			if (applet == null) {
				return false;
			} else {
				// ie may still recognize object, wrap in try
				try {
					// this fails if java is not installed
					if (document.winJavaDetect.getJavaVersion() < 1.4)
						return false;
					else
						return true;
				} catch(e) {
					return false;
				}
			}
		}
	}
	return false;
}

function detectBrowserProps() {
	//initialization, browser, os detection

	var d, dom, nu='', brow='', ie, ie4, ie5, ie5x, ie6, ie7;
	var ns4, moz, moz_rv_sub, release_date='', moz_brow, moz_brow_nu='', moz_brow_nu_sub='', rv_full=''; 
	var mac, win, old, lin, ie5mac, ie5xwin, konq, saf, op, op4, op5, op6, op7;
	var success;
		
	d = document;
	n = navigator;
	nav = n.appVersion;
	nan = n.appName;
	nua = n.userAgent;
	old = (nav.substring(0,1)<4);
	mac = (nav.indexOf('Mac')!=-1);
	win = ( ( (nav.indexOf('Win')!=-1) || (nav.indexOf('NT')!=-1) ) && !mac)?true:false;
	lin = (nua.indexOf('Linux')!=-1);

	var os = '';
	var osAry = new Array('lin', 'mac', 'win');
	for (var i=0; i<osAry.length; i++) {
		if (eval(osAry[i])) {
			os = osAry[i];
		}
	}

	var uaAry = nua.split("/");
	var tmpAry = uaAry[1].split(";");
	var osVersion = $.trim(tmpAry[2]);
	osVersion = osVersion.toLowerCase();
	osVersion = (osVersion.indexOf('windows nt 6') != -1 ? 'vista' : osVersion);

	// begin primary dom/ns4 test
	// this is the most important test on the page
	if ( !document.layers )
	{
		dom = ( d.getElementById ) ? d.getElementById : false;
	}
	else { 
		dom = false; 
		ns4 = true;// only netscape 4 supports document layers
	}
	// end main dom/ns4 test
		
	op=(nua.indexOf('Opera')!=-1);
	saf=(nua.indexOf('Safari')!=-1);
	konq=(!saf && (nua.indexOf('Konqueror')!=-1) ) ? true : false;
	moz=( (!saf && !konq ) && ( nua.indexOf('Gecko')!=-1 ) ) ? true : false;
	ie=((nua.indexOf('MSIE')!=-1)&&!op);
	if (op)
	{
		str_pos=nua.indexOf('Opera');
		nu=nua.substr((str_pos+6),4);
		brow = 'Opera';
		success = 0;
	}
	else if (saf)
	{
		// updated for Safari 3
		var vAry = nua.split("/");
		str_pos=nua.indexOf('Safari');
		//nu=nua.substr((str_pos+7),5);
		var v = vAry[3];
		vArySplit = v.split(" ");
		nu = vArySplit[0];

		// based on Safari build, not AppleWebKit
		var sVerAry = new Array();
		sVerAry['412'] = '2';
		sVerAry['412.2'] = '2';
		sVerAry['412.2.2'] = '2';
		sVerAry['412.5'] = '2.0.1';
		sVerAry['416.12'] = '2.0.2';
		sVerAry['416.13'] = '2.0.2';
		sVerAry['417.8'] = '2.0.3';
		sVerAry['417.9.2'] = '2.0.3';
		sVerAry['417.9.3'] = '2.0.3';
		sVerAry['419.3'] = '2.0.4';
		sVerAry['100'] = '1.1';
		sVerAry['100.1'] = '1.1.1';
		sVerAry['125.7'] = '1.2.2';
		sVerAry['125.8'] = '1.2.2';
		sVerAry['125.9'] = '1.2.3';
		sVerAry['125.11'] = '1.2.4';
		sVerAry['125.12'] = '1.2.4';
		sVerAry['312'] = '1.3';
		sVerAry['312.3'] = '1.3.1';
		sVerAry['312.3.1'] = '1.3.1';
		sVerAry['312.5'] = '1.3.2';
		sVerAry['312.6'] = '1.3.2';
		sVerAry['85.5'] = '1';
		sVerAry['85.7'] = '1.0.2';
		sVerAry['85.8'] = '1.0.3';
		sVerAry['85.8.1'] = '1.0.3';

		if (sVerAry[nu])
			nu = sVerAry[nu];

		brow = 'Safari';
		success = 1; // safari ok
	}
	else if (konq)
	{
		str_pos=nua.indexOf('Konqueror');
		nu=nua.substr((str_pos+10),3);
		brow = 'Konqueror';
		success = 0;
	}
	// this part is complicated a bit, don't mess with it unless you understand regular expressions
	// note, for most comparisons that are practical, compare the 3 digit rv number, that is the output
	// placed into 'nu'.
	else if (moz)
	{
		// regular expression pattern that will be used to extract main version/rv numbers
		pattern = /[(); \n]/;
		// moz type array, add to this if you need to
		moz_types = new Array( 'Firebird', 'Phoenix', 'Firefox', 'Galeon', 'K-Meleon', 'Camino', 'Epiphany', 
			'Netscape6', 'Netscape', 'MultiZilla', 'Gecko Debian', 'rv' );
		rv_pos = nua.indexOf( 'rv' );// find 'rv' position in nua string
		rv_full = nua.substr( rv_pos + 3, 6 );// cut out maximum size it can be, eg: 1.8a2, 1.0.0 etc
		// search for occurance of any of characters in pattern, if found get position of that character
		rv_slice = ( rv_full.search( pattern ) != -1 ) ? rv_full.search( pattern ) : '';
		//check to make sure there was a result, if not do nothing
		// otherwise slice out the part that you want if there is a slice position
		( rv_slice ) ? rv_full = rv_full.substr( 0, rv_slice ) : '';
		// this is the working id number, 3 digits, you'd use this for 
		// number comparison, like if nu >= 1.3 do something
		nu = rv_full.substr( 0, 3 );
		for (i=0; i < moz_types.length; i++)
		{
			if ( nua.indexOf( moz_types[i]) !=-1 )
			{
				moz_brow = moz_types[i];
				break;
			}
		}
		if ( moz_brow )// if it was found in the array
		{
			str_pos=nua.indexOf(moz_brow);// extract string position
			moz_brow_nu = nua.substr( (str_pos + moz_brow.length + 1 ) ,3);// slice out working number, 3 digit
			// if you got it, use it, else use nu
			moz_brow_nu = ( isNaN( moz_brow_nu ) ) ? moz_brow_nu = nu: moz_brow_nu;
			moz_brow_nu_sub = nua.substr( (str_pos + moz_brow.length + 1 ), 8);
			// this makes sure that it's only the id number
			sub_nu_slice = ( moz_brow_nu_sub.search( pattern ) != -1 ) ? moz_brow_nu_sub.search( pattern ) : '';
			//check to make sure there was a result, if not do  nothing
			( sub_nu_slice ) ? moz_brow_nu_sub = moz_brow_nu_sub.substr( 0, sub_nu_slice ) : '';
		}
		if ( moz_brow == 'Netscape6' )
		{
			moz_brow = 'Netscape';
		}
		else if ( moz_brow == 'rv' || moz_brow == '' )// default value if no other gecko name fit
		{
			moz_brow = 'Mozilla';
		} 
		if ( !moz_brow_nu )// use rv number if nothing else is available
		{
			moz_brow_nu = nu;
			moz_brow_nu_sub = nu;
		}
		if (n.productSub)
		{
			release_date = n.productSub;
		}
		brow = moz_brow;
		nu = moz_brow_nu;

		if (brow == 'Netscape') {
			success = (parseFloat(nu) >= 7 ? 1 : 0);
		} else {
			success = 1;
		}
	}
	else if (ie)
	{
		str_pos=nua.indexOf('MSIE');
		nu=nua.substr((str_pos+5),3);
		//brow = 'Microsoft Internet Explorer';
		brow = 'IE';	
		success = (parseFloat(nu) >= 5 && !mac ? 1 : 0);
	}
	// default to navigator app name
	else 
	{
		brow = nan;
		nu=parseFloat(navigator.appVersion);

		if (brow == 'Netscape') {
			success = (parseFloat(nu) >= 7 ? 1 : 0);
		} else {
			success = 0;
		}
	}		
	op5=(op&&(nu.substring(0,1)==5));
	op6=(op&&(nu.substring(0,1)==6));
	op7=(op&&(nu.substring(0,1)==7));
	ie4=(ie&&!dom);
	ie5=(ie&&(nu.substring(0,1)==5));
	ie6=(ie&&(nu.substring(0,1)==6));
	ie7=(ie&&(nu.substring(0,1)==7));

	// default to get number from navigator app version.
	if(!nu) {
		nu = nav.substring(0,1);
		if (brow == 'Netscape') {
			success = (parseFloat(nu) >= 7 ? 1 : 0);
		} else {
			success = 0;
		}
	}
	
	/*ie5x tests only for functionality. dom or ie5x would be default settings. 
	Opera will register true in this test if set to identify as IE 5*/
	ie5x=(d.all&&dom);
	ie5mac=(mac&&ie5);
	ie5xwin=(win&&ie5x);
	var gecko = (nua.indexOf('Gecko')!= -1);

	var ret = new Object();
	ret["browser"] = new Object();
	ret["browser"]["name"] = brow;
	ret["browser"]["version"] = nu;
	ret["browser"]["supported"] = success;
	ret["browser"]["ie6"] = (ie6 ? true : false);
	ret["browser"]["ie7"] = (ie7 ? true : false);
	ret["browser"]["gecko"] = (gecko ? true : false);
	ret["os"] = new Object();
	ret["os"]["name"] = os;
	ret["os"]["version"] = osVersion;
	ret["success"] = success;

	return ret;
}

/* new session button functions */

var actionActivityTypes = {
	classes: 'll_class',
	folders: 'folder',
	meetings: 'll_meeting',
	conferences: 'll_webcast',
	rooms: 'll_support'
};	

function initNewSessionDD(obj, e, ddID, mo, listType) {
	var addTrk = 0;
	var idx = 0;
	for (var i=0; i<addAry.length; i++) {
		if (addAry[i].can_add) {
			addTrk++;
			idx = i;
		}
	}

	if (addTrk == 1) { 
		if (!mo) { // only on click
			prepListStateCookie(listType);
			var evt = {
				data: { 'activity_type':addAry[idx].type,'action_activity_type':actionActivityTypes[addAry[idx].sub_type],'state':'add','client_id':ilcClientID, 'listType':listType } 
			};
			actionAddNew(evt);
		}
	} else if (addTrk > 0) {
		dropdownmenu(obj, e, ddID);
	}
}

function newSessionBtnDisplay(btnID,ddID,listType) {
	// clear dropdown div contents
	// before adding new anchors

	$("#"+ddID).empty();

	var addTrk = 0;
	for (var i=0; i<addAry.length; i++) {
		if (addAry[i].can_add) {
			addTrk++;
			var anchor = document.createElement("a");
			$(anchor)
				.attr('href', "#")
				.bind('click',{'activity_type':addAry[i].type,'action_activity_type':actionActivityTypes[addAry[i].sub_type],'state':'add','client_id':ilcClientID,'listType':listType}, function(evt) { actionAddNew(evt);return false; })
				.text(addAry[i].label);
			$("#"+ddID).append(anchor);	
		}
	}
	if (addTrk == 0) {
		$("#"+btnID).hide();
	} else if (addTrk == 1) {
		// hide dropdown if only one session type
		$("#"+ddID).remove();
		$("#"+btnID).show();
	} else {
		$("#"+btnID).show();
	}
}


/* generic utilities */
function objectCount(thisObj) {
	var objCount = 0

	if (typeof(thisObj) != 'undefined') {
		for (anItem in thisObj) { objCount++ };
	}

	return objCount;
}

function listObjectExists(listType, objectName) {
	var exists = 0;

	if (typeof(listObj[listType]) != 'undefined') {
		if (typeof(listObj[listType][objectName]) != 'undefined') {
			exists = 1;
		}
	}

	return exists;
}

function clearListObject(listType, objectName) {
	if (typeof(listObj[listType]) == 'undefined')
		listObj[listType] = new Object;

	listObj[listType][objectName] = new Object();
}

function clearListArray(listType, arrayName) {
	if (typeof(listObj[listType]) == 'undefined')
		listObj[listType] = new Object;

	listObj[listType][arrayName] = new Array();
}

/* begin anylink js */
/***********************************************
* AnyLink CSS Menu script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var disappeardelay=250  //menu disappear speed onMouseout (in miliseconds)
var enableanchorlink=0 //Enable or disable the anchor link when clicked on? (1=e, 0=d)
var hidemenu_onclick=1 //hide menu when user clicks within menu? (1=yes, 0=no)

/////No further editting needed

var ie5=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

function showhide(obj, e, visible, hidden){
	if (ie5||ns6)
		if (dropmenuobj)
			dropmenuobj.style.left=dropmenuobj.style.top=-500
	if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover") {
		obj.visibility=visible
	} else if (e.type=="click") {
		obj.visibility=hidden
	}
}

function iecompattest(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
	var edgeoffset=0
	if (whichedge=="rightedge"){
		var windowedge=ie5 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
		if (dropmenuobj) {
			dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
			if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
			edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
		}
	}
	else{
		var topedge=ie5 && !window.opera? iecompattest().scrollTop : window.pageYOffset
		var windowedge=ie5 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
		if (dropmenuobj) {
			dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
			if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
				edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
				if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
					edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
			}
		}
	}
	return edgeoffset
}

function dropdownmenu(obj, e, dropmenuID){
	if (window.event) event.cancelBubble=true
	else if (e.stopPropagation) e.stopPropagation()
	if (typeof dropmenuobj!="undefined") //hide previous menu
		if (dropmenuobj)
			dropmenuobj.style.visibility="hidden"
	clearhidemenu()
	if (ie5||ns6){
		obj.onmouseout=delayhidemenu
		dropmenuobj=document.getElementById(dropmenuID)
		if (dropmenuobj) {
			if (hidemenu_onclick) dropmenuobj.onclick=function(){dropmenuobj.style.visibility='hidden'}
			dropmenuobj.onmouseover=clearhidemenu
			dropmenuobj.onmouseout=ie5? function(){ dynamichide(event)} : function(event){ dynamichide(event)}
			showhide(dropmenuobj.style, e, "visible", "hidden")
			dropmenuobj.x=getposOffset(obj, "left")
			dropmenuobj.y=getposOffset(obj, "top");
			dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
			dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
		}
	}
	return clickreturnvalue()
}

function clickreturnvalue(){
	if ((ie5||ns6) && !enableanchorlink) return false
	else return true
}

function contains_ns6(a, b) {
	while (b.parentNode)
		if ((b = b.parentNode) == a)
			return true;
			return false;
}

function dynamichide(e){
	if (ie5&&!dropmenuobj.contains(e.toElement))
		delayhidemenu()
	else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
		delayhidemenu()
}

function delayhidemenu(){
	if (dropmenuobj)
	delayhide=setTimeout("dropmenuobj.style.visibility='hidden'",disappeardelay)
}

function clearhidemenu(){
	if (typeof delayhide!="undefined")
		clearTimeout(delayhide)
}
/* end anylink js */


function clientSelectSubmit(pageType) {
	var form = document.client_select;
	var id = form.client_id.options[form.client_id.selectedIndex].value;
	if (id > -2) {
		setCookie('admin-client',id,'','/',cookieDomain,useSSLCookie);
		form.submit();
	}
}

