//var idobjnavbar
//var idobjsrc
var oldhtml

//var idobjpNum

var tableDnD;

function stripslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
 
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}


function openRow(idr,tbn){
	
    xmlHttptab=GetXmlHttpObject() //See if it works with users browser.

	xmlHttptab.idobj=tbn;
	
	var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";

	var params=Array();
	
	shRec	= document.getElementById('f_'+tbn).elements[tbn+'shRecTab'].value;
	pNum	= document.getElementById('f_'+tbn).elements[tbn+'pNumTab'].value;

	params.push(tbn+'pNum='+pNum);
	params.push(tbn+'shRec='+shRec);
	params.push('Tb='+tbn);
	params.push('id='+idr);
	params.push('oper=openTabRow');
	var mypars=params.join("&");
	
	xmlHttptab.open("POST", url, true);
	
	//Send the proper header information along with the request
	xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttptab.setRequestHeader("Content-length", mypars.length);
	xmlHttptab.setRequestHeader("Connection", "close");

	xmlHttptab.onreadystatechange=function () 
								{
								if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
								 { 
									replaceHtml(xmlHttptab.responseText,this.idobj);
									
									if(window.pagefunction)pagefunction();
									
								 } 
								};
	xmlHttptab.send(mypars);
}

function tabrefresh(tbn){

    eval("xmlHttptab"+tbn+"=GetXmlHttpObject()"); //See if it works with users browser.

	eval("xmlHttptab"+tbn).idobj = tbn;


	var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";

	var params=Array();
	
	shRec	= document.getElementById('f_'+tbn).elements[tbn+'shRecTab'].value;
	pNum	= document.getElementById('f_'+tbn).elements[tbn+'pNumTab'].value;

	params.push(tbn+'pNum='+pNum);
	params.push(tbn+'shRec='+shRec);
	params.push('Tb='+tbn);
	var mypars=params.join("&");
	
	eval("xmlHttptab"+tbn).open("POST", url, true);
	
	//Send the proper header information along with the request
	eval("xmlHttptab"+tbn).setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	eval("xmlHttptab"+tbn).setRequestHeader("Content-length", mypars.length);
	eval("xmlHttptab"+tbn).setRequestHeader("Connection", "close");

	eval("xmlHttptab"+tbn).onreadystatechange=function () 
								{
								if (eval("xmlHttptab"+tbn).readyState==4 || eval("xmlHttptab"+tbn).readyState=="complete")
								 { 
									replaceHtml(eval("xmlHttptab"+tbn).responseText,this.idobj);
									
									if(window.pagefunction)pagefunction();
									
								 } 
								};
	eval("xmlHttptab"+tbn).send(mypars);
}

function closeRow(idr,tbn){

	tabrefresh(tbn);
	
}

function saveField(idr,tbn,me){

	var myelem = document.getElementById(me);	
	var elem   = new Array(myelem);

	sendRow(idr,tbn,elem);
}

function saveRow(idr,tbn){

		var frmName = 'f_'+tbn;

		error       = ChkValues(frmName);

		errorcode		= error[0];
		field			= error[1];
		idfieldobj		= error[2];

		if(error==0){
			var oksave=1;
		}else{
			makeError(errorcode,field,idfieldobj,frmName);
			var oksave=0;
		}
			
		if(oksave==1){
			
			var elem = document.getElementById('f_'+tbn).elements;
		
			sendRow(idr,tbn,elem);
			
		}
}


function sendRow(idr,tbn,elem){

				error=0;
				
				var mystr='';
				
				var params=Array();
				
				shRec	= document.getElementById('f_'+tbn).elements[tbn+'shRecTab'].value;
				pNum	= document.getElementById('f_'+tbn).elements[tbn+'pNumTab'].value;
		
				params.push(tbn+'pNum='+pNum);
				params.push(tbn+'shRec='+shRec);

				for(var i = 0; i < elem.length; i++)
				{
						var splitname = elem[i].name.split("_");
						
						var val=elem[i].value;
						
						var newpar = elem[i].name+"="+encodeURIComponent(val);
						
						if(elem[i].type=="checkbox"){
							
							if(elem[i].checked==true){
								var newpar = splitname[0]+"=1";
							}else{
								var newpar = splitname[0]+"=0";
							}
	
						}

						params.push(newpar);
				}
				
				params.push('Tb='+tbn);
				if(idr!=''){
					params.push('id='+idr);
				}else{
					params.push('newrec=1');
				}
				
				params.push('oper=editRecord');
								
				var mypars=params.join("&");
	
				xmlHttptab=GetXmlHttpObject() //See if it works with users browser.
			   
			    xmlHttptab.idobj = tbn;
			   
				var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";
				
				xmlHttptab.open("POST", url, true);
				
				//Send the proper header information along with the request
				xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttptab.setRequestHeader("Content-length", params.length);
				xmlHttptab.setRequestHeader("Connection", "close");
			
				xmlHttptab.onreadystatechange=function () 
								{
								if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
								 { 
									replaceHtml(xmlHttptab.responseText,this.idobj);

									if(window.pagefunction)pagefunction();
								 } 
								};
				xmlHttptab.send(mypars);	
		
}




