var currentPage = null;
var currentWidth = 0;
var currentHash = location.hash;
var hashPrefix = "#_";
var pageHistory = [];
var arg;
var offsetServerTime = 0;
var comingDaysLag = 0;
window.onresize = resizeTitle;
var XmlRequest;
var xml_request_details;
var titlePxLenth = null;

//Variables pour enregistres les ID du button back (theme - liste des circuits) et fiche circuit
identifiantTheme = 0;
identifiantCircuit = 0;

addEventListener("load", function(event) {
	var body = document.getElementsByTagName("body")[0];
	for (var child = body.firstChild; child; child = child.nextSibling)
	{		
		if (child.nodeType == 1 && child.getAttribute("selected") == "true") {
			showPage(child);			
			break;
		}
	}
	setInterval(checkOrientAndLocation, 300);
}, false);


function hideBar() {
	scrollTo(0, 1); 
}

function checkOrientAndLocation() 
{
	//Permet de gerer le hidebar lors du changement de langue
	if(currentHash == "#_menu")
	{
		hideBar();
	}
	if (location.hash != currentHash) 
	{
		currentHash = location.hash;
        var pageId = currentHash.substr(hashPrefix.length);
        var page = document.getElementById(pageId);
        
        
        if (page)
        {
			hideBar();
            var index = pageHistory.indexOf(pageId);
            var backwards = index != -1;
            if (backwards) {
                pageHistory.splice(index, pageHistory.length);
                if (xml_request_details) 
    				xml_request_details.Abort();
                if (XmlRequest) 
    				XmlRequest.Abort();

             }
            showPage(page, backwards);
        }
    }
}
    
function showPage(page, backwards)
{
	if(page == null) { return;}	
	
	
	location.href = currentHash = hashPrefix + page.id;
	pageHistory.push(page.id);
	var fromPage = currentPage;
	currentPage = page;
		var pageTitle = document.getElementById("pageTitle");
		
	
	var Type = $('pageTitle').getAttribute("name");
	var Identifiant = $('pageTitle').getAttribute("value");		
		
		if (page.title != "not")
		pageTitle.innerHTML = page.title || "";
	
	var homeButton = document.getElementById("homeButton");
	var LangueButton = document.getElementById("LangueButton");
	
	
	if (homeButton) {
		homeButton.style.display = (page.id) == "menu" ? "none" : "inline";
		LangueButton.style.display = (page.id) == "menu" ? "inline" : "none";
		var parent = page.getAttribute("parent");
		if (parent != undefined) {
			homeButton.innerHTML = "back";
			homeButton.href="#_"+parent;
			homeButton.onclick = back_click;
		}
	}
		
	if (fromPage) {
		//setTimeout(swipePage, 0, fromPage, page, backwards);
		swipePage(fromPage, page, backwards);
		//ajax("Type="+Type+"&Identifiant="+Identifiant);				
	}
}

function back_click(){
	
	if(currentPage.id == 'etape'){
		action('CIRCUIT', identifiantCircuit);
	}
	if(currentPage.id == 'fiche')
		action('THEME',identifiantTheme);

}
 
function swipePage(fromPage, toPage, backwards) {
/*	if (toPage.id == "menu") {
		$('result').innerHTML = "";
		//$('index').innerHTML = "";
		//$('index').style.background = "none";
		//$('field_search').value = "";

	}*/
	
	//alert('de '+fromPage.id+' à '+toPage.id);
	if (fromPage.id == "result") {
		$('result').innerHTML = "";
	}

	if (fromPage.id == "fiche") {
		$('fiche').innerHTML = "";
	}
	
	if (fromPage.id == "etape") {
		$('etape').innerHTML = "";
	}

	
	$('pageTitle').style.fontSize = "15px";
	titlePxLenth = null;
	scrollTo(0, 1);

/* 	toPage.style.left = "100%"; */

	toPage.setAttribute("selected", "true");
/* 	var percent = 0; */
/*  	fromPage.style.left = (backwards ? 100 : -100) + "%";  */
/* 	toPage.style.left = (backwards ? -0 : 0) + "%";  */
	//fromPage.removeAttribute("selected");
	fromPage.setAttribute("selected","false");
	//alert('de '+fromPage.id+' à '+toPage.id);	

}




