/**************************************************************************************************************
                                     JAVASCRIPT CONTENT ENABLE/DISABLE
**************************************************************************************************************/
$(document).ready(function() {
	$(".javascript_enabled").show();
	$(".javascript_disabled").hide();
});

/**************************************************************************************************************
                                                 ROUNDABOUT
**************************************************************************************************************/
function initialize_roundabout(){
	//Constructor
	$("div.moveMe").roundabout({
		childSelector: 	"div.moveable",	 
//		btnNext: 		"#next",
//		btnPrev: 		"#previous",
		reflect: 		true, //Reverse roundabout direction
		duration: 		400, // in milliseconds, of course
		minOpacity: 	1, // invisible!
		minScale: 		0.5, // tiny!
		easing:			"easeOutQuad"
	});
	
	//Temporary solution until RoundAbout V2 comes out.
	//btnNext and btnPrevious have been commented out in the roundabout constructor.
	//Once V2 comes out, this segment can be deleted and the two buttons commented back in.
	//The invisible div id="skip" in "forside" can also be deleted.
	var last_in_focus = "0";
	$(".moveMe").focus(function(){
		last_in_focus = $(".roundabout-in-focus").attr('id');
	});
	$("#next").click(function(e){
		e.preventDefault();
		if(last_in_focus == "6"){
			$(".moveMe").roundabout_animateToChild(0);
		}else {
			$(".moveMe").roundabout_animateToNextChild();
		}
	});
	$("#previous").click(function(e){
		e.preventDefault();
		if(last_in_focus == "0"){
			$(".moveMe").roundabout_animateToChild(6);
		}else {
			$(".moveMe").roundabout_animateToPreviousChild();
		}
	});
	
	//Move RouundAbout with arrow keys, and open with enter.
	//This can be simplified, after V2 comes out, by simply calling "roundabout_animateToNext/PreviousChild".
	$(document).keydown(function(e) {
		if($("#popup").css("display") == "none"){
			if (e.keyCode == 39) {
				e.preventDefault();
				if(last_in_focus == "6"){
					$(".moveMe").roundabout_animateToChild(0);
				}else {
					$(".moveMe").roundabout_animateToNextChild();
				}
			}else if(e.keyCode == 37) {
				e.preventDefault();
				if(last_in_focus == "0"){
					$(".moveMe").roundabout_animateToChild(6);
				}else {
					$(".moveMe").roundabout_animateToPreviousChild();
				}
			}else if(e.keyCode == 13) {
				e.preventDefault();
				var page_id = $(".roundabout-in-focus a").attr("href");
				var anchor_index = page_id.indexOf("#");
				if(anchor_index != -1){
					page_id = page_id.substring(anchor_index+1);
					//First open popup
					open_popup();
					//Then load content
					load_content_external(page_id);
					//And update url
					switch_url(page_id);
				}else{
					window.location = page_id;
				}
			}
		}
	});
}

function initialize_roundabout_links(){
	//Event for links inside roundabout element, which are otherwise prevented from following the url.
	$("a.roundabout_link, a.roundabout_link_external").click(function(e) {	
		//Get page url and update.
		var page_id = $(this).attr("href");
		if(page_id != "" || page_id != undefined || page_id != null){
			window.location = page_id;
		}
	});
	
	//Move roundabout to correct image, when corresponding link is clicked.
	$(".menu_intro").click(function(e) {
		$(".moveMe").roundabout_animateToChild(0);
	});
	
	$(".menu_workarea").click(function(e) {
		$(".moveMe").roundabout_animateToChild(1);
	});
	
	$(".menu_customers").click(function(e) {
		$(".moveMe").roundabout_animateToChild(2);
	});
	
	$(".menu_job").click(function(e) {
		$(".moveMe").roundabout_animateToChild(3);
	});
	
	$(".menu_about").click(function(e) {
		$(".moveMe").roundabout_animateToChild(4);
	});
	
	$(".menu_contact").click(function(e) {
		$(".moveMe").roundabout_animateToChild(5);
	});
	$(".menu_blog").click(function(e) {
		$(".moveMe").roundabout_animateToChild(6);
	});
}

$(document).ready(function() {  
	initialize_roundabout();
	initialize_roundabout_links();
});

