var jnedfd=new Array();
var jnedinst=new Array();
var jareaids=new Array();
var jphpareaids=new Array();

/*
the jApplication class which is the center of our library
it contains important variables that are used in other methods
and the method to load on domready
@author:ben
*/
function jApplication(){
	//all the buttons from the application
	this.buttons = new Array();

	/*
	//we increment an array of code to execute once the dom is fully loaded
	@author:ben
	*/
	this.onDOMready = function(codePassed) {
		jCore.DOMcodeToFire.push(codePassed);
		//if it is the first time we come there we can go to the browserDOMready
		if(jCore.DOMfctset===false)	this.browserDOMready();
	}//endfct


	/*
	function to help us detect which browser we are on and use a specific method to load the code on domready
	@author:ben
	*/
	this.browserDOMready = function(){
		//we have been to that function so we flag it
		jCore.DOMfctset=true;

		//to know if the DOM is loaded on internet explorer
		//this is conditional compilation on internet explorer
		//we flag our entrance into that crazy conditional compilation thing
		jCore.flagIE=false;
		/*@cc_on @*/
		/*@if (@_win32)
			jCore.flagIE=true;
			var proto = "src='javascript:void(0)'";
			if (location.protocol == "https:") proto = "src=//0";
			document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
			var script = document.getElementById("__ie_onload");
			script.onreadystatechange = function() {
			    if (this.readyState == "complete") {
			        jCore.DOMready();
			    }
			};
		/*@end @*/

		//if we didn't flagIE that means we need for the winning browser
		if(!jCore.flagIE){
			//to know when the DOM is loaded on mozilla and opera 9
			if (document.addEventListener) {
				document.addEventListener("DOMContentLoaded", jCore.DOMready, null);
			}else{
				//identify safari
				if (/WebKit/i.test(navigator.userAgent)) {
					var _timer = setInterval(function() {
						if (/loaded|complete/.test(document.readyState)) {
							clearInterval(_timer);
							jCore.DOMready();
						}//endif
					}, 10);
				}else{
					//if it is another browser we load it in the window on load
	   				window.onload = jCore.DOMready;
				}//endif
			}//endif
		}//endif
	}//endfct

	/*
	run method
	the axis of all javascript action happening on our application
	@param string namekey : uniquely identify the button
	@param string extra : the string identifying an element in a listing, or passing the value of a checkbox in its content
	@author:ben
	*/
	this.run=function(namekey,extra,htmlEntity) {
		var curButton=this.buttons[namekey];

		//set the formobject for this turn
		this.form=eval('document.'+curButton['formName']);

		//for simple task which dont imply formsubmission we go there
		if(curButton['nosubmit'])	return this.simpleTask(curButton,extra);

		//for a listing task (type toggle) we go there for now
		if(curButton['listing'])	this.joobiTask(curButton,extra);

		//require element selected
		if(curButton['select'] && !this.checkSelection(curButton, namekey))	return false;

		//require confirmation to proceed
		if(curButton['confirm'] && !this.askConfirmation(namekey))	return false;

		//load data from nicedit instance to textarea
		this.loadNeditData();

		//load data from phpedit instance to textarea
		if(curButton['phpedit']) this.loadPHPeditData();

		//validate a form
		if(curButton['validation'] && !this.validate(curButton['formName']))	return false;

		//proceed with multiupload
		if(curButton['mlup'] && jmupload_instance[0].fileList.length>0)	return this.processMup(namekey,htmlEntity);

		//manage pagination navigation
		if(curButton['pagi']) this.navPagi(curButton['limitstart'],extra);

		//reset limitstart when changing filters
		if(curButton['cfil']) this.changeFilter(curButton['limitstart']);

		//right before submitting the form we disable the button
		if(curButton['disable'] && htmlEntity) this.disable(curButton,htmlEntity,'loading');

		//right before submitting the form we disable all the menus around
		if(curButton['disableAll']) this.disableAll();

		this.sendForm(curButton);

		//important do not remove that return false
		//this is most needed when we dont want to be redirected to the href specified in a link
		//we specify a full link in order not to be overriden through a <base> tag
		return false;
	}//endfct


	/*
	function to manage the main tasks used on a list toggle, order,sorting
	@param array curButton : containe all the button parameters
	@param mixed extra : contain extra parameters for the button
	@author:ben
	*/
	this.joobiTask=function( curButton,extra ) {
		switch(curButton['task']){
			case 'order':
				if(curButton['total']){
					for ( var j = 0; j <= curButton['total']; j++ ) {
						box = eval( 'this.form.em' + j );
						if ( box ) {
							box.checked = true;
						}//endif
					}//endfor
				}else{
					this.checkLine(extra);
				}//endif
				break;
			default:
				if(extra['em']){
					curButton['taskvar']+=extra['value'];
					this.tickBox(extra['em']);
				}//endif
		}//endswitch

		//to sort listings by columns
		if(curButton['sorting']){
			this.form.sorting.value = extra;
//			this.form.sorting_dir.value	= curButton['taskvar'];
			task=curButton['params'];
		}//endif

		//check that the taskvar hidden input exist and set its value based on what we get from the argument taskvar
		var testvar = eval(this.form.taskvar);
		if(testvar){
			this.form.taskvar.value=curButton['taskvar'];
		}//endif

		if(curButton['securedyid']){
			this.form.joobieids.value = eval('this.form.joobieids'+curButton['securedyid']).value;
		}
	}//endfct

	/*
	function to tick checkbox if they exist
	@comments:needs to be replaced with the checkline function
	*/
	this.tickBox=function(id){
		box = eval( 'this.form.'+id );
	    //if the element exists
	    if (box) {
	        box.checked = true;
	        this.form.boxchecked.value = 1;
	    }else{
	   		return false;
	   	}
	}//endfct




	/*
	function to disable all the clickable element in case we don't want to get out of that page until the process is finish
	@author : ben
	*/
	this.disableAll=function(){
		//disable link menu horizontal
		menuHori=document.getElementById("joobisubmenu");
		if(menuHori){
			menuHori.parentNode.parentNode.style.display='none';
		}//endif
		//disable toolbar button around that one
		//this.disableSib(button,htmlEntity,classChange);

		//disable cms menu
		switch(jCore.cms){
			case 'joomla15' :
				cmsToolbar=document.getElementById("header-box");
				break;
			case 'joomla10' :
			case 'mambot' :
				cmsToolbar=document.getElementById("myMenuID");
			default:
		}//endswitch
		if(cmsToolbar){
			cmsToolbar.style.display='none';
		}//endif
	}//endfct

	/*
	function to disable a button in the toolbar
	@author ben
	*/
	this.disable=function(button,htmlEntity,classChange){


		//the action of the link is different so that it goes back to the right place
		htmlEntity.onclick = function() {return false;}
		htmlEntity.className='disabledB';
		fChild=htmlEntity.firstChild;

		changeMyClass=null;

		//we look for the class to change depending on wether the button is centered or not
		if(fChild){
			switch(fChild.nodeName){
				case 'CENTER':
					x=fChild.firstChild;
					while(!(x.className.indexOf("jpng-") != -1))
				    {
				       x=x.nextSibling;
				    }
					changeMyClass=x;
					break;
				case 'DIV':
					changeMyClass=htmlEntity.firstChild;
					break;
				default:
					return true;//skip the class change if we do not have a class name to set
			}//endswitch

			//skip the class name change if changeMyClass could not be found
			if(changeMyClass){
				changeMyClass.className=classChange;
			}//endif
		}//endif

		return true;
	}//endfct



	/*
	function to route to the right simple task
	@param array button : identify the button on whch we do the check
	@author:ben
	*/
	this.simpleTask=function(button,extra) {

		switch(button['task']){
			/*
			this function check or uncheck all the boxes of a listing when the header checkbox is ticked
			and set the value of boxchecked which corresponds to the number of checkbox which are checked
			@formname: string the form on which we are working
			@author:ben
			*/
			case 'toggleAllBox':

				var i=button['limitstart'];

				//as long as there is an existing checkbox we just check it
				var currentElement = eval( 'this.form.em'+i);
				while (currentElement){
					this.checkLine('em'+i);
					i++;
					//go to the next check box
					currentElement = eval( 'this.form.em'+i);
				}//endwhile

				//if it is checked then we update the value number
				if (extra) this.form.boxchecked.value = i;
				else this.form.boxchecked.value = 0;
				break;
			case 'checkLine':

				this.checkLine(extra);
				break;

		}//endswitch
		return true;
	}//endfct


	/*
	function to flip on or off the display of an element
	@param string htmlId : the id of the html element
	@author:ben
	*/
	this.flip=function(htmlId) {
		htmlEntity=document.getElementById(htmlId);
		if(htmlEntity.style.display=='none') htmlEntity.style.display='block';
		else	htmlEntity.style.display='none';
	}//endfct

	/*
	function to flip on or off the display of child elements of an element
	@param string htmlId : the id of the html element
	@author:ben
	*/
	this.flipChild=function(htmlId) {

		htmlEntity=document.getElementById(htmlId);
		var i=0;
		for(i=0;i<htmlEntity.childNodes.length;i++){
			if(htmlEntity.childNodes[i].style.display=='none') htmlEntity.childNodes[i].style.display='block';
			else	htmlEntity.childNodes[i].style.display='none';
		}//endfo

	}//endfct

	/*
	function to select a line in a listing by just clicking on the table row
	*/
	 this.checkLine=function(boxid){
		boxRadio = eval( 'this.form.'+boxid);
		parentObj=boxRadio;

		runaway=false
		while(!runaway){
			//get the next parent dom NODE for the next round
			//we put if(parentObj) for all the listing where we dont have any checkbox or radiobutton
			if(parentObj) parentObj=parentObj.parentNode;

			//if we reach the body tag that means there is no tab there, let's return false
			if(parentObj && parentObj.nodeName=='BODY')	return false;
			if(parentObj && parentObj.nodeName=='TR')	runaway=true;
			//if parentObj is not set, we return false
			if(!parentObj) return false;
		}//endwhile

		//get the winner id and get the object so that we can play with it
		parentid=parentObj.getAttribute('id');
		box = document.getElementById(boxid);
		row = document.getElementById(parentid);

		//cases when we click on the check box straight away
		//the check box get checked before we run the function
		if(row.className.indexOf("rowSelected",5) == -1){
			if (box.checked == true){
				box.checked = false;
			}
		}
		//cases when we click on the check box straight away
		//the check box get unchecked before we run the function
		if(row.className.indexOf("rowSelected",5) != -1){
			if(box.checked == false){
				box.checked = true;
			}
		}

		if (box.checked == true){
			box.checked = false;
		 	this.form.boxchecked.value--;
		 	row.className = row.className.substring(0, 4);
		}else{
			if(box.type == 'radio'){
				if(this.form.boxchecked.value==1)	this.form.boxchecked.value--;
				var tr = document.getElementsByTagName("tr");
				for(var i=0;i<tr.length;i++) {
					cssclass=tr[i].className;
					if(cssclass.indexOf("rowSelected",5) != -1){
						cssclass = cssclass.substring(0, 4);
						tr[i].className = cssclass;
					}
				}

			}

			box.checked = true;
	 		this.form.boxchecked.value++;
	 		row.className += ' rowSelected';

		}//end if

		return true;
	}//endfct

	/*
	function to reset the pagination when we change the filter
	@tasksel: string the task on which we want to go
	@formname: string the form on which we are working
	@author:ben
	*/
	this.changeFilter=function(limitname) {

		limitstart = eval( 'this.form.'+limitname);
		if(limitstart)	limitstart.value='';

	}//endfct


	this.navPagi=function(limitname,extra){
		limitstart = eval( 'this.form.'+limitname);
		limitstart.value=extra;
	}
	/*
	function to close a popup
	@author:adrien
	*/
	this.popClose=function(){
		return window.parent.document.getElementById('sbox-window').close();
	}

		/*
	function to create a validation object and validate eventually the form or just a field
	@param string formName : identify the form on whch we do the check
	@author:ben
	*/
	this.validate=function(formname) {
		return validateForm(formname);
	}//endfct


	/*
	function to check that an element is selected in a listing
	@param string formName : identify the form on whch we do the check
	@author:ben
	*/
	this.checkSelection=function(curButton, namekey) {
		var form = eval('document.' + curButton['formName']);

		if(form.boxchecked.value==0){
			//TODO translate the message
			//alert('Please make a selection from the list to '+curButton['task']);
			alert(jCore.msg['selec_'+namekey]);
			return false;
		}

		return true;

	}//endfct

	/*
	function to ask confirmation to the user for the current action
	@author:ben
	*/
	this.askConfirmation=function(namekey) {
			if(confirm(jCore.msg['conf_'+namekey]))	return true;
			else return false;
	}//endfct


 	/*
	function to pass the data of the nedit to the textarea before saving
	@author:ben
	*/

	this.loadNeditData=function() {
		//go through all the nicedit values

		//if there is nicedit
		for (i = 0;i < jnedinst.length;i++){
			textbox=document.getElementById(jareaids[i]);
			//update the values
			if(jnedinst[i].innerHTML=='<br>')	textbox.value='';
			else textbox.value=jnedinst[i].innerHTML;
		}//endfor

		return false;
	}//endfct


 	/*
	function to pass the data of the phpedit to the textarea before saving
	@author:ben
	*/

	this.loadPHPeditData=function() {
		//go through all the nicedit values

		//if there is nicedit
		for (i = 0;i < jphpareaids.length;i++){
			textbox=document.getElementById(jphpareaids[i]);
			//update the values
			textbox.value=editAreaLoader.getValue(jphpareaids[i]);
		}//endfor

		return false;
	}//endfct

	/*
	function to process a multiple uploads of files
	@param string namekey : identify the button on whch we do the check
	@param object htmlEntity : the Htmlentity to return to the run function for button disabling
	@author:ben
	*/
	this.processMup=function(namekey,htmlEntity) {

		//check for multiple uploads to queue
		for(var i=0;i < jmupload_instance.length ;i++) {
			//if this is the last image we upload we set the mlup to false to flag it as finish and execute the getask as follow
			if(i==eval(jmupload_instance.length-1)){
			 	var uploadObject=eval(jmupload_instance[i]);

			 	//we create the call back function which will be called on upload completed
			 	uploadObject.options.onAllComplete = function(){
				 	joobi.buttons[namekey]['mlup']=false;
				 	return joobi.run(namekey,htmlEntity);
			 	}//endfct


			}//endif

			//if there is something to upload
			if(uploadObject.fileList.length>0){
				uploadObject.upload();
				return false;
			}//endif
		}//endfor
		return false;
	}//endfct


	/*
	function to submit the form based on different processes
	@param string namekey : identify the button on whch we do the check
	@author:ben
	*/
	this.sendForm=function(button) {

		//we get the form to be posted
		var form = eval('document.'+button['formName']);

		//we set the task if a task input exist
		var task = eval(form.task);
		if(task){
			form.task.value=button['task'];
		}//endif

		//to set the controller and do a redirect straight away
		if(button['controller']){

			//we set the controller if a controller input exist
			var contro = eval(form.controller);
			if(contro){
				contro.value=button['controller'];
			}//endif
		}//endif

		//if we do an ajax query we just send it to the write place
		if(button['ajx']==1){
			jCore.ajxprms['on']=button['ajx'];
			jCore.ajxprms['extfct']=button['ajxComplete'];
			jCore.ajxprms['div']='div'+button['formName'];
			jCore.ajxprms['url']=button['ajxUrl'];

			//this is to know that we are displaying pure text in the controller(php)
			var url=jCore.ajxprms['url']+'?nothing=true';

			//we make sure that there is an external function which exists
			//if the external function exist then we execute it onComplete of the posted data
			var func= eval('window.'+jCore.ajxprms['extfct']);

			if ( func ){
				var ajax = new Ajax(url, $merge({data: $(form).toQueryString()},{method: 'POST', onComplete : function(msg){func(msg,url,form);}}));
			}else{
				var ajax = new Ajax(url, $merge({data: $(form).toQueryString()},{method: 'POST', onComplete : function(msg){jwriteResponse(msg);}}));
			}

			//we execute the http request
			ajax.request();


		}else{//else we just post the form and refresh the current page
			//we try to post the form
			try {
				form.onsubmit();
			}catch(e){
				//if we have errors what do we do with them?
			}//endif

			//we submit the form now
			form.submit();
		}//endif

		if(button['popclose']){
			this.popClose();
		}

		// The refresh doesn't work very well so we don't refresh at all.
		//if(button['refresh']){
			//setTimeout(window.parent.location.reload(),1500);
		//}

		return true;
	}//endfct

}//endclass


