/**
 * Make input (or something else) empty and rollback to previous value if no changes
 * @param o_input
 * @param optionnal default_text - if null default_text will be the previous value
 */
function input_manipulation (o_input, default_text){
	
	updated = false;
	
	if(!default_text) {
		default_text 	= o_input.value;
	}
	
	o_input.observe("focus", function() {
		if(!updated) {
			this.value 	= '';
		}
	});
	
	o_input.observe("blur", function() {
		if(o_input.value != '') {
			updated 	= true;
		}else{
			this.value 	= default_text;
			updated 	= false;
		}
	});
}

/**
 * Switch element to display on a collection
 * btn_ prev & next are automagically affected to switch functions
 * @param a_winner_collection - object { picture: "pic src", whatever: "innerHTML value"  }
 * @param id_prefix - prefix for ids of elements (btn prev/next & picture)
 * @param auto - automatique roll
 * @return
 */
function switch_element_list (a_collection, id_prefix, rolling_interval) {
	var current 			= 0;
	var collection_length	= a_collection.length - 1;
	var intervalId;
	
	var init = function(){
		update_display();
		$(id_prefix + "btn_next").style.visibility = "hidden";
		$(id_prefix + "btn_next").onclick 	= next_element;
		$(id_prefix + "btn_prev").onclick 	= prev_element;
		
		if(rolling_interval){
			start_automatic_roll();
		}
		
	};
	
	/* update current element*/ 
	var update_display = function(){
		i = 0 ;
		Object.keys(a_collection[current]).each(function(key){
			switch(key){
			case "picture":
					$(id_prefix + "picture").src = a_collection[current][key];
					break;
			case "picture_alt":
				$(id_prefix + "picture").alt = a_collection[current][key];
				break;
			default:
				$(id_prefix + key).innerHTML = a_collection[current][key];
				break;
			}
			
		});
	};
	
	/* Display next latest element*/
	var next_element = function(){
		if(current > 0) {
			current--;
			update_display();
		}
		
		if(current <= 0){
			$(id_prefix + "btn_next").style.visibility = "hidden";
		}
		
		$(id_prefix + "btn_prev").style.visibility = "visible";
		
		start_automatic_roll();
	};
	
	/* Display next previous winner*/
	var prev_element = function(){
		if(current < collection_length) {
			current++;
			update_display();
		}
		
		if(current >= collection_length){
			$(id_prefix + "btn_prev").style.visibility = "hidden";
		}
		$(id_prefix + "btn_next").style.visibility = "visible";
		
		start_automatic_roll();
	};
	
	/* Do roll elements */
	var roll_element = function(){
		if(current >= collection_length){
			current = -1;
			$(id_prefix + "btn_prev").style.visibility = "visible";
			$(id_prefix + "btn_next").style.visibility = "hidden";
		}
		prev_element();
	};
	
	/* start & restart automatic roll */
	var start_automatic_roll = function(){
		clearInterval(intervalId);
		intervalId = setInterval(roll_element, rolling_interval);
	};
	init();
}


