/**
 * @file    js/global.js
 *
 * copyright (c) 2006-2009 Frank Hellenkamp [jonas@depagecms.net]
 *
 * @author    Frank Hellenkamp [jonas@depagecms.net]
 */

// 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]));
    } 
    flashParams = flashParam.join("&amp;");
    if (flashParams != "") {
        params.src += "?" + flashParams;
    }

    //object part
    html1 += "<object type=\"application/x-shockwave-flash\" ";
    html1 += "data=\"" + params.src + "\" ";
    if (params.width) {
	html1 += "width=\"" + params.width + "\" ";
    }
    if (params.height) {
	html1 += "height=\"" + params.height + "\" ";
    }
    if (params.className) {
	html1 += "class=\"" + params.className + "\" ";
    }
    if (params.id) {
	html1 += "id=\"" + params.id + "\" ";
    }

    //param part
    html2 += "<param name=\"movie\" value=\"" + params.src + "\" />";

    if (params.transparent) {
	html1 += "mwmode=\"transparent\"";
	html2 += "<param name=\"wmode\" value=\"transparent\" />";
    }
    html1 += ">";

    return $(html1 + html2 + "</object>");
};
// }}}
// {{{ jquery.fontsize
jQuery.fontsize = {
    defaultSize: 12,
    init: (function() {
        var savedSize = $.cookie('fontsize');
        if (savedSize) {
            this.setSize(savedSize);
        } else {
            this.reset();
        }
    }),
    setSize: (function(newSize) {
        this.fontsize = parseFloat(newSize, this.defaultSize);  
        $("body").css("font-size", this.fontsize + "px");
        $.cookie('fontsize', this.fontsize);  
    }),
    reset: (function() {
        this.setSize(this.defaultSize);
    }),
    decrease: (function() {
        this.setSize(this.fontsize - 2);
    }),
    increase: (function() {
        this.setSize(this.fontsize + 2);
    })
};
// }}}