function deleteRow(idr,tbn,msg){

		if(msg!=''){
			var agree=confirm(msg);
			if (agree){
				var yescanc=1;
			}else{
				var yescanc=0;
				return false ;
			}
		}else{
			var yescanc=1;
		}
				
		if(yescanc){
			
			var elem = document.getElementById('f_'+tbn).elements;
	
			error=0;
			
			var mystr='';
			
			var params=Array();
			
			shRec	= document.getElementById('f_'+tbn).elements[tbn+'shRecTab'].value;
			pNum	= document.getElementById('f_'+tbn).elements[tbn+'pNumTab'].value;
	
			params.push(tbn+'pNum='+pNum);
			params.push(tbn+'shRec='+shRec);
			
			params.push('Tb='+tbn);
			params.push('id='+idr);
			params.push('oper=deleteRecord')	
			var mypars=params.join("&");
			
			xmlHttptab=GetXmlHttpObject() //See if it works with users browser.
		   
		    xmlHttptab.idobj = tbn;
		   
			var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";
			
			xmlHttptab.open("POST", url, true);
			
			//Send the proper header information along with the request
			xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttptab.setRequestHeader("Content-length", params.length);
			xmlHttptab.setRequestHeader("Connection", "close");
		
				xmlHttptab.onreadystatechange=function () 
								{
								if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
								 { 
									replaceHtml(xmlHttptab.responseText,this.idobj);
									if(window.pagefunction)pagefunction();
								 } 
								};
			xmlHttptab.send(mypars);
		}
}

/*
function deletedRow() 
{ 
if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
 { 
 
  replaceHtml(xmlHttptab.responseText);
  
 idobj=null;
 } 
}*/

function replaceHtml(xml,idobj){

	var idobjnavbar = "navbar_" + idobj;
	var idobjsrc    = "Src_" + idobj;
	var idobjpNum   = idobj + "pNumTab";
	
	try //Internet Explorer
	  {
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async="false";
	  xmlDoc.loadXML(xml);
	  }
	catch(e)
	  {
	  try //Firefox, Mozilla, Opera, etc.
		{
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(xml,"text/xml");
		}
	  catch(e) {alert(e.message)}
	  }
	try 
	  {
	  //document.write("xmlDoc is loaded, ready for use");
	  }
	catch(e) {alert(e.message)}

	  if(document.getElementById('tbl_'+idobj)!= null){
	  	document.getElementById('tbl_'+idobj).innerHTML			= xmlDoc.documentElement.childNodes[1].childNodes[0].nodeValue;
	    
		eval(xmlDoc.documentElement.childNodes[4].childNodes[0].nodeValue);

	  }else{
		 document.getElementById('tbl_'+idobj).innerHTML="xx";//alert('Manca idobj')  
	  }
	  
	  if(document.getElementById(idobjnavbar)!=null){
	  	//document.getElementById(idobjnavbar).innerHTML	= xmlDoc.documentElement.childNodes[2].childNodes[0].nodeValue;
	  }else{
		//alert('Manca idobjnavbar')  
	  }

	   if(document.getElementById(idobjsrc)!=null){
	   //document.getElementById(idobjsrc).innerHTML		= xmlDoc.documentElement.childNodes[0].childNodes[0].nodeValue;
	   }else{
		  //alert('Manca idobjsrc') 
	   }


      if(document.getElementById(idobjpNum)!=null){
	   //document.getElementById(idobjpNum).value			= xmlDoc.documentElement.childNodes[3].childNodes[0].nodeValue;
	  }else{
		  //alert('Manca idobjpNum') 
	  }

	//######################
	  //idobj=null;

}


