/**
 * @file    js/global.js
 *
 * copyright (c) 2006-2009 Frank Hellenkamp [jonas@depagecms.net]
 *
 * @author    Frank Hellenkamp [jonas@depagecms.net]
 */

var speed = 400;
var productinfo_visible = false;
var mouseover_viewport = true;
var selected_room = "";
var zoomRatio;

// global helpers
// {{{ getHexColorFromString()
function getHexColorFromString(colorString) {
    if (colorString == "transparent") {
    var hexCode = "000000";
    } else if (colorString.substr(0, 3) == "rgb") {
        var components = colorString.match(/[0-9]+/g);
        var r = parseInt(components[0]).toString(16);
        var g = parseInt(components[1]).toString(16);
        var b = parseInt(components[2]).toString(16);

        if (r.length < 2) r = "0" + r;
        if (g.length < 2) g = "0" + g;
        if (b.length < 2) b = "0" + b;

        var hexCode = r + g + b;
    } else if (colorString.charAt(0) == "#") {
        var hexCode = colorString.substring(1);
    }

    return "0x" + hexCode;
}
/* }}} */

// javascript flash detection
// {{{ jquery.browser.flash
jQuery.extend(jQuery.browser, {
    flash: (function (neededVersion) {
        var found = false;
	var version = "0,0,0";

	try {
	    // get ActiveX Object for Internet Explorer
	    version = new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	} catch(e) {
	    // check plugins for Firefox, Safari, Opera etc.
	    try {
		if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
		    version = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
		}
	    } catch(e) {
		return false;
	    }		
	}

	var pv = version.match(/\d+/g);
	var rv = neededVersion.match(/\d+/g);

	for (var i = 0; i < 3; i++) {
	    pv[i] = parseInt(pv[i] || 0);
	    rv[i] = parseInt(rv[i] || 0);

	    if (pv[i] < rv[i]) {
		// player is less than required
	       	return false;
	    } else if (pv[i] > rv[i]) {
		// player is greater than required
		return true;
	    }
	}
	// major version, minor version and revision match exactly
	return true;
    })
});
// }}}
// {{{ jquery.flash
jQuery.fn.flash = function(params) {
    var html1 = "";
    var html2 = "";
    var flashParam = [];

    for (var p in params.params) {
	flashParam.push(p + "=" + encodeURI(params.params[p]));
    }
    var src = params.src;
    if (flashParam.length > 0) {
        src += "?" + flashParam.join("&amp;");
    }

    //object part
    html1 += "<object type=\"application/x-shockwave-flash\" ";
    html1 += "data=\"" + src+ "\" ";
    if (params.width !== undefined) {
	html1 += "width=\"" + params.width + "\" ";
    }
    if (params.height !== undefined) {
	html1 += "height=\"" + params.height + "\" ";
    }
    if (params.className !== undefined) {
	html1 += "class=\"" + params.className + "\" ";
    }
    if (params.id !== undefined) {
	html1 += "id=\"" + params.id + "\" ";
    }
    html1 +="allowFullScreen=\"true\" ";

    //param part
    html2 += "<param name=\"movie\" value=\"" + src + "\" />";
    html2 += "<param name=\"allowFullScreen\" value=\"true\" />";

    if (params.transparent === true) {
	html1 += "mwmode=\"transparent\"";
	html2 += "<param name=\"wmode\" value=\"transparent\" />";
    }
    html1 += ">";

    var value = $( html1 + html2 + "</object>");
    value.plainhtml = html1 + html2 + "</object>";

    return value;
};
// }}}

