// Window load functions to execute
//addLoadEvent(test);
addLoadEvent(function() { if (BrowserDetect.browser == "Explorer") run_on_IE(); });

function test() {
    Debug(BrowserDetect.browser + " " + BrowserDetect.version + " " + BrowserDetect.OS + "<br />");
}

/* From http://www.dustindiaz.com/top-ten-javascript/ */
function $() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        if (arguments.length == 1)
            return element;
        elements.push(element);
    }
    return elements;
}
/* http://simon.incutio.com/archive/2004/05/26/addLoadEvent */
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}
/* grab Elements from the DOM by className */
function getElementsByClass(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}
/* toggle an element's display */
function toggle(obj) {
    var el = document.getElementById(obj);
    if (el.style.display != 'none') {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
}
/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}


function run_on_IE() {
    sectionLinks();
    //get_chrome();
}

function sectionLinks() {
    var H2s = document.getElementsByTagName('h2');
    var HSH = window.location.hash.replace("#", "");
    if (HSH != "" && H2s.length > 0) {
        for (var i = 0; i < H2s.length; i++) {
            if (H2s[i].attributes['id'] != null) {
                if (H2s[i].attributes['id'].value == HSH) {
                    H2s[i].className = "target";
                }
            }
        }
    }
}

function get_chrome() {
    var HGC = readCookie("HideGetChrome");
    if (HGC != "hide") {
        // Create the "Get Chrome" box
        var T = getElementsByClass("title");
        //var H = document.getElementsByTagName("header")[0];
        var N = document.createElement("h6");
        //Debug(T[0].nodeValue);
        N.nodeValue = 'This site would look better in <a href="http://www.google.com/chrome/">Google Chrome</a>.';
        //Debug(T[0].firstChild.nodeName);
        T[0].insertBefore(N, T[0].firstChild);
        
        //if (H != undefined) {
        //    insertAfter(T, N, H);
        //}
    }
}

function hide_get_chrome() { 
    createCookie("HideGetChrome","hide",365);
}

function addSectionLinksEvent() {
    var H2s = document.getElementsByTagName('h2');
    for (var i = 0; i < H2s.length; i++) {
        var As = H2s[i].getElementsByTagName('a');
        //alert(As.length);
        if(As.length > 0)
            As[0].onmouseup() = sectionLinks();
    }
}

function isMobile() {
    var OS = BrowserDetect.OS;
    if (OS == "iPhone/iPod" || OS == "Pre/Pixi" || OS == "Android")
        return (true);
    return (false);
}

function setFormat() {
    if (document.getElementById && document.getElementsByTagName) {
        var format = readCookie("format");
        if(format == "fixed") fixed();
        else if(format == "fluid") fluid();
    }
}

function setJustification() {
    if (document.getElementById && document.getElementsByTagName) {
        var justification = readCookie("justification");
        if(justification == "flush") flush();
        if(justification == "ragged") ragged();
    }
}

function fixed() {
    var E = document.getElementById("pageContainer");
    E.style.width = "34em";
    E.style.maxWidth = "34em";
    E.style.minWidth = "34em";
    // Set link display text
    var P = document.getElementById("format");
    P.innerHTML = "<a href=\"#\" onclick=\"fluid(); return false;\" title=\"Change to Fluid Layout\">Fixed</a>";
    // Set Cookie
    createCookie("format","fixed",365);
}

function fluid() {
    var E = document.getElementById("pageContainer");
    E.style.width = "75%";
    E.style.maxWidth = "75%";
    E.style.minWidth = "34em";
    // Set link display text
    var P = document.getElementById("format");
    P.innerHTML = "<a href=\"#\" onclick=\"fixed(); return false;\" title=\"Change to Fixed Layout\">Fluid</a>";
    // Set Cookie
    createCookie("format","fluid",365);
}

var exclude = new Array();
exclude[0] = "settings";
exclude[1] = "verse";
exclude[2] = "articlenav";
exclude[3] = "caption";

function flush() {
    var N = document.getElementsByTagName("article")[0].childNodes;
    var found=false;
    for (var i=0; i<N.length; i++) {
        if (N[i].tagName == "P" || N[i].tagName == "BLOCKQUOTE") {
            if(!N[i].attributes["id"] && !N[i].attributes["class"]) {
                N[i].style.textAlign = "justify";
            } else {
                found = false;
                if(N[i].attributes["id"])
                    for(var j=0; j<exclude.length; j++)
                        if(N[i].attributes["id"].value == exclude[j]) {
                            found = true;
                            //break;
                        }
                if(N[i].attributes["class"])
                    for(var j=0; j<exclude.length; j++)
                        if(N[i].attributes["class"].value == exclude[j]) {
                            found = true;
                            //break;
                        }
                if(!found) N[i].style.textAlign = "justify";
            }
        }
    }
    
    var E = document.getElementById("justification");
    E.innerHTML = "<a href=\"#\" onclick=\"ragged(); return false;\" title=\"Change to Ragged Text\">Flush</a>";
    
    createCookie("justification","flush",365);
}

