/////////////////
// VARIABLES 
/////////////////
var preloaderBig = "<center><br><br><br><br><br><br>";
	preloaderBig = preloaderBig+"<img src='http://i.digitalpipelines.com/img/loading-big.gif'><br><br><h3>Loading...</h3><br></center>";
var preloader = "<img src='http://i.digitalpipelines.com/img/loading-small.gif'>";


//////////////////////////////////////////////////////////
// resets element's class name to 'class_name'
//////////////////////////////////////////////////////////
function ClassReset(id,class_name) {
	document.getElementById(id).className = class_name;
}  	
	
/////////////////////////////////////////////////////////
// checks whether element exists
/////////////////////////////////////////////////////////
function Exists(element_id) {
	if (document.getElementById(element_id) == undefined) {
		return false;
	} else {
		return true;
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////
// fades and hides element
///////////////////////////////////////////////////////////////////////////////////////////////
function Fade(element_id,waiting_time) {
	var opac = 100;
	if (waiting_time == undefined) {
		var waiting_time = 1000;
	} 
	while (opac > 0) {
		opac = eval(opac - eval(5));
		waiting_time = eval(waiting_time + eval(100));
		setTimeout("ChangeOpac('"+element_id+"','"+opac+"');",waiting_time);
	}
	setTimeout("Hide('"+element_id+"');",waiting_time);  // hiding so that it is not getting in the way of other clicks
	setTimeout("ChangeOpac('"+element_id+"','100');",waiting_time); // setting opacity to 100% so that the same element is reus.
}  


////////////////////////////////////////////////////////////////////////
// used to refresh images
////////////////////////////////////////////////////////////////////////
function RefreshImage(object_id,name,path)
{
	var full_path = path+name;
	document.getElementById(object_id).src = "http://i.digitalpipelines.com/img/loading-big.gif";
	document.getElementById(object_id).src = full_path;
}


/*

//////////////////////////////////////////////////////////////////////
// passes GET variables to the script and returns response text
//////////////////////////////////////////////////////////////////////
function DataTrade(vars,element_id,preloader)
{
	
	var xmlHttp = GetXmlHttpObject();
	var url=vars+"&sid="+Math.random();
	
	xmlHttp.onreadystatechange=function () 
	{ 	
		// when data comes back
		if (xmlHttp.readyState==4) 	
		{
			// if target was innerHTML of DOM id
			if (element_id != "") { 
				document.getElementById(element_id).innerHTML = xmlHttp.responseText;
			} else {
			// if only return of the value is needed
				return "";
			}
		} else if(preloader != "") { 
		// while waiting for data, will show preloader if needed
			document.getElementById(element_id).innerHTML = preloader; 
		}
	}
	xmlHttp.open("GET",url,true);	 
	xmlHttp.send(null);  
}

*/

/*
// for xhr only?
setHeaders = function(xhr) {

		function safeSet(k, v) {
				try {
						xhr.setRequestHeader(k, v);
				} catch(e) {}
		}

		safeSet("User-Agent", null);
		safeSet("Accept", null);
		safeSet("Accept-Language", null);
		safeSet("Content-Type", "M");
		safeSet("Connection", "keep-alive");
		safeSet("Keep-Alive", null);
}
*/


//////////////////////////////////////////////////////////////////////
// passes either GET or POST variables to the script and returns response text
//////////////////////////////////////////////////////////////////////
function DataPost(vars,element_id,preloader) {
	DataTrade(vars,element_id,preloader,'POST');
}

function DataTrade(vars,element_id,preloader,mode) {   
		
	var xmlHttp = GetXmlHttpObject();
	
  // determining whether to use GET or POST
	if (mode == undefined) { // if mode is not specified
		if (vars.length > 5000) {  // if request is way long, using post
			var mode = "POST"; 
		} else { // otherwise, using get
			var mode = "GET";
		}  
	} 
	
	if (mode == "POST") {
		var url = vars.substring( 0, vars.indexOf("?"));
		var vars = vars.substring( eval(url.length+1), vars.length);
		xmlHttp.open("POST", url, true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", vars.length);
		xmlHttp.setRequestHeader("Connection", "close");
	
	} else {
		var url=vars+"&sid="+Math.random();  
	}
	
	// workaround - in the past, some of those might have been specified as blank
	if (element_id == undefined)  { element_id = ""; }
	if (preloader == undefined)   { preloader = ""; }
			
	xmlHttp.onreadystatechange = function () {   
		// when data comes back
		if (xmlHttp.readyState == 4) {
			
			// if target was innerHTML of DOM id or the return function has been used
			if (element_id != "") { 
				if (element_id.indexOf("(") == -1) { // if no special function was used
					document.getElementById(element_id).innerHTML = xmlHttp.responseText;
				} else {
					eval(element_id+UrlEncode(xmlHttp.responseText)+"')");
				}
				
				if (jquery_jtip_used) { // if jtips are being used, regenerating them
					JT_init();
				}
			} else {
			// if only return of the value is needed
				return "";
			}
	
		} else if(preloader != "") { 
		// while waiting for data, will show preloader if needed
			document.getElementById(element_id).innerHTML = preloader; 
		}
    
    // after AJAX is retrieved, some custom js could be executed
    var custom_js = $('.FMW_js_afterload').html();
    $('.FMW_js_afterload').remove();      
    if (custom_js != "") {
      eval(custom_js);
    }
    
	}
	
	if (mode == "POST") {
		xmlHttp.send(vars);
	} else { 
		xmlHttp.open("GET",url,true);   
		xmlHttp.send(null); 
	}
	
}

////////////////////////////////////////////////////////
// used to start cronjobs and so on
///////////////////////////////////////////////////////
function DataStart(remote_url,redirect) {
	var xhr = $.ajax({
		 url: remote_url
	});
	xhr.abort(); 
	if (redirect) {
		GoTo(redirect);
	}
}

function DataExec(vars)
{
	var xmlHttp = GetXmlHttpObject();
	var url=vars;
	//+"&sid="+Math.random();
	
	xmlHttp.onreadystatechange=function () 
	{ 	
		// when data comes back
		if (xmlHttp.readyState==4) {
			eval(xmlHttp.responseText);
		} 
	}
	xmlHttp.open("GET",url,true);	 
	xmlHttp.send(null);  
}





//////////////////////////////////
// gateway to php
/////////////////////////////////
function TradeData(vars,element_id,preloader)
{
	var xmlHttp = GetXmlHttpObject();
	var url=vars+"&sid="+Math.random();
	xmlHttp.onreadystatechange=function () 
	{ 	
		if ((xmlHttp.readyState==4)&&(element_id!="")) 	
		{ document.getElementById(element_id).innerHTML = xmlHttp.responseText;	delete xmlHttp;}	
		else if(preloader!="") { document.getElementById(element_id).innerHTML = preloader; }
	}
	xmlHttp.open("GET",url,true);	 xmlHttp.send(null);  
}

			// internal AJAX function
			function GetXmlHttpObject()
			{
			var xmlHttp=null;
			try { xmlHttp=new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari
			catch (e)  {  // Internet Explorer
			try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
			catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } }
			return xmlHttp;
			}

/////////////////////////////////
// replaces characters
/////////////////////////////////
function ReplaceChars(entry,out,add) {
temp = "" + entry;

while (temp.indexOf(out)>-1) {
pos= temp.indexOf(out);
temp = "" + (temp.substring(0, pos) + add + 
temp.substring((pos + out.length), temp.length));
}
return(temp);
}

//////////////////////////////////////////////////////////////////////////////////////////////////
// this function should replace SafeInput in the future - urlencode handles everything except '
//////////////////////////////////////////////////////////////////////////////////////////////////
function UrlEncode(entry) {
	entry = urlencode(entry);
	entry = ReplaceChars(entry,"'","--singlequotehere--");
	return(entry);
}

function UrlDecode(entry) {
	entry = ReplaceChars(entry,"--singlequotehere--","'");
	entry = urldecode(entry);

	return(entry);
}


/////////////////////////////////
// replaces those characters that can't be passed in the url without parsing
/////////////////////////////////
function SafeInput(entry) {
	// encoding line break
	//entry = entry.replace(new RegExp( "\n", "g" ),"");
	// encoding + sign
	entry = ReplaceChars(entry,"+","%2B");
	// encoding & sign
	entry = ReplaceChars(entry,"&","%26");
	// encoding = sign
	entry = ReplaceChars(entry,"=","%3d");
	// encoding ' sign
	entry = ReplaceChars(entry,"'","%27");
	// encoding " sign
	entry = ReplaceChars(entry,'"',"%27");
	
	return(entry);
}


function SafeOutput(entry) {
	// decoding &
	entry = ReplaceChars(entry,"&amp;","&");
	// decoding & sign
	entry = ReplaceChars(entry,"%26","&");
	// decoding = sign
	entry = ReplaceChars(entry,"%3d","=");
	// decoding +
	entry = ReplaceChars(entry,"%2B","+"); 
	// decoding ' sign
	entry = ReplaceChars(entry,"%27","'"); 
	// decoding " sign
	entry = ReplaceChars(entry,"%22",'"'); 

	return(entry);
}

///////////////////////////
// hides object
///////////////////////////
function Hide(id) { 
  if (document.getElementById(id) == undefined) {
    eval("Hide: "+id);
  } else {
    document.getElementById(id).style.display = "none"; 
  }
}

//////////////////////////
// unhides object as a block
//////////////////////////
function ShowBlock(id)
{ document.getElementById(id).style.display = "block"; }

///////////////////////////
// unhides object as inline
///////////////////////////
function ShowInline(id)
{ document.getElementById(id).style.display = "inline"; }

///////////////////////////
// switches between "block" and "none" values for display property
///////////////////////////
function ToogleBlock(id)
{
	var style2 = document.getElementById(id).style;
	if (style2.display == "none") { style2.display = "block"; }
	else { style2.display = "none"; }
}
////////////////////////////////////////////////
// same function tailored for hiding table rows
////////////////////////////////////////////////
function ToogleRow(id) {
	var style2 = document.getElementById(id).style;
	if (style2.display == "none") {style2.visibility = "visible"; style2.display="";}
	else {  style2.display = "none"; }
}
//////////////////////////////////////////////////////
// showing collapsed table rows
//////////////////////////////////////////////////////
function ShowRow(id) {
	var style2 = document.getElementById(id).style;
	style2.visibility = "visible"; style2.display="";
}

/////////////////////////////
// switches between "inline" and "none" values for display property 
/////////////////////////////
function ToogleInline(id)
{
	var style2 = document.getElementById(id).style;
	if (style2.display == "none") { style2.display = "inline"; }
	else { style2.display = "none"; }
}
/////////////////////////////////////////////
// returns droplist option id
/////////////////////////////////////////////
function DroplistId(id) {
  if (typeof(id) == 'object') { // can be used with 'this' as parameter
    if (id.selectedIndex == '-1') {
      return -1;
    } else {
      return(id.options[id.selectedIndex].value);
    } 
  } else {
	  if (document.getElementById(id).selectedIndex == '-1') {
		  return -1;
	  } else {
		  return(document.getElementById(id).options[document.getElementById(id).selectedIndex].value);
	  } 
  }
}
////////////////////////////////////
// gets element value
////////////////////////////////////
function Value(id) {
  if (typeof(id) == 'object') { // can be used with 'this' as parameter
    return(id.value);
  } else if(document.getElementById(id)) {
    return(document.getElementById(id).value);
  } else {
    exec('Value: '+id);
  }
}

function ValueSet(id,value_new) {
  if (value_new != undefined) {
	  document.getElementById(id).value = SafeOutput(value_new);
  } else {
    document.getElementById(id).value = '';
  }
}

function ValueUse(id,id_source) {
	document.getElementById(id).value = document.getElementById(id_source).value;
}

function ValueSafe(id) {
	return(SafeInput(document.getElementById(id).value));
}

function ValueRadio(name) {
  var o = $("input:checked[type='radio'][name='"+name+"']").val();
  return(o);
}


////////////////////////////////////
// gets element innerHTML
////////////////////////////////////
function Content(id) {
	return(document.getElementById(id).innerHTML);
}
/////////////////////////////////////
// changes inner HTML
/////////////////////////////////////
function ContentSet(id,content_new) {
	document.getElementById(id).innerHTML = content_new;
}

/////////////////////////////////////
// toogles inner HTML
/////////////////////////////////////
function ContentToogle(id,content_a,content_b) {
	if (document.getElementById(id).innerHTML == content_a) {
		document.getElementById(id).innerHTML = content_b;
	} else {
		document.getElementById(id).innerHTML = content_a;
	}
}

/////////////////////////////////////
// adjusts inner HTML
/////////////////////////////////////
function ContentAdjust(id,crease) {
	var current = eval(document.getElementById(id).innerHTML);
	if (crease == undefined) {
		current = eval(current + 1);
	} else {
		current = eval(current + eval(crease));
	}

	document.getElementById(id).innerHTML = current;
}

/////////////////////////////
// opens up new window
////////////////////////////
function NewWin(id,x,y) {
	if((x*1 == NaN) || (x == "")) x = 800;
	if((y*1 == NaN) || (y == ""))  y = 400;
	window.open("_popup.php?id="+id, "Langas", "resizable=yes,scrollbars=yes,status=no,menubar=yes,titlebar,height="+y+",width="+x+"");
}

/////////////////////////////
// redirects to specified address
/////////////////////////////
function GoTo(loc) { 
	window.location.href = loc; 
}
////////////////////////////////////////////////
// same, but also opens it in a new window
////////////////////////////////////////////////
function Open(url) {
	window.open(url); 
}

////////////////////////////
// confirms action
////////////////////////////
function ConfirmAction(actionDescription,url)
	{  if(window.confirm("Are you sure you want "+actionDescription)){GoTo(""+url+"");}  	}
	
//////////////////////////////////////////////////////////////////////////////////
// on confirm executes another ajax action and outputs (if is set) success message
//////////////////////////////////////////////////////////////////////////////////
function ConfirmAjax(text,action,param,success_message)
{	
	conf = confirm(text); 
	if(conf == true) { eval(action+"('"+param+"')"); }
	if (typeof success_message != 'undefined')
	{ 
		document.getElementById('messages').innerHTML = 
			"<div class='success'>"+success_message+"</div>"; 
	}	
}

////////////////////////////
// gets user input via prompt
////////////////////////////
function EnterText(promptTitle,confirmText,url,defaultText)
{
	var answer = prompt (promptTitle,defaultText)
	if (answer != null) {ConfirmAction(confirmText+"\n\n "+answer,url+answer);}
}

/////////////////////////////////////////////
// checks whether email address is properly formated
//////////////////////////////////////////////
function CheckEmail(email)
{
	var testresults
	var str=email
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str))
	testresults=true
	else{
	testresults=false
	}
	return (testresults)
}

/////////////////
//change the opacity for different browsers 
/////////////////
function ChangeOpac(object_id, opacity) {
		var object = document.getElementById(object_id).style; 
		object.opacity = (opacity / 100); 
		object.MozOpacity = (opacity / 100); 
		object.KhtmlOpacity = (opacity / 100); 
		object.filter = "alpha(opacity=" + opacity + ")"; 
}


////////////////////////////////////////////////////////////////
// enforces maxlength for textareas and so on
////////////////////////////////////////////////////////////////
function InputLimit(element_id,limit) {
	var text = Value(element_id);
	if (text.length > limit) {
		text = text.substring(0,limit);
	}
	ValueSet(element_id,text);
}


////////////////// for items
function FMW_menu_update(item_id,file_name)
{
	// preparing vars
	var name = SafeInput(document.getElementById('name_'+item_id).value);
	var url = SafeInput(document.getElementById('url_'+item_id).value);
	var preloader = '<img src="http://i.digitalpipelines.com/img/loading-small.gif" height="16">';	
	
	// preparing query
	var query = file_name+'?&update='+item_id+'&name='+name+'&url='+url;
	//alert(query);


	// restoring input fields to normal style
	document.getElementById("name_"+item_id).style.border = "1px solid #7B9EBD";
	document.getElementById("name_"+item_id).style.padding = "1px";
	document.getElementById("url_"+item_id).style.border = "1px solid #7B9EBD";
	document.getElementById("url_"+item_id).style.padding = "1px";
	
	// passing via AJAX
	//2/14/2008alert(query + " status_"+ item_id);
	//DataTrade(query,'status_'+item_id,preloader);
	
	// different AJAX usage depending item level
	if (document.getElementById("url_"+item_id).style.display == "none") {
		DataTrade(query,'','');
	} else { 
		DataTrade(query,'status_'+item_id,preloader);
	}
}

//////////////////////////////////////////////////////////////////
function FMW_menu_access(page,group) {
	
	if (document.getElementById('access_'+page+'_'+group).checked == true) { // if the checkbox has been checked
		DataTrade(file_name+'&action_local=menu_access&page='+page+'&group='+group+'&grant=true','','');	
	} else { // if the checkbox has been UNchecked
		DataTrade(file_name+'&action_local=menu_access&page='+page+'&group='+group+'&grant=false','','');	
	}
}

/////////////////////////////////////////////////////////
// calls AJAX for search by email 
/////////////////////////////////////////////////////////
/*clear = "Y";
function _search(div_id,response) {
	ContentSet(div_id+"_results",urldecode(response));
	clear = "Y";
}
function FMW_Search(what,input) {
	
	if (what.indexOf("&div_id=") != -1) {  // if custom id div id is used
		var div_id = what.substr(what.indexOf("&div_id=")+8);
	} else {  // otherwise, reusing 'what' variable
		var div_id = what;
	}
	
	ShowBlock(div_id+'_results'); // making results div visible
	if (Content(div_id+'_results') == "") { // if it's empty, showing preloader
		ContentSet(div_id+'_results','<center>loading...</center>'); 
	} 
	
	if (clear != "N") {
		if (what.indexOf("?") != -1) {  // if a custom file is used as a search backend
			DataTrade(what+"&input="+SafeInput(input),div_id+"_results","");  // quering the file and outputing results
		} else { // using standard gateway
			DataTrade("+search.php?what="+what+"&input="+SafeInput(input),div_id+"_results","");  // quering the file and outputing results
		//DataTrade("+search.php?what="+what+"&input="+SafeInput(input),"_search('"+div_id+"','");
		}
		clear = "N";
	} 
}


*/


///////////////////////////////////////////////////////////
// performs AJAX search
// returns search results to a div under the search field
///////////////////////////////////////////////////////////
function FMW_Search(what,input) {
  
  input = SafeInput(input); 
  
  // handling custom target div id's 
  if (what.indexOf("&div_id=") != -1) {  // if custom id div id is used
    var div_id = what.substr(what.indexOf("&div_id=")+8);
  } else {  // otherwise, reusing 'what' variable
    var div_id = what;
  }
  
  // handling custom backend paths
  if (what.indexOf("?") != -1) {  // if a custom file is used as a search backend
    var path = what+"&input=";
  } else {
    var path = "+search.php?what="+what+"&input=";
  }
  
  // once search has started...
  ShowBlock(div_id+'_results'); // making results div visible
  if (Content(div_id+'_results') == "") { // if it's empty, showing preloader
    ContentSet(div_id+'_results','<center>loading...</center>'); 
  } 
  
  FMW_Search_execute(path,div_id,input); // executing the search
  
}


/////////////////////////////////////////////////////
// enables to have just one AJAX request at a time
/////////////////////////////////////////////////////
function FMW_Search_execute(path,div_id,input) {

  // if there is no search currently running, will proceed right away with search
  if ($("#"+div_id+"_results").data('current_search') == undefined) {
    
    
    $("#"+div_id+"_results").data('last_search', input); // this will be the last search that has been executed so far
    $("#"+div_id+"_results").data('current_search', input); // and for the duration of AJAX, it will be the "current" search
    $.get(path+input,"",function(data) {
      ContentSet(div_id+"_results",data); // show results in the results DIV
      $("#"+div_id+"_results").removeData('current_search'); // once done running, current_search becomes undefined
      if ($("#"+div_id+"_results").data('queued_search') != undefined) { // if there is a pending search
        FMW_Search_execute(path,div_id,$("#"+div_id+"_results").data('queued_search')); // calling itself
        $("#"+div_id+"_results").removeData('queued_search'); // and removing queued search
      } // end of processing queued searches
    });
  
    
  } else { // if search is currently running
    $("#"+div_id+"_results").data('queued_search', input); // will queue the latest input (and overwrite any previously pending searches)
  }
}



////////////////////////////////////////////////////
// get's ticket content into span under header  ||| redo checking for wysiwyg and what tailoring
////////////////////////////////////////////////////	
function FMW_actions(what,wysiwyg,params) {
  
  var what_raw = what;
  if (what.indexOf("&") > 0) {
    what = what.substring(0,what.indexOf("&"));
  }

  
if ( document.getElementById('actions_'+what).style.display == "none") { // if ticket is hidden
	
	//if (Content('actions_'+what) == "") { // if ticket data hasn't been loaded yet
	  
		DataTrade('+actions.php?action='+what_raw,'actions_'+what,'<center>...loading...');
		if (wysiwyg == true) {
			WaitFor('html','wysiwyghtml',"generate_wysiwyg(|html|); ");
		}
	//}
	ShowBlock('actions_'+what);
	
	} else { // if ticket is visible
		Hide('actions_'+what);
	}
}


/////////////////////////////////////////////////////////////////////
// waits for the specified element to be available and then executes specified action
///////////////////////////////////////////////////////////////////////////////////////
function WaitFor(what,limit,action) {
	// if the object, that is created by executing the action that we are waiting for already exists..
	if (limit != undefined)	{
		if (document.getElementById(limit)) { return; }
	}

	if (document.getElementById(what)){
		action = ReplaceChars(action,"|","'");
		eval(action);
	} else {
		setTimeout("WaitFor('"+what+"','"+limit+"','"+action+"')","200");
	}
}


////////////////////////////////////////////////////////////////////////////////////////
// blinks text
////////////////////////////////////////////////////////////////////////////////////////
function Blink(object_id,interval) {
	
	if (interval == undefined) {
		interval = 1000;
	}
	ChangeOpac(object_id, 0);
	setTimeout("ChangeOpac('"+object_id+"', 33);",interval * 0.1);
	setTimeout("ChangeOpac('"+object_id+"', 66);",interval * 0.2);
	setTimeout("ChangeOpac('"+object_id+"', 100);",interval*0.3);
	setTimeout("ChangeOpac('"+object_id+"', 66);",interval*0.8);
	setTimeout("ChangeOpac('"+object_id+"', 33);",interval*0.9);
	setTimeout("Blink('"+object_id+"','"+interval+"');",interval);
}	

/////////////////////////////////////////////////////////////////////////
// main function, gets HTML from php script using predifined variables
/////////////////////////////////////////////////////////////////////////
function ajax_table_refresh(arguments,mode)
{	
	var target_div = "results";
  if (mode == undefined) {
    DataTrade(file_name+"&"+arguments,target_div,preloaderBig);
	} else {
    DataPost(file_name+"&"+arguments,target_div,preloaderBig);
  }  
  /*
	if (dnd_enabled != undefined) {
		WaitFor('main_fmw','dnd_debug','FMW_dnd(|main_fmw|);');
	}
	*/
	//document.getElementById("messages").innerHTML = "";
}

/////////////////////////////////////////////////////////////////////////
// only if the page is realoaded, messages div will not be cleaned
/////////////////////////////////////////////////////////////////////////
function ajax_table_initialize() {	
	var target_div = "results";
	DataTrade(file_name,target_div,preloaderBig);	
}





////////////////////////////////////////////////////////////////////////////////////////////////
// used for ajax table inlays
////////////////////////////////////////////////////////////////////////////////////////////////
function FMW_inlay(row_id,gateway,wysiwyg,wysiwyg_width) {
																															 
	ToogleRow('view_'+row_id); // this function can be used for both expanding and collapsing the row
	
	if (document.getElementById('view_'+row_id).style.display != "none") { // if row has been expanded..
	  if (gateway != undefined) {
  	  DataTrade(gateway+row_id,'edit_'+row_id,'...loading...'); // ...getting data
		  if(wysiwyg != undefined) { // and if wysiyg is enabled
			  if (wysiwyg_width != undefined) { // .. and if it's paramaters are set
				  WaitFor(wysiwyg+row_id,"wysiwyg"+wysiwyg+row_id,"generate_wysiwyg(|"+wysiwyg+row_id+"|,|"+wysiwyg_width+"|);"); 
			  }  else {
				  WaitFor(wysiwyg+row_id,"wysiwyg"+wysiwyg+row_id,"generate_wysiwyg(|"+wysiwyg+row_id+"|,||);"); // generating it..
			  }      
		  }
    }
	} else { // if row is collapsed
		ContentSet('edit_'+row_id,""); // unsetting content 
	}
}

///////////////////////////////////////////////////////
// just to add WUSIWYG area
///////////////////////////////////////////////////////
function WYSIWYG(element_id,element_width) {

  if (element_width != undefined) { // .. and if it's paramaters are set
    WaitFor(element_id,"wysiwyg"+element_id,"generate_wysiwyg(|"+element_id+"|,|"+element_width+"|);"); 
  } else {
    WaitFor(element_id,"wysiwyg"+element_id,"generate_wysiwyg(|"+element_id+"|,||);"); 
  } 
}




////////////////////////////////////////////////////////////////////////////////////////
// js part of the system used to update the data and show immidiate change for the user
////////////////////////////////////////////////////////////////////////////////////////





////////// for mouse over effect
function FMW_sortOver(element_id,direction) {
	//alert(element_id);
	document.getElementById(element_id).style.cursor = 'pointer';
	document.getElementById(element_id).style.backgroundImage="url(http://i.digitalpipelines.com/img/"+direction+"_big.gif)";
}
///////// for mouse out effect
function FMW_sortOut(element_id,direction) {
	document.getElementById(element_id).style.backgroundImage="url(http://i.digitalpipelines.com/img/"+direction+".gif)";
}

//////// main function  - updated both user's and db's view on click
function FMW_sortUpdate(row_start,sort_direction,rpi,gateway) {

	//alert(row_start+'-'+sort_direction+'='+rpi+" "+gateway);
	start_index = eval(document.getElementById(row_start).rowIndex-1); // in order to swap rows, we need to know row index

	// if moving down...
	if (sort_direction == "down") {
	
		if ( $(row_start).next(eval(rpi-1)) != undefined) {
			target = $(row_start).next(eval(rpi-1)).id;
			target_index = eval(start_index+rpi);
		} else {
			target = undefined;
		}
	 
	} 
	
	// if moving up...
	if (sort_direction == "up") {
		if ($(row_start).previous(eval(rpi-1)) != undefined) {
			target = $(row_start).previous(eval(rpi-1)).id;
			target_index = eval(start_index-rpi);
		} else {
			target = undefined;
		}
	} 

	//alert(start_index+" "+target_index);
	
// so if we know both the row_start and target, let's throw in some AJAX
	if (target != undefined) {


	// hiding irrelevant arrows
		
		// if the target row will be moved TO the very top, will hide 'sort_up' button from start row and show it on target row
		if (target_index == 0) { 
			document.getElementById('sort_up_'+row_start).style.visibility = 'hidden';
			document.getElementById('sort_up_'+target).style.visibility = 'visible';
		} 	
		
		// if the start row will be moved FROM the very top, will hide 'sort_up' button from target row and show it on start row
		if (start_index == 0) {
			document.getElementById('sort_up_'+row_start).style.visibility = 'visible';
			document.getElementById('sort_up_'+target).style.visibility = 'hidden';
		} 

		// if the start row will be moved TO the very bottom, will hide 'sort_up' button from start row and show it on target row
		if ($(target).next(eval(rpi-1)) == undefined) {
			document.getElementById('sort_down_'+row_start).style.visibility = 'hidden';
			document.getElementById('sort_down_'+target).style.visibility = 'visible';
		} 
		
		// if the target row will be moved FROM the very bottom, will hide 'sort_up' button from target row and show it on start row
		if ($(row_start).next(eval(rpi-1)) == undefined) {
			document.getElementById('sort_down_'+row_start).style.visibility = 'visible';
			document.getElementById('sort_down_'+target).style.visibility = 'hidden';
		} 
	
	// swapping in the database via AJAX		
		DataTrade(gateway+'&row_start='+row_start+'&target='+target+'&direction='+sort_direction,'','');
		
			
	// ...and then doing the swapping 
		SwapElements('main_fmw',"tr",start_index,target_index);
		// if more than one row is being swapped at a time, will swap the second one as well
		if (rpi == 2) {
			SwapElements('main_fmw',"tr",eval(start_index+1),eval(target_index+1));
		}

			FMW_sortOut(row_start,'up');
			FMW_sortOut(target,'up');
			FMW_sortOut(target,'down');
			FMW_sortOut(row_start,'down');
	
	}
	
	
}



/////////////////////////////////////////////
// shortcut to delete rows from ajax table
/////////////////////////////////////////////
function FMW_rowDelete(row_id,action) {
  Hide(row_id);
  DataTrade(action+row_id);
  if (document.getElementById('view_'+row_id)) {
    Hide('view_'+row_id);
  }
  ContentAdjust("fmw_total_results",-1);
}

////////////////////////////////////////////////////
// swaps 2 elements places (primaraly table rows)
////////////////////////////////////////////////////
function SwapElements(table_name,element_name,i,j)
{
	// table to be worked with
	var oTable = document.getElementById(table_name);
	// elements that will be used in swapping
	var trs = oTable.tBodies[0].getElementsByTagName(element_name);

	
	if(i >= 0 && j >= 0 && i < trs.length && j < trs.length)
	{
		if(i == j+1) {// moving down (forwards) by one
			oTable.tBodies[0].insertBefore(trs[i], trs[j]);
		} else if(j == i+1) { // moving up (backwards) by one
			oTable.tBodies[0].insertBefore(trs[j], trs[i]);
		} else { // more somewhere by more than one
			var tmpNode = oTable.tBodies[0].replaceChild(trs[i], trs[j]);
			if(typeof(trs[i]) != "undefined") {
				oTable.tBodies[0].insertBefore(tmpNode, trs[i]); 
			} else {
				oTable.appendChild(tmpNode); //alert('b');
			}
		}		
	}
	else
	{
		//alert(i+ ' '+j+' '+trs.length+' '+trs.length);
		//alert("Invalid Values!");
	}
}

////////////////////////////////////////////////////////////////
// counts words in the text block. works well with line breaks
////////////////////////////////////////////////////////////////
function CountWords(input) {
	
	var fullStr = input + " ";
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
	var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
	var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
	var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
	var splitString = cleanedStr.split(" ");
	var word_count = splitString.length -1;
	if (fullStr.length <2) {
		word_count = 0;
	}
	return(word_count);
}




////////////////////////////////////////// LEGACY

function ShowObject(id) {
	ShowBlock(id);
}

function ContentCrease(id,new_value) {
	ContentAdjust(id,new_value);
}


/////////////////////////////////////////////////////////////////////////////////////
// in case php.js was not included - to be able to use main.js as standalone library
/////////////////////////////////////////////////////////////////////////////////////
function urlencode( str ) {
		// http://kevin.vanzonneveld.net
		// +   original by: Philip Peterson
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: AJ
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
		// *     example 1: urlencode('Kevin van Zonneveld!');
		// *     returns 1: 'Kevin+van+Zonneveld%21'
		// *     example 2: urlencode('http://kevin.vanzonneveld.net/');
		// *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
		// *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
		// *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
																		 
		var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
		var ret = str.toString();
		
		var replacer = function(search, replace, str) {
				var tmp_arr = [];
				tmp_arr = str.split(search);
				return tmp_arr.join(replace);
		};
		
		// The histogram is identical to the one in urldecode.
		histogram['!']   = '%21';
		histogram['%20'] = '+';
		
		// Begin with encodeURIComponent, which most resembles PHP's encoding functions
		ret = encodeURIComponent(ret);
		
		for (search in histogram) {
				replace = histogram[search];
				ret = replacer(search, replace, ret) // Custom replace. No regexing
		}
		
		// Uppercase for full PHP compatibility
		return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
				return "%"+m2.toUpperCase();
		});
		
		return ret;
}