function ajax(arguments) 
{
	
	var XmlRequest = null;
	if(window.XMLHttpRequest){XmlRequest = new XMLHttpRequest();}
	else if(window.ActiveXObject){XmlRequest = new ActiveXObject("Microsoft.XMLHTTP");}
	else{return(false)}
	
	page = $('pageTitle').getAttribute("page");	
	setupSpinner(page);
	XmlRequest.onreadystatechange = function()
	{
		if( XmlRequest.readyState == 4 )
		{
			if( XmlRequest.status == 200 )
			{
				stopSpinning(page);
				$(page).innerHTML = XmlRequest.responseText;
			}
		}
	}
	
	XmlRequest.open("POST", "Liste.php", true);
	XmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	XmlRequest.send(arguments);
}

//function action(value, key, start, end, chan) {
function action(Type, Identifiant) 
{	
	switch (Type) {			
		case "THEME":
			identifiantTheme = Identifiant;
			$('result').setAttribute("parent", "menu");
			$('result').setAttribute("title", $('T'+Identifiant).getAttribute("title"));
			$('pageTitle').setAttribute("name","THEME");
			$('pageTitle').setAttribute("value",Identifiant);
			$('pageTitle').setAttribute("page","result");
			ajax("Type=THEME&Identifiant="+Identifiant);			
			break;
			
		case "CIRCUIT":
			identifiantCircuit = Identifiant;
			
			$('fiche').setAttribute("parent", "result");
			
			$('pageTitle').setAttribute("name","CIRCUIT");
			$('pageTitle').setAttribute("value",Identifiant);
			$('pageTitle').setAttribute("page","fiche");
			ajax("Type=CIRCUIT&Identifiant="+Identifiant);
			$('fiche').setAttribute("title", $('C'+Identifiant).getAttribute("title"));
			break;
			
		case "ETAPE":
			$('etape').setAttribute("parent", "fiche");			
			$('etape').setAttribute("title", $('E'+Identifiant).getAttribute("title"));
			$('pageTitle').setAttribute("name","ETAPE");
			$('pageTitle').setAttribute("value",Identifiant);
			$('pageTitle').setAttribute("page","etape");
			ajax("Type=ETAPE&Identifiant="+Identifiant);	
			break;
			
		default:
			break;
	}
}

