/* global $j, __contextPath, ajaxCaller, defaultAjaxErrorHandler */
// 
// version 1.0.1
// 
// an associative array containing one element per Multiselect LOV on the page
// The key is the lov id, and the element is an array of LovItem objects
var _lovDefinitions = new Object();

// returns a reference to the multi-select lov definition object
// lovid: the id as it is giben to the control by the framework
function $multilov(lovid /* String */) {
	return _lovDefinitions[lovid];
}

// this object represents an lov "item" ie an item with an id/code and a description
function LovItem(_id, _description) {
	
	this.id = _id;
	this.description=_description;
	this.getlovDescrItem=getlovDescrItem;
	
	function getlovDescrItem(lovid, isReadOnly) {
	
		var cleanId = this.id.toString().replace(" ", "_");
		cleanId = cleanId.toString().replace(".", "_");
		cleanId = cleanId.toString().replace(",", "_");
		cleanId = 'lovrm'+cleanId;

		if(isReadOnly) {
			return '<span class="lovDescrItem">' + this.description +'</span>';
		} else {
			return '<span class="lovDescrItem"><a href="javascript:__removeLovItem(\''+ lovid +'\',\''+ this.id +'\')">' + 
					this.description +'&nbsp;<img border=0 name=\''+cleanId+'\' onmouseover="lovRmButtonDown(\''+cleanId+'\')"'+
					' onmouseout="lovRmButtonUp(\''+cleanId+'\')" ' +
					' title=\"Click to remove\" align="absmiddle" src=\"'+ 
					 nuf.getResource('xNormal.gif') + '\"/></a></span>';
		}
		
	}
}

// this object follows the java object LOVDefinition
function LovDefinition(lovFieldId, lovKey, title, multiselect, pageSize, colLabel, width, height, isReadOnly) {
	
	if(!lovKey)alert('Error, no lovKey passed!');
	
	// note: do NOT bring down the sql datasource it is insecure
	// this.dataSource = null; <-- this is insecure, do not do it! -->
	this.lovFieldId = lovFieldId;
	this.lovKey = lovKey;
	this.pageSize = pageSize;
	this.width = width;
	this.height = height;
	this.colLabel = colLabel;
	this.lovPageTitle = title;
	this.multiselect = multiselect;
	this.isReadOnly = isReadOnly;
	
	//lovHtmlData holds responses from the data servlet 
	// so we don't hit the server every time the user shows the LOV
	this.lovHtmlData = '';
	
	// this is an associative array (hashtable) with all the seledcted 
	// items.  The keys of the hash are the codes (ids)
	this.selectedItems = new Object();
	
	this.addAllHandler = null; // reference to a function that executes after click all button. The first argument will be the id of the control
	this.addItemHandler = null; // reference to a function that executes after click all button
	this.removeItemHandler = null; // reference to a function that executes after click all button
	
	
}

// add a new LOV definition to the 
// _lovDefinitions assoiative array. ATTENTION: this java script function 
// is called from java code in LOVMultiple tag
function __addLovDefinition(lovdef /*:LovDefinition*/) {
	
	if(_lovDefinitions[lovdef.lovFieldId]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovdef.lovFieldId + ' already exists!');
		return;
	}
	
	_lovDefinitions[lovdef.lovFieldId] = lovdef;
}

function __modifyMultiSelectLOVDatasource(lovid /*:String*/, newDataSource /*:String*/) {
	
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + ' already exists!');
		return;
	}
	
	var lovdef = _lovDefinitions[lovid];
	lovdef.lovHtmlData = null;
	
	var vars = new Array();
	vars['action'] = 'setDataSource';
	vars['globalLOVKey'] = lovdef.lovKey;
	vars['newDataSource'] = newDataSource;
	
	ajaxCaller.postForPlainText(__contextPath + '/LovServlet', vars, __onModDatasourceLOVResponse, lovid);	
}

function __onModDatasourceLOVResponse(content, headers, callingContext) {
	// this is just a place holder for __modifyMultiSelectLOVDatasource responce
}

function __addAllLovItems(lovid /*:String*/) {
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + ' already exists!');
		return;
	}
	
	var lovdef = _lovDefinitions[lovid];
	lovdef.lovHtmlData = null;
	
	var vars = new Array();
	vars['action'] = 'MultiSelectLovSelectAll';
	vars['globalLOVKey'] = lovdef.lovKey;
	
	ajaxCaller.postForPlainText(__contextPath + '/LovServlet', vars, __onAddAllLovItemsResponse, lovid);	
}

