// Global variables
var expanded = false;
var storyIndex = 0;
var storiesXml = new Array();
var storyNumberListWidth = 0;

// News story class definition
function newsStory(title, titleImage, teaser, date, dateString, link, linkType, icon, type, linkTitle, linkTitleImage, additionalDisplay) {
	this.title = title.replaceAll("'", "").replaceAll('à', 'a').replaceAll('é', 'e').replaceAll('’', '');
	this.titleImage = titleImage.replaceAll("'", "").replaceAll('à', 'a').replaceAll('é', 'e').replaceAll('’', '');
	this.teaser = teaser.replaceAll("'", "").replaceAll('à', 'a').replaceAll('é', 'e').replaceAll('’', '');
	this.date = date;
	this.dateString = dateString;
	this.link = link;
	
	if (vanilla.ln != "en") this.link += "?region=" + vanilla.ln;
	
	this.linkType = linkType;
	this.icon = icon;
	this.type = type;
	this.linkTitle = linkTitle.replaceAll("'", "").replaceAll('à', 'a').replaceAll('é', 'e').replaceAll('’', '');
	this.linkTitleImage = linkTitleImage.replaceAll("'", "").replaceAll('à', 'a').replaceAll('é', 'e').replaceAll('’', '');
	this.additionalDisplay = additionalDisplay.replaceAll("'", "").replaceAll('à', 'a').replaceAll('é', 'e').replaceAll('’', '');
}

// String replaceAll method
String.prototype.replaceAll = function(stringToReplace, replacement) {
	var string = this;
	while (string.indexOf(stringToReplace) != -1) {
        string = string.replace(stringToReplace, replacement);
    }
    return string;
}

// Onload, load news stories and store in array. Attach event listeners/handlers to mouse interactions.
$(document).ready(function() {
    var numberWidth = 18;  
						 
	if (jQuery.browser.msie) {
		$('.ajaxhome').addClass('ie');	
		
		if (jQuery.browser.version <= "7.0") {	
			DD_belatedPNG.fix('.titleImage, .trans_png');
		}
		
		if (jQuery.browser.version == "6.0") {	
			numberWidth = 19;	
		}
	}
						   
	$.ajax({
		 type: "GET",
		 url: "./homepage_flash_publications.xml",
		 dataType: "text",
		 success: function(xml) {
			xml = parseXml(xml);
			// get promotions
			$(xml).find('promotion').each(function() {
				 var titleText = $(this).find('title').text();
				 var teaserText = $(this).find('teaser').text();
				 var dateText = $(this).find('publication_date').text();
				 var linkText = $(this).find('link_url').text();
				 var contentImageText = $(this).find('content_image').text();
				 
				 var linkTypeText = $(this).find('link_type').text();
				 var iconText = $(this).find('icon').text();
				 var typeText = $(this).find('type').text();
				 var linkTitleText = $(this).find('link_title').text();
				 var additionalDisplayText = $(this).find('additional_display').text();

				 if (linkTitleText == "") {
					linkTitleText = "Find out more"; 
				 }
				 
				 var linkTitleImage = linkTitleText.toLowerCase();
				 linkTitleImage = linkTitleImage.replaceAll(' ', '_') + '.png';
				 
				 var date = new Date().setTime(Date.parse(dateText));
				 
				 storiesXml.push(new newsStory(titleText, contentImageText, teaserText, date, dateText, linkText, linkTypeText, iconText, typeText, linkTitleText, linkTitleImage, additionalDisplayText));
			 });
			// get press releases
			$(xml).find('press_release').each(function() {
				 var titleText = $(this).find('title').text();
				 var titleImage = "";
				 var teaserText = $(this).find('teaser').text();
				 var dateText = $(this).find('publication_date').text();
				 var linkText = $(this).children("link_url").text();
				 var contentImageText = $(this).find('content_image').text();

				 var linkTypeText = $(this).find('link_type').text();
				 var iconText = "icon_pages.gif";
				 var typeText = "Press release";
				 var linkTitleText = $(this).find('link_title').text();
				 
				 if (linkTitleText == "") {
					linkTitleText = "View press release"; 
				 }
				 
				 var linkTitleImage = linkTitleText.toLowerCase();
				 linkTitleImage = linkTitleImage.replaceAll(' ', '_') + '.png';
				 // Fr-CA specific				 
				 linkTitleImage = linkTitleImage.replaceAll('à', 'a');
				 linkTitleImage = linkTitleImage.replaceAll('é', 'e');
				 linkTitleImage = linkTitleImage.replaceAll('’', '');
				 linkTitleImage = linkTitleImage.replaceAll("'", '');
				 
				 var date = new Date().setTime(Date.parse(dateText));
				 
				 storiesXml.push(new newsStory(titleText, contentImageText, teaserText, date, dateText, linkText, linkTypeText, iconText, typeText, linkTitleText, linkTitleImage, ""));
			 });

			 if (storiesXml.length > 1) {
                // sort stories by date objects
    			storiesXml.sort(sortDate);
    			
				$('#storynumbers').append('<ul id="storynumberlist"></ul>');
				
    			for (var i = 0; i < storiesXml.length; i++) {
    				var storyNumberText = (i < 10) ? ("0" + (i+1)) : (i+1); 
    				$('#storynumberlist').append('<li class="story' + (i+1) + '"><a href="" onclick="skipToStory(' + i + '); return false;"><img class="trans_png" src="/img/ajax_homepage/article_' + storyNumberText + '.png" width="18" height="15" alt="' + storyNumberText + '"/></a></li>');
    			}
    			
    			storyNumberListWidth = (storiesXml.length * numberWidth) + 4;
    			$('#storynumbers').css('width', (storyNumberListWidth + 'px'));
    			$('#progressbarcontainer').css('width', ((storyNumberListWidth-3) + 'px'));
    			$('.story1').addClass('active');
    			$('#progressbar').animate({width:((storyNumberListWidth-3) + 'px')}, 8000, 'linear', rotateNews);
             }
			 
			if (storiesXml.length > 0) {
				updateNewsHtml(storyIndex);
				
				// unhide the story box
				$('#storyBox, #progressbarcontainer').css('visibility', 'visible');
			}
			
		 },
		 error: function (xhr, textStatus, errorThrown) {
			// Do nothing for now...
		}
	 });   
			 
	$('#storyBox').click(function() {
		$('#expandbutton').hide();
		if (!expanded) {
			expanded = true;
			$('#storyBox').animate({top:'0', height:'230px', paddingTop:'30px'}, 300, 'linear');
			$('#closebutton, #storyimage').fadeIn();
			$('#progressbarcontainer').fadeOut();
		}
	});
	
	$('#closebutton').click(function() {
		if (expanded) {
			$('#storyBox').animate({top:'202px', height:'260px', paddingTop:'0'}, 300, 'linear', function() {expanded = false;});
			$('#storyBox').removeClass('highlighted');
			$('#closebutton, #storyimage').fadeOut();
			$('#progressbarcontainer').fadeIn();
		}
	});
	
	$('#closebutton').mouseover(function() {
	    var newSrc = $(this).attr('src').replace('.gif', '_rollover.gif');
		$(this).attr('src', newSrc); 
	});
	
	$('#closebutton').mouseout(function() {
	    var newSrc = $(this).attr('src').replace('_rollover.gif', '.gif');
		$(this).attr('src', newSrc); 
	});
	
	$('#storyBox').mouseover(function() {
		$(this).addClass('highlighted'); 
		if (!expanded) {
			$(this).addClass('linkcursor');
			$('#expandbutton').show();	
		}
	});
	
	$('#storyBox').mouseout(function() {
		if (!expanded) {
			$(this).removeClass('highlighted'); 
		}
		$(this).removeClass('linkcursor');
		$('#expandbutton').hide();
	});
});

