var wasDrag = false;
var triedDrag = false;
var lastSelected = null;
var hTable;
var sel;

var DROPFOLDER = "dropfolder";
var DRAGFILE = "dragfile";
var SEARCHFILE = "searchfile";
var CHECKBOXNAME = "PublicObjectListItemTag_PUBLICOBJECT_ID";

/**
* Checks or unchecks all checkboxes with a given name within a given form
* @param form the form containing the checbox(es)
* @param checkboxName Name of the checkbox(es)
* @param value The value to set for checked (true/false)
*/
function setCheckBoxValue(form, checkboxName, value)
{
	var objCheckBoxes = form.elements[checkboxName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = value;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = value;
}
	


/*function _openNewWindow(content, name, specifics)
{
	window.open(content,name,specifics);
}*/

function openNewWindow(content, name, specifics)
{
        var w = window;
        if ( window.dialogArguments ) {
                w = dialogArguments.Editor;
        }
        var newWin = w.open(content,name,specifics);

        window.onunload = newWin.opener.onunload = function(){
	        	newWin.close();
	        };
	        
        newWin.opener = window;
}

function windowOnload() 
{
	if(window.initFolders)
	{
  		initFolders();
	} 
  	
  	if(window.initFiles)
  	{
  	  	initFiles();
  	}
  	
  	if(window.initEditor)
  	{
  		initEditor();
	}
	
	if(window.doWindowOnload)
  	{
  		doWindowOnload();
	}
	
	registerCheckBoxes();
	
}

function doDownload()
{
	var items="";
	  	
  	for ( id in selected )
	 { 
 		
  		if(selected[id]==1)
  		{
	  		if(items!="")
	  		{
	  			items+="***";
	  		}
	  			
	  		items+=id;
  		}
     }

     document.downloadform.items.value=items;			
	 document.downloadform.submit();
}

function deleteItems()
{
	var items="";
	if (confirm("Bent u zeker dat u de geselecteerde items wil verwijderen?")){ 	
  	for ( id in selected )
	 { 
  		if(selected[id]==1)
  		{
	  		if(items!="")
	  		{
	  			items+="***";
	  		}
	  			
	  		items+=id;
  		}
     }

     document.deleteform.items.value=items;			
	 document.deleteform.submit();
	 }
	 
}

function makeSelectable(id)
{
with( document.getElementById( id ).cbe ) {
      show();
      addEventListener('drag', ddOnDragNoAction);
      addEventListener('mouseup', mu );      
      //addEventListener('dragEnd', ddEndListener, false);
      zIndex(1);
      ondrag = ddOnDragNoAction;
      }
}

/**
* Makes an item in the beheer TOC visible and szlectable but not dragable
* @param id The if of the element within the HTML document
*
*/
function makeVisibleWithoutDragable( id )
{
	 	with( document.getElementById( id ).cbe ) 
	 	{
	      show();
	      addEventListener('mouseup', mu );
	    }
}

function makeDragable( id ) {
  	
  	with( document.getElementById( id ).cbe ) {
      show();
      addEventListener('drag',ddOnDrag);
      addEventListener('dragEnd', ddEndListener,false );
      addEventListener('mouseup', mu );
      addEventListener('dragStart', startDrag );      
      zIndex(1);
      ondrag = ddOnDrag;
    }
  }
  
  function makeDropable( id ) {
		with ( document.getElementById(id).cbe) {
			show();
    	}
  }
  
  function startDrag(e)
  {  	
 	startLeft=e.cbeTarget.pageX();
    startTop=e.cbeTarget.pageY();
    sel=e.cbeTarget.id;
  }
  
  function ddOnDragNoAction(e){
  	triedDrag = true;  	
  }
    
  function ddOnDrag(e) {  	    	 
  	  	
  	for ( id in selected ) 
  		if ( ( selected[id] == 1 ) && ( id != e.cbeTarget.id ) )
  			if (allowDrag(id)) cbeGetElementById( id ).cbe.moveBy(e.dx,e.dy);

 	e.cbeTarget.moveBy(e.dx,e.dy);
	
	wasDrag = true;				
	if ((document.getElementById || document.layers) && !is.ie) {

        yMousePos = e.pageY;
        yScrollPos = document.cbe.scrollTop();
        yMousePosMax = window.innerHeight+window.pageYOffset;
        
        if (yMousePos - yScrollPos <= 5 || yMousePos >= yMousePosMax - 5){cbeDragEndEvent(e);}          
    }

  }
  
  function countSelected(){
  	var c = 0;
  	for (id in selected) if (selected[id] ==1)c++; 
  	return c;
  
  }
  
  function allowDrag(type){
  
  	var t = type.lastIndexOf("_");
	type = type.substring(0, t);
	if (type == SEARCHFILE) {return false;}
	else {return true; }
  	
  }
  
  function isDroppable(type){
    	    	
		var t = type.lastIndexOf("_");
		type = type.substring(0, t);
		if (type == DROPFOLDER) {return true;}
		else {return false; }
  
  }
  
  function ddEndListener(e) {  	 	  
	  
	  var px = e.cbeTarget.pageX();
	  var py = e.cbeTarget.pageY();
	  	  
	  if (!allowDrag(e.cbeTarget.id)) alert("tried dragaction");
	  
	  var dropTarget = cbeGetNodeFromPoint(e.pageX, e.pageY, e.cbeTarget.id);	 
	  if (dropTarget && dropTarget.index > 1 && isDroppable(dropTarget.id)) 
	  {	  
	  
	  	var items="";
     	selected[e.cbeTarget.id]=1;
     	var undo=false;

	  	for ( id in selected )
		 { 
		 	
		 	if(selected[id]==1)
  			{
		  		if(items!="")
		  		{
		  			items+="***";
		  		}
	  			
	  			items+=id;
	  		}
	  		
		}
	  		
	  	if(e.shiftKey)
  		{
  			//The shift key means Make a link
  			
  			if(confirm("Bent u zeker dat u een link wil maken naar de geselecterde objecten?"))
  			{
				document.linkform.items.value=items;			
				document.linkform.folder.value=dropTarget.id;
				document.linkform.submit();
			}
			else
			{
				undo=true;
			}
		}
		else if(e.ctrlKey)
		{
			//ctrl means copy file
			if(confirm("Bent u zeker dat u de geselecteerde objecten wil kopieren?"))
  			{
				document.copyform.items.value=items;			
				document.copyform.folder.value=dropTarget.id;
				document.copyform.submit();
			}
			else
			{
				undo=true;
			}
		}
		else
		{
			//no special key used -> move item
			if(confirm("Bent u zeker dat u de geselecterde objecten wil verplaatsen?"))
  			{
				document.moveform.items.value=items;			
				document.moveform.folder.value=dropTarget.id;
				document.moveform.submit();
			}
			else
			{
				undo=true;
			}
		}

	  }
	  else
	  {
	  	undo=true;
	  }
	  
	  if(undo)
	  {	  	
	  	var gox=startLeft - px;
	  	var goy=startTop - py;

	  	for ( id in selected ) 
  			if ( ( selected[id] == 1 ) && ( id != e.cbeTarget.id ) )
  			if (allowDrag(id))  cbeGetElementById( id ).cbe.moveBy(gox,goy);
 		e.cbeTarget.moveBy(gox ,goy);
	  }
	} 
  
  function mu(e) {
  	var last = lastSelected;	
	
  	//just a click, no dragging
	if (!wasDrag){			
		if(e.ctrlKey){
		  	if ( selected[e.cbeTarget.id] == 1) {
		  		if(!triedDrag){
			  		unSelect(e);
			  		if (countSelected() == 1) lastSelected = 2;
			  		else lastSelected = e.cbeTarget.index; 
			  	}
		  	} 
		  	else {
		  		select(e, e.cbeTarget.id); 			  		
		  		lastSelected = e.cbeTarget.index;
		  		}
		 }
		 
		 else if(e.shiftKey){
		 	if (last == null) { 
		 		makeSelection(2, e.cbeTarget.index); 		
		 	}
		 	else {
		 		if(!triedDrag) clearSelection();				
  				
  				if (last < e.cbeTarget.index) makeSelection(last, e.cbeTarget.index);
  				else makeSelection(e.cbeTarget.index, last);  							
		 	}		
		 	lastSelected = last;		 	
		 }
		 
		 else {			
		 	if ( selected[e.cbeTarget.id] == 1 && countSelected() == 1) {			 	
			 	//clearSelection();			 
		  		if (!triedDrag) {
		  			unSelect(e);
		  			lastSelected = 2;
		  			}
		  	} 
		  	else {
			  	if (!triedDrag) clearSelection();			  					  	
			  	
			  	select(e, e.cbeTarget.id);  	
			  	lastSelected = e.cbeTarget.index;
		  		}		 	
		 }
		 		 
  	}
  	//it was a drag
  	else { 
  		select(e, sel);  	
  		}
	
	wasDrag = false;
	triedDrag = false;
  	
  }  
  
  function changeImage(image, on){
  	var temp = image.src.substring(image.src.lastIndexOf("/"),image.src.length);
  	
  	if (temp == sltFile.substring(sltFile.lastIndexOf("/"), sltFile.length) 
  		|| temp == dsltFile.substring(dsltFile.lastIndexOf("/"), dsltFile.length)){
  	
  		if (on) image.src = sltFile;
  		else image.src = dsltFile;
  	
  	}
  	
  	else{
  	
  		if (on) image.src = sltMap;
  		else image.src = dsltMap;
  	
  	}
  
  }
  
  	function unSelect(e){
  		var el = cbeGetElementById( 'img_' + e.cbeTarget.id );
  		selected[e.cbeTarget.id] = 0;
  		e.cbeTarget.zIndex(1);
  		e.cbeTarget.background("transparent");	
  		changeImage(el, false);
  		linkCheckBoxes(/*cbeGetElementById(elemId)*/e.cbeTarget, "inactive");
  		//el.src = '/lips/images/fedpol/selectOff.gif';
  	}
  	
  	function clearSelection(){
		var el2, count;
		lastSelected = null;

		for ( id in selected ) 	{	 	
  				if ( ( selected[id] == 1 )){
  					selected[id] = 0;
  				  	el2 = cbeGetElementById( 'img_' + id );			
  					changeImage(el2, false);//el2.src = '/lips/images/fedpol/selectOff.gif';
  					cbeGetElementById( id ).cbe.background("transparent");
  					cbeGetElementById( id ).cbe.zIndex(1);  			
  					linkCheckBoxes(cbeGetElementById( id ), "inactive");		  					
  				}    				
  		}
	}
	
	function clearSelectionPList(){
		var cBoxes = hTable.values();
		
		for (var i=0; i < cBoxes.length; i++){
			cBoxes[i].checked = false;
		}
	}  	  
 	
 	function select(e, slt){
 		var el = cbeGetElementById( 'img_' + slt );
 		selected[slt] = 1;
 		
 		var ell = cbeGetElementById(slt);
  		ell.cbe.zIndex(0);  		
  		ell.cbe.background("#E2E8EC");
  		changeImage(el, true);//el.src = '/lips/images/fedpol/selectOn.gif';	
  		linkCheckBoxes(ell, "active");	
 	}
 	
	function makeSelection(begin, end){
		var el3;

		for (i = begin; i <= end; i++){  				
  					el3 = cbeGetElementById( 'img_' + cbeAll[i].id );
		 			changeImage(el3, true);//el3.src = '/lips/images/fedpol/selectOn.gif';
		 			cbeAll[i].zIndex(0);
		 			cbeAll[i].background("#E2E8EC");
		 			selected[cbeAll[i].id] = 1;  				
		 			linkCheckBoxes(document.getElementById(cbeAll[i].id), "active");
  				}  		  				
	}
	
	/*
		Select a dragable item and make sure that the corresponding checkbox is checked
	*/
	function selectAll(){
		var comp;
		var ok = true;		
		for (i = 1; i <= cbeAll.length && ok;i++){
			comp = cbeAll[i].id;
			comp = comp.substring(0, comp.lastIndexOf("_"));
			//alert(cbeAll[i].id);
			if (comp == DRAGFILE || comp==SEARCHFILE){
				selected[cbeAll[i].id] = 1;
		  		cbeAll[i].zIndex(0);
		  		cbeAll[i].background("#E2E8EC");		  		
		  		changeImage(cbeGetElementById('img_' + cbeAll[i].id), true);//cbeGetElementById( 'img_' + cbeAll[i].id ).src = '/lips/images/fedpol/selectOn.gif';
		  		linkCheckBoxes(document.getElementById(cbeAll[i].id), "active");
			}
			else if (comp != "" && comp == DROPFOLDER) ok = false;		
		}	
	}
		
	/*
		Check all item checkboxes in the publishlist, there's no dragable file linked 
		to a checkbox.
	*/
	function selectAllPList(){
		var cBoxes = hTable.values();
		
		for (var i=0; i < cBoxes.length; i++){
			cBoxes[i].checked = true;
		}
	}		
 
  function de( e ) {alert("de");
  	alert( e.cbeTarget.id );
  	alert( e.cbeCurrentTarget.id );
  	alert( e.cbeRelatedTarget.id );
  }
  
	function cbeGetNodeFromPointExclusive(x, y, id) {//alert("cbeGetNodeFromPointExclusive");
		var hn /* highNode */, hz=0 /* highZ */, cn /* currentNode */, cz /* currentZ */;
		hn = document.cbe;
		while (hn.firstChild && hz >= 0) {
		
			hz = -1;
			cn = hn.firstChild;
			while (cn) {
			
			if (cn.contains(x, y)) {
				if (cn.id != id ) {
			     cz = cn.zIndex();
			     if (cz >= hz) {
				    hn = cn;
			   	 hz = cz;
			  	}
			  }
			}
			cn = cn.nextSibling;
		}
  }
  return hn;
}


//*************** change cursor on drag ***********
function checkBrowser(){
	this.ver=navigator.appVersion
	this.dom=document.getElementById?1:0
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0;
	this.ie4=(document.all && !this.dom)?1:0;
	this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie5 || this.ie4 || this.ns4 || this.ns5)
	return this
}

