// main.js

/*
 * -----------------------------------------------------------------
 * 'SAUTI' (c) 2005/2006, Kwame Ansong-Dwamena 
 * -----------------------------------------------------------------
 */

/*	
  * This js file controls the image slideshow on the sauti homepage.
  * It takes the names of all images to be included in the slideshow, creates image objects for each one
  * and preloads all the images by setting the src for each object. Each image is displayed as the background
  * image for the 'articleImage' div element in the main sauti .html file except two very similar dark-brown 
  * images that serve as the sliding windows/doors when changing from one image to another. 
  */

var imgArray = new Array();		// array to store actual images
var fibonacciArr = new Array();	// array that holds fibonacci numbers used to move the images in div(id='articleImage') in a decelerating manner.
var FIB_ARR_LENGTH = 13;		// length of fibonacci sequence

var imgIndex = 0;					// index of image to display
var leftPsn = -300;					// left offset relative psn of images
var rightPsn = 0;					// right offset relative psn of images
var counter = FIB_ARR_LENGTH-1;		// index for fibonacci array entries

// Array of image names/src's.
var imgNames = new Array("africa_map.jpg", "innovative_dev.jpg", "mobile_tech.jpg", "personal_reflection.jpg", "drc_elections.jpg", "reflections_africa.jpg", "punishing_genocide.jpg", "mobile_za.jpg", "energy_issues.jpg", "educ_kenya.jpg")

// Calls all the nee=cessary functions to execute the slideshow on the main sauti page as well as the change of text for the article extracts.
function setUp()
{
	preloadImages();					// images preloaded
	buildFibonacciNos();				// builds an array of fibonacci numbers that is used to move images in the div (id='articleImgae')
	createExtract();
	setTimeout("changeImageAndExtract()", 10000)	// wait for 10s before initiating slideshow. This ensures that the first image is displayed for as long as each other image is when the page is loaded/reloaded
}

/* 
  * Preloads images into cache while page loads to prevent delay in slideshow display. For the src, the exact path
  * had to be specified in this function and not any other one otherwise images would not be actually preloaded. 
  */
function preloadImages()
{
	for (var i = 0; i < imgNames.length; i++)
	{
		var image = new Image();
		image.src = "images/" + imgNames[i];
		imgArray[i] = image;
	}
}

// Creates a sequence of fibonacci numbers and stores them in array. These numbers are used to move the div(iid='articleImage') images in a decelerating manner
function buildFibonacciNos()
{
	fibonacciArr[0] = 0;
	fibonacciArr[1] = 1;
	for(var i = 2; i < FIB_ARR_LENGTH; i++)
	{
		fibonacciArr[i] = fibonacciArr[i-1] + fibonacciArr[i-2];	// the next fibonacci number is a sum of the previous two
	}
	
	// adjustments: since the sequence of fibonacci numbers adds up to more than the width of our images, we need to adjust the latter numbers to ensure a total equal to our image width
	var adjustArray = [38, 19, 10, 6, 2, 1];
	for(var i = 0; i < adjustArray.length; i++)
	{
		fibonacciArr[FIB_ARR_LENGTH-1-i] -= adjustArray[i];
	}
}

// Displays the continuous slideshow of images for the corresponding articles as well as the changing text for the article extract.
function changeImageAndExtract()
{
	moveImage();										// takes 1,300ms to move each image
	fade();												// takes 500ms to fade out and change text of article extract
	setTimeout("changeImageAndExtract()", 10000);		// takes 13,000ms after the image is moved
}

/* 
  * Changes the slide images by placing the next image to the immediate left of the currently displayed image and then
  * moves the two images to the right until the next image becomes fully visible. Since the div that holds these images has
  * a 'hidden' style for 'overflow', the next image does not show when it's placed to the immediate left of  the currently 
  * displayed one. It only begins to show when the two images are moving to the right. Also, the currently displayed image 
  * disappears due to the 'overflow: hidden' style applied to the div by the stylesheet. Entire process takes 1300ms.
  */