// room behaviour
// {{{ showRoom()
function showRoom(type) {
    if (!productinfo_visible && selected_room != type) {
        if (type == "products") {
            $("#products .product").show();
            $("#trends .product").hide();

            $("#products").stop().fadeIn("slow", function() {
                $(this).css({
                    opacity: 1
                });
                $("#trends").hide();
            });

            $(".chooser .trends").removeClass("active");
            $(".chooser .products").addClass("active");

            $(".directlinks .trends").hide();
            $(".directlinks .products").show();
        } else {
            $("#trends .product").show();
            $("#products .product").hide();

            $("#products").stop().fadeOut("slow");
            $("#trends").show();

            $(".chooser .trends").addClass("active");
            $(".chooser .products").removeClass("active");

            $(".directlinks .trends").show();
            $(".directlinks .products").hide();
        }

        selected_room = type;
    }
}
// }}}
// {{{ addRoomHandlers()
function addRoomHandlers() {
    // get language from content tag in header
    var lang = $("meta[name = 'Content-Language']")[0].content;
    var $popuphover = $("#popup_hover");

    $(".chooser").fadeIn();
    $(".directlinks").fadeIn();

    // {{{ add handlers for zoom images
    var thumbMoveRatio;
    var oldWidth = $(".viewport").width();
    var newWidth = $(".viewport .view").width();

    zoomRatio = newWidth / oldWidth;

    $(".viewport").hover( function() {
        mouseover_viewport = true;
    }, function() {
        mouseover_viewport = false;
    });
    $(".viewport").mousemove( function(e) {
        if (!productinfo_visible) {
            var offsetX = $(this).offset().left - e.pageX;
            var offsetY = $(this).offset().top - e.pageY;
            
            $(".view", this).stop().css({
                left: offsetX * (zoomRatio - 1),
                top: offsetY * (zoomRatio - 1) * 1.4
            });
        }
    });
    // }}}
    // {{{ add handlers for products 
    $(".product").each(function() {
        var $product = $(this);
        var name = $(this).attr("class").match(/[pt]-[a-zA-Z0-9]*/)[0];
        $("img", this).show().wrap("<span class=\"wrap\"></span>");
        
        var $wrap = $(".wrap", this).hide();

        $product.hover( function() {
            popProduct(name);
        }, function() {
            unpopProduct();
        });

        $product.click( function() {
            showProductInfo(name);

            return false;
        });
    });
    // }}}
}
// }}}
// {{{ popProduct()
function popProduct(name) {
    var $popuphover = $("#popup_hover");
    var $product = $("#products .product." + name + ", #trends .product." + name);
    var $link = $(".directlinks .product." + name);
    var $wrap = $(".wrap", $product);
    var type = name.match(/^[pt]/)[0];
    
    if (productinfo_visible || $product.hasClass("active")) {
        // already visible
        return;
    }

    unpopProduct(false);

    playSound("pop");

    if (type == "t") {
        showRoom("trends");
    } else {
        showRoom("products");
    }

    if (!mouseover_viewport) {
        // move viewport to trend/product
        var $viewport = $(".viewport");
        var $view = $(".view", $viewport);
        var offsetX = $view.offset().left - $product.offset().left;
        var offsetY = $view.offset().top - $product.offset().top;
        
        $view.stop().animate({
            left: offsetX * (zoomRatio - 1),
            top: offsetY * (zoomRatio - 1) * 1.4
        });
    }

    $wrap.hide().show(speed);
    $product.addClass("active");
    $link.addClass("active");

    var $popuphover_img = $popuphover.appendTo($product).children("img");
    $popuphover_img[0].src = $popuphover_img[0].src.replace(/pop-[pt]\.png/, "pop-" + type + ".png");

    $popuphover_img.css({
        opacity: 0,
        top: "-8em",
        left: "-8em",
        width: "250%",
        height: "250%"
    }).animate({
        opacity: 1,
        top: "0.5em",
        left: "0.5em",
        width: "80%",
        height: "80%"
    }, {
        duration: speed,
        complete: function() {
            $(this).animate({
                top: "0em",
                left: "0em",
                width: "100%",
                height: "100%"
            }, {
                duration: speed / 3
            });
        }
    });
}
// }}}
// {{{ unpopProduct()
function unpopProduct(animated) {
    if (typeof animated == 'undefined') {
        animated = true;
    }

    var $popuphover = $("#popup_hover");
    var $product = $("#products .product.active, #trends .product.active");
    var $link = $(".directlinks .product.active");
    var $wrap = $(".wrap", $product);

    if (productinfo_visible) {
        // already hidden
        return;
    }

    $product.removeClass("active");
    $link.removeClass("active");

    $popuphover.children("img").stop().hide();

    if (animated) {
        $wrap.fadeOut(speed);
    } else {
        $wrap.stop().hide();
    }
}
// }}}
// {{{ showProductInfo()
function showProductInfo(name) {
    if (productinfo_visible) {
        return;
    }

    var $popuphover = $("#popup_hover");
    var $product = $("#products .product." + name + ", #trends .product." + name);
    var $productinfo = $(".productinfo");

    $productinfo.hide().load($product[0].href + " .productinfo > div", null, function() {
        var $close = $(".close", $productinfo);

        if ($close.length > 0) {
            document.location = "#" + name;

            playSound("popinfo");

            $popuphover.children("img").stop().hide();
            popProduct(name);
            productinfo_visible = true;

            $("body").mouseup(function() {
                hideProductInfo(name);

                return false;
            });
            $(".close", $productinfo).click(function() {
                hideProductInfo(name);

                return false;
            });

            $(".content", $productinfo).hide();

            $productinfo.fadeIn("slow", function() {
                $(".content", $productinfo).slideDown();
            });
        }
    });

    return false;
}
// }}}
// {{{ hideProductInfo()
function hideProductInfo(name) {
    var $productinfo = $(".productinfo");

    if (!productinfo_visible) {
        // product info not visible
        return;
    }

    document.location = "#base";

    $("body").unbind("mouseup");

    productinfo_visible = false;
    unpopProduct();

    $("div", $productinfo).fadeOut(speed, function() {
        $productinfo.hide();

        $("div", $productinfo).remove();
    });

    return false;
}
// }}}