/**************************************************************************************************************
										JQUERY ADDRESS - SITE NAVIGATION
**************************************************************************************************************/
//Alters the url for AJAX request to allow for browser history functionality.
function switch_url(page_id)
{
	if(page_id != ""){
		//Set the title, visible on browser tabs, to correct value.
		var browser_tab = page_id;
		//Only last part of the url.
		browser_tab = browser_tab.substring(browser_tab.indexOf("/")+1); //Fails silently
		//First letter gets capitalized. Underscores get converted to spaces.
		browser_tab = browser_tab.charAt(0).toUpperCase() + browser_tab.slice(1).replace(/_/g, " ");
		browser_tab += " | IT Minds";
		$.address.title(browser_tab); 
		//Set the visible url to correct value
		$.address.value(page_id);
	}else{
		//Default to IT Minds if the url is emtpy.
		$.address.title("IT Minds"); 
		$.address.value(page_id);
	}
}

//Loads popup content based on url anchor-tag from the browser history.
function load_content_external(page_id){
	if(page_id != ""){
		
		//First check if it's a parent or child page.
		//If it's a child page...
		var divide_index = page_id.indexOf("/");
		if(divide_index != -1){
			var parent = page_id.substring(0, divide_index);
			var child = page_id.substring(divide_index+1);
			
			//If so, then check if the previous page is/has the same parent, and therefore the same submenu.
			if(parent == window.custom_referer){
				//Fade previous content
				$(".popup_article").fadeToggle(200, function() {;
					//Animation complete
					//Load page data
					get_subpage(page_id);
				});
				//Return previously active link to normal and set new link as active.
				$(".local_navigation_active").toggleClass("local_navigation_active");
				$(".local_navigation").each(function(){
					if($(this).attr("href").substring($(this).attr("href").indexOf("#")+1) == page_id){
						$(this).toggleClass("local_navigation_active");
						return false;
					}
				});	
				
			//If it has a different parent. Call "get_page_and_subpage" instead.
			}else{
				//Fade previous content
				$(".popup_block_content_box").fadeToggle(200, function() {
					//Animation complete
					//Load page data
					get_page_and_subpage(page_id);
				});	
				//Return previously active link to normal and set new link as active.
				$(".global_navigation_active").toggleClass("global_navigation_active");
				$(".global_navigation").each(function(){
					if($(this).attr("href").substring($(this).attr("href").indexOf("#")+1) == parent){
						$(this).toggleClass("global_navigation_active");
						return false;
					}
				});		
			}
			
		//If it's a parent page...			
		}else{
			//Fade previous content
			$(".popup_block_content_box").fadeToggle(200, function() {
				//Animation complete
				//Load page data
				get_page(page_id);
			});
			//Return previously active link to normal and set new link as active.
			$(".global_navigation_active").toggleClass("global_navigation_active");
			$(".global_navigation").each(function(){
				if($(this).attr("href").substring($(this).attr("href").indexOf("#")+1) == page_id){
					$(this).toggleClass("global_navigation_active");
					return false;
				}
			});
		}	
	}
}

$(document).ready(function() {
	//Set strict to false to avoid extra slashes in url.
	$.address.strict(false);
	//Define the callback function that gets called after the externalChange event has fired.
	$.address.externalChange(function(e)
	{
		//Don't do anything if there is no anchor(#) value.
		if(e.value != ""){
			//Check if the popup is visible.
			if($("#popup").css("display") != "none"){	
				load_content_external(e.value);	
				switch_url(e.value);
				
			}else{
				//First open popup
				open_popup();
				//Then load content
				load_content_external(e.value);
				//And update url
				switch_url(e.value);
			}
		}else{
			//Remove popup and fade layer if there's nothing after the anchor(#).
			if($("#popup").css("display") != "none"){
				close_popup();
			}
		}
	});
});