function moveImage()
{
	var imgDiv = document.getElementById("articleImage");		// article image div
	imgDiv.innerHTML = createInnerHTMLString();					// string that contains html tags and attribs to position images in div
	rightPsn += fibonacciArr[counter];
	leftPsn += fibonacciArr[counter];
	counter--;
	if(counter >= 0) {
		setTimeout("moveImage()", 100);
	}else {														// reset/modify variables for next images
		imgIndex++;
		counter = FIB_ARR_LENGTH-1;
		leftPsn = -300;
		rightPsn = 0;
	}
}

// Creates a string of html tags and attributes that positions the left and right images in the div (id=articleImage).
function createInnerHTMLString()
{
	if(imgIndex >= imgArray.length) imgIndex = 0;											// reset imgIndex if it equals length of imgArray i.e. 10 in this case
	var rightImage = "<img src='" + imgArray[imgIndex].src;
	rightImage += "' style='position: relative; top: 0; left: " + rightPsn + "px;' />";		// position of right image
	var nextImgIndex = imgIndex + 1;
	if(nextImgIndex >= imgArray.length) nextImgIndex = 0;									// reset index of next image, i.e. the left image
	var leftImage = "<img src='" + imgArray[nextImgIndex].src;
	leftImage += "' style='position: relative; top: -303px; left: " + leftPsn + "px;' />";	// position of left image
	return (rightImage + leftImage);
}


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

/*
  * THE FOLLOWING LINES OF CODE CONTROL THE DISPLAY OF TEXT (ARTICLE EXTRACT) IN THE MIDDLE DIV(ID='articleExtract').
  * ORIGINALLY, THESE LINES WERE IN A SEPARATE .JS FILE CALLED EXTRACT.JS BUT ISSUES WITH SYNCHRONIZING THE CHANGE OF THE TEXT
  * WITH THAT OF IMAGES CAUSED THESE CODES TO BE COMBINED WITH THIS .JS FILE TO ENSURE THAT IT CAN BE CALLED AT THE RIGHT TIME AND
  * ELIMINATE ANY TIMING ISSUES, MAINLY LAGGING.
  */

 
//array of titles of the various articles
var titleArr = new Array();
titleArr[0] = "Causality and the Casualty of Truth: Writing the Past to Explain Africa’s Present";
titleArr[1] = "Reflections from Africa I: Most Innovative Developments In 2005";
titleArr[2] = "Mobile Telecommunications In Africa: Past, Present and Future of A Continent-Wide Technological Phenomenon";
titleArr[3] = "Personal Reflection";
titleArr[4] = "The Role of Elections in Post-Conflict Situations: A Study of Conditions, Goals, and the Democratic Republic of the Congo";
titleArr[5] = "Reflections from Africa II: Most Innovative Developments In 2005";
titleArr[6] = "Punishing Genocide: The International Prosecution of Rwanda’s War Criminals";
titleArr[7] = "Mobile Phone Use and Policy in Southern Africa";
titleArr[8] = "Energy Issues in Sub-Saharan Africa";
titleArr[9] = "Learning of Science and Mathematics among Female Students in Secondary Schools in Economically Disadvantaged Areas of Kenya: Challenges and Prospects";


//array of quotes associated with the articles
var quoteArr = new Array();
quoteArr[0] = "The continent was seen as the one part of the world for which the future was likely to be far worse than the past.";
quoteArr[1] = "";
quoteArr[2] = "";
quoteArr[3] = "";
quoteArr[4] = "";
quoteArr[5] = "";
quoteArr[6] = "";
quoteArr[7] = "";
quoteArr[8] = "";
quoteArr[9] = "";

//array of the names of quoters of the various quotes associated with the articles
var quoterArr = new Array();
quoterArr[0] = "David Reiff";
quoterArr[1] = "";
quoterArr[2] = "";
quoterArr[3] = "";
quoterArr[4] = "";
quoterArr[5] = "";
quoterArr[6] = "";
quoterArr[7] = "";
quoterArr[8] = "";
quoterArr[9] = "";

