
/**
*    Content constructor
*/
function CDropdownContent() {
	this.init();
}

/**
*     init
*/
CDropdownContent.prototype.init = function() {

	this.llista=new Array();
}

/**
*     addItem
*/
CDropdownContent.prototype.addItem = function(code,text,title) {
	try {
		var len=this.llista.length;
		this.llista[len]=new Object;
		this.llista[len].text=text;
		this.llista[len].title=title;
		this.llista[len].code=code;
	}
	catch (e) {
		alert("Error a CDropdown.addItem()\n" + e.message);
	}
}

/**
*     addSeparator
*/
CDropdownContent.prototype.addSeparator = function() {
	try {	
		var len=this.llista.length;
		this.llista[len]=new Object;
		this.llista[len].text="";
		this.llista[len].title="";
		this.llista[len].code="-";
	}
	catch (e) {
		alert("Error a CDropdown.addSeparator()\n" + e.message);
	}
}

/**
*     removeItem
*/
CDropdownContent.prototype.removeItem = function(code) {
	/*var len=this.codes.length;

	var i=0;
	while (this.codes[i]!=code) i++;
	if (i<=len) */
	alert("TODO:\nCDropdownContent.prototype.removeItem");
}

/**
*     length
*/
CDropdownContent.prototype.length = function() {
	return this.llista.length;
}

/**
*     getCode
*/
CDropdownContent.prototype.getCode = function(i) {
	return this.llista[i].code;
}
/**
*     getText
*/
CDropdownContent.prototype.getText = function(i) {
	return this.llista[i].text;
}
/**
*     getTitle
*/
CDropdownContent.prototype.getTitle = function(i) {
	return this.llista[i].title;
}

/**
*     toString
*/
CDropdownContent.prototype.toString = function() {
	return this.llista.toString();
}

/**
*	Ordena el contingut del dd segons el text.
*/
CDropdownContent.prototype.ordenaText = function() {
	this.llista.sort(this.compareText);
}

/**
*	Mètode utilitzat per reordenar la llista de continguts per el seu nom.
*	@param {CDropdownContent} a un contingut
*	@param {CDropdownContent} b un contingut
*/
CDropdownContent.prototype.compareText = function(a,b) {
	if (a.text<b.text) return -1;
	if (a.text>b.text) return 1;
	return 0;
}

//-----------------------------------------------------------------------
//-----------------------------------------------------------------------

	
/**
*     constructor
*     @param {Object} target element that will fire this dropdown
*     @param {CDropdownContent} contents El contingut a mostrar
*     @param {Number} width Permet especificar un width diferent al de defecte(180px)
*     @param {Number} maxHeight Permet especificar un height màxim. Quan el contingut supera aquest height apareix l'scroll.
*/
function CDropdown(target,contents,width,maxHeight) {
	//if ( arguments.length > 0 )
	this.init(target,contents,width,maxHeight);
}

/**
*     constructor
*     @param {Object} target element that will fire this dropdown
*     @param {CDropdownContent} contents El contingut a mostrar
*     @param {Number} width Permet especificar un width diferent al de defecte(180px)
*     @param {Number} maxHeight Permet especificar un height màxim. Quan el contingut supera aquest height apareix l'scroll.
*/
CDropdown.prototype.init = function(target,contents,width,maxHeight) {
	this.target=target;

	if (width) this.TOTALWIDTH=parseInt(width);
	else this.TOTALWIDTH=180;

	if (maxHeight) this.TOTALHEIGHT=parseInt(maxHeight);
	else this.TOTALHEIGHT=140;// = 10 elements

	this.contentsLength=contents.length();
	if (target!=null)this.targetHeight=target.offsetHeight;

	// currently selected div id
	this.wsCurrentSelId=-1;
	dropDownCurrentSelId=-1;
	var top=findPosY(target)+this.targetHeight;
	var left=findPosX(target);
	// create a new div in the html we'll fill with the dropdown
	this.ddDiv=document.createElement("div");
	this.ddDiv.setAttribute("id", "dropDownDiv");
	this.ddDiv.style.zIndex="10000";
	this.ddDiv.style.backgroundColor="#FFFFFF";
	this.ddDiv.style.border="1px solid #404040";
	this.ddDiv.style.borderBottom="2px solid #CCC8C0";
	this.ddDiv.style.position="absolute";
	this.ddDiv.style.top=top+"px";
	this.ddDiv.style.left=left+"px";
	
	
	//this.ddDiv.style.overflow="auto";
	//this.ddDiv.style.overflowX="hidden";
	//this.ddDiv.style.overflowY="visible";
	this.ddDiv.style.overflow="scroll";// ara hem de fer-ho aixi pq es vegi bé amb IE6
	this.ddDiv.style.overflowX="hidden";
	this.ddDiv.style.display="block";
//	this.ddDiv.style.width=(this.TOTALWIDTH)+"px";
	// nomes posem height si ens ha d'apareixer l'scroll. 1 element=14px height
	if (this.contentsLength*14>(this.TOTALHEIGHT)) this.ddDiv.style.height=this.TOTALHEIGHT+"px";

	
	this.ddDiv.innerHTML ='carregant...';

	//afegim el nou div al node BODY de l'html
	this.bodyN=document.getElementsByTagName("body")[0];
	this.bodyN.appendChild(this.ddDiv);

	window.dropdownMouseOver=this.dropdownMouseOver;
	window.dropdownMouseClick=this.dropdownMouseClick;
	window.dropdownHide=this.hide;
	window.dropdownObj=this;
	window.CDROPDOWN_IS_VISIBLE=false;

	// save current function for this event
	window.currentEventMouseDown=document.onmousedown;

	// If click is outside the dropdown closes it.
	document.onmousedown=function(evt){
		//DebugOut("CDropdown.mousedown()",DEBUG);
		if (!evt && window.event) evt=event;
		var tg = (evt.target) ? evt.target : evt.srcElement;
		//DebugOut("CDropdown.mousedown() target:"+tg.id,DEBUG);

		// Si click a fora el DD el tanquem
		if (tg && tg.id.indexOf("wsResult_")<0 && tg.id!="dropDownDiv" ) {
			window.dropdownHide();
		}
	}

	this.htmlCode=this.loadContents(contents);
	
}