/**************************************************************************************************************
                                                 AJAX CALLS
**************************************************************************************************************/
//Load page content with a synchronous AJAX	call
function get_page(page_id){
	$.ajax({
		url:		"index.php/page_loader/get_page/" + page_id,
		dataType:	"html",
		success:	function(response){
						//Cut out the content inside the body element.
						var content = response.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
						//IE specific HTML5 hack. Uses the html5_inner.js shiv.
						var scripts = "";
						if($.browser.msie){
							var version = $.browser.version.substring(0, 1);
							if(version == "6" || version == "7" || version == "8"){
								//Gets script tags, which innerShiv strips.
								$(content).filter('script').each(function(){
									scripts += '<script type="text/javascript" src="' + $(this).attr("src") + '"></script> \n';
								});
								content = innerShiv(content);
							}
						}
						$(".popup_block_content_box").html(content);
						if(scripts != ""){
							$(".popup_block_content_box").append(scripts);
						}
						$(".popup_block_content_box").fadeToggle(200, function() {
							//Animation complete
						});
					},
		async:		false
	});	
	//Update custom referer for jQuery Address
	window.custom_referer = page_id;
}

//Load subpage content with a synchronous AJAX call
function get_subpage(page_id){
	$.ajax({
		url:		"index.php/page_loader/get_page/" + page_id,
		success:	function(response){
						//Cut out the content inside the body element.
						var body_content = response.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
						//Hack to include script tags, which jQuery's .html() method otherwise strips.
						//Note: The script tags get parsed out when getting the content of article, not when setting the content like so: $(".popup_article").html(content);
						var scripts = "";
						$(body_content).filter('script').each(function(){
							scripts += '<script type="text/javascript" src="' + $(this).attr("src") + '"></script> \n';
						});
						//The content:
						var content = "";
						var temp_container = $("<div></div>");
						//IE specific HTML5 hack. Uses the html5_inner.js shiv.
						if($.browser.msie && ($.browser.version.substring(0, 1) == "6" || $.browser.version.substring(0, 1) == "7" || $.browser.version.substring(0, 1) == "8")){
							var temp = innerShiv(body_content);
							temp_container.html(temp);
						}
						//Not IE.
						else{
							temp_container.html(body_content);
						}
						content = temp_container.find("article:first").html();				
						$(".popup_article").html(content);
						if(scripts != ""){
							$(".popup_article").append(scripts);
						}
						//Fade content back in
						$(".popup_article").fadeToggle(200, function() {
							//Animation complete
						});
					},
		async:		false
	});
	//Update custom referer for jQuery Address
	window.custom_referer = page_id.substring(0, page_id.indexOf("/"))
}

//Load page and subpage content with a synchronous AJAX	call
function get_page_and_subpage(page_id){	
	$.ajax({
		url:		"index.php/page_loader/get_page/" + page_id,
		dataType:	"html",
		success:	function(response){
						//Cut out the content inside the body element.
						var content = response.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
						//IE specific HTML5 hack. Uses the html5_inner.js shiv.
						var scripts = "";
						if($.browser.msie){
							var version = $.browser.version.substring(0, 1);
							if(version == "6" || version == "7" || version == "8"){
								//Gets script tags, which innerShiv strips.
								$(content).filter('script').each(function(){
									scripts += '<script type="text/javascript" src="' + $(this).attr("src") + '"></script> \n';
								});
								content = innerShiv(content);
							}
						}

						$(".popup_block_content_box").html(content);
						if(scripts != ""){
							$(".popup_block_content_box").append(scripts);
						}
						$(".popup_block_content_box").fadeToggle(200, function() {
							//Animation complete
						});
					},
		async:		false
	});
			
	//Return previously active link to normal and set new link as active.
	$(".local_navigation").each(function(){
		if($(this).attr("href").substring($(this).attr("href").indexOf("#")+1) == page_id){
			$(this).toggleClass("local_navigation_active");
			return false;
		}
	});	
	//Update custom referer for jQuery Address
	window.custom_referer = parent;
}

/**************************************************************************************************************
                                                 POPUP LIGHTBOX
**************************************************************************************************************/
//Open popup and apply fade layer.
function open_popup(){
	//Fade in the popup
	$("#popup").fadeIn(1200);
	$(".popup_block_edge").before("<div class=\"popup_block_top\"></div>");
	$(".popup_block_edge").after("<div class=\"popup_block_bottom\"></div>");
	
	//Fade in background
	$("body").append("<div id=\"fade\"></div>"); //Add the fade layer to bottom of the body tag.
	$("#fade").css({"filter" : "alpha(opacity=80)"}).fadeIn(1200); //Fade in the fade layer - .css({"filter" : "alpha(opacity=80)"}) is used to fix the IE Bug on fading transparencies
}

