function init_scrollbar()
{
	var total_width = 0;

	// Sum up the width of all blocks.
	// The result is same as:
	// width_scroll_content = scroll_content.width();
	$('.block-item,.block-pulse').each(function(index) {
		total_width += parseInt($(this).width(), 10);
	});
	//alert(total_width);
	
	$('#content-slide').width(total_width);
	
	//scrollpane parts
	scroll_viewer = $('#viewer-slide'); // scroll-frame
	scroll_content = $('#content-slide'); // scroll-content
	scroll_location_pixel = 0;
	scroll_location_percentage = 0;
	width_scroll_content = scroll_content.width();
	// Keep these lines below for debugging:
	//alert(width_scroll_content);
	
	scrollbar = $('#slider').slider({
		min: 0,
		animate: true,
		create: on_scrollcreate,
		change: on_scrollchange,
		slide: on_scrollslide
	});
	
	// Always scroll the scroll content from 0 percentage.
	scrollbar.slider("value",0);
}

function on_scrollchange(event, ui)
{
	//var scroll_maximum = scroll_viewer.attr("scrollWidth") - scroll_viewer.width();
	var scroll_maximum = scroll_content.width() - scroll_viewer.width();
	scroll_viewer.animate({scrollLeft: ui.value * (scroll_maximum / 100) }, 1000);
	scroll_location_percentage = ui.value;
	scroll_location_pixel = ui.value * (scroll_maximum/ 100);
	// Keep these lines below for debugging:
	//alert(scroll_location_pixel);
	//alert(scroll_maximum);
	//alert(scroll_location_percentage);
	//alert(ui.value);
}

function on_scrollslide(event, ui)
{
	//var scroll_maximum = scroll_viewer.attr("scrollWidth") - scroll_viewer.width();
	var scroll_maximum = scroll_content.width() - scroll_viewer.width();
	scroll_viewer.attr({scrollLeft: ui.value * (scroll_maximum / 100) });
	
	//scroll_viewer.attr({scrollLeft: ui.value * (scroll_maximum / 100) });
	//As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. 
	//In addition, .attr() should not be used on plain objects, arrays, the window, or the document. 
	//To retrieve and change DOM properties, use the .prop() method.
    scroll_viewer.prop({scrollLeft: ui.value * (scroll_maximum / 100) });
}

function on_scrollcreate(event, ui) 
{
	//location_article();
	
	//get_mosaic();
}

function location_article()
{
	$('.tile-item,#menu-header li').click(function(){
	
		var path = $(this).find('a').attr('href');
		
		// Make sure always remove the object sibling's current-menu class name.
		$(this).siblings().removeClass('current-menu');
		
		// Then add the class name to the object.
		$(this).addClass('current-menu');
		
		// Redirect the page.
		if(path) document.location.href = path;
		
		return false;
	});

}

function do_hashchange()
{
	//$('.tile-tag > ul > li > ul > li > a,#article-tags > ul > li > a').click(function(){
	//$('a.get-mosaic,#article-tags > ul > li > a').click(function(){
	$(window).hashchange(function() {

		var hash = location.hash;
		//alert(hash);
		
		// Check if the fragment/ hash doesn't exit, then slide up and remove the container.
		if(hash == "" || hash == "#/") 
			if($('#container-article').length > 0) 
				$('#container-article').remove();
				scroll_content.css({width: width_scroll_content + 'px'});
		
		// Attach the load article function.
		do_fragment();
					
		return false;
	});

}