function __onAddAllLovItemsResponse(content, headers, callingContext) {
	
	if (content) {
		
		var obj = jQuery.parseJSON(content);
		var lovid = obj['lovid'];
		var data = obj['data'];
	
		for(var i=0; i < data.length; i++) {
			var lovitem = data[i];
			 __addLovItem(lovid, lovitem[0], lovitem[1]);
		 }
		if($multilov(lovid).addAllHandler ) {
			$multilov(lovid).addAllHandler.call(this,lovid) ;
		}
		__updateLovDisplay(lovid);

	}
}

function filterValues(lovid){
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + 'not found!');
		return;
	}
	var lovdef = _lovDefinitions[lovid];
	
	var vars = {};

	vars['globalLOVKey'] = lovdef.lovKey;
	vars['lovFieldId'] = lovid;
	
	var searchField = document.getElementById('searchField');
	vars['searchField'] = searchField && searchField.value;
	vars['SKIP_SET_CHARACTER_ENCODING'] = 1;
	
	$j.ajax(
		{	cache: false,
			async: false,
			type: "POST",
			dataType:'text',
			url: __contextPath + '/LovServletGridRenderer',
			success: function(content){
				replaceResponseDiv('popupLOVGrid', content);
				if (content.toString().length<=100000) {
					// if data is up to 100K, store for later use :-)
					var lovdef = _lovDefinitions[lovid];
					lovdef.lovHtmlData = content; 
				}
				__showLOVPopup(lovid);	
			},
			data: vars,
			timeout: 30*1000, // allow up to 20 seconds
			error: defaultAjaxErrorHandler
		});
}

/**
 * This function adds an lov item object to the _lovDefinitions
 * collection.
 */
function __addLovItem(lovid, id, description) {
	
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + 'not found!');
		return;
	}
	var lovdef = _lovDefinitions[lovid];
	var newlovitem;
	
	if(lovdef.selectedItems[id]) {
		newlovitem = lovdef.selectedItems[id];
		newlovitem.description = description;
		
	} else {
		newlovitem = new LovItem(id, description);
		lovdef.selectedItems[id] = newlovitem;
	}
	
}
/**
 * Remove an item from lov collection of lovid with id
 */
function __removeLovItem(lovid, id) {
	
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + 'not found!');
		return;
	}
	var lovdef = _lovDefinitions[lovid];
	if(lovdef.selectedItems[id]) {
		delete lovdef.selectedItems[id];
	}
	__updateLovDisplay(lovid);
}

/**
 * This function clears all items of an lov
 */
function __clearLovItems(lovid) {
	
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + 'not found!');
		return;
	}
	var lovdef = _lovDefinitions[lovid];
	lovdef.selectedItems = new Object();
	__updateLovDisplay(lovid);
	
}


/**
 * Shows the LOV popup div
 */
function launchLovPopup(lovid) {
	
	if(!_lovDefinitions[lovid]) {
		// if this does not exist, it means we did not add it on page load
		alert('Error: lov definition for ' + lovid + 'not found!');
		return;
	}
	var lovdef = _lovDefinitions[lovid];
	
	// first: check of lovHtmlData has data for this lOV.
	if (lovdef.lovHtmlData) {
		replaceResponseDiv('popupLOVGrid', lovdef.lovHtmlData);
		__showLOVPopup(lovid);
		return;
	}
	
	var vars = {};

	vars['globalLOVKey'] = lovdef.lovKey;
	vars['lovFieldId'] = lovid;
	
	$j.ajax(
			{	cache: false,
				async: false,
				type: "POST",
				dataType:'text',
				url: __contextPath + '/LovServletGridRenderer',
				success: function(content){
					replaceResponseDiv('popupLOVGrid', content);
					if (content.toString().length<=100000) {
						// if data is up to 100K, store for later use :-)
						var lovdef = _lovDefinitions[lovid];
						lovdef.lovHtmlData = content; 
					}
					__showLOVPopup(lovid);	
				},
				data: vars,
				timeout: 30*1000, // allow up to 20 seconds
				error: defaultAjaxErrorHandler
			});

}

