var debug = false;
var imgp = getValue("imgpath");

var imageholder = 'waiting';
var imagewait = imgp+'waiting.gif';
var imageblank = imgp+'spacer.gif';
var idfield = '';	//store the place to put the ID
// initialize controls..

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

msg_connerror = 'There seems to be a problem with your internet connection please try again';

function test(m){
alert(m);
}
function getValue (control){
	if (!control.tagName)
		mycontrol = getCtrl(control);
	if (!mycontrol) return null;
	if (mycontrol.value)
		return mycontrol.value;
	
	if (mycontrol.innerHTML)
		return mycontrol.innerHTML;

	if (mycontrol.tagName == "SPAN")
	{
		return  mycontrol.firstChild.nodeValue;
	}
	/*
	switch(mycontrol.type) 
	{ 
		case "text":    
			val = mycontrol.value; 				
			break; 
		case "textarea":
			val = mycontrol.value; 				
			break; 		
		case "password":
			val = mycontrol.value; 				
			break; 		
			
	}
	return val;
	*/
}
function setValue (mycontrol, newvalue)
{
  if (!mycontrol.tagName)
  mycontrol = getCtrl(mycontrol);
  if (mycontrol.value)
	 mycontrol.value = newvalue;
  if (mycontrol.innerHTML)
	 mycontrol.firstChild.nodeValue = newvalue;
}
function getCtrl (control){
	try {
 	return document.getElementById(control);
	} catch(er)
	{
		return null;
	}
}
function getxmlvalue(response, key, idx)
{
	try
	{
	if (!idx)
		idx = 0;
		return response.getElementsByTagName(key)[idx].firstChild.data;
	} catch (er)
	{
	   return '';
	}
}
// ------------------------------------------------------FCK FUNCTIONS ------------------------------------------
function GetContents(fckeditorname)
{
	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(fckeditorname) ;

	// Get the editor contents in XHTML.
	return  oEditor.GetXHTML( true )  ;		// "true" means you want it formatted.
}

function SetContents( instanceName, text )
{  
  // Get the editor instance that we want to interact with.
  var oEditor = FCKeditorAPI.GetInstance( instanceName ) ;
  
  // Set the editor contents.
  oEditor.SetHTML( text ) ;
} 

function CheckIsDirty(FCK)
{
	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(FCK) ;
	return  oEditor.IsDirty() ;	
}

function ResetIsDirty(FCK)
{
	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(FCK) ;
	oEditor.ResetIsDirty() ;	
	//alert( 'The "IsDirty" status has been reset' ) ;
}

// ------------------------------------------------------FCK FUNCTIONS ------------------------------------------
//GENERIC FUNCTIONS FOR ANY FORM WITH FCK RICHT TEXT EDITOR
function updatefks( fkcontrols )
{
	fkarr = fkcontrols.split(",");
	//alert(fkarr);
	for (q=0; q < fkarr.length ; q++)
	{
		hiddencontrol = getCtrl(fkarr[q]);
		str = GetContents(fkarr[q]);
		str = str.replace(/src=\"..\/..\//g,"src=\"./");
		//alert(str);
		hiddencontrol.value = str;
	}	
}
function savefkform(myform, url, id_holder, fkcontrols)
{
	updatefks(fkcontrols);
	saveformajax(myform, url, id_holder);
}

//generic function for any form/url
function saverteformajax(myform, url, id_holder)	{

	updateRTEs();
	//updatefck(getCtrl('Content'));
	saveformajax(myform, url, id_holder);
}
//generic function for any form/url
function saveformajax(myform, url, id_holder)	{

	  data = getFormValues(myform);
//	  showScript(data);

	  //var url = "makeFiles.php";
	  idfield = id_holder;
	  var ajax = new AJAXInteraction (url, confirmsaveajax);
	  ajax.doPost(data);

}
function showresult(r)
{
 
 //showScript (r);  
}
// generic function for any page
// @todo ajax, Debug this routine!
function confirmsaveajax(response)
{ 
	try{
	  //if ajax worked fine, set id, 
	 
	  st  = response.getElementsByTagName("status")[0].firstChild.data;
	  r_msg = response.getElementsByTagName("msg")[0].firstChild.data;
	  
	  if (st == "ok")
	  {
		try{  
		id = response.getElementsByTagName("idx")[0].firstChild.data; 		
		setValue(idfield, id);
		} catch(e) {
			//alert("no id"); 
		}
		//setValue(idfield, r_msg);
		//setValue('mode', 'Update');
		msg ('msgajax', 'text', r_msg);			//use a common name for every single page
	  }
	  else 
	  {
		 msg ('msgajax', 'Error', r_msg);			//use a common name for every single page
	  }
	}
	catch(e)
	{
	  //alert('here');
	  alert (e.message);
	}
}