function do_fragment()
{
	var fragment = location.hash;
	//alert(fragment);
	
	// Check if fragment exists.
	if(fragment)
	{
		// Check if '/' exists in the fragment eg. #/article-1
		// Then, split the string with '/' to get the last item in the array eg. article-1
		if (fragment.indexOf("/") > 0)
		{
			//var url_next = window.location;
			// Get the last second item in the array.
			var array_fragment = fragment.split('/');
			var directory = array_fragment[array_fragment.length - 3];
			var request = array_fragment[array_fragment.length - 2];
			//var page_url = $(array_fragment).last()[0];
		}
		// If '/' does not exisit, then check if '#' exists in the fragment eg. #article-1
		// Then, split the string with '#' to get the last item in the array eg. article-1
		else if (/#/i.test(fragment))
		{
			//var url_next = window.location;
			// Get the last second item in the array.
			var array_fragment = fragment.split('#');
			var directory = array_fragment[array_fragment.length - 3];
			var request = array_fragment[array_fragment.length - 2];
			//var page_url = $(array_fragment).last()[0];
		}
		
		//alert(directory);
		//alert(request);
		//alert(total_width);
		//var array_url = path.split('/');
		// Check if the keyword exists in the array.
		//if ($.inArray(keyword, array_url)) alert('match!');
		if ($.inArray('tag', array_fragment) == 1) get_mosaic(directory,request);
		if ($.inArray('tags', array_fragment) == 1) get_mosaic(directory,request);
		if ($.inArray('pulse', array_fragment) == 1) get_mosaic('pulse','pulse');
		if ($.inArray('story', array_fragment) == 1) get_article(directory,request,fragment);
		if ($.inArray('page', array_fragment) == 1) get_article(directory,request,fragment);
		
	}
		
}

function get_mosaic(directory,request)
{
	// Make sure always remove current-menu class name of the menu li.
	if($('li').hasClass('current-menu')) $('li').removeClass('current-menu');

	// Set the binder opacity to 0.
	scroll_content.animate({
		opacity:0
	},500, function(){
	
		// Load the article into container_article.
		$(this).load( http_root + rp_local_template + 'mosaic-' + directory + '.php?tag_name=' + request, function(){
		
			var total_width = 0;

			$('.block-item').each(function(index) {
				total_width += parseInt($(this).width(), 10);
			});
			
			// Keep for debuggin:
			//alert(total_width);
			
			// Update and change the width of the current mosaic. 
			scroll_content.width(total_width);
			
			// Reset the global width of the scroll content.
			width_scroll_content = total_width;
			
			// Send the percentage to scrollbar.
			scrollbar.slider("value",0);
			
			
			$(this).animate({
				opacity:1
			},2000);
			
			// Attach the grayscale plugin.
			//$(".tile-shield").grayscale_tile_image();
			
			// Attach the image tile reveal plugin.
			//$(".tile-shield").reveal_tile_image();
			
			var timeout = setTimeout(function()
			{
				// Attach the grayscale plugin.
				$(".tile-shield").grayscale_tile_image();
				
				// Attach the image tile reveal plugin.
				$(".tile-shield").reveal_tile_image();
			
			}, 3000 ); 
			
			// Attach the text tile reveal plugin.
			//$(".tile-gray").reveal_tile_text();
			$(".tile-gray").reveal_tile_text({objectDelay:250});
			
			// Unbind the click event from menu-header li.
			$('.tile-item,#menu-header li').unbind('click');
			
			// Attach the get_article function back.
			location_article();
			
		});
	
	});
}


function get_article(directory,request,fragment)
{
	
	// http://api.jquery.com/attribute-ends-with-selector/
	var parent = $('.tile-item a[href$="' + fragment + '"]').parents('.block-item');
	
	// Check if the keyword exists in the array.
	//if ($.inArray(keyword, array_url)) alert('match!');
	
	if (directory == 'story') template = 'article-sub-items.php';
	else template = 'article-main-items.php';
		
	// Always set the scroll content to its original width.
	scroll_content.css({width: width_scroll_content + 'px'});
	
	if($('#container-article').length > 0)
	{
			
		//alert($('#container-article').length);
		//alert($('#container-article').width());
		
		// Remove any previous ajax loaded page.
		$('#container-article').remove();
		
	};
	
	// Create a div after the parent clicked element.
	// Else prepend the div before the elements.
	if(parent.length > 0) 
	{
		// Make sure always remove current-menu class name of the menu li.
		if($('li').hasClass('current-menu')) $('li').removeClass('current-menu');
		
		// Create a div after object's parent.
		parent.after('<div id="container-article"></div>');
	}
	else 
	{
		
		// Prepend the div.
		scroll_content.prepend('<div id="container-article"></div>');
		//if($('.blocks').length > 0) $('.blocks').prepend('<div id="container-article"></div>');
		//else $('#content-slide').prepend('<div id="container-article"></div>'); // fix for IEs, including IE9.
	}
	
	// Set the div to a variable and set its css.
	var container_article = $('#container-article').css({
		float:'left',
		width:0
	});
	
	// Load the article into container_article.
	container_article.load( http_root + rp_local_template + template + '?page_url=' + request, function(){
		
		// Get the width of the loaded article first.
		
		// This won't work on IE
		//var width_binder_article = container_article.width();
		
		// Do this way instead.
		// Set default variable and the targets.
		var width_binder_article = 0;
		var width_page_item = 500; // width of the div.article-right
		var object_binder_article = $('#binder-article');
		var object_article_item = $('.article-item');
		
		object_article_item.each(function(){
			
			// Set the varible of the object in each article item.
			var object_article_page = $('.article-page',this);
			var object_exit_article = $('.exit-article-bits',this);
			var object_stories_like_this = $('.stories-like-this',this);
			var object_article_right = $('.article-right',this);
			
			// Calculate the width.
			// Sum the width of each article item for the article binder.
			// Set the width of the object in each article item.
			width_binder_article += $('.article-left',this).width() + (width_page_item * object_article_page.length) + 50; // 50 is the margin spacing in the layout.
			object_exit_article.width(object_exit_article.width() * object_article_page.length);
			object_stories_like_this.width(object_stories_like_this.width() * object_article_page.length);
			// Keep these line below for debuggin:
			//total_width_binder_articles += parseInt($(this).width(), 10);
			//alert($('.article-left',this).width());
			//alert(object_article_page.length);
			//object_article_right.width((width_page_item * object_article_page.length));
			//$(this).width($('.article-left',this).width() + (width_page_item * object_article_page.length));
			//alert(width_binder_article);
			
			// Fix for IE < 9.
			object_article_right.width(width_page_item * object_article_page.length);
		
		});
		
		
		// Fix for IE < 9.
		/*
		object_article_right.each(function(){
		
			var object_article_page = $('.article-page',this);
			
			$(this).width(width_page_item * object_article_page.length);
			//alert($(this).width());
		
		});
		*/
		
		// Set the binder width and opacity to 0 to hide it first.
		// Set the width for other objects.
		object_binder_article.width(width_binder_article).css({opacity:0});
		
		// Add the article width into the existing content container width.
		scroll_content.width(scroll_content.width() + width_binder_article);
		
		// Get the position of current requested article.
		var position_article = $('.requested-article',this).position();
		
		object_binder_article.animate({
			opacity:1
		},1000);
		
		// Animate container_article.
		$(this).animate({
			width:width_binder_article
		},500,function(){
		
			// Store the prevous scroll content in pixel.
			var previous_scroll_content = width_scroll_content;
			//alert(previous_scroll_content);
			
			// Store the prevous scroll location in pixel.
			var previous_scroll_location_pixel = scroll_location_pixel;
			//alert(scroll_location_pixel);
			
			// Store the prevous scroll location in percentage.
			var previous_scroll_location_percentage = scroll_location_percentage;
			
			// Get and store the width of the loaded article/ content.
			var width_article = container_article.width();
			//alert(width_article);
			
			// Get and store the current width of the scroll content.
			var current_width_scroll_content = previous_scroll_content + width_article;
			
			// Update and change the width of the scroll content first.
			scroll_content.width(current_width_scroll_content + 2);
			
			// Then get the position of current requested article.
			//var requested_item = $('.requested-article').css({background:'red'});
			var requested_item = $('.requested-article');
			var position_request = requested_item.position();
			
			// Get the current maximum scrolling limit.
			// Calculate the lcation percentage of the requested item.
			var scroll_maximum = scroll_content.width() - scroll_viewer.width();
			var percentage = Math.round(((position_request.left)/scroll_maximum) * 100);
			// In the test prototype, you need to add scroll_location_pixel to get the percentage but not in this case which puzzles me.
			//var percentage = Math.round(((position_request.left + scroll_location_pixel)/scroll_maximum) * 100);
			
			// Send the percentage to scrollbar.
			scrollbar.slider("value",percentage);
			
			// Attach the exit function.
			exit_article (container_article,previous_scroll_location_percentage,previous_scroll_content);
			//alert(previous_scroll_content);
			//get_mosaic();
			
			// Issues with using AddThis on an all AJAX site and was able to come up with a couple of solutions for this issue.
			// It turns out there is a variable that you can pass when loading the AJAX script as well as a way to re-initialize the script if the DOM is reloaded via AJAX.
			// To briefly summarize, the solution is loading AddThis with the variable domready=1 appended, and re-initializing the script 
			// by deleting the initial load and then reloading the script dynamically:
			//getScript_Addthis();
			//var t=setTimeout("getScript_Addthis()",500);
			
			// Addthis counter causes a bug so use your own buttons.
			$(".popup-share").click(function(){
				var object = $(this);
				var object_url = object.attr("href");
				window.open(object_url,'Share', 'width=600, height=600, scrollbars=yes');
				return false;
			});
			
		});

	});
		
}

function exit_article(container_article,previous_scroll_location_percentage,previous_scroll_content)
{
	$('.exit-article').click(function(){
		
		// Make sure always remove current-menu class name of the menu li.
		if($('li').hasClass('current-menu')) $('li').removeClass('current-menu');
		
		// Set the binder opacity to 0.
		$('#binder-article').animate({
			opacity:0
		},1000);
		
		// Animate the container to 0 width.
		container_article.animate({
			width: 0
		}, 500, function(){
		
			// Set the width of the scroll content to the previous size.
			scroll_content.css({width: previous_scroll_content + 'px'});
			
			// Remove the container.
			container_article.remove();
			
			// Using percentage to scroll back to the previous location.
			scrollbar.slider("value", previous_scroll_location_percentage);
			
			// Remove the fragment.
			location.hash = '/';
			
		});
			
		return false;
	});
}

/* load the AddThis script through ajax */
function getScript_Addthis()
{
	
	/*
	issues with using AddThis on an all AJAX site and was able to come up with a couple of solutions for this issue.

	It turns out there is a variable that you can pass when loading the AJAX script as well as a way to re-initialize the script 
	if the DOM is reloaded via AJAX.
	
	To briefly summarize, the solution is loading AddThis with the variable domready=1 appended, and re-initializing the script 
	by deleting the initial load and then reloading the script dynamically:
	*/
	
	var script_addthis = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1'; //http://s7.addthis.com/js/250/addthis_widget.js#username=lauthiamkok
			
	if (window.addthis){
		window.addthis = null;
	}
	
	$.getScript(script_addthis, function() {
	  //alert('Load was performed.');
	});

}