function cursorInit(){
	oCursor=new makeCursorObj('divCursor')
	scrolled=bw.ns4 || bw.ns5?"window.pageYOffset":"document.body.scrollTop"
	if(bw.ns4)document.captureEvents(Event.MOUSEMOVE)
	document.onmousemove=move;
}

function makeCursorObj(obj,nest){
	nest=(!nest) ? '':'document.'+nest+'.'										
   	this.css=bw.dom? document.getElementById(obj).style:bw.ie4?document.all[obj].style:bw.ns4?eval(nest+"document.layers." +obj):0;														
	this.moveIt=b_moveIt; 																	
	return this
}

function b_moveIt(x,y){this.x=x; this.y=y; this.css.left=this.x; this.css.top=this.y}

function move(e){
	x=bw.ns4 || bw.ns5?e.pageX:event.x
	y=bw.ns4 || bw.ns5?e.pageY:event.y
	if(bw.ie4 || bw.ie5) y=y+eval(scrolled)
	oCursor.moveIt(x+fromLeft,y+fromTop)
}

//******************** new layout *******************//

function selectionAction(action){
	if (action == "all") selectAll();
	if (action == "del") deleteItems();
	if (action == "none") clearSelection();
	if (action == "allPList") selectAllPList();
	if (action == "nonePList") clearSelectionPList();
}

