//elements
var mainDiv, infoTables, infoTablesNr = 0, displayedSlide = 0, nextSlide = 0, totalCounterImgObjects = 0, counterObjects;

//xml
var mainDivWidth, changeSlidesInterval = 0, autoRefreshSlideshow, slidesSpeed = 0, eachMoveCoversThisNrOfPixels = 0;

//timers
var timedAjaxReload, counterTimer;

//action
var displayedSlidePosition = 0, nextSlidePosition = mainDivWidth, callingFunction = 0, calledCounter = 0, loadedInfoTable = 1, clickAnyArrow = 0, goToDirection = "left";

//titles array
var array_data = new Array();

//ajax object
var myRequest = getXMLHTTPRequest();


/*
	Function:	getXmlSettings();
	Action:		- 	reads, using AJAX, the XML file (cpanel.xml) that contains
					slideshow settings
				-	passes the data to applySettings() function
*/
function getXmlSettings(){

	var randomNr = parseInt(Math.random()*9999999);

	myRequest.open("GET", '/newsflash_cpanel.xml?rand=' + randomNr, true);
	myRequest.onreadystatechange = applySettings;
	myRequest.send(null);

}

addEvent(window, 'load', getXmlSettings, false);

/*
	Function:	applySettings();
	Action:		- 	applies all settings found into cpanel.xml file
*/
function applySettings(){

	if(myRequest.readyState == 4){

		if(myRequest.status == 0 || myRequest.status == 200){

            //XML values will be passed to variables
			mainDivWidth = myRequest.responseXML.getElementsByTagName('mainDivWidth')[0].childNodes[0].nodeValue;

			var mainDivHeight = myRequest.responseXML.getElementsByTagName('mainDivHeight')[0].childNodes[0].nodeValue;

			var defaultSlidesLeftPosition = mainDivWidth;

			slidesSpeed = myRequest.responseXML.getElementsByTagName('slidesSpeed')[0].childNodes[0].nodeValue;

			eachMoveCoversThisNrOfPixels = myRequest.responseXML.getElementsByTagName('eachMoveCoversThisNrOfPixels')[0].childNodes[0].nodeValue;

			changeSlidesInterval = myRequest.responseXML.getElementsByTagName('changeSlidesInterval')[0].childNodes[0].nodeValue;

			autoRefreshSlideshow = myRequest.responseXML.getElementsByTagName('autoRefreshSlideshow')[0].childNodes[0].nodeValue;

            counterAlignment = myRequest.responseXML.getElementsByTagName('counterAlignment')[0].childNodes[0].nodeValue;

			//APPLYING values
			mainDiv = document.getElementById('newsflashDiv');
			infoTables = mainDiv.getElementsByTagName('table');
			infoTablesNr = infoTables.length;

			/* 	main DIV width
				the DIV that contains all info tables (slides)
			*/
			mainDiv.style.width = mainDivWidth + "px";
			mainDiv.style.height = mainDivHeight + "px";

			/* 	slide 0 width
				slide 0 => 	the slide that is visible on first page load or after page
							refresh
			*/
			infoTables[0].style.width = mainDivWidth + "px";
            infoTables[0].style.height = mainDivHeight + "px";

			//slides width
			for(var i = 1; i < infoTablesNr; i++){

				infoTables[i].style.width = mainDivWidth + "px";
                infoTables[i].style.height = mainDivHeight + "px";
				infoTables[i].style.left = -defaultSlidesLeftPosition + "px";
				
			}
			
			//setting counter objects
			totalCounterImgObjects = Math.ceil(changeSlidesInterval / 1000);
            var counterObjectsCell = document.getElementById('showCounterObjects');
            
            //place the objects inside desired cell
            for(var i = 0; i < totalCounterImgObjects; i++){
                
                counterObjectsCell.innerHTML += '<img src="/img3/newsflash/counter_a.jpg" width="10" height="1" alt="" />';
                
            }
            
            counterObjects = counterObjectsCell.getElementsByTagName('img');
            
            //set desired counter alignment
            counterObjectsCell.setAttribute('align', counterAlignment);

			/* 	how many times should we call the moveInfo() function so that the next slide will cover the entire visible space?
			*/
			callingFunctionInterval = Math.ceil(mainDivWidth / eachMoveCoversThisNrOfPixels);

			//call next function
			loadMultiArrayInfo();

        }

    }

}

/*
	Function:	loadMultiArrayInfo();
	Action:		- 	reads, using AJAX the HTML file (titles.htm) that contains
					all the information needed
*/
function loadMultiArrayInfo(){

	var randomNr = parseInt(Math.random()*99999999);

//  	myRequest.open("GET", 'newsflash_titles.htm?rand=' + randomNr, true);
  	myRequest.open("GET", 'ev.shtml', true);
  	myRequest.onreadystatechange = responseAjax;
	myRequest.send(null);

}

/*
	Function:	responseAjax();
	Action:		-	creates an array containing the informations extracted from
					/titles.htm/ file
				-	calls the loadInfo() function\
                -   recalls loadMultiArrayInfo() function using the autoRefreshSlideshow variable value written into the XML file
*/
function responseAjax(){

	if(myRequest.readyState == 4){

		if(myRequest.status == 0 || myRequest.status == 200){
            
			array_data = eval('('+myRequest.responseText+')');
			
			loadInfo();

        }
        
    }

	clearTimeout(timedAjaxReload);
	timedAjaxReload = setTimeout("loadMultiArrayInfo()", autoRefreshSlideshow);
}


