﻿/*
If you are using this, you are incredibly lucky. This was made by none other than the Awesome Master Programmer.
*/
if (!Namespace("umen.ui.PageTreeView")) {
    umen.ui.PageTreeView = function (topUL, output, selected, trigger, flat) {
		this.topUL = topUL;
		this.output = output;
		this.outputFilter = ["#", output].join("");
		this.trigger = trigger;
		this.flat = flat;
		this.topULFilter = ["#", this.topUL].join("");
		this.refresh(selected);
    }

    umen.ui.PageTreeView.prototype.select = function (selected) {
    	var me = this;
    	var $topUl = $(this.topULFilter);
    	var $output = $(this.outputFilter);
    	$output.val(selected);
    	if (selected) {
    		var $sel = $topUl.find(["input[id$='hfHl'][@value='", selected, "']"].join(""));
    		$sel = $sel.prev("a.pgs_hlp");

    		var $related = $sel.parentsUntil(this.topULFilter).filter("ul.pgs");
    		if (!me.flat) {
    			$related.show('fast');
    			$related.siblings("ul.pgs").show('fast');
    		}

    		this.highlight($sel, $topUl);
    	}
    }
    
    umen.ui.PageTreeView.prototype.highlight = function ($sel) {
        var $topUl = $(this.topULFilter);
		$topUl.find("li.pgs").addClass("pgs_nsel");
		$topUl.find("a.pgs").removeClass("pgs_sel");
		$sel.parents("li.pgs").addClass("pgs_sel");
		$sel.parents("li.pgs").removeClass("pgs_nsel");
		$sel.addClass("pgs_sel");
    }

    umen.ui.PageTreeView.prototype.refresh = function (selected) {
    	var me = this;
    	var $topUl = $(this.topULFilter);
    	this.select(selected);
		
		$("a.pgs_hlu,a.pgs_hlss,a.pgs_hls").unbind("click");
    	$("a.pgs_hlu,a.pgs_hlss,a.pgs_hls").click(
            function () {
            	var $lnk = $(this);
            	//var $parents = $lnk.parentsUntil(me.topULFilter).filter("ul.pgs");
            	var $sibblings = $lnk.siblings("ul.pgs");
            	if (!me.flat) {
            		$sibblings.toggle('fast');
            	}
            }
        );

    	$("a.pgs_hlp").unbind("click");
    	$("a.pgs_hlp").click(
            function () {
            	$sel = $(this);
            	me.highlight($sel);
            	var id = $sel.next("input").val(); //$sel[0].id.split('_');
            	//id = id[id.length - 1];
            	var $output = $(me.outputFilter);
            	$output.val(id);
            	if (me.trigger) { return me.trigger(); }
            	else { return false; }
            }
        )
    }
};
