/*********************************************************\
* AJAX/JSON-Script zur Erzeugung des Produktfinder-Baums  *
* Version 0.5                                             *
* Datum: 11.02.10                                          *
* Autor: MSC                                              *
\*********************************************************/

var ProductFinder = function()
{
    //Objekt Variablen
    var self = this;
    this.tree = {
        Applications:   {children: null, links: null},
        Markets:         {children: null, links: null},
        Products:       {children: null, links: null}
    };
    this.url = dbpath + '/CUS_aJSONPF';
    this.param = {
        openAgent:      null,
        viewname:       'CUS_vJSONPF',
        doctype:        'topic',
        language:       language,
        viewnamechild:  'WUI_Content_TreeSelection'
    };
    this.layerIsVisible = [];
    this.currentChoice = [];
    this.backgroundActive = false;
    // Objekt-Methoden
    this.getChildren = function(param) { // Holt die Kinder
        if (this.currentChoice[param.level] == param.category) { // Schließen des Layers bei wiederholtem Klick
            this.removeLayers(param.level);
            $(param.event.target).parent().attr('className','list');
            this.currentChoice[param.level] = null;
            return;
        }
        this.currentChoice[param.level] = param.category;
        $(param.event.target).parent().parent().find('.listActive').attr('className','list').find('a');
        $(param.event.target).parent('.list').attr('className','listActive');
        switch (param.level) {
        case 1:
            this.finderLeft = $(param.event.target).offset().left - 19;
            this.finderTop = $(param.event.target).offset().top - 4;
            this.finderLabel = $(param.event.target).text();
            if (!this.tree[param.category].children) { // Sind nicht im Baum und werden per AJAX vom Server geholt
                this.param.node = escape(param.category);
                $.getJSON(this.url, this.param, function(json) {self.buildTree(json, [param.category], true, param.level);});
            } else {
                this.createLayer({entries: this.tree[param.category].children, level: param.level});
            }
            break;
        case 2:
            this.path = param.category.split('//');
            this.finderLeft = $(param.event.target).parent().parent().offset().left + $(param.event.target).parent().parent().width() -2;
            this.finderTop = $(param.event.target).offset().top - 11 ;
            this.finderLabel = null;
            if (!this.tree[unescape(this.path[0])].children[this.path[1]].children) {
                this.param.node = param.category;
                $.getJSON(this.url, this.param, function(json) {self.buildTree(json, self.path, true, param.level);});
            } else {
                this.createLayer({entries: this.tree[this.path[0]].children[this.path[1]].children, level: param.level});
            }
            break;
        case 3:
            this.path = param.category.split('//');
            this.finderLeft = $(param.event.target).parent().parent().offset().left + $(param.event.target).parent().parent().width() -1;
            this.finderTop = $(param.event.target).offset().top - 11;
            this.finderLabel = null;
            if (!this.tree[unescape(this.path[0])].children[this.path[1]].children[this.path[2]].children) {
                this.param.node = param.category;
                $.getJSON(this.url, this.param, function(json) {self.buildTree(json, self.path, true, param.level);});
            } else {
                this.createLayer({entries: this.tree[this.path[0]].children[this.path[1]].children[this.path[2]].children, level: param.level});
            }
            break;
        case 4:
            this.path = param.category.split('//');
            this.finderLeft = $(param.event.target).parent().parent().offset().left + $(param.event.target).parent().parent().width() -1;
            this.finderTop = $(param.event.target).offset().top - 11;
            this.finderLabel = null;
            if (!this.tree[unescape(this.path[0])].children[this.path[1]].children[this.path[2]].children[this.path[3]].children) {
                this.param.node = param.category;
                $.getJSON(this.url, this.param, function(json) {self.buildTree(json, self.path, true, param.level);});
            } else {
                this.createLayer({entries: this.tree[this.path[0]].children[this.path[1]].children[this.path[2]].children[this.path[3]].children, level: param.level});
            }
            break;
        }
    };

    this.createLayer = function(param) { // Erzeugt den Layer
        if (this.layerIsVisible[param.level]) {
            this.removeLayers(param.level)
        }
        $("body").append('<div style="display:none; position: absolute; top: '+this.finderTop+'px; left: '+this.finderLeft+'px;" id="finder_level_'+param.level+'"><div><div></div>');
        $('#finder_level_'+param.level+' div:first').append('<span class="finderHead"><a href="#">'+(this.finderLabel?this.finderLabel:'')+'</a></span>');
        if (this.finderLabel) { // Schließfunktion für Level 1
            $('#finder_level_'+param.level+' div:first span a').click(function(event) {self.removeLayers(param.level, true); self.currentChoice[1] = null; return false});
        }
        for (var i in param.entries) { // Listenelemente bauen
            if (typeof param.entries[i] == 'object') {
                var label = unescape(param.entries[i].text);
                if (label.length > 31) {
                    label = label.substr(0, 28) + '...';
                }
                if (param.entries[i].type == 'category') {

                    $('#finder_level_'+param.level+' div:first').append('<span class="list" title="'+unescape(param.entries[i].text)+'"><a href="#" rel="level_'+param.level+'" id="'+param.entries[i].id+'">'+label+'</a></span>');
                } else if (param.entries[i].type == 'link') {
                    $('#finder_level_'+param.level+' div:first').append('<span class="link"><a href="'+param.entries[i].docid+'?open&amp;reopen=prodnav" title="'+unescape(param.entries[i].text)+'">'+label+'</a></span>');
                }
            }
        }
        $('#finder_level_'+param.level+' div:first').append('<span class="finderFoot"></span>');
        $("a[rel=level_"+param.level+"]").click(function(event) {
            finder.getChildren({category: this.id, level: param.level+1, event: event});
            return false;
        }).parent().click(function(event) {
            finder.getChildren({category: this.firstChild.id, level: param.level+1, event: {target: event.target.firstChild}});
        });
        // Ermitteln der Bildschirmhöhe und Positionieren des Layer wie Windows-Menüs
        var screenHeight = $(window).height();
        var elementHeight = $('#finder_level_'+param.level).height() + this.finderTop;
        if (param.level > 1 && elementHeight > screenHeight) {
            $('#finder_level_'+param.level).css({'bottom': (screenHeight - this.finderTop - 40) + 'px', 'top': ''});
        }
        //$('#finder_level_'+param.level).fadeIn('slow');
        $('#finder_level_'+param.level).show();
        this.layerIsVisible[param.level] = true;
    };

    this.removeLayers = function(level, reset) // Entfernen des aktuellen und der darunterliegenden Layer
    {
        for (var i = level; i <= 4; i++) {
            if (this.layerIsVisible[i]) {
                //$('#finder_level_'+i).fadeOut('slow');
                $('#finder_level_'+i).remove();
                this.layerIsVisible[i] = false;
                //this.currentChoice[i] = null;
            }
        }
        if (reset) {
            this.layerIsVisible = [];
            this.currentChoice = [];
            $('#jquery-overlay').remove();
            $('#productNavigator').css({position: 'static'});
            this.backgroundActive = false;
        }
        //this.currentChoice[level] = null;
    }

    this.buildTree = function(json, section, build, level) { // Einhängen der Kinder in den Baum
        if (json.length > 0) {
            for (var i = 0; i< json.length; i++) {
                if (json[i].text != '') {
                    if (json[i].type == 'category') {
                        json[i].children = null;
                        json[i].links = null;
                    }

                    switch (section.length) {
                    case 1:
                        if (!this.tree[section[0]].children) {
                            this.tree[section[0]].children = [];
                        }
                        this.tree[section[0]].children[json[i].text] = json[i];
                        break;
                    case 2:
                        if (!this.tree[section[0]].children[section[1]].children) {
                            this.tree[section[0]].children[section[1]].children = [];
                        }
                        this.tree[section[0]].children[section[1]].children[json[i].text] = json[i];
                        break;
                    case 3:
                        if (!this.tree[section[0]].children[section[1]].children[section[2]].children) {
                            this.tree[section[0]].children[section[1]].children[section[2]].children = [];
                        }
                        this.tree[section[0]].children[section[1]].children[section[2]].children[json[i].text] = json[i];
                        break;
                    case 4:
                        if (!this.tree[section[0]].children[section[1]].children[section[2]].children[section[3]].children) {
                            this.tree[section[0]].children[section[1]].children[section[2]].children[section[3]].children = [];
                        }
                        this.tree[section[0]].children[section[1]].children[section[2]].children[section[3]].children[json[i].text] = json[i];
                        break;

                    }
                }
            }
        }
        if (build) {
            switch (section.length) {
            case 1:
                this.createLayer({entries: this.tree[section[0]].children, level: level});
                break;
            case 2:
                this.createLayer({entries: this.tree[section[0]].children[section[1]].children, level: level});
                break;
            case 3:
                this.createLayer({entries: this.tree[section[0]].children[section[1]].children[section[2]].children, level: level});
                break;
            case 4:
                this.createLayer({entries: this.tree[section[0]].children[section[1]].children[section[2]].children[section[3]].children, level: level});
                break;
            }
        }
    };

    this.init = function(section) { //Constructor-Funktion, holt die oberste Ebene
        this.param.node = escape(section);
        $.getJSON(this.url, this.param, function(json) {self.buildTree(json, [section], false, null);});
    };

    this.buildBackground = function() {
        if (!this.backgroundActive) {
            $('body').append('<div id="jquery-overlay"></div>');
            var arrPageSizes = ___getPageSize();

            $('#jquery-overlay').css({
                    backgroundColor:	this.ovl.bgColor,
                    opacity:			this.ovl.opacity,
                    zIndex:             this.ovl.zIndex,
                    width:				arrPageSizes[0],
                    height:				arrPageSizes[1]
            }).fadeIn();
            $('#jquery-overlay').bind('click', function(){self.removeLayers(1, true);});
            $('#productNavigator').css({zIndex: 20001, position: 'relative'});
            this.backgroundActive = true
        }
    };

    // Constructor
    for (var i in this.tree) {
        this.init(i);
    }
    this.ovl = {
        bgColor: '#000',
        opacity: 0.7,
        zIndex: 20000
    };

};

$(function() { // Initialisieren des Finder-Objekts und Registrierung der Links
    finder = new ProductFinder();
    $("#finderLaunchIcon").click(function(){$('#productfinder').slideDown("slow");});
    $("#pfinderCloser").click(function() {finder.removeLayers(1, true); $('#productfinder').slideUp("slow");});
    $("a[rel=finder]").click(function(event) {finder.buildBackground();finder.getChildren({category: this.id, level: 1, event: event}); return false});
});


var ___getPageSize = function() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
    return arrayPageSize;
};