/** 
*	Genera el codi html del dd a partir de l'objecte CDropdownContent
*
*	@param {CDropdownContent} contents Contingut a mostrar
*	@priv
*/
CDropdown.prototype.loadContents = function(contents) {
	var str="";

	var len=contents.length();
	for (i=0;i<len ;i++ ){
		if (contents.getCode(i)=="-") {//separador
			str+=this.getHtmlNewSeparator(i,contents.getCode(i),contents.getText(i),contents.getTitle(i));
		} else {
			str+=this.getHtmlNewItem(i,contents.getCode(i),contents.getText(i),contents.getTitle(i));
		}
	}
	return str;
}

/** 
*    Carrega uns valors per defecte, serveix per testejar.
*/
CDropdown.prototype.demoLoad = function() {
//	DebugOut(">>> demoLoad", DEBUG);
	
	var initTime = new Date();

	//>>var str="<table cellpadding='0' cellspacing='0' border='1'>";
	var str="";

	
	// create some items
	for (i=0;i<16 ;i++ ){
		str+=this.getHtmlNewItem(i,"code " + i,"text " + i,"title " + i);
	}

	
	this.htmlCode=str;

	//alert(new Date() - initTime);
}

//--------------------------------------------------------------------------


/** 
*    Returns the HTML header of the dropdown list
*	@priv
*/
CDropdown.prototype.getHtmlHeader = function() {
	var str='';
	return str;
}

/** 
*   Returns the HTML footer of the dropdown list
*	@priv
*/
CDropdown.prototype.getHtmlFooter = function() {
	var str='';
	return str;
}

/** 
*    Adds a new item to the dropdown list
*	@priv
*/
CDropdown.prototype.getHtmlNewSeparator = function(num,code,text,title) {

	var str='';
	str+='<div id="wsResult_'+num+'" cCode="'+code+'" cText="'+text+'" class="treeGroupTitle" style="background-color:#FFFFFF; text-overflow:ellipsis;overflow:hidden;white-space:nowrap; width:'+this.TOTALWIDTH+'px; cursor:pointer; valign:middle;" class="treeLevelTitle" title="'+title+'"><img src="img/blanc.gif" width="5px" height="5px"/><img src="img/separador.gif" width="'+(this.TOTALWIDTH-10)+'px" height="2px" /><img src="img/blanc.gif" width="5px" height="1px"/></div>';
	return str;
}

/** 
*    Adds a new item to the dropdown list
*	@priv
*/
CDropdown.prototype.getHtmlNewItem = function(num,code,text,title) {

	var str='';
	str+='<div id="wsResult_'+num+'" cCode="'+code+'" cText="'+text+'"  onMouseOver="javascript:window.dropdownMouseOver('+num+');" onClick="javascript:window.dropdownMouseClick('+num+');" class="treeGroupTitle" style="background-color:#FFFFFF; text-overflow:ellipsis;overflow:hidden;white-space:nowrap; width:'+this.TOTALWIDTH+'px; cursor:pointer;" class="treeLevelTitle" title="'+title+'"><img src="img/blanc.gif" width="5px" height="1px"/>'+text+'<img src="img/blanc.gif" width="5px" height="1px"/></div>';
	return str;
}

