function checkBoxDisplay(chkbox, elemIdToDisplay) {
	if( chkbox.checked ) {
		document.getElementById(elemIdToDisplay).style.display= 'block';
	}
	else {
		document.getElementById(elemIdToDisplay).style.display= 'none';
	}
}

function bind1(func, arg) {
    return function() { func(arg); }
}

function bind2(func, arg1, arg2) {
    return function() { func(arg1, arg2); }
}

function focusOnTextbox(textbox, initValue) {
    if( textbox.value == initValue ) {
        textbox.value = '';
        textbox.style.color = 'black';
    }
}

function postProcess() {
    for(i = 0; i < document.forms.length; ++i) {
        f = document.forms[i];
        for(j = 0; j < f.elements.length; ++j) {
            elem = f.elements[j];
            if( elem.type == "text" ) {
                initVal = initValue[elem.name];
		//alert(elem.name + ": "  + initVal);
                if( initVal ) {
                    elem.onfocus = bind2(focusOnTextbox, elem, initVal);
                    if( initVal == elem.value || elem.value == '' ) {
                        elem.style.color = 'gray';
                        elem.value = initVal;
                    }
                }
            }
        }
    }

    if( initFocus != null ) {
        initFocus.focus();
    }

    setBrowserDimensions();
}

var winW = 630, winH = 460;

function setBrowserDimensions() {
    if (typeof window.innerWidth != 'undefined') {
        winW = window.innerWidth;
        winH = window.innerHeight;
    } else {
        winW = document.body.offsetWidth;
        winH = document.body.offsetHeight;
    }
}

function replaceElemAndFlash(url, elem) {
   var f = loadJSONDoc(url);
   f.addCallback(function(response) { replaceElemAndFlashResponseHandler( response, elem )});
}

function replaceElemAndFlashResponseHandler(response, elem) {

   //replace the link with the response data
   swapDOM(elem, DIV(null, response['replace']));
   
   //replace the flash message with the flash response
   setFlash(response['flash']);
}

function removeItemRowAndFlash(url, elem) {
   var f = loadJSONDoc(url);
   f.addCallback(function(response) { removeRowAndFlashResponseHandler( response, elem, 'stuff' )});
}

function removeRowAndFlashResponseHandler(response, elem, tableName) {
   //find the row that elem is in
   elem = findParentWithType(elem, 'TR');

   var table = findParentWithType(elem, 'TABLE');

   //remove the row
   removeElement(elem);

   //if no rows left, replace the table with the "no items" text
   //one row is the headers
   if( table.rows.length < 2 ) {
      addElementClass(tableName+'List', 'invisible');
      removeElementClass('no'+tableName, 'invisible');
   }

   //replace the flash message with the flash response
   setFlash(response['flash']);
}

/**
 * Find the parent node of elem whose nodeType equals parentType.
 * ParentType should be an HTML element name in all caps.
 * Element should be a dom element.
 */
function findParentWithType(elem, parentType) {
   //find the row that elem is in
   while( elem && elem.nodeName != parentType ) {
      elem = elem.parentNode;
   }

   return elem;
}

function setFlash(flashContents) {
   setHtml(getElement('flash'), flashContents);
}

function toggleVisible(elem) {
    toggleElementClass("invisible", elem);
}

function makeVisible(elem) {
    removeElementClass(elem, "invisible");
}

function makeInvisible(elem) {
    addElementClass(elem, "invisible");
}

function isVisible(elem) {
    // you may also want to check for
    // getElement(elem).style.display == "none"
    return !hasElementClass(elem, "invisible");
};

function popUp(url) {
   var f = doSimpleXMLHttpRequest(url);
   f.addCallback(function(response) { popUpHandler( response )});
}

function hidePopUp() {
	var popUp = document.getElementById("popUp");
	makeInvisible(popUp);
}

function popUpHandler(response) {
   var newHtml = response.responseText;

   //replace the old content with the response data
   var popUp = document.getElementById("popUp");
   setHtml(popUp, newHtml);

   var coords = new MochiKit.DOM.Coordinates(0,0);
   var winDim = getViewportDimensions();

   makeVisible(popUp);
   var scripts = getElementsByTagAndClassName('SCRIPT', null, popUp);
   if( scripts ) {
      for(var i = 0; i < scripts.length; ++i) {
         eval(scripts[i].innerHTML);
      }
   }


   var elemDim = MochiKit.DOM.elementDimensions(popUp);
   coords.x = (winDim.w - elemDim.w) / 2;
   coords.y = (winDim.h - elemDim.h) / 2;
   setElementPosition(popUp, coords);
}