//the object that we are gonna use to manage all kind of javascript
var joobi = new jApplication();




/*
the jCore object
it contains important variables that are used in other methods
@author:ben
*/
var jCore = {

	themecolor : 'red',
	site : '',
	confirm : [],
	nedit : false,
	ajxprms : [],
	mlup : false,
	DOMfctset : false,//fct to tell that we already set the dom function
	DOMcodeToFire : [],//array of function containing js code to fire on DOM loaded
	msg : [],//array of translated messages
	req : [],//required field per form

	//fire all the code which should be run on DOMready
	DOMready : function() {
		//execute all the functions added onDOMready
		for (i = 0;i < jCore.DOMcodeToFire.length;i++)	jCore.DOMcodeToFire[i]();
	}//endfct



};//endobject



/* function to check if the passed variable is a string
@testVar: mixed
@author:ben
*/
 function isString(testVar){
     return typeof testVar == 'string';
 }



/*
function which write a message into a div or any HTML container
@msg:can be anything including html
@div:the id of the div or container in which you want to write
@classes:if the class of the container needs to be specific
@append: append (true) or replace (false, default value)
@return: void
@author:ben
*/
function jwriteResponse(msg,div,classes,append){
	//if the div,class parameter is not specified then we take the one from the ajax param
	if(!div) div=jCore.ajxprms['div'];
	if(!classes) classes=jCore.ajxprms['extfct'];

	//we reach the div element
	mydiv=document.getElementById(div);

	//if the div exist then we try to write text in it
	if(mydiv){
		//if the css classname is not specified then we update it
		if(!mydiv.className)	mydiv.className = classes;

		//we append the message if required
		if(append){
			mydiv.innerHTML += msg;
		}else{
			mydiv.innerHTML = msg;
		}
	}//endif
}//endfct


