$(document).ready(function() {
	
	/* URL handler */
	var cur_frag;
	
	setInterval(function(){
		if (cur_frag != location.hash) { // Fires on navigation to site and naviagtion within site.
			location.hash = location.hash || "home"; // If no fragment, then default to home.
			$("#sidebar .nav li[name='" + location.hash.slice(1) + "']").click();
			cur_frag = location.hash;
			$.parse_frag(cur_frag);
		}
	}, 300); // Poll location.hash every 300 milliseconds - virtually no performance hit
	
		
	/* Nav handler */
	$("#sidebar .nav li").click(function() {
		if(location.hash.slice(1) != $(this).attr("name")) location.hash = $(this).attr("name");
	}).hover(function(){
		$(this).addClass("hover");
	}, function(){
		$(this).removeClass("hover");
	});
	
	$("#sidebar .nav li a").click(function(event) {
		event.preventDefault();
	});
	
	
	/* Header+shadow transparency handler */
	if ((navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1)) {
		$("#header").supersleight();
	}
	
	/* Sponsor handler */	
	$("#sidebar .sponsors ul").each(function() {
		var ads = $(this).children("li");
		var size = $(ads).size();
		$(this).empty();
		
		var i = Math.round(Math.random() * (size - 1));
		for (var j = 0; j< size; j++) {
			if (i == size) i = 0;
			$($(ads)[i]).appendTo($(this));
			i++;
		}

	});
	
	/* Google analytics handler */
	//var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	//document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
	//try {
		//var pageTracker = _gat._getTracker("UA-8139137-1");
		//pageTracker._trackPageview();
	//} catch(err) {}
	
	
	/* Google maps handler */
	/**/
	
	/* Loading graphic */
	$("#loading").ajaxStart(function(){
   		$(this).show();
	}).ajaxStop(function(){
   		$(this).hide();
	});
	
	/* Disable selection handler */
	disableSelection($("#sidebar ul").add($("#header")).add($("#subhead")));
																 
});