/*
function savedRow() 
{ 
if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
 { 
   	replaceHtml(xmlHttptab.responseText);
   	oldhtml=document.getElementById(idobj).innerHTML;
 } 
}
*/

function showResult(str)
{
	if(idobj!=null){
		 //document.getElementById(idobj).innerHTML=oldhtml;
	}
	//oldhtml=document.getElementById(str).innerHTML;
	
	idobj=str;

    xmlHttptab=GetXmlHttpObject() //See if it works with users browser.
   
	var url = "test.php";
	
	var params = "id="+str;
	
	xmlHttptab.open("POST", url, true);
	
	//Send the proper header information along with the request
	xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttptab.setRequestHeader("Content-length", params.length);
	xmlHttptab.setRequestHeader("Connection", "close");

	xmlHttptab.onreadystatechange=function () 
								{
								if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
								 { 
									alert('showResult');
								 } 
								};;
	xmlHttptab.send(params);

} 

function savecomment(idobj1,idobj2){

	if (xmlHttptab==null)
	 {
	 alert ("Browser does not support HTTP Request");
	 return;
	 } 

	var url="test2.php?id="+Math.random();
	xmlHttptab.onreadystatechange=fillcomment(idobj1,idobj2);
	xmlHttptab.open("GET",url,true);
	xmlHttptab.send(null);
	
}

function fillcomment(idobj1,idobj2) 
{ 
 	idobj=null;
	document.getElementById(idobj1).innerHTML=document.getElementById(idobj2).value;
	
}


function changeOrder(idtable,tabstyle,tabname){

		var table 		 = document.getElementById(idtable);
		var tablecofield = document.getElementById(idtable+"_co");
		
		//tablecofield.innerHTML="<a onclick=\"exitordermode('"+idtable+"','"+tabstyle+"')\">esci</a>";
		
		tableDnD = new TableDnD();
	
		table.className=tabstyle+"_ord";
	
		var listid=new Array();
		
		// Redefine the onDrop so that we can display something
		tableDnD.onDrop = function(table, row) {
			var rows = this.table.tBodies[0].rows;

			for (var i=0; i<rows.length; i++) {
				
				var myitem = rows[i].id.split("_");
				var myid = myitem.pop()
				if(myid!='nr'){
					listid.push(myid);
				}
			}
			
			var orderlistid = listid.join(",");

				params=new Array();
				params.push("orderlist="+orderlistid);

				params.push("Tb="+tabname);
				params.push("oper=orderRecord")	
				var mypars=params.join("&");
				
				xmlHttptab=GetXmlHttpObject() //See if it works with users browser.

				var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";

				xmlHttptab.open("POST", url, true);
				
				//Send the proper header information along with the request
				xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttptab.setRequestHeader("Content-length", params.length);
				xmlHttptab.setRequestHeader("Connection", "close");

 
				xmlHttptab.send(mypars);	
	
		}
	
	
	tableDnD.init(table);
}

function exitordermode(idtable,tabstyle){
		var table 		 = document.getElementById(idtable);
		var tablecofield = document.getElementById(idtable+"_co");
		
		tablecofield.innerHTML="<a onclick=\"changeOrder("+idtable+","+tabstyle+")\">Sposta Ordine</a>";
		table.className=tabstyle;
}

function orderby(field,tbn,idpage){

			params=new Array();
			params.push('field='+field);
			params.push('Tb='+tbn);
			params.push('oper=persOrderRecord')	
			params.push('idpage='+idpage)	
			var mypars=params.join("&");

			xmlHttptab = GetXmlHttpObject() //See if it works with users browser.
		   
		    xmlHttptab.idobj = tbn;
		   
			var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";
			
			xmlHttptab.open("POST", url, true);
			
			//Send the proper header information along with the request
			xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttptab.setRequestHeader("Content-length", params.length);
			xmlHttptab.setRequestHeader("Connection", "close");
		
			xmlHttptab.onreadystatechange=function () 
								{
								if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
								 { 
									replaceHtml(xmlHttptab.responseText,this.idobj);
								 } 
								};
			xmlHttptab.send(mypars);
}


/** Keep hold of the current table being dragged */
var currenttable = null;