//Close popup and fade layer.
function close_popup(){
	$("#fade , .popup_block").fadeOut(function() {
		//fade them both out
		$("#fade, div.popup_block_top, div.popup_block_bottom").remove();  
		// Return url to frontpage
		switch_url(""); 
	});
}

//Bind events necessary to close the popup.
function bind_popup_events(){
	//When clicking on the close or fade layer.
	$(".btn_close, #fade").live("click submit", function(e) {
		e.preventDefault();
		close_popup();
	});
	//Close/open popup with ESCAPE key.
	$(document).keyup(function(e) {
		if (e.keyCode == 27) {
			if($("#popup").css("display") != "none"){
				e.preventDefault();
				close_popup();
			}else{
				history.back(-1);	
			}
		}
	});
}

$(document).ready(function() {
	bind_popup_events();
});

/**************************************************************************************************************
                                                  FEED READER
**************************************************************************************************************/
function get_rss(rss_url) {
	//Insert load image
	$("#jqfeed").empty().html("<img class=\"load_image\" src=\"layout/images/load_animations/feed_loading.gif\" alt=\"Vent venligst mens nyhederne hentes\" />");
	//Use jQuery"s AJAX get() to fetch the feed.$.get
	$.get("index.php/rss_proxy/get_feed/" + rss_url, function(feed_data) {
		//Remove load image
		$("#jqfeed").empty();
		
		//Find the first 2 items in the feed.
		var count = 1;
    	$(feed_data).find("item").each(function() {
			if(count < 3) {
				//Pull attributes out of the current item. $(this) is the current item.
				var title = $(this).find("title").text();
				var link = $(this).find("link").text();
				var description = $(this).find("description").text();
				var pub_date = $(this).find("pubDate").text();
				var author = $(this).find("author").text();
				//Find the first image in the current item i.e. the thumbnail. 
				//May have to be adjustet for individual feed as there is no standard way of doing this.
				var thumbnail = "";
				var temp_container = $("<div></div>");
				temp_container.html(description);
				thumbnail = temp_container.find("img:first").attr("src");
			
				//Filter html tags from description (We only want the plan text);
				//Note: This removes ALL html tags.
				var desc_stripped = description.replace(/(<.*?>)/ig,"");
				//Truncate text to corrext length if necessary
				if(desc_stripped.length > 250){
					last_index = desc_stripped.substring(0,250).lastIndexOf(" ");
					desc_stripped = desc_stripped.substring(0,last_index) + "......";
				}
				
				//Date formatting:
				var date_obj = new Date(pub_date);				
				//Format the date to danish locale using the JS Date object. 
				var reg_date = date_obj.toLocaleDateString();				
				//Format date meet HTML5 datetime format requirements(yyyy-mm-dd).
				var date_time = date_obj.getFullYear()+"-"+(date_obj.getMonth()+1)+"-"+date_obj.getDate();		
				
				//Create and insert html here.
				var feed_html = "<article class=\"feed_item\">";
				feed_html += "<header class=\"feed_item_header\">"
				if(thumbnail != ""){
					feed_html += "<div class =\"feed_item_thumb\"><img src=\"" + thumbnail + "\" alt=\"feed item thumbnail\" /></div>";
				}
				feed_html += "<h2 class=\"feed_item_title\"><a href=\"" + link + "\" target=\"_blank\" title=\"Overskrift\">" + title + "</a></h2>";
				feed_html += "<time datetime=\"" + date_time + "\" pubdate=\"pubdate\"><em class=\"feed_item_date\">" + reg_date + "</em></time>";
				feed_html += "</header>";
				feed_html += "<p class=\"feed_item_describtion\">" + desc_stripped + "</p>";
				feed_html += "<a href=\"" + link + "\" class=\"feed_item_link\" target=\"_blank\" title=\"Link til artikel\">Læs Mere...</a>";
				feed_html += "</article>";
				//IE specific HTML5 hack. Uses the html5_inner.js shiv.
				if($.browser.msie){
					var version = $.browser.version.substring(0, 1);
					if(version == "6" || version == "7" || version == "8"){
						feed_html = innerShiv(feed_html);
					}
				}

				//Insert feed item jqfeed section
				$("#jqfeed").append(feed_html);
				count++;
			}else{
				return false;
			}
		});
	});
}

$(document).ready(function() {
	get_rss("www.it-minds.dk/blog/feed");
});
