$(document).ready(function() {
	restoreHTML()
	$("body").removeClass("degradeStyle")
	testCookie()
	generateEmail();
    latestTabs()
    //makeClickable()
	generateMarkup()
	recallSettings()
	if(ie()==1) { fixHeight() }
	setPictureWidth()
 });

function unclean(x) {	// restore escaped HTML tags
	var y = x.replace(/#lt#/g, "<")
	y = y.replace(/#gt#/g, ">")
	return y
}

function restoreHTML() {
	handMarkup = unclean(handMarkup)
	skillMarkup = unclean(skillMarkup)
	optionsButton = unclean(optionsButton)
	sourcesButton = unclean(sourcesButton)
	showAllTab = unclean(showAllTab)
	skill1Notice = unclean(skill1Notice)
	skill2Notice = unclean(skill2Notice)
	contactText = unclean(contactText)
	contactBroken = unclean(contactBroken)
	choosingOptions = unclean(choosingOptions)
	helpContent1 = unclean(helpContent1)
	helpContent2 = unclean(helpContent2)
}

function makeEmail(email_rot13) {
	// Input: a rot13-encrypted email address
	// Example: fbzrbar@rknzcyr.bet
	// Obtained by encoding someone@example.org using http://rot13.de/index.php

	// Output: a mailto link
	// Example: <a href="mailto:someone@example.org">someone@example.org</a>

	var email = "<n uers=\"znvygb:" + email_rot13 + "\">" + email_rot13 + "</a>";
	return rot13(email);
}

function rot13(string) {	// encodes or decodes rot13
	return string.replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
}

function generateEmail() {	// Email addresses obfuscated by javascript
	$(".emailMissing").remove();
	$(".createEmail").append(makeEmail("zvxr@onqzvagbaovoyr.pbz"));
	$(".emailPresent").removeClass("emailPresent");
}

function testCookie() {		// tests for cookies; creates extra options on pass
	createCookie("test", "pass", 0);
	if (readCookie("test")) {
		if (!readCookie("hand")) { createCookie("hand", 2, 365) }
		createOptions()
	}
}

function testCSS() {
	var x = $("#contentBR").css("width")
	if (x == "23px") { return 1 }   //CSS exists
}

function ie() {		 // cunning browser detect, using conditional comments
	var x = document.getElementById("browserIE"); if (x) { return 1 }
}

function setPictureWidth() {
	$(".picture").each(function() {
		var x =	$(this).find("img").eq(0).attr("width")
		$(this).find("dl").width(x)
	})

}

function latestTabs() {
    $("#articleList").hide()
    $("#tabLatest li").eq(0).addClass("active")
    $("#tabLatest a").eq(0).click(function() {
        $("#tabLatest li").removeClass("active")
        $(this).parents("li").addClass("active")
        $("#articleList").hide()
        $("#videoList").show()
        return false
    })
    $("#tabLatest a").eq(1).click(function() {
        $("#tabLatest li").removeClass("active")
        $(this).parents("li").addClass("active")
        $("#articleList").show()
        $("#videoList").hide()
        return false
    })
}

function makeClickable() {
    $(".latest ul.hoverMe li").each(function(){
        $(this).click(function() {
            window.location = $(this).find("a").attr("href")
            return false
        })
        $(this).hover(
            function() {
                $(this).css({cursor: "pointer"})
                $(this).stop().animate({
                    backgroundColor: "#ffd",
                    borderTopColor: "#ffa500",
                    borderBottomColor: "#ffa500",
                    borderLeftColor: "#ffa500",
                    borderRightColor: "#ffa500"
                }, {queue:false,duration:300})
            },
            function() {
                $(this).css({cursor: "auto"})
                $(this).stop().animate({
                    backgroundColor: "#fff",
                    borderTopColor: "#fff",
                    borderBottomColor: "#fff",
                    borderLeftColor: "#fff",
                    borderRightColor: "#fff"
                }, {queue:false,duration:300})
            }
        )
    })
}

function createOptions() {
	$("#handFallback").remove()
	$("#optionsContent").append(handMarkup)
	if (testCSS()==1) {
        $("#optionsContent").append('<div class=\"tocMargin\"></div>')
		createSourceHide()
		createTabs()
	}
	optionHandlers()
}

function optionHandlers() {
	$(".hand1").click(function(){hand(1)});	$(".hand2").click(function(){hand(2)})
}


function hand(x) {
	if (x == readCookie("hand")) { return }
	if (x == 0) { x = 1 }
    $("#handList input").eq(x-1).attr("checked", "checked")
	$("#handTabs li").removeClass("here"); $("#handTabs li").eq(x-1).addClass("here")
	if (x==1) { $("img[src*='/R_']").each( function() { var s = this.src.split("/R_")[0] + "/L_" + this.src.split("/R_")[1]; this.src = s }) }
	if (x==2) { $("img[src*='/L_']").each( function() { var s = this.src.split("/L_")[0] + "/R_" + this.src.split("/L_")[1]; this.src = s } ) }
	$(".hand, div.tabList a").each( function() {
		if ($(this).text() == left) { $(this).text(right) }
		else if ($(this).text() == Left) { $(this).text(Right) }
		else if ($(this).text() == right) { $(this).text(left) }
		else if ($(this).text() == Right) { $(this).text(Left) }
		else if ($(this).text() == clockwise) { $(this).text(anticlockwise) }
		else if ($(this).text() == Clockwise) { $(this).text(Anticlockwise) }
		else if ($(this).text() == anticlockwise) { $(this).text(clockwise) }
		else if ($(this).text() == Anticlockwise) { $(this).text(Clockwise) }
	})
	createCookie("hand", x, 365)
}


function createSourceHide() {
	$("#sourcesHeading").after(sourcesButton)
	$("#hideSources").click(function(){
		if ($("#hideSources").val() == hideSources) {
			$("#hideSources").val(showSources); createCookie("sources", "hide", 365)}
			else if ($("#hideSources").val() == showSources) {
				$("#hideSources").val(hideSources); createCookie("sources", "show", 365)
			}
		$("#sourcesHeading, #sourcesContent").slideToggle("slow"); if (ie()==1) { fixHeight2() }
	})
}

function recallSettings() {
	var h =	readCookie("hand")
        $("#handList input").eq(1).attr("checked", "checked")  //hack to force Chrome to check a radio box
        if (h==1) { hand(0) }
	var x = readCookie("sources"); if (x == "hide") { $("#hideSources").val(showSources); $("#sourcesHeading, #sourcesContent").hide() }
}

function createTabs() {
	$("dl.tabs").before(showAllTab)
	$("dl.tabs dd").each(function() {
		var x = $(this).attr("class"); var y =  $(this).parents(".tabs").prev(".tabList")
		y.find("li.showAll").before('<li><a href="#"></a></li>')
		y.find("li:not([class])").attr("class", x).find("a").text(x)
	})

    $(".tabList li:first").addClass("here")
    $(".tabs").each(function() {
        $(this).find("dd:gt(0)").hide()
    })
    tabHandlers()


}

function tabHandlers() {
	$("div.tabList li[class!='showAll'] a").click(function(e) {
        e.preventDefault()
        var x = $(this).parent().index()
		$(this).parents("div.tabList").next("div.tabs").find("dd").hide()
		$(this).parents("div.tabList").next("div.tabs").find("dd").eq(x).show()
		$(this).parent().addClass("here").siblings().removeClass("here")
        if (ie()==1) { fixHeight2() }
	})
	$("div.tabList li[class='showAll'] a").click(function(e) {
		e.preventDefault(); $(this).parents("div.tabList").next("div.tabs").find("dd").show()
		$(this).parent().addClass("here").siblings().removeClass("here")
	})
}

function generateMarkup() {
	$("div#contentPage h2").not(".generated, #topicsHeading").append('<span class="h2bg"></span>')
	$("div#contentPage h2").not(".generated, #topicsHeading").addClass("generated").after('<div class="h2Sub"></div>')
	if (ie()==1) {
		$(".lead:not(.generated)").wrap("<div class='gen ieLead'><div><div><div><div><div><div><div></div></div></div></div></div></div></div>").after("<div class='leadBR'></div>")
		$(".tip:not(#pageNav):not(.generated)").wrap("<div class='gen'><div><div><div><div><div><div><div><div></div></div></div></div></div></div></div></div>")
		$(".gen").each(function(i){var c = "generated "+$(this).find(".lead, .tip").attr("class"); $(this).find(".lead, .tip").removeClass(); $(this).attr("class", c)})
		$(".tabList li.showAll").remove()
	}
	else {

		$(".lead:not(.generated)").each(function() {
			var x =	$(this).children().clone()
			var y = $(this).attr("class"); var c = y+" generated"
			$(this).after("<div id='temp'><div class='TL'></div><div class='TR'></div><div class='BL'></div><div class='BR'></div><div class='table'><div class='tr topRow'><div class='td'></div><div class='td'></div><div class='td'></div></div><div class='tr contentRow'><div class='td left'></div><div class='td content'></div><div class='td right'></div></div><div class='tr bottomRow'><div class='td'></div><div class='td'></div><div class='td'></div></div></div></div>")
			$(this).next().attr("class", c).find("div.content").append(x)
			$(this).remove()
			var z = $("div#temp").clone()			// Add a cloning step, so that Webkit will parse the CSS right from the outermost DIV
			$("div#temp").after(z).remove()
			$("div#temp").removeAttr("id")
		})
		$(".tip:not(.generated)").each(function() {
			var x = $(this).clone(); var p = ""
				if ($(this).attr("id") == "pageNav") { p = "pageNav " }
				else { p = "" }
			var y = $(this).attr("class"); var c = p+y+" generated"
			$(this).after("<div id='temp'><div class='TL'></div><div class='TR'></div><div class='BL'></div><div class='BR'></div><div class='table'><div class='tr topRow'><div class='td'></div><div class='td'></div><div class='td'></div></div><div class='tr contentRow'><div class='td left'></div><div class='td content'><div class='gradient'></div></div><div class='td right'></div></div><div class='tr bottomRow'><div class='td'></div><div class='td'></div><div class='td'></div></div></div></div>")
			$(this).next().attr("class", c).find("div.content").prepend(x).children(".tip").removeClass()
			$(this).remove()
			var z = $("div#temp").clone()			// Add a cloning step, so that Webkit will parse the CSS right from the outermost DIV
			$("div#temp").after(z).remove()
			$("div#temp").removeAttr("id")
		})
	}
}