function rotateNews() {
	$('#progressbar').css('width', '0');
	if (!expanded) {
		var index = storyIndex + 1;
		
		if (index >= storiesXml.length) {
			index = 0;	
		}

		$('#story').css('margin-left', '300px');
		$('#story').css('opacity', '0');
		updateNewsHtml(index);
		$('#story').animate({marginLeft:'0', opacity: '1.0'}, 1000);
		
		for (var i = 0; i < storiesXml.length; i++) {
			if (i == index) {
				$('.story' + (i+1)).addClass('active');
			} else {
				$('.story' + (i+1)).removeClass('active');	
			}
		}
		
		storyIndex = index;	
	}
	$('#progressbar').animate({width:(storyNumberListWidth + 'px')}, 8000, 'linear', rotateNews);
}

function rotateExpandedNews() {
	var index = storyIndex + 1;
		
	if (index >= storiesXml.length) {
		index = 0;	
	}

    updateNewsHtml(index);
    
    for (var i = 0; i < storiesXml.length; i++) {
		if (i == index) {
			$('.story' + (i+1)).addClass('active');
		} else {
			$('.story' + (i+1)).removeClass('active');	
		}
	}
	
	storyIndex = index;	
}

// construct the HTML for a complete news story
function updateNewsHtml(index) {
    var storyXml = storiesXml[index];
	var htmlText = "";
		
	if (storyXml.titleImage == '') {
		htmlText += "<span><img src='/img/icons/" + storyXml.icon + "' height='16' width='16' alt=''/> " + storyXml.type + " (" + storyXml.dateString + ")</span>";
		htmlText += "<h1>" + storyXml.title + "</h1><p>" + storyXml.teaser + "</p>";
	} else {
		htmlText += "<img class='titleImage' src='/img/ajax_homepage/content/" + storyXml.titleImage + "' height='196' width='759' alt='" + storyXml.type + " - " + storyXml.dateString + " - " + storyXml.title + " - " + storyXml.teaser + "'/>";
	}
	
	htmlText += '<ul class="subsectionlink"><li><a href="' + storyXml.link + '"'
	if (storyXml.linkType == "external") {
		htmlText += 'onclick="window.open(this.href); return false;"';
	}
	htmlText += '><img class="trans_png" src="/img/ajax_homepage/button_text/' + storyXml.linkTitleImage + '" height="16" alt="' + storyXml.linkTitle + '"/></a></li></ul>';

	$('#story').html(htmlText);
	
	if (storyXml.additionalDisplay != '') {
        $('#storyimage').html('<img alt="" src="/img/' + storyXml.additionalDisplay + '"/>');
    } else {
        $('#storyimage').html(' ');
    }
}

function skipToStory(storyNumber) {
	storyIndex = storyNumber - 1;
	
	if (expanded) {
        rotateExpandedNews();
    } else {
        $('#progressbar').stop();
        rotateNews();
    }
}

function parseXml(xml) {
	if (jQuery.browser.msie) {
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(xml);
		xml = xmlDoc;
	}
	return xml;
}

function sortDate(a, b) {
	return b.date - a.date;	
}