//array of the names of the writers of the articles
var authorArr = new Array();
authorArr[0] = "Jeremy Kasile Goldberg";
authorArr[1] = "Sauti Journal";
authorArr[2] = "Eugene Carl Adogla";
authorArr[3] = "Lauren Elyssa Young";
authorArr[4] = "Julie Michelle Veroff";
authorArr[5] = "Sauti Journal";
authorArr[6] = "Krishanu Sengupta";
authorArr[7] = "Tim Sanders";
authorArr[8] = "J. F. Cornelius & J. T. Barton";
authorArr[9] = "Dr. Dinah Mwinzi and Dr. Isaac N. Kimengi";

//array of the article extracts
var extractArr = new Array();
extractArr[0] = "David Rieff accurately assesses Africa’s image in the West. From magazines like The Economist to articles like Rieff’s in academic journals, Africa’s fate seems to be nigh certain: the continent is “bleak, inhospitable… in a state of crisis. Mainstream newspaper and magazine writers pen an incessant stream of tales about African countries governed by corrupt despots, who rule over states that are among the most underdeveloped on Earth, with little to offer other than raw materials and a steady supply of violent conflicts to occupy our televisions. Africa’s failure has become cliché; books and articles chronicle this...";
extractArr[1] = "In the last year, Rwanda has shown that it is not only dealing with its own problems, but is willing to reach out and have an impact on the health of the entire region. On May 30, 2005, Rwanda hosted the second COMESA1 Business Summit during which Rwanda’s president, Paul Kagame, was elected as chairman of the regional association. Considering that Rwanda was abandoned by the peacekeepers of the world in 1994, they sent a powerful message to the world in 2005 by sending thousands of troops to Southern Sudan as part of an African Union peacekeeping force. In 2005, Rwanda was able to assert itself as a key player in the economic and social development of East Africa. This year Rwanda hopes to become an official member of the East African Community, and will have the chance to become a key player in regional politics (The EAC currently consists of Kenya, Uganda, and Tanzania)...";
extractArr[2] = "It would definitely not be an exaggeration to claim that cellular telephony represents high technology’s most successful foray in to the African continent. The numbers clearly bear out this assertion: as at the end of August 2005, a mere 18 years after the first cell phones arrived in Africa, the number of mobile handsets in active use by subscribers stood at 76.8 million (representing a conservative estimation). The annualized aggregate growth rate in handset numbers was pegged at a healthy 58%, a figure that clearly propelled the African cellular market to outperform all others worldwide1. Cumulative growth between 1998 and 2005 stood at an astonishing 5,000, a technology-related growth rate that has...";
extractArr[3] = "It was the end of a three-day journey through the Zambian countryside on a bus, which also carried several pounds of dust and the heavy smell of the fish that had preceded us as passengers. We had been in this bus since our original transport broke down about an hour into our journey. However, we had been warned about these kinds of logistical problems, and I was proudly unfazed. But now, our destination was racing towards us from the horizon so fast I was afraid it might hit us. No one spoke as we pressed our faces to the dirty windows to get the best view of this place we had been learning about, talking about, and dreaming about for the past six months: Mwange Refugee Camp. Mwange harbors 24,000 refugees from the conflict in the Democratic Republic of the Congo (DRC), most of whom had been living there since 1998. I traveled to Mwange with a group of eight students through an organization called FORGE to bring opportunities to the refugees. When we got off the bus in Mwange, the first thing...";
extractArr[4] = "Since the mid-1990s, elections have come to be seen as an integral part of post-conflict reconstruction operations. According to Simon Chesterman, this belief is rooted in theoretical literature on democratic peace and the right to democratic governance, and in normative support from successful operationsin Namibia and Cambodia.1 However, the focus of elections tends to be on their form, or the “simple, single-moment, horse race-type event – the actual2 balloting and the intriguing issue of who ‘wins’ and who ‘loses,’” rather than their substance. Instead,the focus should be on what elections are actually meant to achieve, the conditions necessary to ensure the success of elections, and the definition of success. I will argue...";
extractArr[5] = "The introduction of free Primary school education was undoubtedly a significant development in Kenya’s education sector. Education in Kenya has been based on an 8-4-4 system since the late 1980s, with eight years of primary education followed by four years of secondary school and four years of college or university. With the generally poor standards of living among the people, many could not afford to go school before the ministry of education implemented this program in January 2003. Through the program, every citizen was offered an opportunity to acquire basic education up to Standard eight (equivalent to 8th Grade), although further education past this level still relies on personal resources. Nevertheless, this program has elicited major problems in the education sector which may not have been adequately considered. The available education resources can only adequately support half...";
extractArr[6] = "After the Nuremberg and Tokyo war crimes trials punished German and Japanese military officials for violations of international law and laws of war committed during World War II,1 the world waited over forty years without witnessing any other international prosecutions.2 Then, suddenly, in the early 1990s, two ad hoc internationalcriminal courts were created by the Security Council of the United Nations.3 Within nearly a year of one another, Security Council Resolutions created the International Criminal Tribunal for Yugoslavia (ICTY) and the InternationalCriminal Tribunal for Rwanda (ICTR). However, the resultant rebirth of international prosecution of war criminals did not cease with those two temporary courts. In 1998, nearly fifty years...";
extractArr[7] = "This essay looks at phone usage in the Southern African Development Community, a regional entity comprised of fourteen countries in Southern Africa (see map, Appendix 1). I choose to concentrate on the SADC because it is a cognizable and well-defined region of Africa with which I have personal experience. Of the fourteen countries in the SADC, I have travelled to eight and secured local mobile phone service in six. Although market penetration within the SADC remains small at just over 9% (see Appendix 2), mobile phone use in Africa as a whole has been growing at a rate of more than 50% per year, higher than that of any other continent (LaFraniere 2005). In addition, mobile phone use in the SADC region outstrips that of landline phones Countries in the SADC vary tremendously with respect to mobile phone use. The percentage of populationusing mobile phones varies from 1% in Malawi...";
extractArr[8] = "Sub-Saharan Africa lags the rest of the world in electrification; only 23.5% of the population has access to electricity.  This is particularly alarming because poverty and energy production and consumption are strongly correlated (see Figure 1), though experts debate which factor is the causal force.  The problem is cyclical, as both poverty and lack of energy contribute to the impact of the other.  Sub-Saharan Africa has low purchasing power, which leads to their inability to pay for the adequate energy resources that it needs.  In turn, this lack of energy contributes to current poverty levels.  Many single out energy poverty as the root much of Africa’s problems, because of its pivotal role in efficient daily activity and productive industry.  Substantial time and effort is spent to procure firewood or other forms of biomass for fueling traditional energy sources.  For instance, in rural sub-Saharan Africa, many women carry 20kg of fuel wood an average of 5km each day. (IEA, 2002) Additionally...";
extractArr[9] = "International comparisons of school achievement for both primary and secondary education have demonstratedthat African pupils are learning much less than their counterparts in other parts of the world. At the secondary school level, studies have demonstrated that the achievementof African students is particularly low in the key subjects of science and mathematics.Worldwide women choose to enroll in greater proportionsin arts, human studies and social science s than they do in science and mathematics related courses. The origin of this under representation is largely structural, created in and through the social...";