/*
Store all checkboxes in a hashtable and add an eventlistener to everyone of them
*/
function registerCheckBoxes(){
	var inp = document.getElementById("contentOverview");
	
	if (inp) {
		hTable = new Hashtable();
		inp = inp.getElementsByTagName("INPUT");
		for (var i = 0; i < inp.length; i++){
			if (inp[i].type == "checkbox") {
				hTable.put(inp[i].value, inp[i]);
				try{
						inp[i].addEventListener('click', cBoxClickAction, false);
				}
				catch(e){inp[i].attachEvent('onclick', cBoxClickActionIE);}
			}
		}
	}	
}

/*
Get the checkbox by the id of the element and check or uncheck the box
*/
function linkCheckBoxes(elem, markup){
	var val = elem.id.substring(9, elem.id.length);
	var cBox = hTable.get(val);
	
	if (markup == "active"){
		cBox.checked = true;		
	}
	else if (markup == "inactive"){
		cBox.checked = false;
	}		 	
}

function cBoxClickAction(e){cBoxClick(e, e.currentTarget);}
function cBoxClickActionIE(e){cBoxClick(e, event.srcElement);}

function cBoxClick(e, cBox){
	 	var dragFile = cbeGetElementById(DRAGFILE+"_"+cBox.value);
		//Apparently the box is checked first and then the action gets executed
		if (dragFile){
			if (cBox.checked == true) select(e, dragFile.id);
			else if (cBox.checked == false) uSelect(dragFile);
		}
}

function uSelect(dragFile){
		var elemId = dragFile.id;
  		var el = cbeGetElementById( 'img_' +  elemId);
  		selected[elemId] = 0;
  		dragFile.style.zIndex = 1;
  		dragFile.style.background = "transparent";
  		changeImage(el, false);
}

