﻿// -- New code (michalstanko 2009-01-19)
jQuery.micronnexus = {}; // namespace
        
jQuery.micronnexus.wsCache = {}; // cache for web services reponses

jQuery.micronnexus.callWebService = function(url, callbackFunc, data) {
	var jsonString = $.compactJSON(data); // from jquery.json-1.3.js
	
	var uId = url + jsonString; // unique string representing this call (url + data uniquely identify the call)
	
	if (typeof jQuery.micronnexus.wsCache[uId] == "undefined") { // fresh call - do ajax call:
	    $.ajax({
	        type: "POST",
	        url: url,
	        contentType: "application/json; charset=utf-8",
	        data: jsonString,
	        dataType: "json",
	        success: function(data, textStatus) {
				jQuery.micronnexus.wsCache[uId] = data;
				callbackFunc(data);
			}
	    });
	} else { // been called before - return from the cache:
		callbackFunc(jQuery.micronnexus.wsCache[uId]);
	}
}

/**
* Fills a dropdown with options.
* @method fillDropDown
* @static
* @param  {Object}        $ddl             jQuery object
* @param  {Object}        items            Array of key-valye objects
* @param  {String}        valueFieldName   Property name holding the value for the VALUE parameter of the OPTION
* @param  {String}        textFieldName    Property name holding the value for the text of the OPTION
* @param  {Boolean}       clear            Delete all options from the select element before appending new ones?
* @param  {String|Number} preselectedValue Value to preselect after options are added (optional)
*/
jQuery.micronnexus.fillDropDown = function($ddl, items, valueFieldName, textFieldName, clear, preselectedValue) {
    if (typeof clear == "undefined") var clear = false;
    if (clear) $ddl[0].options.length = 0;
    
	var sel = $ddl[0];
	
	// Opera bug workaround:
	if (typeof window.opera != "undefined") {
		var tmpItems = [];
		for (var i = 0; i < sel.options.length; i++) {
			tmpItems[tmpItems.length] = new Option(sel.options[i].text, sel.options[i].value, false, false);
		}
		sel.options.length = 0;
		for (var i = 0; i < tmpItems.length; i++) {
			sel.options[sel.options.length] = tmpItems[i];
		}
	}
	// end Opera bug workaround
	
	for (var i = 0; i < items.length; i++) {
        if (typeof items[i][valueFieldName] != "undefined" && typeof items[i][textFieldName] != "undefined") {
			sel.options[sel.options.length] = new Option(items[i][textFieldName], items[i][valueFieldName], false, (preselectedValue == items[i][valueFieldName]) ? true : false);
        }
    }
	
}