// functions to retrieve field values
function getFormValues(f, indexCtrl){

	var data="";
	
	var amp = "";
	
	for (n = 0 ; n < f.elements.length  ; n++ )
    {

	if (f.elements[n].name != "") 		//clean the code of alien elements with no name in controls
	{
	   if (n>0) 
	   {
		   amp = "&";
	   }
	   
		 //alert( amp + f.elements[n].name + "=" +  f.elements[n].value); 
		 
												 
		switch(f.elements[n].type) 

       { 

           case "text": 
		   
                val = f.elements[n].value; 
				
                data += amp + f.elements[n].name +  "=" + encodeURIComponent(val) ; 

                 break; 
				 
           case "password": 
		   
                val = f.elements[n].value; 
				
                data += amp + f.elements[n].name +  "=" + encodeURIComponent(val) ; 

                 break; 	
				 
           case "select-one": 
		   
		   		val = f.elements[n].value; //	f.elements[n].options[f.elements[n].selectedIndex].value

                data += amp + f.elements[n].name + "=" +  encodeURIComponent(val); 

                break; 
				
			case "hidden":
			
				val = f.elements[n].value; //	f.elements[n].options[f.elements[n].selectedIndex].value

                data += amp + f.elements[n].name + "=" +  encodeURIComponent(val); 

                break; 
				
			case "textarea":
			
                val = f.elements[n].value; 
				
                data += amp + f.elements[n].name +  "=" + encodeURIComponent(val) ; 

                 break; 
			
			case "radio" :
			
                val = getCheckedValue(f.elements[n]); 
				
				if (val != "")
                	data += amp + f.elements[n].name +  "=" + encodeURIComponent(val) ; 

                 break; 
				
			case "checkbox" :
			
				if  (f.elements[n].checked)

				{
					val = f.elements[n].value; 
				    
					  data += amp + f.elements[n].name +  "=" + encodeURIComponent(val) ; 
             
					
				}

                 break; 
			
			default:
				
				//alert (f.elements[n].type);				
				break;

       } 
	}

	}
	return data;
}
function getCheckedValue(radioObj){
	
	if(!radioObj)
	
		return "";
		
	var radioLength = radioObj.length;
	
	if (radioLength == undefined)
	
		if (radioObj.checked)
		
			return radioObj.value;
			
		else
		
			return "";
			
	for(var i = 0; i < radioLength; i++) 
	{
		
		if(radioObj[i].checked) 
		{
			
			return radioObj[i].value;
			
		}
		
	}
	
	return "";
}

//show an image as feedback when available
function showvisualfeedback(calling)
{
try
{
	if (calling)
	{
		if (imageholder) setsrc(imageholder, imagewait);
	}
	else
	{
		if (imageholder) setsrc(imageholder, imageblank);
	}
  } catch (er) {
  }
}
function setsrc(imageholder, image)
{
	document.getElementById(imageholder).src = image;
}
// --------------------------------------------------------------------------------
//                              AJAX FUNCTIONS
// --------------------------------------------------------------------------------
function AJAXInteraction(url, callback, callonfailure) {


    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {

	  if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    
    function processRequest () {
	try{
      // readyState of 4 signifies request is complete
      if (req.readyState == 4) {
	// status of 200 signifies sucessful HTTP call
		//if ((req.status == 200)||(req.status == 0)) {
        if (req.status == 200) {
          if (debug) showScript (req.responseText);
		  showvisualfeedback(false);
          if (callback) callback(req.responseXML);
        }
	  }
	} catch(e) {
		if (callonfailure) {
			callonfailure();
		}else{
			alert (msg_connerror);
		}
	}
    }
    
	this.doGet = function() {
      // make a HTTP GET request to the URL asynchronously
      req.open("GET", url, true);
      if (debug) showScript(url);
	  showvisualfeedback(true);
      req.send(null);
    }
    
    this.doPost = function(data){
	  req.open("POST", url, true);
	  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      req.setRequestHeader("Content-length", data.length);
      req.setRequestHeader("Connection", "close");
	  showvisualfeedback(true);
      if (debug) {
	    showScript ("url "  + url  + "formdata:" + data);
	  }
	  if (!data) data = ' ';
      req.send(data);
	}
}

// --------------------------------------------------------------------------------
//                           AJAX FUNCTIONS WITH TEXT RETURN
// --------------------------------------------------------------------------------
function AJAXTextAction(url, callback) 
{
	var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {
	  var tempReq = false;
	  if (window.XMLHttpRequest) 
	  {
		try{
		  tempReq - new XMLHttpRequest();
		  tempReq.overrideMimeType('text/html');
          return new tempReq;
		  }
		  catch(er)
		  {
			 return new XMLHttpRequest();
			 
		  }        
      } else if (window.ActiveXObject) {
		 try {
            tempReq = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               tempReq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
        return tempReq;
      }
    }
    
	function processRequest () {
      if (req.readyState == 4) {
        if (req.status == 200) {
            result = req.responseText;
			showvisualfeedback(false);
		    if (callback) callback(req.responseText);
        }
      }
    }
    
    this.doGet = function() {
      // make a HTTP GET request to the URL asynchronously
      req.open("GET", url, true);
      //if (debug) alert(url);
	  showvisualfeedback(true);
      req.send(null);
    }
    
	this.doPost = function(data) {
      // make a HTTP GET request to the URL asynchronously
      req.open("POST", url, true);
	  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      req.setRequestHeader("Content-length", data.length);
      req.setRequestHeader("Connection", "close");
      //if (debug) alert ("url " + chr(13) + url + chr(13) + "formdata:" + chr(13) + data); 

	  showvisualfeedback(true);
      req.send(data);
    }
	
}

function showScript (content)
{
	var x = (screen.width - 400)/2
	var y = (screen.height - 200)/2
	var newwin=window.open("","myscript", 'WIDTH=400,HEIGHT=200,RESIZABLE=yes,SCROLLBARS=yes,STATUS=1,LEFT=' + x + ',TOP='+y);
	newwin.document.writeln("<hr>"+content);
//	newwin.write (content);
}

// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}
