
function loadpage(tab,page,values){
	// changing the MAIN tabs with AJAX'd CONTENT

	// we want to know if unsaved changes have been made to any forms so we can warn the user 
	var ignorchanges = 1; // assume yes
	if (formIsDirty(document.getElementById('formedit'))){ 
		ignorchanges = confirm ('Leaving this page will loose any changes \n'+'that you have made. \n '+'Are you sure?');
	}
	if(ignorchanges){
		
		//need to unload the TINYMCE controls BEFORE we change the elements out, OR if you dynamically load another textarea it WILL NOT get any controls assigned.
		// of course you need to have the TINYMCE assigned before you remove it too... or error
		toggleEditor('elm1');
		
		changeTab(tab);
		togglePage(); // hide content and show loading layer
		loadContent(page,values,updateform);
	}
}

function togglePage(){
	if(document.getElementById('loading').style.display != 'block'){
		document.getElementById('formcontent').style.display='none';
		document.getElementById('loading').style.display='block';
	}else{
		document.getElementById('formcontent').style.display='block';
		document.getElementById('loading').style.display='none';
	}
}

function changeTab(obj){ 
      var top = obj.parentNode.parentNode;
      var ob = null;
      var i = 0;
      
      for ( i = 0; i < top.childNodes.length; i++ ){
         ob = top.childNodes[i];
         RemoveClassName(ob, 'selected');
      }
      
      var items = top.getElementsByTagName('a');
	  
	  for(var i=0; i<items.length ;i++) {
	  	 RemoveClassName(items[i], 'selected');
      }

      AddClassName(obj, 'selected');
}

function changeForm(obj){
      var top = document.getElementById('formcontent');
      
      var items = top.getElementsByTagName('fieldset');
	  for(var i=0; i<items.length ;i++) {
   		 items[i].style.display="none";
      }

      document.getElementById(obj).style.display="block";
}

function loadContent(pagename,values,actionfunction){
	// values is optional and may not be present and since this is a GET request must be attached to the URL will null post values
	if(values){
		values = '?'+values;
	}else{
		values = '';
	}
    
    var fullurl = '/_layouts/' + encodeURIComponent(pagename) + '.php'+values;

	httpRequest("GET",fullurl,values,true,actionfunction);
}

function postContent(pagename,values){
	// values is optional and may not be present this is used by form submission as a POST request
	if(values){
		values = '?'+values;
	}else{
		values = '';
	}
    var fullurl = '/_layouts/' + encodeURIComponent(pagename) + '.php'+values;
	
	httpRequest("POST",fullurl,values,true);
}

// one of the AJAX readystate functions to update the  form area
function updateform(form) {

    if(request.readyState == 4){
		if(request.status == 200){
			results = request.responseText;
			document.getElementById('formcontent').innerHTML = results;		
		} else {
			alert("A problem occurred with communicating between the XMLHttpRequest object and the server program.");
		}
		
		
		toggleEditor('elm1');
		
		togglePage(); //hide the loading layer again
		
	}//end outer if
}


// one of the AJAX readystate functions to update field in a form
function updatefield(obj) {
	
    if(request.readyState == 4){
		if(request.status == 200){
			result = request.responseText;
			obj.style.backgroundImage="url(/library/interface/opt_"+result+".gif)";			
		}  else {
			alert("A problem occurred with communicating between the XMLHttpRequest object and the server program."+"\nError: status code is " + request.status);
		}
		
	}//end outer if
}



/* Wrapper function for constructing a request object.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not. */