function oldPopUpHandler(response) {
   var newHtml = response.responseText;

   //replace the link with the response data
   //alert(response['replace']);
   //alert(elem);
   var popUp = document.getElementById("popUp");
   setHtml(popUp, newHtml);

   var s = popUp.style;
   s.display = "block";
   var newleft = ((winW - popUp.clientWidth) / 2) + "px";
   s.left = newleft;
   s.top = ((winH - popUp.clientHeight) / 2) + "px";
}

function getPixNum(str) {
  if( /\s*([0-9]+)\s*px\s*/.test(str) ) {
    return parseInt($1);
    //return 1;
  } else {
    return 0;
  }
}

function ajaxFormSubmit(form, successFunction) {
	var toSend = []
	for( var i = 0; i < form.elements.length; i++) {
		var formElem = form.elements[i];
		if( formElem.name ) {
			if( formElem.type != "radio" || formElem.checked ) {
				toSend[formElem.name] = formElem.value;
			}
		}
	}

//alert("afs 2");
	var res;
//TODO fix so post requests go as post... this code is borken
//	if( form.method && (form.method.toUpperCase() == 'POST') ) {
//alert("afs 3");
//		res = doXHR(form.action, {'sendContent': queryString(toSend), 'method': form.method});
//alert("afs 4");
//	} else {
//alert("afs 5");
		res = doSimpleXMLHttpRequest(form.action, toSend);
//TODO SOON: indicate that the call is in progress somehow... at least disable the button used to submit
//alert("afs 6");
//	}

	res.addCallback(successFunction);
	var errFunction = function(req) {
		alert("Error: " + req);
	};
//alert("afs 7");

	return false; 
}

function setHtml(container, newHtml) {
	container.innerHTML = newHtml;
}

function getJSON(req) {
	return eval("(" + req.responseText + ")");
}

//You must set up global actionField and statusField variables (which point to the
//html containers of the item action and item status) before calling this function.
function requestActionSubmit(form) {
	var successFunction = function(req) {
//alert("successFunction 1");
		var retval = getJSON(req);

		if( retval["mainError"] ) {
//alert("successFunction 2");
   			var error = document.getElementById("requestActionError");
   			setHtml(error, retval["mainError"]);
		} else {
//alert("successFunction 3");
			hidePopUp();

//alert("successFunction 4");
//alert("successFunction 4 " + form.req.value);
   			var actionField = document.getElementById("req."+form.req.value);
			removeRowAndFlashResponseHandler(retval, actionField, 'req');
		}
	};

	ajaxFormSubmit(form, successFunction);
	return false;
}

//You must set up global actionField and statusField variables (which point to the
//html containers of the item action and item status) before calling this function.
function itemActionSubmit(form) {
var debug = 0;
if( debug ) alert("pre successFunction 1");
	var successFunction = function(req) {
if( debug ) alert("successFunction 1");
		var retval = getJSON(req);

		if( retval["mainError"] ) {
if( debug ) alert("successFunction 2");
   			var error = document.getElementById("itemActionError");
   			setHtml(error, retval["mainError"]);
		} else {
if( debug ) alert("successFunction 3");
			hidePopUp();

if( debug ) alert("successFunction 4");
if( debug ) alert("successFunction 4" + form.item2.value);
   			var actionField = document.getElementById("actions."+form.item2.value);
if( debug ) alert("successFunction 4.5" + actionField);
			setHtml(actionField, retval['action']);
if( debug ) alert("successFunction 5");
   			var statusField = document.getElementById("status."+form.item2.value);
			setHtml(statusField, retval['status']);
if( debug ) alert("successFunction 6");
			setFlash(retval['flash']);
if( debug ) alert("successFunction 7");
		}
	};

	ajaxFormSubmit(form, successFunction);
if( debug ) alert("itemActionSubmit");
	return false;
}


initValue = new Object();
initFocus = null;