// audio player
// {{{ initFlashAudio
function initFlashAudio() {
    audioInitiated = true;
}
// }}}
// {{{ flashAudioSetCurrentTime
function flashAudioSetCurrentTime(position) {
    audio.currentTime = position;
}
// }}}
// {{{ initAudioPlayer
function initAudioPlayer() {
    var path = $("head script[src$='/global.js']")[0].src;
    path = path.substring(0, path.length - 9);
    hasAudio = false;

    // {{{ native audio support
    try {
        audio = new Audio();

        if (audio.canPlayType("audio/mpeg") == "probably") {
            audio.rewind = function() {
                this.currentTime = 0;
            }
            audioInitiated = true;

            hasAudio = true;
        }
    // }}}
    // {{{ add flash player, when flash is available
    } catch(e) { }

    if (!hasAudio && $.browser.flash("8,0,0")) {
        audioInitiated = false;

        // add flash audio player to play media
        var html = $().flash({
            src:            path + "audio.swf",
            width:          "18px",
            height:         "18px",
            className:      "audio_plugin",
            id:             "audio_plugin",
            transparent:    true
        }).plainhtml;

        var wrap = $("<div></div>").prependTo("#container")[0];
        wrap.innerHTML = html;

        // add audio api functions to control flash audio-player
        audio = {
            src: "",
            currentTime: 0,
            play: function() {
                if (audioInitiated == true) {
                    $("#audio_plugin")[0].audioPlay();
                }
            },
            pause: function() {
                if (audioInitiated == true) {
                    $("#audio_plugin")[0].audioPause();
                }
            },
            load: function() {
                if (audioInitiated == true) {
                    $("#audio_plugin")[0].audioLoad(this.src);
                }
            },
            rewind: function() {
                if (audioInitiated == true) {
                    $("#audio_plugin")[0].audioRewind();
                }
            }
        }

        hasAudio = true;
    }
    // }}}
}
// }}}
// {{{ playSound()
function playSound(sound) {
    if (hasAudio) {
        if (audioInitiated) {
            var path = $("head script[src$='/global.js']")[0].src;
            path = path.substring(0, path.length - 9);

            audio.src = path + sound + ".mp3";
            audio.load();
            audio.play();
        }
    }
}
// }}}