function ragged() {
    var N = document.getElementsByTagName("article")[0].childNodes;
    var found=false;
    for (var i=0; i<N.length; i++) {
        if (N[i].tagName == "P" || N[i].tagName == "BLOCKQUOTE") {
            if(!N[i].attributes["id"] && !N[i].attributes["class"]) {
                N[i].style.textAlign = "left";
            } else {
                found = false;
                if(N[i].attributes["id"])
                    for(var j=0; j<exclude.length; j++)
                        if(N[i].attributes["id"].value == exclude[j]) {
                            found = true;
                            break;
                        }
                if(N[i].className)
                    for(var j=0; j<exclude.length; j++)
                        if(N[i].className == exclude[j]) {
                            found = true;
                            break;
                        }
                if(!found) N[i].style.textAlign = "left";
            }
        }
    }
    
    var E = document.getElementById("justification");
    E.innerHTML = "<a href=\"#\" onclick=\"flush(); return false;\" title=\"Change to Flush Text\">Ragged</a>";
    
    createCookie("justification","ragged",365);
}

function wide() {
    // Deactivate animation control buttons
    // Perform animation
    // Re-activate buttons
    var S = document.getElementById("pageContainer");
    var em = GetComputedStyle(document.body, "font-size").replace("px", "");
    
    //em = 17.33333;

    var StartWidth = GetComputedStyle(S, "width").replace("px", "");
    StartWidth /= em;

    //Debug("Start: " + StartWidth);
    // 50% of body width
    var EndWidth = GetComputedStyle(document.body, "width").replace("px", "") / 2;
    EndWidth /= em;
    
    //Debug(" End: " + EndWidth);
    //doSplineWidth(StartWidth, EndWidth, S, "px");
    doSplineWidth(StartWidth, EndWidth, S, "em");
    
}

function GetComputedStyle(element, style) {
    if (document.defaultView && document.defaultView.getComputedStyle) {
        var styles = document.defaultView.getComputedStyle(element, '');
        if (styles) {
            return (styles[style]);
        }
    }
}

function narrow() {
    var S = document.getElementById("pageContainer");
    var em = GetComputedStyle(document.body, "font-size").replace("px", "");
    var StartWidth = GetComputedStyle(S, "width").replace("px", "");
    StartWidth /= em;
    var EndWidth = 34;
    doSplineWidth(StartWidth, EndWidth, S, "em");
}

function Debug(output) {
    $("debug").innerHTML += output;
}

function doSplineWidth(start, end, E, unit) {
    var Range = end - start;
    var Step = 0;
    var Steps = 40;
    var Delay = 4;
    Debug("Start of Resize: " + E.style.width + "=" + start + unit + "<br />");
    var ID = window.setInterval(
        function() {
            E.style.width = (start + Range * splineValue(Step / Steps)) + unit;
            Step++;
            if (Step > Steps) {
                window.clearInterval(ID);
                Debug("End of Resize: " + E.style.width + "=" + end + unit + "<br />");
                // Set a cookie for the proper width of the article?
            }
        }
    , Delay);
}

function splineValue(percent) {
    // Generate the value of a spline at a certain percent in the range [0,1]
    var x = percent;
    var f = 0.0;
    if (x >= 0 && x <= 1) {
        f = 6 * Math.pow(x, 5) - 15 * Math.pow(x, 4) + 10 * Math.pow(x, 3);
    }
    if (x >= 1) f = 1;
    //document.getElementById("JS_Out").innerHTML = document.getElementById("JS_Out").innerHTML + f + "<br />";
    return (f);
}

function alertSize() {
    /* http://www.howtocreate.co.uk/tutorials/javascript/browserwindow */
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  var S = 'Width = ' + myWidth + '\nHeight = ' + myHeight;
  //window.alert(S);
  return (S);
}


/* Cookie Functions Courtesy Quirks Mode [http://www.quirksmode.org/js/cookies.html] */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
/* End Cookie functions*/

/* Browser detection code courtest Quirks Mode [] */
var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.userAgent,
		    subString: "webOS",
		    identity: "Pre/Pixi"
		},
		{
		    string: navigator.userAgent,
		    subString: "Android",
		    identity: "Android"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();
/* End Browser Detect*/