function httpRequest(reqType,url,values,asynch,actionfunction){
	//Mozilla-based browsers
	if(window.XMLHttpRequest){
		request = new XMLHttpRequest( );
	} else if (window.ActiveXObject){
		request=new ActiveXObject("Msxml2.XMLHTTP");
		if (! request){
			request=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	//the request could still be null if neither ActiveXObject
	//initialization succeeded
	if(request){
		initReq(reqType,url,values,asynch,actionfunction);
	} else {
		alert("Your browser does not permit the use of all of this application's features!");
	}
}

/* Initialize a request object that is already constructed.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
isAsynch: Whether to send the request asynchronously or not. */
function initReq(reqType,url,values,isAsynch,actionfunction){

	request.onreadystatechange = actionfunction;
	request.open(reqType,url,isAsynch);
	/* Set the Content-Type header for a POST request */
	if(reqType == 'POST'){
		request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	}
	request.send(values);
}

/*
Function to submit a webform which we will do only after passing clientside data testing
*/
function formsubmit(form){

	/*	Client side check for required fields if all data entered then submit else warn.*/
	if(precheckvalues(form)){
		// function returned true we have values that need information checked / completed.
		alert ('Some fields are required to be completed before saving.');
		return false;
		
	}else{		
		// ok fields have been checked so we now get ready for from submission
		getdata(form);
		
		//Quickly force WYSIWYG editor to save its data back to form
        saveedit(element.id);
		return true;
	}
}


/*This will loop through a form and retrive Name=value paries for submission*/
function getdata(obj) {
	// form items  select text textarea input hidden checkbox password
  var getstr = "?";
  for (i=0; i<obj.getElementsByTagName("input").length; i++) {
     if (obj.getElementsByTagName("input")[i].type == "text") {
           getstr += obj.getElementsByTagName("input")[i].name + "=" + obj.getElementsByTagName("input")[i].value + "&";
     }
     if (obj.getElementsByTagName("input")[i].type == "checkbox") {
           if (obj.getElementsByTagName("input")[i].checked) {
              getstr += obj.getElementsByTagName("input")[i].name + "=" + obj.getElementsByTagName("input")[i].value + "&";
           } else {
              getstr += obj.getElementsByTagName("input")[i].name + "=&";
           }
     }
     if (obj.getElementsByTagName("input")[i].type == "radio") {
           if (obj.getElementsByTagName("input")[i].checked) {
              getstr += obj.getElementsByTagName("input")[i].name + "=" + obj.getElementsByTagName("input")[i].value + "&";
           }
     }  
     if (obj.getElementsByTagName("input")[i].tagName == "SELECT") {
        var sel = obj.getElementsByTagName("input")[i];
        getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
     }
     
  }
  return getsstr;
}

/* Ensure that required values exist */
function precheckvalues(checkform){
	 var errorcount = 0;
	 var found = 0;
	 // ok we will check all required fields have input, trick here is I have placed a class on these 'required' fields to make it easier to find.	 class='input_required' 
	 for ( i = 0; i < checkform.elements.length; i++ ){
            ob = checkform.elements[i];
            if(HasClassName(ob,'input_required') && (ob.value.length == 0)){
	            AddClassName(ob.parentNode, 'error');
            	errorcount++;
            }else if(HasClassName(ob,'input_required')){
            	// this is to remove the error class if the form is updated and resubmitted .. others errors might stop the submition so we remove this if it is ok to avoid confusion
            	RemoveClassName(ob.parentNode, 'error');
            	found++;
            }
            
      }
	// Now we check any fileds that have specific requirements eg unique
	
	// ok return true if we need to halt submit else false
	alert('error ' + errorcount + ' found. ' +found + ' of ' + i);
	if(errorcount > 0){
		return true; // found some problems
	}else{
		return false; // no problems found
	}
}


/* javascript code to determine if form details have been changed from thier original defaults
  to alert user on trying to leave without saving changes' NOTE form ELEMENTS MUST have a default set or it will trigger this alert. */
function formIsDirty(form){
	if(form){
		
		var changedelements = 0; // count the errors
		
	    for (var i = 0; i < form.elements.length; i++){
    
       	 
          var element = form.elements[i];
          var type = element.type;
          var top = element.parentNode;
          var formfieldset = 'formtab_' + top.parentNode.id;
          
          //Quickly force any WYSIWYG editor to save its data back to form
          saveedit(element.id);
 
          if (type == "checkbox" || type == "radio"){
            if (element.checked != element.defaultChecked){
                	//update the element visually (doing the parent so labels etc covered by new class
                	AddClassName(top, 'warning');
                	// update the pages tab since I name the tabs after the forms they show I can find the element form and get the tab
                	marktab(formfieldset);
                	changedelements++;
            }
          }else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") {
          	
            if (element.value != element.defaultValue){
                	AddClassName(top, 'warning');               
                	marktab(formfieldset); 	
                	changedelements++;
            }
          }else if (type == "select-one" || type == "select-multiple"){
            for (var j = 0; j < element.options.length; j++){
                if (element.options[j].selected !=  element.options[j].defaultSelected){
                	AddClassName(top, 'warning');
                	marktab(formfieldset);
                	changedelements++;
                }
            }
          }
    	}
    	
    	if(changedelements != 0){
    		// just highlite the save button
    		document.getElementById('frmsubmit').className='buttonchanged';
    		return true;
    	}else{
    		return false;
    	}
	}
}
// reset form to default / original setting - with javascript confirmation.
function resetForm(formname) {
	if (confirm("Are you sure you want to undo any changes?")) {
		document.formname.reset();
	}
}

// changes the clss of to 'warning
function marktab(divid){
  	if(document.getElementById(divid)){
  		var tab = document.getElementById(divid);
  		AddClassName(tab, 'warningtab');
  	}
}


function checkmyName(obj,reference){
	
	if(obj.value.length == 0){
		//if blank then error and blank is bad
		obj.style.backgroundImage="url(/library/interface/opt_RED.gif)";
	
	}else if(obj.value == obj.defaultValue){
		//check that the obj name has changed from/returned to the default
		// if not then green if so then check name against dBreference
		obj.style.backgroundImage="url(/library/interface/opt_Green.gif)";
	}else{
		obj.style.backgroundImage="url(/library/interface/small_loading.gif)"; //just to indicate it's waiting
		var url = 'category_new';
		var values = 'action=check&name=' + encodeURIComponent(obj.value) + '&table=category';
		loadContent(url,values,updatefield(obj));
	}
}

// This will remove or add contorls  - needed for AJAX page loads
function toggleEditor(id) {
	if (window.tinyMCE){
	if (!tinyMCE.get(id))
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
	}
}

// This will force TINYMCE to dump edited data back into the text area .. needed as a check for dirty forms when trying to move away from a page.
function saveedit(id){
	if (window.tinyMCE){
		for (n in tinyMCE.instances) {
               
            // get current item
                inst = tinyMCE.instances[n];
                           
            // is not an instance? ABORT I SAY!
                if (!tinyMCE.isInstance(inst))  continue;
       
            // it's an instance : set startContent and give a polish (set not dirty)
	//              inst.startContent   = tinyMCE.trim(inst.getBody().innerHTML);
    //            inst.isNotDirty     = true;
        }

	}
//if (window.tinyMCE){
//	if (tinyMCE.activeEditor.isDirty()){
  	// alert("You must save your contents.");
//	}
//}
/*

	if (window.tinyMCE){ // IF we are using tinyMCE then ..
		if(tinyMCE.getInstanceById(id).isDirty()) {
	//	if(tinyMCE.get(id).isDirty) {  // if tthe TINY MCE has had it's content chnaged ...
			 tinyMCE.triggerSave();      //  save the content back to the text area
		}
	}*/
}

function stripspaces(string,updatefield){
	cleanstring = string.split(' ').join('');
	target = document.getElementById(updatefield);
	target.value = cleanstring;	
}



// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass){

   // if there is a class
   if ( objElement.className ){

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ ){

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper ) {

            // we found it
            return true;

            }

         }

      }

   // if we got here then the class name is not there
   return false;

   }

// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist) {

   // if there is a class
   if ( objElement.className ) {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
      if ( blnMayAlreadyExist ) {

         // get uppercase class for comparison purposes
         var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
         for ( var i = 0; i < arrList.length; i++ ) {

            // if class found
            if ( arrList[i].toUpperCase() == strClassUpper ) {

               // remove array item
               arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
               i--;

               }

            }

         }

      // add the new class to end of list
      arrList[arrList.length] = strClass;

      // add the new class to beginning of list
      //arrList.splice(0, 0, strClass);
      
      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   else
      {

      // assign modified class name attribute      
      objElement.className = strClass;
   
      }

   }


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass){

   // if there is a class
   if ( objElement.className ){

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ ) {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper ) {

            // remove array item
            arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
            i--;

            }

         }

      // assign modified class name attribute
      objElement.className = arrList.join(' ');
   }
   // if there was no class
   // there is nothing to remove

}