$.parse_frag = function(frag) {
	var page = frag.match(/\#([a-z]*)/)[1]; // Match page
	var query = (frag.match(/\?/)) ? frag.match(/\?([a-z\-]*)/)[1] : ""; // Match query string
	$.loadpage(page, query);
}

$.loadpage = function(page, query) {
	$.ajax({
		dataType: "html",
		url: "public/html/" + page + ".html",
		error: function() {
			location.hash = "home";
		},
		success: function(data) {
			$("#sidebar .nav li[name='" + page + "']").addClass("active").animate({marginLeft: "12px"}, 300).siblings().removeClass("active").animate({marginLeft: "0px"}, 300);
			$("#main").html(data.match(/<body>([\s\S]*)<\/body>/)[1]);
			document.title = "TiECON East 2009 :: " + page;
		},
		complete: function() {
			injectbind();
			if (query) $.scrollTo($("#" + query), 1000);
		}
	});
}

function injectbind(){
		
	/* Transparency handler */
	if ((navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1)) {
		$("#main ul.bullet").supersleight();
	}
	
	/* Agenda tabs handler */
	$("#main .agenda_tab").click(function(){
		$(this).css("background-position", "bottom").siblings(".agenda_tab").css("background-position", "top");
		$("." + $(this).attr("id")).fadeIn(450);
		$("." + $(this).siblings(".agenda_tab").attr("id")).hide();
	});
	
	/* Panel handler */
	$("#main .panel .arrow, #main .panel .heading").click(function(){
		$(this).siblings().andSelf().filter(".arrow").toggleClass("active");
		$(this).siblings(".desc").slideToggle("fast");
	});
	
	/* FAQ link handler */
	$("#main .faq li").hover(function() {
		$(this).css("text-decoration", "underline");
  	}, function() {
	  	$(this).css("text-decoration", "none");
  	}).click(function(){
		$(this).scroll();
	});
	
	/* Entrepreneur Forum link handler */
	$("#main a[href='#eforum']").click(function() {
		$.scrollTo(0, 0);
	});
	
	/* Speaker link handler */
	$("#main .panel .photos li[name]").css("cursor", "pointer").click(function() {
			
		$("#sidebar .nav li[name='speakers']").click();
		$.scrollTo(0, 0);
		$.loadpage("speakers", $(this).attr("name"));
		
	});
	
	$("#main .panel .photos li a").click(function(event) {
		event.stopPropagation();
	});
	
	/* Disable handler */
	disableSelection($("#main .panel .arrow, #main .panel .heading, img"));
	
	/* Panel description engrave handler */
	//$("#main .panel .desc p").engrave();
	
	if(location.hash.slice(1) == "home") {		
		var posts = new google.feeds.Feed("http://tieconeast.wordpress.com/feed/");
		var comments = new google.feeds.Feed("http://tieconeast.wordpress.com/comments/feed/");
		
		posts.load(function(result) {
			var entry = result.feed.entries[0];
			var entry_id = entry.content.match(/com\/(\d{2,})/)[1];

			$("#feed").append('\
			<h1 class="small_margin"><a href="' + entry.link + '">' + entry.title + '</a></h1> \
			<h2 class="margin">' + new Date(entry.publishedDate).toDateString() + ' by ' + entry.author + '</h2> \
			<p>' + entry.content.replace(/(<([^>]+)>)/ig,"").substr(0, 500).replace(/^\s+|\s+$/g, '') + '...</p> \
			<h5 class="small_margin">Posted in ' + entry.categories[0] + '</h5> \
			<p class="big_margin"><a target=_blank class="link" href="' + entry.link + '">Continue Reading</a> | <a target=_blank class="link" href="http://tieconeast.wordpress.com">More Entries</a></p>');
			
			comments.load(function(result) {
				
				//alert(entry_id);
				
				var i = 0;
				if (result.feed.entries[i].title.indexOf($("#feed h1 a").html()) == -1) $("#feed").append("<div class='comment'><h1 class='margin'>No comments yet.</h1></div>");
				else {
					while (result.feed.entries[i].title.indexOf($("#feed h1 a").html()) != -1) {
					
						var comment = result.feed.entries[i];
						$("#feed").append("<div class='comment'><h1>" + comment.title.substr(comment.title.lastIndexOf("by ") + 3) + " says:</h1><p>" + comment.content.replace(/(<([^>]+)>)/ig,"") + "</p></div>");
					
						i++;
					}
				}
				
				$("#feed").append('\
				<form action="http://tieconeast.wordpress.com/wp-comments-post.php" method="post" id="commentform"> \
					<input type="hidden" name="comment_post_ID" value="' + entry_id + '" id="comment_post_ID" /> \
					<input type="hidden" name="comment_parent" id="comment_parent" value="0" /> \
					<fieldset> \
						<input type="text" name="author" id="author" style="height: 16px;" tabindex="1" aria-required="true" /> \
						<label for="author">Name (required)</label> \
					</fieldset> \
					<fieldset> \
						<input type="text" name="email" id="email" style="height: 16px;" tabindex="2" aria-required="true" /> \
						<label for="email">Email (not published) (required)</label> \
					</fieldset> \
					<fieldset> \
						<input type="text" name="url" id="url" value="" style="height: 16px;" tabindex="3" /> \
						<label for="url">Website</label> \
					</fieldset> \
					<textarea name="comment" id="comment" tabindex="4"></textarea> \
					<input name="submit" type="submit" id="submit" style="margin: 0 24px 12px 0; width: 125px;" tabindex="5" value="Submit Comment" /> \
					<input type="checkbox" name="subscribe" id="subscribe" style="clear: none; margin: 2px 6px 0 0; width: 16px;" value="subscribe" style="width: auto;" /> \
					<label for="subscribe" id="subscribe-label" style="clear: none; margin: 3px 0 0 0; width: 300px;">Notify me of follow-up comments via email.</label> \
				</form>');
				
			});
			
		});
	
	}
	
}

$.fn.scroll = function(){
	$.scrollTo($("#" + $(this).attr("name")), 1000);
}

//$.fn.disableSelection = function() {
//}

function disableSelection(target){
	if (typeof target[0].onselectstart!="undefined") { //IE route
		for (var i = 0; i < target.length; i++) {
			target[i].onselectstart=function(){return false}
		}
	} else if (typeof target[0].style.MozUserSelect!="undefined") {//Firefox route
		for (var i = 0; i < target.length; i++) {
			target[i].style.MozUserSelect="none";
		}
	} else //All other route (eg: Opera)
		for (var i = 0; i < target.length; i++) {
			target[i].onmousedown=function(){return false}
			target[i].style.cursor = "default";
		}
}

/*$.fn.engrave = function(c, o) {
	var html = $(this).html();
	var color = (typeof(c) == "undefined") ? "#fff" : c;
	var color = (typeof(o) == "undefined") ? "0.4" : o;
	$(this).html("");
	$(document.createElement("span")).html(html).addClass("engraved").css({"color" : "#fff", "opacity" : "0.3"}).appendTo($(this));
	$(document.createElement("span")).html(html).addClass("unengraved").appendTo($(this));
	
}*/

$.preloadImages = function(){
	for(var i = 0; i<arguments.length; i++) {
		$("<img>").attr("src", arguments[i]);
	}
}