/*	
	Function:	loadInfo();
	Action:		-	each info table (slide) will get informations
				-	the first slide will be visible on first page load or after page
					refresh
				-	starts the counter by calling the counter() function
*/
function loadInfo(){
	
	for(var i = 0; i < infoTablesNr; i++){
		
		var cells = infoTables[i].getElementsByTagName('td');
		
		cells[0].innerHTML = '<img src="' + array_data[i][2] + '" alt="">';
		cells[1].innerHTML = '<span id="newsflashTitles">' + array_data[i][0] + '</span><br /><br />' + array_data[i][1];
		
	}
    
    counter();
	
}


/*	
	Function:	showNextSlide(); 
	Action:		-	establish the index of the visible and the next slides
				-	starts the counter by calling counter() function
				-	calls moveInfo() function
*/
function showNextSlide(){
	
	if(goToDirection == "right"){
		
		nextSlide = (nextSlide > 0) ? nextSlide - 1 : (infoTablesNr - 1);
		displayedSlide = (nextSlide == (infoTablesNr - 1)) ? 0 : nextSlide + 1;
		nextSlidePosition = -mainDivWidth;
		
	}
	else {
		
		nextSlide = (nextSlide < (infoTablesNr - 1)) ? nextSlide + 1 : 0;
		displayedSlide = (nextSlide == 0) ? (infoTablesNr - 1) : nextSlide - 1;
		nextSlidePosition = mainDivWidth;
		
	}

	//resetting variables
	loadedInfoTable = 0;
	callingFunction = 0;
	displayedSlidePosition = 0;
	
	stopTimers();
	
	resetCounter();
	
	counter();
	
	moveInfo(nextSlide, displayedSlide);
	
}


/*	
	Function:	moveInfo(); 
	Action:		- 	recursive function
				-	moves from right to left or left to right two tables (slides) at once
					(visible + next slide)
*/
function moveInfo(nextSlide, displayedSlide){
	
	if(callingFunction <= callingFunctionInterval){
		
		//setting position
		infoTables[displayedSlide].style.left = displayedSlidePosition + "px";
		infoTables[nextSlide].style.left = nextSlidePosition + "px";
		
		//modify position considering the alignment
		if(goToDirection == "right"){
			
			displayedSlidePosition += parseInt(eachMoveCoversThisNrOfPixels);
			nextSlidePosition += parseInt(eachMoveCoversThisNrOfPixels);
			
		}
		else {
			
			displayedSlidePosition -= parseInt(eachMoveCoversThisNrOfPixels);
			nextSlidePosition -= parseInt(eachMoveCoversThisNrOfPixels);
			
		}
		
		//how many times this function recalled itself?
		callingFunction += 1;
		
		//recursive calling
		setTimeout('moveInfo(\'' + nextSlide + '\' , \'' + displayedSlide + '\')', slidesSpeed);

	}
	else {
		
		//resetting variables
		loadedInfoTable = 1;
		clickAnyArrow = 0;
		goToDirection = "left";

	}
		
}


/*	
	Function:	counter(); 
	Action:		- 	recursive function
				-	changes each counter images src img/newsflash/counter_a.jpg
					with img/newsflash/counter_b.jpg after each pasing second
                -   the value of /totalCounterImgObjects/ variable represents
                    the number of times this function will call itself
                -	calls showNextSlide() function when the counter time expires.
                	Everytime the counter expires, another slide will be
                	loaded
*/
function counter(){
    
	if(calledCounter < totalCounterImgObjects){
	   	
        counterObjects[calledCounter].setAttribute('src', '/img3/newsflash/counter_b.jpg');
        
		calledCounter += 1;
		
        counterTimer = setTimeout('counter()', 1000);
		
	}
	else {
		
		showNextSlide();
		
	}
	
}


/*	
	Function:	resetCounter(); 
	Action:		- 	resets the counter() function
*/
function resetCounter(){
    
    calledCounter = 0;
    
    for(var i = 0; i < totalCounterImgObjects; i++){
            
       counterObjects[i].setAttribute('src', '/img3/newsflash/counter_a.jpg');
            
    }
    
}

/*	
	Function:		stopMovement();
	Calling event:	onmouseover();
	Action:			-	stops slides movement on mouse over
					-	changes the slides background on mouse over
					-	sets another slide attribute (onmouseup) for the mainDiv element,
						which will acces the desired URL
*/
function stopMovement(){

	stopTimers();
	
	infoTables[nextSlide].style.backgroundColor = '#e2edf4';
	
	mainDiv.onmouseup = function(){
        
        window.open(array_data[nextSlide][3], '_parent');
        
    }
	
}


/*
	Function:		startMovement();
	Calling event: 	onmouseuot();
	Action:			- 	calls counter() function. the counter will continue
					-	changes the slides background
	
*/
function startMovement(){
	
	if(loadedInfoTable == 1){
        
        infoTables[nextSlide].style.backgroundColor = '#ffffff';
        
        stopTimers();
        
        counterTimer = setTimeout('counter()', 1000);
		
	}
	
}


/*
	Function:	clickOnArrows();
	Action:		-	sets the slides movement direction
				-	calls showNextSlide() function
				-	right arrow click -> slides will move towards left
				-	left arrow click -> slides will move towards right
*/
function clickOnArrows(direction){
	
	if(clickAnyArrow == 0){
		
		clickAnyArrow = 1;
		
		goToDirection = direction;
        
		showNextSlide();
        
	}
	
}


/*	
	Function:		stopTimers();
	Action:			-	resets timers
*/
function stopTimers(){
	
	clearTimeout(timedAjaxReload);
    clearTimeout(counterTimer);
	
}

