var $GLOBAL_TREEVIEW_OBJ;
var test = 0;
$.fn.treeview = function(options) {
    $GLOBAL_TREEVIEW_OBJ = this;
    var nodeCount = 0;
    var levelCount;
    var initialed = false;
    this.maxID = 0;
    options = $.extend({
        speed: 250,
        expanded: false,
        unique: true,
        checkbox: false,
        align: "right",
        indent: "10px",
        onSelect: null
    }, options);
    this.expandAll = function() {
        $("." + options.align + "_perentNode").each(function() {
            if ($(this).hasClass("collapsed")) {
                $(this).find(".handler:first").removeClass(options.align + "_collapsed_handler").addClass(options.align + "_expanded_handler");
                $(this).find("ul:first").slideDown(options.speed);
                $(this).swapClass("collapsed", "expanded");
            }
        });
    };
    this.collapseAll = function() {
        $("." + options.align + "_perentNode").each(function() {
            if ($(this).hasClass("expanded")) {
                $(this).find(".handler:first").removeClass(options.align + "_expanded_handler").addClass(options.align + "_collapsed_handler");
                $(this).find("ul:first").slideUp(options.speed);
                $(this).swapClass("collapsed", "expanded");
            }
        });
    };
    this.reverse = function() {
        $("." + options.align + "_perentNode").each(function() {
            $GLOBAL_TREEVIEW_OBJ.swap($(this));
        });
    };
    this.swap = function(node) {
        node = ((typeof node) == "object") ? node: $("#node" + node);
        var $el = node.find("ul:first");
        var $hnd = node.find(".handler:first");
        if ($el.length > 0) {
            if ($el.parent("li").hasClass("expanded")) {
                $el.slideUp(options.speed);
            } else {
                $el.slideDown(options.speed);
            }
            $hnd.swapClass(options.align + "_collapsed_handler", options.align + "_expanded_handler");
            $el.parent("li").swapClass("collapsed", "expanded");
        }
    };
    this.clear = function() {
        nodeCount = 0;
        levelCount = 0;
        $(this).html("");
    };
    this.jsonLoad = function(path, params, callback, clear) {
        $.post(path, params, function(xml) { $GLOBAL_TREEVIEW_OBJ.jsonDecode(xml, callback, clear); });
    };
    this.jsonDecode = function(jsonText, callback, clear) {
        if (clear) {
            this.clear();
        }
        try {
            var jsonObj = eval("(" + jsonText + ")");
        } catch(e) {
            alert("Invalid JSON output");
        }
        for (i = 0; i < jsonObj.length; i++) {
            this.addNode(jsonObj[i]);
        }
        initialed = true;
        if (callback && (typeof callback) == "function") {
            callback();
        }
    };
    function getParentNode(pID) {
        var $parentNode = (pID > 0) ? $("#node" + pID) : $GLOBAL_TREEVIEW_OBJ;
        return ($parentNode.length > 0) ? $parentNode: $GLOBAL_TREEVIEW_OBJ;
    }
    function fixParent($el) {
        var $handler = $el.find(".handler:first");
        if ($el.find("ul:first").length > 0) {
            return true;
        } else {
            var ind = (parseInt($el.attr("level")) > 0) ? options.indent: "0px";
            var $c_ul = $('<ul class="treeview_nodes"></ul>').css({
                padding: "0px " + ind,
                margin: "0px " + ind
            });
            $el.append($c_ul);
            $el.removeClass(options.align + "_childNode").addClass(options.align + "_perentNode");
            if (options.expanded) {
                $el.addClass("expanded");
                $handler.addClass(options.align + "_expanded_handler");
            } else {
                $el.addClass("collapsed");
                $handler.addClass(options.align + "_collapsed_handler");
                $el.find("ul:first").slideUp();
            }
            return false;
        }
    }
    function validateChild(childInfo) {
        return {
            parent: (childInfo.parent == null ? 0 : childInfo.parent),
            id: (childInfo.id == null ? (++this.maxID) : childInfo.id),
            caption: (childInfo.caption == null ? "": childInfo.caption),
            title: (childInfo.title == null ? "":  childInfo.title),
            link: (childInfo.link == null ? "javascript: void(0);": childInfo.link),
            target: (childInfo.target == null ? "self": childInfo.target)
        };
    }
    this.selected = new Array();
    this.select = function(curr) {
        this.selected = new Array();
        $(".node_check").each(function() {
            if ($(this).attr("checked")) {
                $GLOBAL_TREEVIEW_OBJ.selected.push($(this).val());
            }
        });
        this.selected = JSON.stringify(this.selected);
        
        if((typeof options.onSelect) == 'function' && curr.checked){
            var $el = $('#node' + (curr.value) + '_caption');
            
            var dataArray = ($el.attr('data')).split('&');
            var datas = new Array();
            if(dataArray.length > 0){
                $.each(dataArray, function(index, value){
                    var nv = value.split('=');
                    datas[nv[0]] = nv[1];
                });
            }
            
            options.onSelect({
                id: curr.value,
                caption: $el.html(),
                target: $el.attr('target'),
                title: $el.attr('title'),
                data: datas,
                link: $el.attr('href')
            });
        }
    };
    this.addNode = function(nodeInfo, callback) {
        //nodeInfo = validateChild(nodeInfo);
        nodeInfo = $.extend({
            parent: 0,
            id:++this.maxID,
            caption:"",
            title:"",
            link:"javascript: void(0);",
            target:"self",
            data:""
        }, nodeInfo);
        
        if ($("#node" + nodeInfo.id).length > 0 && options.unique) {
            return false;
        }
        var $parent = getParentNode(nodeInfo.parent);
        if (options.checkbox) {
            var checkbox = '<input type="checkbox" value="' + nodeInfo.id + '" class="node_check" onclick="$GLOBAL_TREEVIEW_OBJ.select(this)">';
            var strStyle = "padding-" + options.align + ": 14px; ";
        } else {
            var checkbox = "";
            var strStyle = "";
        }
        var $child = $('<li id="node' + (nodeInfo.id) + '" level="1" class="' + options.align + '_childNode"><div class="handler" style="float: ' + options.align + ";background-position: " + options.align + ' center" onclick="$GLOBAL_TREEVIEW_OBJ.swap(' + nodeInfo.id + ')"></div>' + checkbox +
            '<a id="node' + (nodeInfo.id) + '_caption" href="'+nodeInfo.link+'" title="'+nodeInfo.title+'"'+
            ' alt="'+nodeInfo.title+'" target="'+nodeInfo.target+'" data="'+nodeInfo.data+'">'+nodeInfo.caption+'</a></li>').css({
            backgroundPosition: (options.align + " top"),
            clear: "both",
            border: "0px"
        });
        if (parseInt($parent.attr("level")) > 0) {
            fixParent($parent);
            $parent.find("ul:first").append($child);
        } else {
            $parent.append($child);
        }
        var cl = parseInt($parent.attr("level")) + 1;
        $child.attr("level", cl);
        this.maxID = (nodeInfo.id > this.maxID) ? nodeInfo.id: this.maxID;
        levelCount = (cl > levelCount) ? cl: levelCount;
        if (callback && (typeof callback) == "function") {
            callback();
        }
        return true;
    };
    $(this).attr("level", 0);
    return this;
}; 