/** Capture the onmousemove so that we can see if a row from the current
 *  table if any is being dragged.
 * @param ev the event (for Firefox and Safari, otherwise we use window.event for IE)
 */
document.onmousemove = function(ev){
    if (currenttable && currenttable.dragObject) {

        ev   = ev || window.event;
        var mousePos = currenttable.mouseCoords(ev);
        var y = mousePos.y - currenttable.mouseOffset.y;
        if (y != currenttable.oldY) {
            // work out if we're going up or down...
            var movingDown = y > currenttable.oldY;
            // update the old value
            currenttable.oldY = y;
            // update the style to show we're dragging
            currenttable.dragObject.className = "selected";
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = currenttable.findDropTargetRow(y);
            if (currentRow) {
                if (movingDown && currenttable.dragObject != currentRow) {
                    currenttable.dragObject.parentNode.insertBefore(currenttable.dragObject, currentRow.nextSibling);
                } else if (! movingDown && currenttable.dragObject != currentRow) {
                    currenttable.dragObject.parentNode.insertBefore(currenttable.dragObject, currentRow);
                }
            }
        }

        return false;
    }
}

// Similarly for the mouseup
document.onmouseup   = function(ev){
    if (currenttable && currenttable.dragObject) {
        var droppedRow = currenttable.dragObject;
        // If we have a dragObject, then we need to release it,
        // The row will already have been moved to the right place so we just reset stuff
        droppedRow.className = "";
        currenttable.dragObject   = null;
        // And then call the onDrop method in case anyone wants to do any post processing
        currenttable.onDrop(currenttable.table, droppedRow);
        currenttable = null; // let go of the table too
    }
}


/** get the source element from an event in a way that works for IE and Firefox and Safari
 * @param evt the source event for Firefox (but not IE--IE uses window.event) */
function getEventSource(evt) {
    if (window.event) {
        evt = window.event; // For IE
        return evt.srcElement;
    } else {
        return evt.target; // For Firefox
    }
}

/**
 * Encapsulate table Drag and Drop in a class. We'll have this as a Singleton
 * so we don't get scoping problems.
 */
function TableDnD() {
    /** Keep hold of the current drag object if any */
    this.dragObject = null;
    /** The current mouse offset */
    this.mouseOffset = null;
    /** The current table */
    this.table = null;
    /** Remember the old value of Y so that we don't do too much processing */
    this.oldY = 0;

    /** Initialise the drag and drop by capturing mouse move events */
    this.init = function(table) {
        this.table = table;
        var rows = table.tBodies[0].rows; //getElementsByTagName("tr")
        for (var i=0; i<rows.length; i++) {
			// John Tarr: added to ignore rows that I've added the NoDnD attribute to (Category and Header rows)
			var nodrag = rows[i].getAttribute("NoDrag")
			if (nodrag == null || nodrag == "undefined") { //There is no NoDnD attribute on rows I want to drag
				this.makeDraggable(rows[i]);
			}
        }
    }

    /** This function is called when you drop a row, so redefine it in your code
        to do whatever you want, for example use Ajax to update the server */
    this.onDrop = function(table, droppedRow) {
        // Do nothing for now
    }

	/** Get the position of an element by going up the DOM tree and adding up all the offsets */
    this.getPosition = function(e){
        var left = 0;
        var top  = 0;
		/** Safari fix -- thanks to Luis Chato for this! */
		if (e.offsetHeight == 0) {
			/** Safari 2 doesn't correctly grab the offsetTop of a table row
			    this is detailed here:
			    http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
			    the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
			    note that firefox will return a text node as a first child, so designing a more thorough
			    solution may need to take that into account, for now this seems to work in firefox, safari, ie */
			e = e.firstChild; // a table cell
		}

        while (e.offsetParent){
            left += e.offsetLeft;
            top  += e.offsetTop;
            e     = e.offsetParent;
        }

        left += e.offsetLeft;
        top  += e.offsetTop;

        return {x:left, y:top};
    }

	/** Get the mouse coordinates from the event (allowing for browser differences) */
    this.mouseCoords = function(ev){
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    }

	/** Given a target element and a mouse event, get the mouse offset from that element.
		To do this we need the element's position and the mouse position */
    this.getMouseOffset = function(target, ev){
        ev = ev || window.event;

        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    }

	/** Take an item and add an onmousedown method so that we can make it draggable */
    this.makeDraggable = function(item) {
        if(!item) return;
        var self = this; // Keep the context of the TableDnd inside the function
        item.onmousedown = function(ev) {
            // Need to check to see if we are an input or not, if we are an input, then
            // return true to allow normal processing
            var target = getEventSource(ev);
            if (target.tagName == 'INPUT' || target.tagName == 'SELECT') return true;
            currenttable = self;
            self.dragObject  = this;
            self.mouseOffset = self.getMouseOffset(this, ev);
            return false;
        }
        item.style.cursor = "move";
    }

    /** We're only worried about the y position really, because we can only move rows up and down */
    this.findDropTargetRow = function(y) {
        var rows = this.table.tBodies[0].rows;
		for (var i=0; i<rows.length; i++) {
			var row = rows[i];
			// John Tarr added to ignore rows that I've added the NoDnD attribute to (Header rows)
			var nodrop = row.getAttribute("NoDrop");
			if (nodrop == null || nodrop == "undefined") {  //There is no NoDnD attribute on rows I want to drag
				var rowY    = this.getPosition(row).y;
				var rowHeight = parseInt(row.offsetHeight)/2;
				if (row.offsetHeight == 0) {
					rowY = this.getPosition(row.firstChild).y;
					rowHeight = parseInt(row.firstChild.offsetHeight)/2;
				}
				// Because we always have to insert before, we need to offset the height a bit
				if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
					// that's the row we're over
					return row;
				}
			}
		}
		return null;
	}
}



