jQuery(document).ready(function(){ MC.init(); });

var MC = {

    // standard text color - see style.css
    textColor: "#333333",
    // selected text color - see style.css
    selectedTextColor: "#e71818",
    // selected menu item
    selectedMenuItem: null,

    // init method
    init: function() {
        jQuery(".sidebar .expandable>.menuTitle").bind("click", function() { jQuery(this).nextAll().slideToggle("fast"); return false; });

        // init history handling
        jQuery.historyInit(function(hash) { 
                if (hash  &&  hash.length > 0) {
                    if (hash.indexOf(".xhtml") > 0)
                        MC.show(hash);
                    else
                        MC.loadProducts(hash); 
                }
                else
                    MC.show("start.xhtml");
            });

		// set onlick event for buttons
		jQuery("a[href^='#']").click(function(){
			// 
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			// moves to a new page pageload is called at once. 
			$.historyLoad(hash);
			return false;
		});
    },

    // loads a .xhtml page into 'content'
    show: function(url) {
        // reset menu item color
        if (MC.selectedMenuItem != null) {
            MC.selectedMenuItem.removeAttribute("style");
            MC.selectedMenuItem = null;
        }

        var jQueryElement = jQuery(".sidebar a[href$='" + url + "']"); // find the menu link
        var element = jQueryElement.get(0); // get the dom element of the jquery element

        if (element) {
            MC.selectedMenuItem = element; // mind for resetting
            MC.selectedMenuItem.style.color = MC.selectedTextColor; // set menu item color
        }

        jQuery("#content").fadeOut(function() {
            jQuery.get(url, null, function(text) {
                jQuery("#content").empty();
                jQuery("#content").append(text);

                var i = 0;
                var sleepMethod = function() {
                    // check if all images have been loaded
                    var allImagesLoaded = true;
                    var images = jQuery("#content img");
                    for (var j = 0; j < images.size(); j++)
                        if (images.get(j).naturalWidth <= 0)
                            allImagesLoaded = false;

                    // wait at most 5 sec
                    i ++;
                    if (i < 40  &&  !allImagesLoaded) {
                        window.setTimeout(sleepMethod, 100); // wait again
                        return;
                    }

                    // show content
                    jQuery("#content").fadeIn();
                    tb_init('a.thickbox, area.thickbox, input.thickbox');
                };
                window.setTimeout(sleepMethod, 1000);

            }, "text");
        });
    },

    // loads the products into 'content'
    loadProducts: function(url) {
        // reset menu item color
        if (MC.selectedMenuItem != null) {
            MC.selectedMenuItem.removeAttribute("style");
            MC.selectedMenuItem = null;
        }

        var jQueryElement = jQuery(".sidebar a[href$='" + url + "']"); // find the menu link
        jQueryElement.parents(".expandable").children().slideDown(); // show it (if sub menu)
        var element = jQueryElement.get(0); // get the dom element of the jquery element

        MC.selectedMenuItem = element; // mind for resetting
        MC.selectedMenuItem.style.color = MC.selectedTextColor; // set menu item color

        jQuery("#content").fadeOut(function() {
            jQuery("#content").empty();
            jQuery("#content").show();
            var i = 1;
            while (i < 50) {
                try {
                    MC.loadProduct(url, i);
                }
                catch (e) {}
                i ++;
            }
        });
    },

    // loads a single product (text and thumbnail)
    loadProduct: function(path, nr) {
        var xm = function(path, nr) {
            jQuery.get(path + nr + ".xhtml", null, function(text) {
                // parse text - use first line as title, only
                var title = "" + text;
                if (title.indexOf("\n") >= 0)
                    title = title.substring(0, title.indexOf("\n"));

                var productId = "product" + nr;

                // load thumbnail and add product once the thumbnail is loaded
			    var imgPreloader = new Image();
			    imgPreloader.onload = function() {		
                    // create product content xhtml
                    var product = "<div class='frame product'><div id='" + productId + "' class='productContent' style='display: none;'>"
                            + "<div class='productThumbnail'>"
                            + "<div class='productThumbnailBox'>"
                            + "<img src='" + path + nr + "th.jpg' alt=''></img>"
                            + "</div>"
                            + "</div>"
                            + "<div class='productText'>" + title + "</div>"
                            + "</div></div>";
                    jQuery("#content").append(product);

                    var thumb = jQuery("#" + productId + " img");

                    // in IE7 and less vertical positioning must be done the hard way
	                if (jQuery.browser.msie  &&  jQuery.browser.version <= 7)
		                thumb.css({ marginTop: "" + ((300 - imgPreloader.height) / 2) });

                    // add click handler
                    thumb.click(function() {
                        if (text.indexOf("<") < 0) // no markup - add breaks at end of lines
                            text = text.replace(/\n/g, "<br />");

                        MC.showProduct(path + nr + ".jpg", text);
                        return false;
                    });

                    // fade in
                    jQuery("#" + productId).fadeIn();
                };
                imgPreloader.src = path + nr + "th.jpg";
            }, "text");
    	};
        xm(path, nr);
    },

    // partially borrowed from thickbox
    showProduct: function(url, text) {
        jQuery("body").append("<div id='TB_load'><img src='"+ tb_pathToImage + "' /></div>");//add loader to the page
        jQuery('#TB_load').show();//show loader

        try {
            if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
                jQuery("body","html").css({height: "100%", width: "100%"});
                jQuery("html").css("overflow","hidden");
                if (document.getElementById("TB_HideSelect") === null) { //iframe to hide select elements in ie6
                    jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                    jQuery("#TB_overlay").click(tb_remove);
                }
            }
            else{ //all others
                if (document.getElementById("TB_overlay") === null) {
                    jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                    jQuery("#TB_overlay").click(tb_remove);
                }
            }
		
            $("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity

            imgPreloader = new Image();
            imgPreloader.onload = function() {		
                imgPreloader.onload = null;
			
                // resizing large images if needed
                var pagesize = tb_getPageSize();
                var x = pagesize[0] - 100;
                var y = pagesize[1] - 200;
                var imageWidth = imgPreloader.width;
                var imageHeight = imgPreloader.height;
                if (imageWidth > x) {
	                imageHeight = imageHeight * (x / imageWidth); 
	                imageWidth = x; 
	                if (imageHeight > y) { 
		                imageWidth = imageWidth * (y / imageHeight); 
		                imageHeight = y; 
	                }
                } else if (imageHeight > y) { 
	                imageWidth = imageWidth * (y / imageHeight); 
	                imageHeight = y; 
	                if (imageWidth > x) { 
		                imageHeight = imageHeight * (x / imageWidth); 
		                imageWidth = x;
	                }
                }

                if (imageWidth < 32)
                    imageWidth = 32;
                if (imageHeight < 32)
                    imageHeight = 32;

                // determine total width/height
                TB_WIDTH = imageWidth + 30;
                if (TB_WIDTH < 200)
                    TB_WIDTH = 200;
                TB_HEIGHT = imageHeight + 85 + 80; // 85 = borders + margins + paddings + ...; 80 is caption height (-> thickbox.css)

                jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Schliessen'>"
                        + "<img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' /></a>" 
                        + "<div id='TB_caption'><div>" + text + "</div></div>"
                        + "<div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Schliessen'>Schliessen</a> oder Esc</div>"); 		
                jQuery("#TB_caption").css("width", (TB_WIDTH - 75) + "px");
			
                jQuery("#TB_closeWindowButton").click(tb_remove);
			
                document.onkeydown = function(e){ 	
                    if (e == null) { // ie
	                    keycode = event.keyCode;
                    }
                    else { // mozilla
	                    keycode = e.which;
                    }
                    if (keycode == 27){ // close
	                    tb_remove();
                    }	
                };

                tb_position();			
        		$("#TB_load").remove();
                jQuery("#TB_ImageOff").click(tb_remove);
                jQuery("#TB_window").css( {display:"block"} ); //for safari using css instead of show
			};

			imgPreloader.src = url;
        }
        catch (e) {
    		$("#TB_load").remove();
        }
    }
}


