/*
 * jQuery plug-in WG SelectboxChained  1.0
 * Copyright (c) 2010 Roberto Lee
 */
 /*
 * Copyright (c) 2010 Roberto Lee (webgenerator.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Date: 2010-01-04
 * Rev: 1
 */


jQuery.fn.SelectboxChained = function(options) {// 'this' is a jQuery object at this point - with all the jQuery functions
	defaults = {
		target: null,
		targetfirsttitle: "",	//adds an option item with empty value
        key: "artid", 			//maps the value to find in the json
        value: "txt",			//maps the value to find in the json
		cb: function() {}
	};

	var config = $.extend(defaults, options);
	if (!(config.target instanceof $)) config.target = $(config.target);

  	return this.each(function() {// return so we don't break the chain now we are inside of a jQuery function, the DOM element is the context so 'this' has changed to become a DOM element.
    	//elem_select = this;

    	if((this.tagName.toLowerCase() == "select") && (config.target.tagName() == "select"))
    	{
			$(this).change( function() {
				//Empty the selectbox
                config.target.empty();

				var chosenval = $(this).val();
				if((chosenval != "") && (chosenval != null))
				{
	                var ajaxdata = null;
	                if (typeof config.data == 'string') {
	                    ajaxdata = config.data + '&' + this.name + '=' + chosenval;
	                } else if (typeof config.data == 'object') {
	                    ajaxdata = config.data;
	                    ajaxdata[this.name] = chosenval;
	                }

					//Retrieve the json feed
	                $.ajax({
	                    url: config.url,
	                    data: ajaxdata,
	                    type: (config.type || 'get'),
	                    dataType: 'json',
	                    success: function (json) {
	                        var options = [], i = 0, o = null;

							//Parse the json feed
	                        for (i = 0; i < json.length; i++) {
	                        	config.target.get(0).options[i] = new Option(StrFromChar(typeof json[i] == 'object' ? json[i][config.value] : json[i]) , typeof json[i] == 'object' ? json[i][config.key] : json[i]);
	                        }

	                        //Create empty title option
			                if(config.targetfirsttitle != ""){
			                    $(config.target.get(0)).prepend("<option value=\"\">"+config.targetfirsttitle+"</option>");
			                }

							//Hand control back to browser for a moment
							setTimeout(function () {
						    	config.target
			                                .find('option:first')
			                                .attr('selected', 'selected')
			                                .parent("select")
			                                .trigger('change');
							}, 0);

							$(config.target.get(0)).css({display : 'inline'});

							config.cb.call();
	                    },
	                    error: function (xhr, desc, er) {
	                    	$.log("error retrieving the json feed." + desc)	;
	                    }
	                });
				}
				else
				{
					$(config.target.get(0)).css({display : 'none'});
				}
			});
    	}
    	else
    	{
    		$.log("one of elements is not a selectbox")	;
    	}
  	});
};



/*
	USAGE SAMPLE
    $(document).ready(function() {
        jQuery("#cid").SelectboxChained({
            target: jQuery("#select_training"),
            targetfirsttitle: 'kies training...',
            url: '<$VIEW code="OVERVIEW_JSON"$>',
	    	type: 'post',
            data: { ajax: true, action: "trlist" }
        }).trigger('change');

        jQuery("#select_training").SelectboxChained({
            target: jQuery("#select_trainingdateandloc"),
            targetfirsttitle: 'kies datum...',
            url: '<$VIEW code="OVERVIEW_JSON"$>',
	    	type: 'post',
            data: { ajax: true, action: "trdata" }
        }).trigger('change');
    });
*/

jQuery.fn.tagName = function(){
        if(1 === this.length){
                return this[0].tagName.toLowerCase();
        } else{
                var tagNames = [];
                this.each(function(i, el){
                        tagNames[i] = el.tagName.toLowerCase();
                });
                return tagNames;
        }
};



(function($) {

   $.fn.log = function(msg) {
      if (typeof (console) == "undefined") {
         console = { log: function() { } };
      }
      if (console) {
         console.log("%s: %o", msg, this);
      }
      return this;
   }
})(jQuery);

jQuery.log = function(msg) {
      if (typeof (console) == "undefined") {
         console = { log: function() { } };
      }
      if (console) {
         console.log("%s: %o", msg, this);
      }
};



function StrFromChar(str)
{
	//Makes special characters displaying correctly
	var regexp = /(\&{1}\#{1}\d+\;{1})/gi; //FIND ISO LATIN CODE
	//var regexpnumbers = /(\d+)/gi; //FIND DIGITS

	var match_arr = str.match(regexp);
	if(match_arr)
	{
		for(i=0;i<match_arr.length;i++)
		{
			var foundiso = match_arr[i];
			var foundisonumber = foundiso.replace("&#","").replace(";","")
			textstring = str.replace(foundiso, String.fromCharCode(foundisonumber));
		}
	}
	return str;
}