/**
 * @file    js/global.js
 *
 * copyright (c) 2006-2010 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.iphone
jQuery.browser.iphone = function() {
    return /iphone/.test(navigator.userAgent.toLowerCase());
}();
// }}}
// {{{ 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]));
    }

    //object part
    html1 += "<object type=\"application/x-shockwave-flash\" ";
    html1 += "data=\"" + params.src + "?" + flashParam.join("&amp;") + "\" ";
    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 + "\" ";
    }

    //param part
    html2 += "<param name=\"movie\" value=\"" + params.src + "?" + flashParam.join("&amp;") + "\" />";

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

    return $(html1 + html2 + "</object>");
};
// }}}

// jquery replacmenets/extensions
// {{{ jquery fx custom
jQuery.fx.prototype.custom = function(from, to, unit){
    this.startTime = (new Date()).getTime();
    this.start = from;
    this.end = to;
    this.unit = unit || this.unit || "px";
    this.now = this.start;
    this.pos = this.state = 0;
    this.update();

    var self = this;
    function t(){
        return self.step();
    }

    t.elem = this.elem;

    jQuery.timers.push(t);

    if ( jQuery.timers.length == 1 ) {
        var timer = setInterval(function(){
            var timers = jQuery.timers;
            
            for ( var i = 0; i < timers.length; i++ ) {
                if ( !timers[i]() ) {
                    timers.splice(i--, 1);
                }
            }

            if ( !timers.length ) {
                clearInterval( timer );
            }
        }, 75);
    }
}
// }}}

// 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
    $(".teaser").click( function() {
        document.location = $("a", this)[0].href;
    });
    // }}}
    // {{{ add popupmenu for n2
    $("#navigation ul#n2").hover( function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });
    // }}}
    // {{{ add popupmenu filters
    function showPopupCategory(name, link) {
        // close other popups
        $(".popup").hide();
        $(".section.projects .details a").removeClass("active");

        if (link.hasClass("active")) {
            link.removeClass("active");
            $("." + name + ".popup").hide();
            $(".prevnext").removeClass("open");
        } else {
            // remove active-maker for other filters
            $("#n3 .filter_kategorie a, #n3 .filter_name a, #n3 .filter_land a").removeClass("active");

            link.addClass("active");
            $("." + name + ".popup").show();
            $(".prevnext").addClass("open");
        }
        link.blur();

        return false;
    }

    function showThumbs(link) {
        // close other popups
        $(".popup").hide();
        $(".section.projects .details a").removeClass("active");

        var catInfoIsOpen = $(".info:not(.details)").length > 0;

        if (link.hasClass("active")) {
            link.removeClass("active");
            $(".thumbnails.popup").hide();
            $(".article, .info.details, .prevnext").show();
            $("#description").hide();
            $("img", link).each( function() {
                this.src = this.src.replace(/_active\.png/, ".png");
            });
        } else {
            link.addClass("active");
            $(".thumbnails.popup").show();
            if (catInfoIsOpen) {
                $(".thumbnails.popup").addClass("catinfoopen");
            } else {
                $(".thumbnails.popup").removeClass("catinfoopen");
            }
            $(".article, .info.details, .prevnext").hide();
            $("img", link).each( function() {
                this.src = this.src.replace(/\.png/, "_active.png");
            });
        }
        link.blur();

        return false;
    }

    $("#n3 .filter_kategorie").click( function() {
        return showPopupCategory("filter_kategorie", $("a", this));
    });
    $("#n3 .filter_name").click( function() {
        return showPopupCategory("filter_name", $("a", this));
    });
    $("#n3 .filter_land").click( function() {
        return showPopupCategory("filter_land", $("a", this));
    });
    $("#n3 .thumbs").click( function() {
        return showThumbs($("a", this));
    });

    $(".subnav.filter_name a").each( function() {
        var maxlength = 19;
        var text = $(this).text();

        if (text.length > maxlength) {
            var shorttext = text.substring(0, maxlength - 3) + "…";
        } else {
            var shorttext = text;
        }

        $(this).text(shorttext);
    });
    
    // }}}
    
    // {{{ add detail handler for info
    $(".section.projects .details, .section .newsentry h2").each( function() {
        var content = $(this).next(".description").hide();

        $(this).filter("h2").add("a", this).not(".share a").click( function() {
            if ($(this).hasClass("active")) {
                $(this).prev(".date").removeClass("active");
                $(this).removeClass("active").blur();
                $(".prevnext").removeClass("open");
                content.hide();
            } else {
                // hide other popups
                $(".popup").hide();
                $(".description").hide();
                $(".date.active, h2.active").removeClass("active");

                $(this).prev(".date").addClass("active");
                $(this).addClass("active").blur();
                $(".prevnext").addClass("open");
                content.show();
            }
            return false;
        });
    });
    $(".section .newsentry:first h2").click();
    // }}}
    // {{{ add handler for subpages
    $(".subpages").each( function() {
        var pagecontainer = $(this);
        var subpages = $(".subpage", this);
        var activePage = 0;

        if (subpages.length > 1) {
            pagecontainer.append("<a href=\"#prev\" class=\"prev\"></a><a class=\"next\" href=\"#next\"></a>");
        }

        function showPage(page) {
            if (page >= subpages.length) {
                activePage = subpages.length - 1;
            } else if (page < 0) {
                activePage = 0;
            } else {
                activePage = page;
            }
            pagecontainer.animate({
                marginLeft: (activePage * -31.5) + "em"
            });
        }
        
        $(".prev", pagecontainer).click( function() {
            showPage(activePage - 1);
            $(this).blur();

            return false;
        });
        $(".next", pagecontainer).click( function() {
            showPage(activePage + 1);
            $(this).blur();

            return false;
        });
    });
    // }}}
    
    // {{{ add handlers for slideshow images
    $(".slideshow").each( function() {
        var divs = $("div", this);
        var speed = Number($(this).attr("data-slideshow-speed"));
        if (!speed) {
            var speed = 3000;
        }

        var pause = Number($(this).attr("data-slideshow-pause"));
        if (!pause) {
            var pause = 3000;
        }
        // no animation on iphone
        if ($.browser.iphone) {
            speed = 0;
            pause = 1000000;
        }

        divs.css({
            top: 0
        });
        for (var i = 1; i < divs.length; i++) {
            $(divs[i]).hide();
        }

        var fadeIn = function(n) {
            // wait
            $(divs[n]).animate({empty: 0}, pause, function() {
                // fade in
                $(this).fadeIn(speed, function() {
                    if (n < divs.length - 1) {
                        // fade in next image
                        fadeIn(n + 1);
                    } else {
                        // hide all images, fade out last
                        for (var i = 1; i < divs.length - 1; i++) {
                            $(divs[i]).hide();
                        }
                        $(divs[n]).animate({empty: 0}, pause, function() {
                            $(divs[n]).fadeOut(speed, function() {
                                fadeIn(1);
                            });
                        });
                    }
                });
            });
        }
        fadeIn(1);
    });
    // }}}
    
    // {{{ add handlers for share buttons
    $(".share").toggle(function() {
        $("#sharepopup").show();
    }, function() {
        $("#sharepopup").hide();
    }).each(function() {
        $("#sharepopup a").click(function() {
            document.location = this.href;

            return false;
        });
    });
    // }}}
}
// }}}
/* {{{ addTouchEvents() */
function addTouchEvents() {
    if (!$.browser.msie) {
        if ($(".prevnext").length > 0) {
            var prevlink = $(".prev_project")[0].href;
            var nextlink = $(".next_project")[0].href;

            $("body").touchwipe({
                wipeLeft: function() { 
                    document.location = nextlink;
                },
                wipeRight: function() { 
                    document.location = prevlink;
                },
                min_move_x: 30,
                preventDefaultEvents: true
            });
        }
    }
}
/* }}} */
/* {{{ addFormEvents() */
function addFormEvents() {
    // {{{ replace labels with extra submit button
    $("#bestarchitects-products .input-number").each( function() {
        var text = $(".label", this).hide().text();
        var input = $("input", this)[0];

        $(this).append("<input type=\"submit\" value=\"" + text + "\">").click( function() {
            if (input.value == 0) {
                input.value = 1;
            }
        });
    });
    // }}}
    // {{{ replace buttons by textlinks
    var formnum = 0;

    $("form").each(function() {
        var form = this;

        $("input:submit", form).each( function() {
            var $button = $(this);

            $button.hide();
            $button.after( 
                $("<a href=\"#\" class=\"textbutton\">" + this.value + "</a>").click(function() {
                    $button.click();

                    return false;
                })
            );
        });
    });
    // }}}
    
    $("#bestarchitects-order-step0").each( function() {
        var form = this;

        $("#bestarchitects-order-step0-has_delivery_address input").each( function() {
            if (this.checked) {
                $("#deliveryaddress", form).show();
            } else {
                $("#deliveryaddress", form).hide();
            }
            $(this).change( function() {
                if (this.checked) {
                    $("#deliveryaddress", form).show();
                } else {
                    $("#deliveryaddress", form).hide();
                }
            });
        });
    });
}
/* }}} */
// {{{ resizeFullscreenImgs()
function resizeFullscreenImgs() {
    var availableHeight = [
        1200,
        900,
        600
    ];
    
    var defaultW = 1600;
    var defaultH = 1200;

    var content = $("#content");
    var view = $(window);

    var areaH = view.height();
    var areaW = view.width();

    if (content.height() > areaH) {
        areaH = content.height();
    }
    if (content.width() > areaW) {
        areaW = content.width();
    }

    if (areaW / areaH < defaultW / defaultH) {
        var newH = areaH;
        var newW = Math.ceil(defaultW / defaultH * areaH);
    } else {
        var newH = Math.ceil(areaW * defaultH / defaultW);
        var newW = areaW;
    }
    
    var newML = (areaW - newW) / 2;
    var newMT = (areaH - newH) / 2;
    
    $("#background").css({
        height: areaH,
        width: areaW
    });
    $("#background .images").css({
        left: newML,
        top: newMT,
        height: newH,
        width: newW
    });

    var imgH = availableHeight[0];
    if (!$.browser.iphone) {
        // get fitting image size, but keep smallest size for iphone
        for (var i = 0; i < availableHeight.length; i++) {
            if (newH < availableHeight[i] * 1.5) {
                imgH = availableHeight[i];
            }
        }
    }
    var imgW = Math.floor(defaultW / defaultH * imgH);

    $("#background img").each(function() {
        var newSrc = this.src.replace(/\.resize_([^x]+)x([^x]+)/, "") + ".resize_" + imgW + "x" + imgH;
        this.src = newSrc;
        //$("h2").text(imgW + "x" + imgH);
    })
}
// }}}

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

    // add resizer
    $(window).resize( resizeFullscreenImgs );
    $(".fullscreenImg img").load( resizeFullscreenImgs );

    // add form events
    addFormEvents();

    // add touch events
    addTouchEvents();

    // replace content
    replaceEmailRefs();
    replaceInteractiveContent();
    resizeFullscreenImgs();
    setTimeout("resizeFullscreenImgs()", 200);
    
    // hide urlbar
    if ($.browser.iphone) {
        $(window).load(function() {
            this.scrollTo(0, 1);
        });
    }
});
// }}}
    
/* vim:set ft=javascript sw=4 sts=4 fdm=marker : */