function movenode(tabmat,tabstr,idstart,idend){


 	xmlHttptab=GetXmlHttpObject() //See if it works with users browser.
		
	var url="../www/ajaxindex.php?pag=../engine/ajaxphp/matedit.php";
	
	var params = Array();
		
	params.push('idstart='+ idstart);
	params.push('idend='+ idend);
	params.push('tabmat='+ tabmat);
	params.push('tabstr='+ tabstr);

	params.push('oper=movenode');
	var mypars=params.join("&");
	
	xmlHttptab.open("POST", url, true);
	
	//Send the proper header information along with the request
	xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttptab.setRequestHeader("Content-length", mypars.length);
	xmlHttptab.setRequestHeader("Connection", "close");
	xmlHttptab.send(mypars);
	
}

function rsResetOrder(tbn,idpage){

			params=new Array();
			params.push('Tb='+tbn);
			params.push('oper=rsResetOrder')	
			params.push('idpage='+idpage)	
			var mypars=params.join("&");

			xmlHttptab = GetXmlHttpObject() //See if it works with users browser.
		   
		    xmlHttptab.idobj = tbn;
		   
			var url="../www/ajaxindex.php?pag=../engine/ajaxphp/tabedit.php";
			
			xmlHttptab.open("POST", url, true);
			
			//Send the proper header information along with the request
			xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttptab.setRequestHeader("Content-length", params.length);
			xmlHttptab.setRequestHeader("Connection", "close");
		
			xmlHttptab.onreadystatechange=function () 
								{
								if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
								 { 
										history.go(0);
								
								 } 
								};
			xmlHttptab.send(mypars);
}




/*
var inforowtbname;
function inforow(tbn,id){
	xmlHttptab=GetXmlHttpObject() //See if it works with users browser.

	var url = RootPath+"engine/ajaxphp/tabedit.php";
	
	var params=Array();
	
	inforowtbname = tbn;
	
	params.push('Tb='+tbn);
	params.push('id='+id);
	params.push('oper=inforow');
	var mypars=params.join("&");
	
	xmlHttptab.open("POST", url, true);
	
	//Send the proper header information along with the request
	xmlHttptab.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttptab.setRequestHeader("Content-length", mypars.length);
	xmlHttptab.setRequestHeader("Connection", "close");

	xmlHttptab.onreadystatechange=function(){
				if (xmlHttptab.readyState==4 || xmlHttptab.readyState=="complete")
				 { 
				 
				 	document.getElementById('infotbrowbox_'+inforowtbname).innerHTML=xmlHttptab.responseText;
					
				 } 
	};
	
	xmlHttptab.send(mypars);
}
function closeinforow(tbn){
	document.getElementById('infotbrowbox_'+inforowtbname).innerHTML="";
}
*/