function urldecode( str ) {
		// http://kevin.vanzonneveld.net
		// +   original by: Philip Peterson
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: AJ
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
		// *     example 1: urldecode('Kevin+van+Zonneveld%21');
		// *     returns 1: 'Kevin van Zonneveld!'
		// *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
		// *     returns 2: 'http://kevin.vanzonneveld.net/'
		// *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
		// *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
		
		var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
		var ret = str.toString();
		
		var replacer = function(search, replace, str) {
				var tmp_arr = [];
				tmp_arr = str.split(search);
				return tmp_arr.join(replace);
		};
		
		// The histogram is identical to the one in urlencode.
		histogram['!']   = '%21';
		histogram['%20'] = '+';
		
		for (replace in histogram) {
				search = histogram[replace]; // Switch order when decoding
				ret = replacer(search, replace, ret) // Custom replace. No regexing   
		}
		
		// End with decodeURIComponent, which most resembles PHP's encoding functions
		ret = decodeURIComponent(ret);
 
		return ret;
}


///- DATE& TIME

function dt_now(param) {
	var format = "dt";  if (param != undefined) { format = param;  }
	var dt = new Date(); 
	var o = "";
	
	var year = dt.getFullYear();
	var month = dt.getMonth()+1;
	if (month < 10) {
		month = "0"+month;
	}
	var day = dt.getDay()+1;
	if (day < 10) {
		day = "0"+day;
	}
	
	if (format == "d") {
		o = year+"-"+month+"-"+day;
	}
	
	return(o);
		
}