/** 
*    Adds a comment to the dropdown list
*	@priv
*/
CDropdown.prototype.getHtmlComment = function(text) {

	var str='';
	str+='<div id="wsComment" style="background-color:#FFFFFF; text-overflow:ellipsis;overflow:hidden;white-space:nowrap; width:190px" class="treeLevelTitle"><img src="img/blanc.gif" width="5px" height="1px"/>'+text+'<img src="img/blanc.gif" width="5px" height="1px"/></div>';
	return str;
}

/** 
*    Receives mouse over event
*	@priv
*/
CDropdown.prototype.dropdownMouseOver = function(divId) {
	try {
		
		//DebugOut("dropdownMouseOver()"+divId,DEBUG);
		
		var divObj_new=document.getElementById("wsResult_"+divId);
		if (divObj_new==null) {
			return;
		}

		// Primer desactivem tots
		try {
			var i=0;
			while (true) {
				var divObj_old=document.getElementById("wsResult_"+i);
				divObj_old.style.backgroundColor="#FFFFFF";
				divObj_old.style.color="#000000";
				i++;
			}
		}catch (e) {}

		// Activem el seleccionat
		divObj_new.style.backgroundColor="#0A246A";// blau clar: "#3875D7";
		divObj_new.style.color="#FFFFFF";
		
		this.wsCurrentSelId=divId;
		dropDownCurrentSelId=divId;
		return false;
	
	}
	catch (e) {
		alert("Error a CDropdown.dropdownMouseOver()\n"+e.message);
	}
}

/** 
*	Metode que s'executa en escollir un element del dd. S'ha de implementar en instanciar-lo.
*/
CDropdown.prototype.processFunction = function(code,text,title) {}


/** 
*	Receives mouse click event. 
*	@priv
*/
CDropdown.prototype.dropdownMouseClick = function(divId) {
	//DebugOut("CDropdown.dropdownMouseClick();",DEBUG);
	var divObj_new=document.getElementById("wsResult_"+divId);
	if (divObj_new==null) {
		this.wsCurrentSelId=-1;
		dropDownCurrentSelId=-1;
		return;
	}
	var title=divObj_new.getAttribute("title"); 
	var code=divObj_new.getAttribute("cCode");
	var text=divObj_new.getAttribute("cText");

	//alert("CLICK\n\ncode:" + code + "\ntext:" + text);
	if (code!="-") {
		window.dropdownHide();//this.hide();
		window.dropdownObj.processFunction(code,text,title);
	}
}


/** 
*    Hides the dropdown div
*	@priv
*/
CDropdown.prototype.hide = function() {
	DebugOut("CDropdown.hide();",DEBUG);
	
	var bodyN=document.getElementsByTagName("body")[0];
	var c=document.getElementById("dropDownDiv");
	try {
		bodyN.removeChild(c);
	} catch (e){}
	

	// Assign event to  handle keys pressed.
	
	window.dropdownMouseOver=null;
	window.dropdownMouseClick=null;
	window.dropdownHide=null;
	document.onkeydown=null;//TODO: save currently assigned method and then restore it.

	// restore onmousedown event;
	document.onmousedown=window.currentEventMouseDown;
	window.currentEventMouseDown=null;

	window.CDROPDOWN_IS_VISIBLE=false;

	
}

/** 
*    Shows the dropdown div
*     @param openUp if true shows the dd at the top of the target
*/
CDropdown.prototype.show = function(openUp) {

	this.wsCurrentSelId=-1;
	dropDownCurrentSelId=-1;
	this.ddDiv.style.visibility="hidden";
	this.ddDiv.innerHTML=this.htmlCode;
	
	if (openUp==true) {
		this.ddDiv.style.top=(parseInt(this.ddDiv.style.top)-this.targetHeight-this.ddDiv.offsetHeight)+"px";
	}

	this.ddDiv.style.visibility="visible";

	// Assign event to  handle keys pressed.
	document.onkeydown=this.eventKeyDown;

	window.CDROPDOWN_IS_VISIBLE=true;
}

/** 
*    Processes the key down events
*	@priv
*/
CDropdown.prototype.eventKeyDown = function(e) {
//	alert("eventKeyDown"+e);
	try {
		
		var KeyID = (window.event) ? event.keyCode : e.keyCode;

		//DebugOut("keydown. code:"+KeyID,DEBUG);

		var newId=-1;

		switch(""+KeyID) {
			case "38":	//up
			newId=dropDownCurrentSelId-1;
			if (newId>=0 ) dropdownMouseOver(newId);
			break;

			case "40":	//Down
			newId=dropDownCurrentSelId+1;
			if (newId>=0 ) {
				//alert("aki");
				dropdownMouseOver(newId);
			}
			break;

			case "13":	//Enter
			dropdownMouseClick(dropDownCurrentSelId);
			break;

			case "27":	//Esc
			dropdownHide();
			break;

		}
	}
	catch (e) {
		alert("Error a CDropdown.eventKeyDown()\n"+e.message);
	}


}


