/*!
 * Tuho-engine (C) 2010-2011 Ville Lahdenvuo
 * 
 * See http://tuhoojabotti.com/ for more information
 *
!*/

/*********************\
\**** CONFIG *********/
var sloganDelay			= 10000;
var footerDelay			= 10000;
var urlBlacklistRegExp	= /\?|\!|\.|,|;|:|'/g;
var pagePath			= "../pages/";
var sloganPath			= "../pages/";
var imgPath				= "../imgs/";
var errorMsg			= 'Whoops! Probably just a missing page, timeout or something else nasty. Try playing <a title="Hosting by K-Pelit" href="http://www.kpelit.net/?c=1378">Crazy Bubbles!</a> while I get it sorted out!';
var editMode			= false;

/*********************\
\**** GLOBAL VARS ****/
var siteLoaded  = false;
var pageLoaded  = false;
var currentPage = "";
var currentTab	= "";
var slogans     = [];
var warnings	= 0;
var plugins     = ['gallery'];

/*********************\
\**** INITIALIZATION */
$(document).ready(function(){
    var plugin = "";
    $("#logo img").attr("src",imgPath+"loading.gif");		// Indicate the user we are loading now.
	// LOAD PLUGINS
    for(plugin in plugins){
        if(plugins.hasOwnProperty(plugin)){
            $.ajax({
              "async": false,
              "url": 'lib/plugins/' + plugins[plugin] + '/plugin.js',
              "dataType": 'script'
            });
            $.getCSS('lib/plugins/' + plugins[plugin] + '/plugin.css');
        }
    }
    // CSS3 CHECK
	if(!Modernizr.borderradius){ShowWarning("Warning: <a href='http://www.css3.info/preview/rounded-border/'>Rounded Borders<\/a> are not supported by your browser. <a href='http://www.google.com/chrome/'>Get Chrome!<\/a>");}
    // LOAD SLOGANS
	$.jsonp({"url": sloganPath+"slogan.json","callback":"slogans",
		"success": function(data){
			slogans = data;
			setInterval(updateSlogan,sloganDelay);
		},"error": function(d,msg){ShowWarning("An error occured while retriewing slogans.");}
	});
	// INITIALIZE NAVIGATION
	$.address.init(function(event){
		$("nav").mouseleave(function(){updateHover($('li[title$="'+currentPage+'"]'));});
		$("nav li").each(function(){						// Clicking the navigation changes the path, but only if it's not the current one.
			$(this).click(function(){
				var title = $(this).attr("title");
				if("/"+currentPage!==title){$.address.path(title);}
			});
			$(this).hoverIntent({
                "over"    : function(){updateHover(this);},
                "out"     : function(){/* Do nothing! */},
                "interval": 50
            });
		});
	})
	// HANDLE URL CHANGE
	.change(function() {
		if(siteLoaded){
			var pNames		= $.address.pathNames();
            var page		= pNames[0];
			//var accordion   = pNames.slice(1);
			// HANDLE PAGE
			if(!page){page = "index"; $.address.path("/index");}
			if(page !== currentPage){currentPage = page; LoadPageContent(page);}
            updateHover($('li[title$="'+currentPage+'"]'));
		}
	});
	// SHOW THE CONTENT!
	$("header").fadeIn(400,function(){
        $("nav").slideDown('fast',function(){
            siteLoaded=true;
            $.address.update();
            updateHover($('li[title$='+currentPage+']')); // Initialize the hover effect.
            $("nav #hover").fadeIn(100);
        });
    });
	// FOOTER ANIMATION
	$("footer").animate({"width":"800px","margin-left":"-400px","opacity":"1"},600);
	var fTimer=setTimeout(hideFooter,footerDelay);
	$("footer").click(function(){
		clearTimeout(fTimer);
		hideFooter();
		$("footer").unbind();
	});
	// ERROR HANDLING, KINDA ;-)
	$("#warning_icon").toggle(
		function(){$('.warning').stop(true,true).slideDown(300);},
		function(){$('.warning').stop(true,true).slideUp(300);}
	);
});

/*********************\
\**** ACCORDION ******/