function dt_es(dt) {
	var o = "";
	var year = dt.substring(6,10);
	var month = dt.substring(0,2);
	var day = dt.substring(3,5);
	
	o = year+"-"+month+"-"+day;
	
	return(o);
}


function vld_url(url) {
  /*
  j.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
  if (!j.test(url)) {
  */
  
  if (url.indexOf(' ') != -1) { // has spaces
    return false;
  } else if (url.indexOf('.') == -1) { // has no . 
    return false;
  } else if (url.length < 5) { // to short to be valid
    return false;
  } else {
    return true;
  }
}

function BorderColor(id,color) {
  id.style.border = '1px solid '+color;
}

function str_chr2ord(input) {

  var character = "";
  var o = "";
  var za = 0;
  while (input.length > 0) { za++;
    character = input.substring(0,1);
    o+= "&"+ord(character)+";";
    input = input.substring(1);
    if (za > 1000000) { alert('out of bounds'); return; }
  }
  return o;
}


/**
* tabHighlight correlates with dsn_tabs
*/
function tabsHighlight(id)
{
	$('.tabs_highlight').each(function(){
		if ( $(this).attr('id') == id ) {
			if ( $(this).html() !== $(this).attr('name') ) {
				return;
			}
			else {
				$(this).html('<b><u>' + $(this).attr('name') + '</u></b>');
			}
		}
		else {
			$(this).html($(this).attr('name'));
		}
	});
}