function $(i) 
{
	return document.getElementById(i);
}
function changeFontSize()
{
	$('pageTitle').style.fontSize = "18px";
}
/*
function pref_save(service, key, selected) {
		switch (service) {
			case "zone":
				var children = $('settings_zone').childNodes;
				var tags = document.getElementsByTagName("div");
				var query = "";
				for (var x = 0; x < tags.length; x++) {
					if (tags[x].parentNode.id == "settings_zone") {
						if (tags[x].innerHTML == key) {
							tags[x].style.background = "url(images/check.png) no-repeat right center";
							tags[x].style.backgroundColor = "white";
							tags[x].style.color = "#2c5082";
						}
						else {
							tags[x].style.background = "white";
							tags[x].style.color = "black";
						}
					}
				}
				pref_zone = key;
				createCookie("zone", pref_zone);
				break;
			default:
				break;
		}
		$('selectedZone').innerHTML = pref_zone;

}

function setTitleBar(value) {
	$('pageTitle').innerHTML = value
}


function slider_toggle(image, type) {
	if (image.style.backgroundPositionX == "0px")
		image.style.backgroundPositionX = "-54px";
	else
		image.style.backgroundPositionX = "0px";
	
	if (type == "allChannels") {
		createCookie("allChannels", image.style.backgroundPositionX);
		if ($('field_search').value != "") {
			validate();
		}	
	}
	else
		createCookie("channels", generateChannelQuery());

}

function generateChannelList() {
	var list = "";
	for (var x = 0; x < channels.length; x++) {
		list += '<li>'+ channels[x].name +'<div class="slider" style="background-position-x: -54px;" id="slider_'+ channels[x].id +'" onclick="slider_toggle(this)"></div></li>'

	}
	var len = channels.length;
	$('settings_channel').innerHTML = list;
}

function generateChannelQuery() {
	var tags = document.getElementsByTagName("div");
	var query = "";
	for (var x = 0; x < tags.length; x++) {
		if (tags[x].className == "slider" && tags[x].id != "allChannels") {
			var idName = tags[x].id;
			if ($(idName).style.backgroundPositionX == null) {
				idName = idName.replace("slider_", "");
				query += idName +",";
			
			}
			else if ($(idName).style.backgroundPositionX == "-54px") {
			}
			else if ($(idName).style.backgroundPositionX == "0px") {
				idName = idName.replace("slider_", "");
				query += idName +",";
			}
		}
	}
	return query;
}

function generateDayList() {
	var time = new Date();
	var timeNow = parseInt(time.getHours()) + parseInt(offsetServerTime);
	switch (pref_zone) {
		case "Eastern":
			timeNow = timeNow + 3;
			break;
		case "Central":
			timeNow = timeNow + 2;
			break;
		case "Mountain":
			timeNow = timeNow + 1;
			break;
	}
	if (timeNow >= 24) {
		timeNow = timeNow - 24;
	}
	extra = 0;
	if (timeNow < 4) {
		extra++;
	}
	else if (parseInt($('server_time').innerHTML) > parseInt(time.getHours())) {
		extra++;
	}
	var days= ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"];

	today = new Date();
	days = [
		{day:"Tomorrow", classNames:"round_rect round_rect_top", lag:"1"},
		{day:days[today.getDay() + 2 - extra], classNames:"round_rect", lag:"2"},
		{day:days[today.getDay() + 3 - extra], classNames:"round_rect", lag:"3"},
		{day:days[today.getDay() + 4 - extra], classNames:"round_rect round_rect_buttom", lag:"4"},
	];
	var list = "";
	for (var x = 0; x < days.length; x++) {
		list += "<a href='#_coming_selected' onclick=\"action('coming', '"+ days[x].lag +"', '"+ days[x].day +"')\" class='"+ days[x].classNames +"'>"+ days[x].day +"</a>";
	}
	$('coming').innerHTML = list;

}

function setChannelState() {
	var query = readCookie("channels");
	if (query == null)
		query = "abc,cbs,fox,nbc,bbc,pbs,cw,ane,cnn,hbo,cnbc,discovery,tvm,fx,espn,";
	
	var spl = query.split(",");
	for (var x = 0; x < spl.length - 1; x++) {
		if ($("slider_"+ spl[x]))
			$("slider_"+ spl[x]).style.backgroundPositionX = "0px";
	}	
}
*/
var level = 1;
var timer;
function setupSpinner(idName, clName) 
{
	clName = (clName != undefined) ? clName : "";

	$(idName).innerHTML = '<div id="spinner" class="'+ clName +'"></div>';
	$(idName).style.backgroundColor = "transparent";
	$('spinner').style.display = "block";
	clearTimeout(timer);
	startSpinning();
	
}

function startSpinning(idName) {
	level = (level == 12) ? 1 : level;
	var pixel = 48 * level;
	$("spinner").style.backgroundPositionX = "-"+ pixel +"px";
	level++;
	timer = setTimeout(startSpinning, 50);
}

function stopSpinning(idName) {
	if ($("spinner"))
		$("spinner").style.display = "none";
	clearTimeout(timer);
	//$(idName).style.backgroundColor = "white";

	level = 1;
}

function createCookie(name,value,days) {
	days = 365;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function expand(num, titleBar) {
	var child = titleBar.childNodes;
	child[1].style.BackgroundPositionX = (child[1].style.BackgroundPositionX == "0px") ? "-13px" : "0px";
	titleBar.nextSibling.style.display = (titleBar.nextSibling.style.display == "none") ? "block" : "none";

}


function clear(id) {
	$("error").style.display = "none";
	$(id).value = "";
}

function resizeTitle() {
	if (titlePxLenth != null) {
		var pixels = titlePxLenth;
		var availableSpace = document.body.clientWidth - 140;
		if (pixels > availableSpace) {
			var fontNewSize = parseInt((availableSpace / pixels) * 20);
			if (fontNewSize < 12)
				fontNewSize = 12;

		}
		else {
			var fontNewSize = 20;
		}
		$('pageTitle').style.fontSize = fontNewSize +"px";
	}

}