/*
// POST STRUCTURE
<article>
	<h3>TITLE</h3> – <details open="open">DESCRIPTION</details><aside>DATE</aside>
	<div class="content"><p>CONTENT</p></div>
</article>

// DATA STRUCTURE
page({
    "title": "News &amp; Blog",
    "content": [{ // EXAMPLE OF ARTICLE PLUGIN USAGE
        "type": "article"
        "topic": "@Servers switchin'",
        "description": "Time to get a new server",
        "date": "1.1.2011",
        "text": "<p>After being generously hosted by my mate <a href='http://mikecann.co.uk/'>Mike</a>. I decided it was time to get my own host. I was browsing through many candidates, most of them were okay, but I ended up registering to <a href='http://www.kapsi.fi/english.html'>Kapsi</a>. It's a finnish organization that offers free internet services to it's members. It currently costs 30€ per year, which is very cheap as it gives 50 Gb of space and two shells to play with.</p>"
    }, { // EXAMPLE OF GALLERY PLUGIN USAGE
        "type": "gallery"               // Which plugin to use to create the content
        "topic": "Best of Nature",      // Topic of the content
        "description": "Check this out, new photos!",
        "date": "1.1.2011",
        "config":{                      // Content config
            "path": "pics/nature/",         // Path to pics
            "display": "tab"/"*lightbox",   // How to open the picture when clicked *default
            "perload": 8                    // How many pics per load       
        }
    }, { // EXAMPLE OF LINK PLUGIN USAGE
        "type": "link"               // Which plugin to use to create the content
        "topic": "Linktest",         // Topic of the content
        "description": "Click here to open Google!",
        "date": "1.1.2011",
        "href": "http://google.com/",// Url to open
    }]
});
*/

function OpenContent(article){
    $("h3",article).addClass("open").animate({"font-size":'1.6em'},100,function(){$(".content",article).slideDown(100);});
    if(DecodeUrl($.address.pathNames().slice(1).join(" ")).indexOf(EncodeTitle($(article).data("url"))) === -1){
        $.address.path($.address.path()+"/"+EncodeTitle($(article).children("h3").text())); //If not on url then add it
    }
}
function CloseContent(article){ //Just by updating the url we call the update event which does the job for us.
    $(article).children(".content").slideUp(100,function(){$(article).children("h3").removeClass("open").animate({"font-size":"1.2em"},100);});
    $.address.path($.address.pathNames()[0]+"/"+DecodeUrl($.address.pathNames().slice(1).join("/")).replace(EncodeTitle($(article).children("h3").text()),''));
}

function CreateContent(data,error,append){
	// Create a piece of content
	var article = $('<article '+(error===true?'class="error"':'')+'><h3>'+data.topic+'</h3> &ndash; <div class="description" open="open">'+data.description+'</div><aside title="Last modified"> '+(data.date!==undefined?data.date:"before 02.02.2011")+'</aside><div class="content"></div></article>');
	if(append===undefined){
		article = article.appendTo("section");
	}else{
		$("h2").after($(article));
	}
	// See if it should be opened
	$(article).data("url",EncodeTitle($(article).children("h3").text().replace('@',''))); //Add some data to the element
	var open = (data.topic.match("^@") && $.address.pathNames().slice(1).join(" ") === "") || (DecodeUrl($.address.pathNames().slice(1).join(" ")).indexOf($(article).data("url")) !== -1);
	$(article).children("h3").text($(article).children("h3").text().replace('@','')); //Clear this metadata
	if(open){OpenContent(article);}
	// Assign events to it
	article.children("h3").click(
		function(){
            if($(this).hasClass("open")){   // It's open, close it.
				CloseContent(this.parentNode);
			}else{							// It's closed, open it.
				OpenContent(this.parentNode);
			}
		}
	);
    // Let's bring it to life!
    try {
        window[data.type + "PluginInit"](data, article);
    }catch(e) {
        ShowWarning('Oops failed to use plugin: ' + data.type + '<br /><details open="closed">' + e + '</details>');
    }
	return article;
}