var articleNum = 0;
var opacityNum = 10;
var t;

// Creates and changes the extracts of articles in the div(id='articleExtract')
function changeExtract()
{
	createExtract();
	//setTimeout("switchExtract()", 10000);
	switchExtract();
}

// Creates the innerHTML text for the div(id='articleExtract')
function createExtract()
{
	//var title = "<h2 style='margin: 0; text-align: center; padding: 0;'><a href='html/article" + articleNum + ".html' style='margin: 0; font: 20px Georgia, Serif; color: #690; text-decoration: none;' onmouseover='underlineLink(this)' onmouseout='removeUnderlineLink(this)'>" + titleArr[articleNum] + "</a></h2>";
	var title = "<h2 style='margin: 0; text-align: center; padding: 0; font: 20px Georgia, Serif;' id='hdr'><a onmouseover='underlineLink(this)' onmouseout='removeUnderlineLink(this)' style='text-decoration: none; color: #690;' href='html/vol2/article" + (articleNum+1) + ".html'>" + titleArr[articleNum] + "</a></h2>";
	var quote = "<div><p style='margin: 0; font-style: italic; font-size: 11px; text-align:center'>" + quoteArr[articleNum] + "</p></div>";
	var twoDashes = "";
	if(quoterArr[articleNum].length > 0) twoDashes = "--";
	var quoter = "<div><p style='margin: 0; font-style: italic; font-size: 11px; text-align: right; padding-right: 15px;'>" + twoDashes + quoterArr[articleNum] + "</p></div>";
	var author = "<div><p style='margin: 0; font-size: 11px; text-align: left; padding-left: 10px;'><i>by</i> " + authorArr[articleNum] + "</p></div>";
	//var extract = "<div style='margin: 0; font-size: 11px; padding-top: 1px;'>" + "<b style='color: red; font-size: 15px;'>" + extractArr[articleNum].substring(0,1) + "</b>" + extractArr[articleNum].substr(1) + "<div style='position: relative; top: -12px; text-align: right; padding-right: 10px;'><a href='html/vol2/article" + (articleNum + 1) + ".html' style='color: #330099; text-decoration: none;' onmouseover='underlineLink(this)' onmouseout='removeUnderlineLink(this)'><b>FULL STORY</b></a></div>" + "</div>";
	var extract = "<div style='margin: 0; font-size: 11px; padding-top: 1px;'>" + "<b style='color: red; font-size: 15px;'>" + extractArr[articleNum].substring(0,1) + "</b>" + extractArr[articleNum].substr(1) + "<div style='width: 90px; position: relative; top: -12px; left: 250px; text-align: right; padding-right: 10px; color: #330099;' id='lnk" + articleNum + "'><b><a onmouseover='underlineLink(this)' onmouseout='removeUnderlineLink(this)' style='text-decoration: none;' href='html/vol2/article" + (articleNum+1) + ".html'>FULL STORY</a></b></div>" + "</div>";
	document.getElementById("extractDiv").innerHTML = title + quote + quoter + author + extract;
}