// 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() {
    // {{{ replace flash images
    $("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;";
	}
    });
    // }}}
}
// }}}
// {{{ initFlashAudio
function initFlashAudio() {
    audioInitiated = true;
}
// }}}
// {{{ flashAudioSetCurrentTime
function flashAudioSetCurrentTime(position) {
    audio.currentTime = position;
}
// }}}
// {{{ replaceInteractiveContent()
function replaceInteractiveContent() {
    // {{{ add events for gallery
    $(".gallery li").click( function() {
        var imgHeight = $("img", this)[0].height;

        $(this).animate({
            height: imgHeight
        }, {
            complete: function() {
                $(this).addClass("active");
            }
        });
        $("img", this).animate({
            top: 0
        });
        $(".gallery li.active").animate({
            height: "8em"
        }, {
            complete: function() {
                $(this).removeClass("active");
            }
        });
        $(".gallery li.active img").animate({
            top: "-10em"
        });
    });
    // }}}
    // {{{ add behaviour to audio links
    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
        $(".albums").prepend( 
            $().flash({
                src:		path + "audio.swf",
                width:		"18px",
                height:		"18px",
                className:		"audio_plugin",
                id:		        "audio_plugin",
                transparent:        true
            }) 
        );
        // add audio api functions to conrol 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;
    }
    // }}}

    if (hasAudio) {
        // add functionality to audio links
        $(".albums a.title[href$='.mp3']").each(function() {
            this.file = this.href;
            this.href = "#play";
            this.paused = true;

            // add additional html elements
            $(this).parent().append("<a class=\"play\" href=\"#play\"><img src=\"" + path + "play.png\"></a><a class=\"pause\" href=\"#pause\"><img src=\"" + path + "pause.png\"></a><a class=\"rewind\" href=\"#rewind\"><img src=\"" + path + "rewind.png\"></a><a class=\"next\" href=\"#next\"><img src=\"" + path + "next.png\"></a>");
            $(this).siblings("span.time").before("<span class=\"currentTime\">0:00/</span>");

            // {{{ playpause()
            this.playpause = function() {
                if (audioInitiated) {
                    if (this.paused) {
                        this.play();
                    } else {
                        this.pause();
                    }
                }
            }
            // }}}
            // {{{ play()
            this.play = function() {
                if (audio.src != this.file) {
                    var playing = $(".audio_playing");
                    var playing = $(".audio_playing").animate({
                        backgroundColor: "#2A2A2A",
                        lineHeight: "1.7em", 
                        paddingLeft: 0,
                        marginTop: 0,
                        marginBottom: 0
                    }, {
                        duration: 700
                    });
                    playing.children("span.time").css({color: "#ffffff"});
                    playing.children("a.play,a.pause,a.rewind,a.next,span.currentTime").hide();
                    playing.children("a.title").each(function() {
                        this.paused = true;
                        clearInterval(this.intervalID);
                    });
                    playing.each(function() {
                        $(this).removeClass("audio_playing");
                    });
                    audio.src = this.file;
                    audio.load();
                }

                $(this).parent().animate( {
                    backgroundColor: "#ffffff",
                    lineHeight: "2.8em", 
                    paddingLeft: "1em",
                    marginTop: "0.4em",
                    marginBottom: "0.4em"
                }, {
                    duration: 700,
                    queue: false,
                    complete: function() {
                        $(this).addClass("audio_playing");
                    }
                });
                this.paused = false;

                $(this).siblings("span.time").css({color: "#2A2A2A"});
                $(this).siblings("a.play").hide();
                $(this).siblings("a.pause,a.rewind,a.next").show();
                $(this).siblings("span.currentTime").show();

                audio.play();

                // fix for safari not firing event
                this.intervalID = setInterval("$(audio).trigger('timeupdate');", 1000);
            }
            // }}}
            // {{{ pause()
            this.pause = function() {
                this.paused = true;

                $(this).siblings("a.pause").hide();
                $(this).siblings("a.play").show();

                audio.pause();
            }
            // }}}
            // {{{ rewind()
            this.rewind = function() {
                if (Math.floor(audio.currentTime) > 0) {
                    audio.rewind();
                } else {
                    var songs = $(".albums a.title[href='#play']");

                    for (var i = 1; i < songs.length; i++) {
                        if ($(songs[i]).parent().attr("class") == "audio_playing") {
                            $(songs[i - 1]).click();
                        }
                    }
                }
            }
            // }}}
            // {{{ next()
            this.next = function() {
                var songs = $(".albums a.title[href='#play']");

                for (var i = 0; i < songs.length; i++) {
                    if ($(songs[i]).parent().attr("class") == "audio_playing") {
                        if (i != songs.length - 1) {
                            $(songs[i + 1]).click();
                        } else {
                            $(songs[0]).click();
                        }
                    }
                }
            }
            // }}}
            // {{{ click
            $(this).click(function() {
                this.playpause();
                this.blur();

                return false;
            });
            // }}}
            // {{{ timeupdate listener
            $(audio).bind("timeupdate", function() {
                var minutes = Math.floor(audio.currentTime / 60);
                var seconds = Math.floor(audio.currentTime % 60);
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }
                $(".audio_playing .currentTime").text(minutes + ":" + seconds + "/");
            });
            // }}}
            // {{{ add click events to play, pause an rewind buttons
            $(this).siblings("a.play,a.pause").click(function() {
                $(this).siblings("a.title").click();

                return false;
            });
            $(this).siblings("a.rewind").click(function() {
                $(this).siblings("a.title")[0].rewind();
                this.blur();

                return false;
            });
            $(this).siblings("a.next").click(function() {
                $(this).siblings("a.title")[0].next();
                this.blur();

                return false;
            });
            // }}}
        });
    }
    // }}}
}
// }}}
// {{{ startPlaying()
function startPlaying() {
    // play first song
    if (audioInitiated == true) {
        $(".albums a.title[href='#play']:first").click();
    } else {
        setTimeout("startPlaying();", 500);
    }
}
// }}}

// {{{ register events
$(document).ready(function() {
    // replace content
    replaceEmailRefs();
    replaceInteractiveContent();

    // add flash content
    if ($.browser.flash("8,0,0")) {
        replaceFlashContent();

	$("body").addClass("flash");
    }
    
    if ($(".albums").length > 0) {
        startPlaying();
    }
});
// }}}
    
/* vim:set ft=javascript sw=4 sts=4 fdm=marker : */
