addEvent(window, 'load', initForm);

var highlight_array = new Array();

function initForm(){
	initializeFocus();


}



// for radio and checkboxes, they have to be cleared manually, so they are added to the
// global array highlight_array so we dont have to loop through the dom every time.
function initializeFocus(){
	fields = getElementsByClassName(document, "*", "field");
	for(i = 0; i < fields.length; i++) {
		if(fields[i].type == 'radio' || fields[i].type == 'checkbox' || fields[i].type == 'file') {
			fields[i].onclick = function(){clearSafariRadios(); addClassName(this.parentNode.parentNode, "focused", true)};
			fields[i].onfocus = function(){clearSafariRadios(); addClassName(this.parentNode.parentNode, "focused", true)};
			highlight_array.splice(highlight_array.length,0,fields[i]);
		}
		else {
			fields[i].onfocus = function(){clearSafariRadios();addClassName(this.parentNode.parentNode, "focused", true)};
			fields[i].onblur = function(){removeClassName(this.parentNode.parentNode, "focused")};
		}
	}
}

function clearSafariRadios() {
	for(var i = 0; i < highlight_array.length; i++) {
		removeClassName(highlight_array[i].parentNode.parentNode, 'focused');
	}
}





/*--------------------------------------------------------------------------*/

//http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

//http://www.bigbold.com/snippets/posts/show/2630
function addClassName(objElement, strClass, blnMayAlreadyExist){
   if ( objElement.className ){
      var arrList = objElement.className.split(' ');
      if ( blnMayAlreadyExist ){
         var strClassUpper = strClass.toUpperCase();
         for ( var i = 0; i < arrList.length; i++ ){
            if ( arrList[i].toUpperCase() == strClassUpper ){
               arrList.splice(i, 1);
               i--;
             }
           }
      }
      arrList[arrList.length] = strClass;
      objElement.className = arrList.join(' ');
   }
   else{  
      objElement.className = strClass;
      }
}

//http://www.bigbold.com/snippets/posts/show/2630
function removeClassName(objElement, strClass){
   if ( objElement.className ){
      var arrList = objElement.className.split(' ');
      var strClassUpper = strClass.toUpperCase();
      for ( var i = 0; i < arrList.length; i++ ){
         if ( arrList[i].toUpperCase() == strClassUpper ){
            arrList.splice(i, 1);
            i--;
         }
      }
      objElement.className = arrList.join(' ');
   }
}

//http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj["e"+type+fn] = fn;
    obj[type+fn] = function() { obj["e"+type+fn]( window.event ) };
    obj.attachEvent( "on"+type, obj[type+fn] );
  } 
  else{
    obj.addEventListener( type, fn, false );	
  }
}

/*-------------------------------------------------------------------

           IVP Section (jQuery-based)

  -------------------------------------------------------------------*/
var clueTipOpen = 0;
$(document).ready(function(){
    // Expand any form sections with pre-filled out members
    $(".toggler-c").each(function(){
       // check for formItems for values
       var hasNonDefault = false;
       $(this).find(".formItem").each(function(){
           // if(!$(this).hasClass("defaultItem")) hasNonDefault = true; 
           if($(this).attr("rel") != "defaultItem") hasNonDefault = true; 
       });
       // if any of them have anything set, then show the section 
       if (hasNonDefault)
           $(this).show();
    });
    bindFormElements();
    // Validate before we allow form to submit
    $("form").submit(function (e) {
        // do the validation
        var passedValidation = true; 
        $('input[formVal]').each(function(){
            if (!validateFormElement(this))
                passedValidation = false;
        });
        if (!passedValidation)
           return false;
        // passed validation
        else
        {
            // Clear any default values and submit
            $("input.defaultItem").val("");
            return true;
        }
    });
});
function bindFormElements()
{
    // Set clear/prompt on input fields
    $("input.formItem").each(function(){
      // Set the input when empty to contain a prompt which is cleared when clicked
      var txt = $(this).attr("Title");
      var helpTxt = txt;
      var endTitle = txt.indexOf(':');
      if (endTitle >= 0)
      {
         txt = txt.substr(0, endTitle);
         helpTxt = helpTxt.substr(endTitle);
      }     
      txt = txt + "...";
      $(this).focus(function(e) { clearElement(this); });
      $(this).blur(function(e) { promptElement(this, txt); })
      promptElement(this, txt);
      // Add tooltips to anything which has a 'title'
      if(txt != "...")
      {
          // add 'cluetip' tooltips to the form elements
          
          /* UNCOMMENT TO ENABLE THE (ANNOYING) CLUETIPS :)  
          $(this).cluetip({
              splitTitle: ":",
              arrows: true,
              activation: 'focus',
              dropShadow: true,
              onShow: function(ct, c){ clueTipOpen = 1; },
              delayedClose: 1000 * Math.ceil(helpTxt.length / 30) + 1,
              cluetipClass: 'jtip'
              });
          */
          
          // hide the tooltip if the users starts typing
          $(this).keypress(function(){
              if(clueTipOpen == 1)
              {
                  clueTipOpen = 0;
                  $("#cluetip").hide();
              }
            });
      }
    });
    // Validation when an invalid element loses focus (may now be valid)
    $('input[formVal]').bind("blur", function (e) {
        if($(this).hasClass("invalid"))
            validateFormElement(this);
    });
}
function validateFormElement(element)
{
    // Get the validation parameters 
    eval( 'var cmd = ' + $(element).attr('formVal') + ';' );
    // Get rid of any error message
     $("#errorList").find("li").each(function() {
       if($(this).text() == cmd.message)
         $(this).remove();
     });
    $("#errorList").html($("#errorList").html().replace("<li>" + cmd.message + "</li>", ""));
    // Get the current value (if it's the default 'prompter text', then no value for validation purposes)
    newVal = $(element).val();
    if ($(element).hasClass("defaultItem"))
        newVal = "";
    // Validate
	if ( cmd instanceof Object && ( cmd.valid instanceof RegExp && !cmd.valid.test(newVal) ) || ( cmd.valid instanceof Function && !cmd.valid(newVal) ) ) {
	    // Show the error and mark as invalid
	    $(element).addClass("invalid");
		$("#errorList").append("<li>" + cmd.message + "</li>");
		$("#errorList").show();
		return false;
	} else if ( ( cmd instanceof RegExp && !cmd.test(newVal) ) || ( cmd instanceof Function && !cmd(newVal) ) ) {
	    // Show the error and mark as invalid
	    $(element).addClass("invalid");
		$("#errorList").append("<li>" + cmd.message + "</li>");
		$("#errorList").show();
		return false;
	}
	else {
        // Passed validation; mark as valid
	    $(element).removeClass("invalid");
        // If there aren't any errors in the list anymore, hide the error box 
        if($("#errorList").html().trim() == "") $("#errorList").hide();
    	return true;
    }
}