// replace content, depending on reader capabilities
// {{{ replaceEmailChars()
function replaceEmailChars(mail) {
    mail = unescape(mail);
    mail = mail.replace(/ \*at\* /g, "@");
    mail = mail.replace(/ \*dot\* /g, ".");
    mail = mail.replace(/ \*punkt\* /g, ".");
    mail = mail.replace(/ \*underscore\* /g, "_");
    mail = mail.replace(/ \*unterstrich\* /g, "_");
    mail = mail.replace(/ \*minus\* /g, "-");
    mail = mail.replace(/mailto: /, "mailto:");

    return mail;
}
// }}}
// {{{ replaceEmailRefs()
function replaceEmailRefs() {
    $("a[href*='mailto:']").each(function() {
        // replace attribute
        $(this).attr("href", replaceEmailChars($(this).attr("href")));
        
        //replace content if necessary
        if ($(this).text().indexOf(" *at* ") > 0) {
            $(this).text(replaceEmailChars($(this).text()));
        }
    });
}
// }}}
// {{{ replaceFlashContent()
function replaceFlashContent() {
    $("img.flash_repl").each(function() {
    var parent = $(this).parent().prepend( 
        $().flash({
        src:        this.src.replace(/\.jpg|\.gif|\.png/, ".swf").replace(/\&/, "&amp;"),
        width:        this.width,
        height:        this.height,
        className:    "flash",
        id:        this.id ? this.id + "_flash" : null,
        transparent:    $(this).hasClass("trans")
        }) 
    );
    if (parent[0].nodeName == "A") {
        // deactivate link for surrounding a-node in safari
        parent[0].href = "javascript:return false;";
    }
    });
}
// }}}
// {{{ replaceInteractiveContent()
function replaceInteractiveContent() {
    // get language from content tag in header
    var lang = $("meta[name = 'Content-Language']")[0].content;

    // add click event for teaser
    $(".aside.teaser li, .aside.small li").click( function() {
        document.location = $("a", this)[0].href;
    });
    $('.productinfo').click(function(event){
         event.stopPropagation();
    });
    
    $(".product").click(function() {
        return false;
    });

    var $explore = $(".explore");
    var view_css = {
        width: "115.2em",
        height: "76.8em",
        top: "-50px",
        left: "-100px"
    };

    var loc = document.location + "";
    var matches = loc.match(/(^[^#\?]*)(#[pt]-.*)$/);

    if (matches !== null) {
        // show productinfo for specific element
        var hash = matches[2].substr(1);

        $(".viewport .view").css(view_css);
        addRoomHandlers();
        showProductInfo(hash);
    } else if ($explore.length > 0) {
        $explore.fadeIn().click(function() {
            $(this).fadeOut();
            $(".viewport .view").animate(view_css , {
                complete: function() {
                    addRoomHandlers();
                }
            });
        });
    } else {
        var name = $(".productinfo > div").attr("class");

        if (name !== undefined) {
            // redirect to base location for room
            document.location = $(".close")[0].href + "#" + name;
        }
    }
    $(".explore .hint.products").mouseover( function() {
        showRoom("products");
    });
    $(".explore .hint.trends").mouseover( function() {
        showRoom("trends");
    });
    $(".chooser .products").click( function() {
        showRoom("products");

        return false;
    });
    $(".chooser .trends").click( function() {
        showRoom("trends");

        return false;
    });
}
// }}}

// {{{ register events
$(document).ready(function() {
    $("body").addClass("javascript");

    // replace content
    replaceEmailRefs();
    replaceInteractiveContent();
    initAudioPlayer();

    // add flash content
    if ($.browser.flash("8,0,0")) {
        replaceFlashContent();

    $("body").addClass("flash");
    }
});
// }}}
    
/* vim:set ft=javascript sw=4 sts=4 fdm=marker : */

