var current_value = 0;
var current_value_px = 0;
var previous_day_url = false;
var next_day_url = false;

// Fonctions principales
function deplacer_programmes(valeur) {
	current_value = valeur;
	current_value_px = valeur*580/7200;
	hashize(current_value);
	$('.liste_move').css({left: (current_value_px*-1)+'px'});
}

function second_to_hours(seconds) {
	var tps = new Date();
	tps.setHours(0);
	tps.setMinutes(0);
	tps.setSeconds(seconds);
	var hours = tps.getHours()+'';
	var minutes = tps.getMinutes()+'';
	return  (hours.length == 1 ? '0' : '')+hours+'h'+(minutes.length == 1 ? '0' : '')+minutes;
}

function hash_to_seconds(hash) {
	if(!hash) hash = window.location.hash;
	var heures = 0;
	var minutes = 0;
	if(!hash.match(/[0-9]{2}h[0-9]{2}/gi)) {
		$('#now_link').parent('li').addClass('on'); 
		var now_tps = new Date();
		return now_tps.getHours()*3600+(now_tps.getMinutes() > 30 ? 30 : 0)*60;
	}
	var hashes = hash.split('#').join('').split('h');
	heures = hashes[0];
	minutes = hashes[1];
	return heures*3600+minutes*60;
}

function hash_now() {
	var now_tps = new Date();
	var now_hours = now_tps.getHours()+'';
	if(now_tps.getMinutes() > 30) var now_minutes = 30+'';	
	else var now_minutes = 0+'';	
	return (now_hours.length == 1 ? '0' : '')+now_hours+'h'+(now_minutes.length == 1 ? '0' : '')+now_minutes;
}

function hashize(valeur) {
	window.location.hash=second_to_hours(valeur);	
	document.getElementById('heure').selectedIndex = window.location.hash.split('#')[1].split('h')[0]*1;
	$('#liste_chaines li a').each(function(i, e){$(e).attr('href', $(e).attr('href').split('#')[0]+window.location.hash);});
	$('#day_hours').html(window.location.hash.split('#')[1]);
}

// OnLoad
function init_hash(hash) {
	current_value = hash_to_seconds(hash);
	deplacer_programmes(current_value);	
	$('#slider').slider('value', current_value);	
}

function init_programmes() {	
	init_hash();
	$('.mover').click(function () {
			switch($(this).attr('name')) {
				case 'left':
					var valeur = current_value+1800; 
					if(valeur <= 79200) {
						$('#slider').slider('value', valeur);
						deplacer_programmes(valeur);
					}
					else {
						window.location.href = next_day_url;
						return false;
					}
				break;
				case 'right':
					var valeur = current_value-1800; 
					if(valeur >= 0) {
						$('#slider').slider('value', valeur);
						deplacer_programmes(valeur);
					}
					else {
						window.location.href = previous_day_url;
						return false;
					}
				break;
			}
		return false;
	});
	
	$("#slider").slider({ 
		value: current_value,
		min: 0,
		max: 79200,
		step: 1800,
		slide: function(event, ui) {
			deplacer_programmes(ui.value);	
		}
	});	
}
