// For use with element focusing logic
var lastElementFocused = new Array();
lastElementFocused['main'] = '';

// Set logic to warn the user before exiting if changes were made.
var changesMade = false;
window.onbeforeunload = confirmExit;

function markChanges(){
	changesMade = true;

	// Turn on the save button if there is one
	focusNewElement('save_button', 'save_buton');
}

function toggleCheckbox(id){
	element = document.getElementById(id);

	if (element.checked){
		element.checked = false;
	} else {
		element.checked = true;
	}

	// Mark that changes were made
	markChanges();
} // end toggleCheckbox

function checkAllByName(prefix, checkValue){
	if (!checkValue) { checkValue = 0; }

	var inputs = document.getElementsByTagName("INPUT");

	for (x in inputs){
		if (inputs[x].name){
			if (inputs[x].name.substr(0, prefix.length) == prefix) {
				inputs[x].checked = checkValue;
			} // end if name matches prefix
		} // end if input has a name
	} // end for each input

	// Mark that changes were made
	markChanges();

} // end checkAllByName()

function checkAllInRange(startnum, howmany, checkValue){
	// If no boxes to check, get out now
	if (!howmany) {
		return;
	}

	if (!checkValue) {
		checkValue = 0;
	}

	if (!startnum) {
		startnum = 0;
	}

	endnum = startnum + howmany;

	// Set the boxes from startnum to endnum
	for(i = startnum; i <= endnum; i++){
		thisName = "cbx_" + i;

		if(document.getElementById(thisName)){
			el = document.getElementById(thisName);
			el.checked = checkValue;
		}
	}

	markChanges();

} // end checkAllFromNum()

function confirmExit(){
	if (changesMade){
		return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
	}
} // end confirmExit()

function setBillToUserList(firm_id) {
	// Clear the current bill-to user list
	document.forms['add_billing_firm'].bill_to_user_id.options.length=0;

	firm_id = document.forms['add_billing_firm'].firm_id.value;

	if (firm_id >0){
		firm_list = document.forms['add_billing_firm'].elements['bill_to_user_id_' + firm_id];

		for(i = 0; i < firm_list.options.length; i++){
			document.forms['add_billing_firm'].bill_to_user_id.options.add(
				new Option(
					firm_list.options[i].text,
					firm_list.options[i].value
					)
				);
		} // end for
	} // end if firm chosen
} // end setBillToUserList

// Unfocus the last focused element in the group
function unFocusLastElement(group) {
	if (!group) { group = 'main'; }

	// Hide previous focus element
	if (lastElementFocused[group]){
		document.getElementById(lastElementFocused[group]).style.display = 'none';
	}
}

function focusNewElement(id, group) {
	if (!group) { group = 'main'; }

	// Hide previous focus element
	unFocusLastElement(group)

	// Show the new element, and remember that we did
	lastElementFocused[group] = id;
	document.getElementById(id).style.display = 'block';
} // end FocusNewElement

function setClass(id, newclass){
	document.getElementById(id).className=newclass;
} // end setClass

function toggleClass(id, class_1, class_2){
	if (document.getElementById(id).className == class_1) {
		document.getElementById(id).className = class_2;
	} else {
		document.getElementById(id).className = class_1;
	}
} // end toggleClass

function toggleVisible(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = 'block';
	} else {
		document.getElementById(id).style.display='none';
	}
} // end toggleVisible

function rowSwitcher(rownum){
	if (document.getElementById("filedetails"+rownum).style.display=='none') {
		document.getElementById("filedetails"+rownum).style.display='block';
		document.getElementById("rowicon"+rownum).src = '/img/icons/collapse_12.png';
	} else {
		document.getElementById("filedetails"+rownum).style.display = 'none';
		document.getElementById("rowicon"+rownum).src = '/img/icons/expand_12.png';
	}
} // end rowSwitcher

