/********** Homepage article ticker **********/

/********** Data request and format **********/

// All types of article that will display.
var articleTypes = new Array("newsItems", "mpeItems", "blogItems");

// Main news articles array.
var newsArticles = new Array();

// Main mpe articles array.
var mpeArticles = new Array();

// Main direct news articles array.
var directNewsArray = new Array();

// Main blog articles array.
var blogArticles = new Array();

// So only one ajax call runs at a time.
var requestStatus = false;

// Used in the ajax calls to loop through and get content for all the article types.
var typeStatus  = 0;

// Regex to match article ids.
var matchIds = new RegExp(/\[id=(.+)\]/);

// Clean up the article arrays so there are no undefined elements.
function cleanArrays(array, name)
{
	var tempArray    = new Array();
	var tempArrayKey = 0;
	
	for(var i = 0; i < array.length; i++)
	{
		if(array[i]["id"] && array[i]["content"])
		{
			tempArray[tempArrayKey] = new Array();
			
			tempArray[tempArrayKey]["id"]      = array[i]["id"];
			tempArray[tempArrayKey]["content"] = array[i]["content"];
			tempArrayKey++;
		}
	}
	
	return tempArray;
}

// Add the articles into the main articles array.
function addArticles(data, type)
{
	var individualArticles = data.split("||");
	
	for(var i = 0; i < individualArticles.length; i++)
	{
		// Create a multidimentional array for each type.
		switch(type)
		{
			case "newsItems":
				newsArticles[i] = new Array();
				break;
				
			case "mpeItems":
				mpeArticles[i] = new Array();
				break;
				
			case "blogItems":
				blogArticles[i] = new Array();
				break;
		}
		
		articleId = individualArticles[i].match(matchIds);
		
		if(articleId != null)
		{
			// Add the article ID for each type.
			switch(type)
			{
				case "newsItems":
					newsArticles[i]["id"] = articleId[1];
					break;
					
				case "mpeItems":
					mpeArticles[i]["id"] = articleId[1];
					break;
					
				case "blogItems":
					blogArticles[i]["id"] = articleId[1];
					break;
			}
		}
		
		// Strip out the ID.
		articleContent = individualArticles[i].replace(matchIds, "");
		
		// Put the previously slashed chars back.
		articleContent = articleContent.replace(/\\'/g, "'");
		articleContent = articleContent.replace(/\\"/g, '"');
		
		// Add the content for each type.
		switch(type)
		{
			case "newsItems":
				newsArticles[i]["content"] = articleContent;
				break;
				
			case "mpeItems":
				mpeArticles[i]["content"] = articleContent;
				break;
				
			case "blogItems":
				blogArticles[i]["content"] = articleContent;
				break;
		}
	}
	
	// Clean the new arrays.
	switch(type)
	{
		case "newsItems":
			newsArticles = cleanArrays(newsArticles);
			break;
			
		case "mpeItems":
			mpeArticles  = cleanArrays(mpeArticles);
			break;
			
		case "blogItems":
			blogArticles = cleanArrays(blogArticles);
			break;
	}
}

// Check if a number is even.
function isEven(num)
{
  return !(num % 2);
}

// Merge the News and Mobile Phones Exposed articles together staggered.
function mergeNewsMpe()
{
	// Eventual length of directNewsArray.
	var totalNews = newsArticles.length + mpeArticles.length;
	
	// Keep a record of the elements being used.
	var newsCount = 0;
	var mpeCount  = 0;
	
	var mainArrayKey = 0;
	
	for(var i = 2; i < (totalNews + 2); i++)
	{
		if(isEven(i))
		{
			directNewsArray[mainArrayKey] = newsArticles[newsCount];
			directNewsArray[mainArrayKey]["type"] = "news";
			newsCount++;
		}
		else
		{
			directNewsArray[mainArrayKey] = mpeArticles[mpeCount];
			directNewsArray[mainArrayKey]["type"] = "mpe";
			mpeCount++;
		}
		
		mainArrayKey++;
	}
}

// Get the articles for each article type via an ajax request.
function requestArticleItems()
{
	// There are still article types to find articles for.
	if(requestStatus == false && typeStatus < articleTypes.length)
	{
		requestStatus = true;
		
		// Get the news articles.
		$.get("/ajax-article-ticker.php?at=" + articleTypes[typeStatus] + "&ajax=1", function(data)
		{
			addArticles(data, articleTypes[typeStatus]);
			requestStatus = false;
			typeStatus++;
			requestArticleItems();
		});
	}
	else
	{
		// All the articles needed have been recieved so can start ticking.
		mergeNewsMpe();
		
		// Start both the news and blog tickers.
		startTicker(true, true);
	}
}

// Entry point.
requestArticleItems();

/********** Data request and format end **********/

/********** Ticker actions **********/

// Global timer.
var pauseTimer = 10000;

// Global fade speed.
var articleFadeSpeed = "normal";

// News current array key.
var currentNewsKey = 0;

// Blog current array key.
var currentBlogKey = 0;

// Inteval for the news articles.
var newsInterval = null;

// Inteval for the blog articles.
var blogInterval = null;

// Actions news article changes.
function changeNewsArticle()
{
	if(currentNewsKey < (directNewsArray.length - 1))
	{
		// Go to the next article.
		currentNewsKey++;
	}
	else
	{
		// At the end so go back to the begining.
		currentNewsKey = 0;
	}
	
	// Fade the previous article out, replace with the new on and fade back in.
	$("#newsContent").fadeOut(articleFadeSpeed, function()
	{
		$("#newsContent").html(directNewsArray[currentNewsKey]["content"]);
		$("#newsContent").fadeIn(articleFadeSpeed);
		
	});
}

// Actions blog article changes.
function changeBlogArticle()
{
	if(currentBlogKey < (blogArticles.length - 1))
	{
		// Go to the next article.
		currentBlogKey++;
	}
	else
	{
		// At the end so go back to the begining.
		currentBlogKey = 0;
	}
	
	// Fade the previous article out, replace with the new on and fade back in.
	$("#blogContent").fadeOut(articleFadeSpeed, function()
	{
		$("#blogContent").html(blogArticles[currentBlogKey]["content"]);
		$("#blogContent").fadeIn(articleFadeSpeed);
		
	});
}

// The blog articles start slightly after the news articles.
function setBlogGoing()
{
	blogInterval = setInterval("changeBlogArticle()", pauseTimer);
}

// Now start the rotations and set up the event listeners.
function startTicker(news, blog)
{
	if(news == true)
	{
		// Start the news straight away.
		newsInterval = setInterval("changeNewsArticle()", pauseTimer);
	}
	
	if(blog == true)
	{
		// Staggered start for the blog articles.
		setTimeout("setBlogGoing()", (pauseTimer / 2));
	}
}

/********** Ticker actions end **********/

/********** Billboard Scripts **********/
if($("#billboard"))
{
	// Rounded corners on the billboard tabs.
	$("#control").prepend('<span id="bb-cl"></span><span id="bb-cr"></span>');
	
	// Set the interval at which switches will occur.
	var pauseTime = 10000;
	
	// How long can a banner be still after user control.
	var inactivityTime = 20000;
	
	// Main interval object.
	var interval = null;
	
	// Main banners array.
	var banners = $("#window").find("a");
	
	// Total amount of banners to scroll around.
	var totalBanners = banners.length;
	
	// Set the starting banner as the last banner item to start at the beginning.
	var currentBanner = totalBanners - 1;
	
	var globalFadeSpeed = "normal";
	
	// Lock controls during animations.
	var controlsLock = false;
	
	// Watch inactivity.
	var inactivity = null;
	
	// Actually does the banner transitions.
	function switchBanner()
	{
		// If the current banenr is the last banner.
		if(currentBanner == (totalBanners - 1))
		{
			currentBanner = 0;
		}
		else
		{
			currentBanner++;
		}
		
		// Show all the tabs in the up state.
		$("#control ul li").attr("class", "inactive");
		
		// Show the current banner's tab in the over state.
		$("#op" + (currentBanner + 1)).parent("li").attr("class", "active");
		
		// Get the previuos banner id.
		var prevBanner = currentBanner - 1;
		
		// If the current banner is the first then the last banner is the one before the total.
		if(currentBanner == 0)
		{
			prevBanner = (totalBanners - 1);
		}
		
		// Fade out all other banners.
		for(var i = 0; i < totalBanners; i++)
		{
			if(i != currentBanner && i != prevBanner)
			{
				$(banners[i]).fadeOut(globalFadeSpeed);
			}
		}
		
		// Fade out the previuos banner.
		$(banners[prevBanner]).fadeOut(globalFadeSpeed);
		
		// Fade in the next banner.
		$(banners[currentBanner]).fadeIn(globalFadeSpeed, function()
		{
			// Release the controls.
			controlsLock = false;
		});
	}
	
	// Main function that initiates the interval to switch banners.
	function rotateBanners()
	{
		interval = setInterval("switchBanner()", pauseTime);
	}
	
	// Restart the rotation after inactivity.
	function restartRotation()
	{
		clearTimeout(inactivity);
		rotateBanners();
	}
	
	// When the user controls the banners.
	function userControl(id)
	{
		clearInterval(interval);
		currentBanner = parseInt(id.replace("op", "")) - 2;
		switchBanner();
	}
	
	function watchInactivity()
	{
		clearTimeout(inactivity);
		inactivity = setTimeout("rotateBanners()", inactivityTime);
	}
	
	// When the page has loaded.
	$(document).ready(function()
	{
		// Start the banner rotation.
		rotateBanners();
		
		// Get all the tabs ready for assignment of triggers.
		var userTabs = $("#control").find("a");
		
		// Assign the triggers.
		for(var i = 0; i < userTabs.length; i++)
		{
			$(userTabs[i]).click(function()
			{
				var lastBanner = currentBanner;
				
				// make sure users cannot change the banners in the middle of a transition.
				if(controlsLock == false)
				{
					controlsLock = true;
					watchInactivity();
					userControl($(this).attr("id"));
				}
				
				var currentTabNumber = parseInt($(this).attr("id").replace("op", ""));
				
				// If the current tab is clicked on again then the user is sent to the link.
				if((lastBanner + 1) != currentTabNumber)
				{
					return false;
				}
			});
		}
		
		// Show first banner.
		switchBanner();
	});
}
/********** Billboard Scripts End **********/

/********** Text Link Hover on See Deals Link Hover Top Ten **********/
$(".seealldealslink").hover(function()
{
	$(this).siblings().css("textDecoration", "underline");
},
function()
{
	$(this).siblings().css("textDecoration", "");
});
/********** Text Link Hover on See Deals Link Hover Top Ten end **********/