
$(function() {
	// attach cookie-setting handler to hreflang-anchors, so we don't override explicit user choices
    $("a[hreflang]").click(function() {
    	$.cookie("explicitLanguageChoice", "yes", {path: "/"});
    });

	if ($.cookie("explicitLanguageChoice") != "yes") {
        var langMetaTags = $("link[rel='alternate'][type='text/html'][hreflang]");
        var acceptLang = "en-us,en;q=0.5";
    
        // focus only on first preference
        var prefLang = acceptLang.substring(0, acceptLang.indexOf(';'));
        var ind = prefLang.indexOf(',');
        if (ind != -1) {
            prefLang = prefLang.substring(0, ind);
        }
        
        // is the current page already in the right language?
        if ($("meta[http-equiv='Content-Language']")[0].content == prefLang) {
        	return;
        }
                
        // attempt to find match for entire locale (e.g., 'de-DE')
        for (var i = 0; i < langMetaTags.length; i++) {
            var tag = langMetaTags[i];
            if (tag.hreflang == prefLang) {
	            $.cookie("explicitLanguageChoice", "yes", {path: "/"});
                window.location.href = tag.href;
                return;
            }
        }
        
        // if we're here, then match has failed; attempt to find match for just the first part (e.g., 'de')
        prefLang = prefLang.substring(0, 2);
        for (var i = 0; i < langMetaTags.length; i++) {
            var tag = langMetaTags[i];
            if (tag.hreflang.substring(0, 2) == prefLang) {
	            $.cookie("explicitLanguageChoice", "yes", {path: "/"});
                window.location.href = tag.href;
                return;
            }
        }
        
        // if we're here, everything has failed, redirect to german site...
        for (var i = 0; i < langMetaTags.length; i++) {
            var tag = langMetaTags[i];
            if (tag.hreflang == 'de-DE') {
	            $.cookie("explicitLanguageChoice", "yes", {path: "/"});
                window.location.href = tag.href;
                return;
            }
        }
    }
});