// BASIC ARTICLE PLUGIN IS HARDCODED
function articlePluginInit(data, context){ $(".content",context).html(data.text); }
// ALSO LINK PLUGIN, BECAUSE I JUST MADE IT!
function linkPluginInit(data, context){ $("h3",context).unbind().html('<a href="'+data.href+'">' + $("h3",context).html() + '</a>'); }

function LoadPageContent($uri){
	$("section").fadeOut(200,function(){
        $("#logo img").attr("src",imgPath+"loading.gif");   //Loading...
		pageLoaded = false;
        if(!$uri){$uri = "index";}
		$.jsonp({
			"url": pagePath+$uri.toLowerCase()+".json","callback":"page",
			"success": function(data) {						// Success!
				$("section").empty().append('<h2>&#8226; '+data.title+' &#8226;</h2>');
				$.each(data.content,function(){ CreateContent(this); });
				if(editMode===true){InitEditing();}
				pageLoaded=true;
				$("section").fadeIn(200,function(){$("#logo img").hide().attr("src",imgPath+"logo.png").fadeIn(500);});
			},"error": function(d,msg){						// Ooops!
				$("section").empty().append('<h2 style="text-shadow:red 2px 2px 3px;color: black;">&#8226; Error &#8226;</h2>');
				CreateContent({"topic": "@Hey, why did you break it?","description": "Yes, I'm blaming you!","post": "<p>"+errorMsg+"</p>"},true);
				pageLoaded=true;
				$("section").fadeIn(200,function(){$("#logo img").hide().attr("src",imgPath+"logo.png").fadeIn(500);});
			}
		});		
	});
}

/*********************\
\**** MISC HELPERS ***/

function hideFooter(){
	$("footer").animate({'width':'25px','margin-left':'-12px','opacity':'0'},600,function(){$(this).remove();});
}
function updateSlogan(){
	//ANIMATE IT! (Using CSS3 TRANSFORMATIONS!)
    if(Modernizr.csstransforms){
        $("header cite").css({
            "top":'-20px',
            "opacity":'0',
            "-webkit-transform":"scale(0.2,0.2)",
            "-moz-transform":"scale(0.2,0.2)",
            "-o-transform":"scale(0.2,0.2)"
        });setTimeout(function(){$("header cite").html("&ldquo;"+slogans[Math.ceil(slogans.length*Math.random()-1)]+"&rdquo;").css({
            "top":'0px',
            "opacity":'1',
            "-webkit-transform":"scale(1,1)",
            "-moz-transform":"scale(1,1)",
            "-o-transform":"scale(1,1)"
        });},800);
    }else{ // Fallback to js :/ (Just a quick fade...)
        $("header cite").fadeOut(800,function(){$("header cite").html("&ldquo;"+slogans[Math.ceil(slogans.length*Math.random()-1)]+"&rdquo;").fadeIn(800);});
    };
}
function DecodeUrl(url){
	return decodeURIComponent(url).replace(/\s|\+/g,'-').toLowerCase();
}
function EncodeTitle(title){
	return title.replace(urlBlacklistRegExp,'').replace(/\s|\+/g,'-').toLowerCase();
}
function ShowWarning(t,d){
	warnings++;if(warnings===1){$("#warning_icon").fadeIn(1000);}
	$("#warning_icon").html(warnings+'<img src="imgs/error.png" width="16" height="16" alt="error" title="Click to see errors" />');
	$('<p class="warning">'+t+'</p>').appendTo('#warnings').slideDown(500).delay((d===undefined)?10000:d).slideUp(1000);
}
function updateHover(title){
	if(!title){return;}
	p = $(title).position();
	l = $(title).innerWidth();
	//ANIMATE IT! (Using CSS3 TRANSFORMATIONS!)
    if(Modernizr.csstransforms){
        $(title).css({"color":"rgb(255,255,255)", "top":"-5px"}).siblings().css({"color":"rgb(255,207,121)", "top":"0px"});
        $("#hover").css({"width":l - 4, "left":p.left});
    }else{ // Fallback to js :/
        $(title).animate({"color":"rgb(255,255,255)", "top":"-5px"},200).siblings().stop(true).animate({"color":"rgb(255,207,121)", "top":"0px"},200);
        $("#hover").stop(true).animate({"width":l - 4, "left":p.left},300);
    }
}