function __showLOVPopup(lovid) {
	
	var lovdef = _lovDefinitions[lovid];
	if(!lovdef){
		alert('ERROR: lovdef with name:'+ lovid +' not found!!');
		return;
	}
	if(!$('popupLOVtitle'))alert('popupLOVtitle not found');
	$('popupLOVtitle').innerHTML = lovdef.lovPageTitle;
	$j("#popupLOV").height= lovdef.height;
	$j("#popupLOV").width= lovdef.width;
	
	__centerLOVPopup();
	//load popup
	loadPopup();
	
	// update checkboxes!
	var numrows = $(lovid+'_numrows').value.IntegerPart();
	for(var rownum=0;rownum<=numrows;rownum++) {
		var itm = $('lovitm'+rownum);
		var code = itm.getAttribute('lovCode');
		itm.checked = lovdef.selectedItems[code] != null;
	}

}


//SETTING UP OUR POPUP
//0 means disabled(hidden); 1 means enabled(shown);
nuf.lovPopupStatus = 0;


function loadPopup(){
//loading popup with jQuery magic!
//loads popup only if it is disabled
	if(__lovPopupStatus===0){
		$j("#popupLOVbackground").css({
			"opacity": "0.7"
		});
		$j("#popupLOVbackground").fadeIn("slow");
		$j("#popupLOV").fadeIn("slow");
		__lovPopupStatus = 1;
	}
}

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(__lovPopupStatus===1){
		$j("#popupLOVbackground").fadeOut("slow");
		$j("#popupLOV").fadeOut("slow");
		__lovPopupStatus = 0;
	}
}


//centering popup
function __centerLOVPopup(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth||document.documentElement.scrollWidth;
	var windowHeight = document.documentElement.clientHeight||document.documentElement.scrollHeight;
	
	var popupHeight = $j("#popupLOV").height();
	var popupWidth = $j("#popupLOV").width();
		
	//centering
	$j("#popupLOV").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	$j("#popupLOVbackground").css({
		"height": windowHeight,
		"width": windowWidth
	});

}

//Press Escape event!
$j(document).bind('keydown', function (e) {
	e = e?e:event;
	if(e.keyCode===27 && __lovPopupStatus===1){
		disablePopup();
	}
});

function __onFilterBtnKeyDown(e, lovId){
	e = e?e:event;
	if(e.keyCode===13 && __lovPopupStatus===1){
		filterValues(lovId);
		
		var searchField = $j('#searchField');
		var strLength = searchField.val().length;
		searchField.focus();
		searchField[0].setSelectionRange(strLength, strLength);		
	}
}

function __selectLovItem(lovId, rowNumber) {
	$('lovitm'+rowNumber).checked = true;
	__updateSelectedLOVItems(lovId);
}

function __updateSelectedLOVItems(lovid) {
	
	var numrows = $(lovid+'_numrows').value.IntegerPart();
		
	for(var rownum=0;rownum<=numrows;rownum++) {
		var itm = $('lovitm'+rownum);
		if(itm.checked) {
			__addLovItem(lovid, itm.getAttribute('lovCode'), itm.getAttribute('lovDescr'));
		}
	}
	__updateLovDisplay(lovid);
}

function __updateLovDisplay(lovid) {
	var lovdef = _lovDefinitions[lovid];
			
	var itmsArray = lovdef.selectedItems;
	var lovDescriptions = new Array();
	var lovCodes = new Array();
	for(var key in itmsArray) {
		var lovitem = itmsArray[key];
		lovDescriptions[lovDescriptions.length]=lovitem.getlovDescrItem(lovid, lovdef.isReadOnly);
		lovCodes[lovCodes.length]=lovitem.id;
	}
	
	$j('#Display_' + lovid).html( lovDescriptions.join());
	$(lovid).value = lovCodes.join();
}

function lovRmButtonUp(imgName) {
	if (document.images) {
		document[ imgName ].src =nuf.getResource('xNormal.gif');
	}
}
function lovRmButtonDown(imgName) {
	if (document.images) {
		document[ imgName ].src = nuf.getResource('xBlack.gif');
	}
}

$j(document).ready(function() {

	var POPUP_DIVS = 
			  "<div id=\"popupLOV\" style=\"position: absolute;\">"
			+ "  <div id=\"popupLOVheader\">"
			+ "    <div id=\"popupLOVtitle\">Select LOV value</div>"
			+ "    <div id=\"popupLOVClose\" onclick=\"disablePopup()\" style=\"background:url("+nuf.getResource('dialog_close.gif') + ") no-repeat\" ></div>"
			+ "  </div>" 
			+ "  <div id=\"popupLOVGrid\"></div>"
			+ "</div>"
			+ "<div id=\"popupLOVbackground\" onclick=\"disablePopup()\"></div>";
	
	$j('body').append(POPUP_DIVS);
	
});