/* jquery.tools */
(function(c){c.tools=c.tools||{version:{}};c.tools.version.tooltip="1.0.2";var b={toggle:[function(){this.getTip().show()},function(){this.getTip().hide()}],fade:[function(){this.getTip().fadeIn(this.getConf().fadeInSpeed)},function(){this.getTip().fadeOut(this.getConf().fadeOutSpeed)}]};c.tools.addTipEffect=function(d,f,e){b[d]=[f,e]};c.tools.addTipEffect("slideup",function(){var d=this.getConf();var e=d.slideOffset||10;this.getTip().css({opacity:0}).animate({top:"-="+e,opacity:d.opacity},d.slideInSpeed||200).show()},function(){var d=this.getConf();var e=d.slideOffset||10;this.getTip().animate({top:"-="+e,opacity:0},d.slideOutSpeed||200,function(){c(this).hide().animate({top:"+="+(e*2)},0)})});function a(f,e){var d=this;var h=f.next();if(e.tip){if(e.tip.indexOf("#")!=-1){h=c(e.tip)}else{h=f.nextAll(e.tip).eq(0);if(!h.length){h=f.parent().nextAll(e.tip).eq(0)}}}function j(k,l){c(d).bind(k,function(n,m){if(l&&l.call(this)===false&&m){m.proceed=false}});return d}c.each(e,function(k,l){if(c.isFunction(l)){j(k,l)}});var g=f.is("input, textarea");f.bind(g?"focus":"mouseover",function(k){k.target=this;d.show(k);h.hover(function(){d.show()},function(){d.hide()})});f.bind(g?"blur":"mouseout",function(){d.hide()});h.css("opacity",e.opacity);var i=0;c.extend(d,{show:function(q){if(q){f=c(q.target)}clearTimeout(i);if(h.is(":animated")||h.is(":visible")){return d}var o={proceed:true};c(d).trigger("onBeforeShow",o);if(!o.proceed){return d}var n=f.position().top-h.outerHeight();var k=h.outerHeight()+f.outerHeight();var r=e.position[0];if(r=="center"){n+=k/2}if(r=="bottom"){n+=k}var l=f.outerWidth()+h.outerWidth();var m=f.position().left+f.outerWidth();r=e.position[1];if(r=="center"){m-=l/2}if(r=="left"){m-=l}n+=e.offset[0];m+=e.offset[1];h.css({position:"absolute",top:n,left:m});b[e.effect][0].call(d);c(d).trigger("onShow");return d},hide:function(){clearTimeout(i);i=setTimeout(function(){if(!h.is(":visible")){return d}var k={proceed:true};c(d).trigger("onBeforeHide",k);if(!k.proceed){return d}b[e.effect][1].call(d);c(d).trigger("onHide")},e.delay||1);return d},isShown:function(){return h.is(":visible, :animated")},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return f},onBeforeShow:function(k){return j("onBeforeShow",k)},onShow:function(k){return j("onShow",k)},onBeforeHide:function(k){return j("onBeforeHide",k)},onHide:function(k){return j("onHide",k)}})}c.prototype.tooltip=function(d){var e=this.eq(typeof d=="number"?d:0).data("tooltip");if(e){return e}var f={tip:null,effect:"slideup",delay:30,opacity:1,position:["top","center"],offset:[0,0],api:false};if(c.isFunction(d)){d={onBeforeShow:d}}c.extend(f,d);this.each(function(){e=new a(c(this),f);c(this).data("tooltip",e)});return f.api?e:this}})(jQuery);





