/*
 * jQuery optionTree Plugin
 * version: 1.0.1
 * @requires jQuery v1.2 or later
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * @version $Id: jquery.optionTree.js,v 1.2 2010/04/08 14:01:19 vrioux Exp $
 * @author  Krzysztof Kotowicz <kkotowicz at gmail dot com>
 */

/**
 * Converts passed JSON option tree into dynamically created <select> elements allowing you to
 * choose nested options.
 *
 * @param String tree options tree
 * @param array options additional options (optional)
 */
 var finalParentID = 0;
(function($){
$.fn.optionTree = function(tree, currentSel, currentPageID, options) {

    options = $.extend({
        choose: ' ',
        preselect: {},
        select_class: '',
        leaf_class: 'final',
        empty_value: ''
    }, options || {});

    var cleanName = function (name) {
        return name.replace(/_*$/, '');
    };

    var removeNested = function (name) {
        $("select[name^='"+ name + "']").remove();
    };

    var setValue = function(name, value) {
        $("input[name='" + cleanName(name) + "']").val(value).change();
    }

    return this.each(function() {

        var name = $(this).attr('name') + "_";

        // remove all dynamic options of lower levels
        removeNested(name);

        if (typeof tree == "object") { // many options exists for current nesting level

            // create select element with all the options
            // and bind onchange event to recursively call this function

            var $select = $("<select>").attr('name',name)
            .change(function() {
                if (this.options[this.selectedIndex].value != '') {
                        $(this).optionTree(tree[this.options[this.selectedIndex].value], currentSel, currentPageID, options);
                } else {
                       removeNested(name + '_');
                       setValue(name, options.empty_value);
                }
				finalParentID = this.options[this.selectedIndex].value;
            });

            if ($(this).is('input'))
                $select.insertBefore(this);
            else
                $select.insertAfter(this);

            if (options.select_class)
                $select.addClass(options.select_class);

            $("<option>").html(options.choose).val('').appendTo($select);
            $.each(tree, function(k, v) {
				if ((k != 'title') && (k != 'url')) {

					// Check if self, and if yes, then do NOT add this as a choice for a parent!
					if (k != currentPageID) {
						var o = $("<option>").html(v['title'])
							.attr('value', k);
						var clean = cleanName(name);
							if (options.leaf_class && typeof v != 'object') // this option is a leaf node
								o.addClass(options.leaf_class);

							o.appendTo($select);
						
							// Check to update selectboxes with current value :
							if (currentSel > 0) {
								// If exact match, preselect :
								if (currentSel == k) {
									o.get(0).selected = true;
									$select.change();
								} else {
									selectIfInTree(v,currentSel,o);
									$select.change();
								}
							}
							
						}
					}
            });

        } else { // single option is selected by the user (function called via onchange event())
			console.log(" CRISS DE MARDE",name,tree);
            setValue(name, tree);
        }
    });

}
})(jQuery);

var continueRecursingNow = true;
function continueRecursing() {
	return continueRecursingNow;
}
function stopRecursing() {
	continueRecursingNow = false;
}

function selectIfInTree(tree, currentSel, o) {
	// If child-match, preselect :
	result = $.each(tree, function(k, v) {
		if ((typeof(v) == 'object') && (typeof(v) != 'string')) {
			// Verify the object is not a leaf :
			if ((k != 'url') && (k != 'title')) {
				//console.log(" comparing ",currentSel,k);
				if (k == currentSel) {
					//console.log("preselect ",currentSel,k);
					o.get(0).selected = true;
//					$select.change();
					stopRecursing();
					return false;
				}
			}
		}
	});
	if (continueRecursing()) {
		$.each(tree, function(k, v) {
			var done;
			done = false;
			// Verify we have an object to iterate through
			if ((typeof(v) == 'object') && (typeof(v) != 'string')) {
				// Verify the object is not a leaf :
				if ((k != 'url') && (k != 'title')) {
					//console.log(" recursive ",k,v);
					selectIfInTree(v, currentSel, o);
					if (!continueRecursing()) return false;
				}
			}
		});
	}
}