/*
  * Changes the mouse cursor to a 'pointer ( a hand)' when the mouse is over the parameter 'link'.
  * Underlines the 'link' parameter.
  */
function underlineLink(link)
{
	link.style.cursor = "pointer";
	link.style.textDecoration = "underline";
}

/*
  * Changes the mouse cursor to the default one for the system/browser when the mouse is out of the parameter 'link'.
  * Removes the underline text-decoration from the 'link' parameter.
  */
function removeUnderlineLink(link)
{
	link.style.cursor = "default";
	link.style.textDecoration = "none";
}

// This function controls the timing of when to fade, change the text of the extract and when to unfade to display the new text
function switchExtract()
{
	fade();														// fade
	setTimeout("unfade()", 650);								// unfade
	setTimeout("switchExtract()", 13000);						// recall function immediately
}

// Creates the fading effect of the div(id="articleExtract') and then changes the text for the div. Takes a 500ms to fade.
function fade()
{
	//document.getElementById("articleExtract").style.opacity = 1;
	document.getElementById("extractDiv").style.opacity = opacityNum/10;							// for firefox/mozilla
	document.getElementById("extractDiv").style.filter = "alpha(opacity=" + opacityNum*10 + ")";	// for IE
	if(opacityNum > 0)
	{
		opacityNum--;				// reduce the opacity index
		setTimeout("fade()", 50);	// recall function after 200ms
	}else
	{
		//clearTimeout(t);										// clear the time variable; this is to ensure that program does not slow down the browser after running for a very long time
		articleNum++;											// increment the article number
		if(articleNum > extractArr.length-1) articleNum = 0;	// reset article number if it's more than the total number of articles
		createExtract();										// create the extract for the next article
		unfade();
	}
}

// Creates the unfading effect just before the text of the div(id="articleExtract') is changed. Takes a 500ms to unfade.
function unfade()
{
	document.getElementById("extractDiv").style.opacity = opacityNum/10;							// for firefox/mozilla
	document.getElementById("extractDiv").style.filter = "alpha(opacity=" + opacityNum*10 + ")";	// for IE
	if(opacityNum < 10)
	{
		opacityNum++;						// increment opacity index
		setTimeout("unfade()", 50);			// recall function
	}
}