function initSearch(){
	var el = document.getElementById('ocrOptions');
	var checked = document.search.searchOCR.checked;

	var e = document.getElementById('searchArea');
	var img = document.getElementById('searchImage');

	e.style.visibility = '';
	e.style.position = '';
	img.src = '/images/advanced_search_.gif';

	if (checked){
		el.style.visibility = '';
		el.style.position = '';
	}
}

function flipOCR(){
	var e = document.getElementById('ocrOptions');
	var checked = document.search.searchOCR.checked;

	if (checked){
		e.style.visibility = 'visible';
		e.style.position = 'relative';
	} else {
		e.style.visibility = 'hidden';
		e.style.position = 'absolute';
	}
}

function swapSearch(){
	var el = document.getElementById('ocrOptions');
	var within = document.getElementById('withinWindow');
	var checked = document.search.searchOCR.checked;

	var e = document.getElementById('searchArea');
	var img = document.getElementById('searchImage');

	if (e.style.visibility == 'hidden'){
		e.style.visibility = 'visible';
		e.style.position = 'relative';
		img.src = '/images/advanced_search_left.gif';
		if (checked){
			el.style.visibility = 'visible';
			el.style.position = 'relative';
		}
	} else {
		e.style.visibility = 'hidden';
		e.style.position = 'absolute';
		img.src = '/images/advanced_search_down.gif';

		if (checked){
			el.style.visibility = 'hidden';
			el.style.position = 'absolute';
		}

		within.style.visibility = 'hidden';
		within.style.position = 'absolute';
	}
}

function tagChange(){
	var selectedIndex = document.search.advancedSearch.selectedIndex;
	var append = "";

	document.getElementById('advancedSearch').selectedIndex = 0;

	switch (selectedIndex){
		case 0:
		break;
		case 1:
		append=" and ";
		break;
		case 2:
		append=" and not ";
		break;
		case 3:
		append=" or ";
		break;
		case 4:
		append=" before ";
		break;
		case 5:
		//Open Window
		var win = document.getElementById('withinWindow');
		win.style.visibility = 'visible';
		win.style.position = 'relative';
		append = "";
		break;
	}
	appendVal(append);
}

function hideWithin(){
	var win = document.getElementById('withinWindow');
	win.style.visibility = 'hidden';
	win.style.position = 'absolute';
}

function withinVal(){
	var words = document.search.words.value;
	string = " within" + words + "w ";
	appendVal(string);
}

function appendVal(append){
	searchQuery = document.search.query.value;
	searchQuery = searchQuery.replace(/\s$/g, "");
	document.search.query.value = searchQuery+append;
	SetEnd(document.search.query);
	document.search.query.focus();
}

function SetEnd (inputVar){
	if (inputVar.createTextRange){
		var inputRange = inputVar.createTextRange();
		inputRange.moveStart('character', inputVar.value.length);
		inputRange.collapse();
		inputRange.select();
	}
}

function worksheetSetup(printPage)
{
	// Print the page
	if (printPage)
	{
		window.print();
	}
	// Click the next button
	if(document.getElementById('nextlink'))
	{
		el = document.getElementById('nextlink');
		location.href = el.href;
	}
}

$(document).ready(function() {
setTimeout('startSystemTasks()', 1000);

});

function startSystemTasks() {
	// Kick off the tasks processor
	// Give it 1 second and disconnect, then start listening for messages
    $.ajax({
        timeout: 1000,
        url: '/stasks.php',
        complete: onComplete
    });
};

// Comet does the message polling
function pollMessages() {
    $.ajax({
        url: '/msg.php?webroot=./..',
        complete: onComplete
    });
};

function onComplete(xhr, status) 
{	
	if ( (status == "success") || (status="timeout") )
	{
		var htmlResponse = xhr.responseText;
		$("#messages").prepend(htmlResponse);
		
		setTimeout('pollMessages()', 15000);
	}
	else 
	{
	// handle errors
	}
};