/**
Function to delete an item from a cross table on the fly.
*/
function deletecross(url,form,eid,sid,id,map){
	var ajax = new Ajax(url,{
				postBody:'sid='+sid+'&eid='+eid+'&'+map+'='+id+'&map='+map
				}
				).request();
	div = 'jmpic_'+sid+'_'+eid+'_'+id;
	mydiv=document.getElementById(div);
	var myFx = new Fx.Style(div, 'opacity').addEvent('onComplete', function(){ mydiv.style.display='none'}); //display a transition from transparent to opaque.
	myFx.start(1,0);
}//endfct


/**
Function to toggle yesno and publish item
lala added
*/
function joobitoggle(url,map,valueto,sid,eid,xfrmajaxx,id,tyep,style,opt,cont){
	new Ajax(url+'&map='+map+'&valueto='+valueto+'&sid='+sid+'&eid='+eid+'&xfrmajaxx='+xfrmajaxx+'&id='+id+'&tyep='+tyep+'&style='+style+'&opt='+opt+'&cont='+cont,{
			method:'get',
			update:$(id),
		}).request();
}//endfct



/**
Function to build a list of images to insert in a nicedit.
@author:maud
*/
var mylist=new Array();
function makeImgList(vcheck,vimg){
	if (vcheck==true) { mylist.push(vimg); }
	else {
		var mynewlist=new Array();
		for (i = 0;i < mylist.length;i++){
			if(mylist[i]!=vimg) mynewlist.push(mylist[i]);
		}//endfor
		mylist=mynewlist;
	}
}//endfct



/**
Function to insert the selected images in the first nicedit area
@author:maud
*/
function processImages(){
	window.parent.document.getElementById('sbox-window').close();
	for (i = 0;i < mylist.length;i++){
		window.parent.jnedfd[0].execCommand('insertImage',false,mylist[i]);
	}//endfor
}//endfct

