//List area
var fixed_zone;
var moved_zone;
var first_index_zone;
var cursor;
var alist_wait;
//current index
var current_index=1;
//Showed items count
var nbitem_showed;
//Height of one item
var item_height;
//Number max of items
var nbmax_item;
//Hieght of the scrollbar
var scroll_height;

//Current cursor position
var cursor_pos;
var cursor_rel_pos;
var cursor_height;

//If cursor is clicke move mouse move the cursor
var cursor_clicked=false;

//Position var
var first_displayed=1;
var last_index;
var first_index=0;
var temp_index=0;

//Param ajax return
var ajax_nbget=500;
var ajax_limit=400;
var ajax_ending = true;

//Mouvement mouse
var mouse_pos_start=0;
var mouse_pos_end;
var mouse_move_end;
var mouse_delta=0;

//Interval
var mouse_interval;
var repeat_interval=50;

//Ajax return
function get_items(insert,start,nb)
{
	ajax_ending=false;
	var url = 'demos/utf8list/items&list_start='+start+'&list_nb='+nb;
	new Ajax.Updater(moved_zone, urlaff, {
	asynchronous: 'true', 
	postBody: 'tpl='+url,
	insertion: insert,
	onComplete: function(xhr)
	{
		//ajuste la position
		if(insert=='top')
		{
			first_index = first_index - nb;
			var id_deleted = (current_index + ajax_limit);
			if(id_deleted<last_index)
			{
				//Deleted the last items
				var list = $$('.alist_item');
				var cptsup=list.length-1;
				var nbsup=0;
				while(list[cptsup].id != ('alist_item_' + id_deleted))
				{
					Element.remove(list[cptsup]);
					cptsup--;
					nbsup++;
				}
	
				//Set the new position
				last_index = last_index - nbsup;
				newpos = (current_index-first_index-1)*item_height*-1;
				moved_zone.style.top = newpos + "px";
			}
		}
		else
		{
			var id_deleted = (current_index - ajax_limit - nbitem_showed);
			if(id_deleted>first_index)
			{
				//Deleted the first items
				var list = $$('.alist_item');
				var nbsup=0;
				while(list[nbsup].id != ('alist_item_' + id_deleted))
				{
					Element.remove(list[nbsup]);
					nbsup++;
				}
				
				//Set the new position
				first_index = first_index + nbsup;
				newpos = (current_index-first_index-nbitem_showed)*item_height*-1;
				moved_zone.style.top = newpos + "px";
			}
		}
		ajax_ending=true;
		temp_index = nbmax_item;
	}
	});
}

function get_items_cursor(first,nb,disp)
{
	ajax_ending=false;
	var url = 'demos/utf8list/items&list_start='+first+'&list_nb='+nb;
	new Ajax.Updater(moved_zone, urlaff, {
	asynchronous: 'true', 
	postBody: 'tpl='+url,
	onComplete: function(xhr)
	{
		ajax_ending=true;
		first_index = first;
		last_index = first+nb;
		first_displayed = disp;
		selectline(disp);
		new Effect.Fade(alist_wait, {queue:'end', duration:0.1});
		//Set the new position
		newpos = (current_index-first_index-1)*item_height*-1;
		moved_zone.style.top = newpos + "px";
		move_list();
	}
	});
}

function getMousePosition(event)
{
    var e = event || window.event;
    var scroll = new Array((document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft,(document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop);;
    return new Array(e.clientX + scroll[0] - document.body.clientLeft,e.clientY + scroll[1] - document.body.clientTop);
}

function init_list()
{
	//Init list field
	fixed_zone = $("alist_container_show");
	moved_zone = $("alist_container_move");
	selected_index_zone = $("alist_selected_index");
	cursor = $("alist_scrollbar_cursor");
	alist_wait = $('wait');

	//Init list movement
	var odim = fixed_zone.getDimensions();
	var list_height = odim.height;
	var first_item = $("alist_item_1");
	var odim = first_item.getDimensions();
	item_height = odim.height;
	nbitem_showed = Math.floor(list_height/item_height);
	
	//Init scrollbar movement
	nbmax_item =  $("alist_nbmax_item").value;
	temp_index = nbmax_item;
	var odim = $('alist_scrollbar_middle').getDimensions();
	scroll_height = odim.height;
	var odim = cursor.getDimensions();
	cursor_height = odim.height;
	scroll_height -= cursor_height;
	tab_pos = cursor.cumulativeOffset();
	cursor_pos = tab_pos[1];
	cursor_rel_pos=0;
	//Int ajax return
	last_index = $$(".alist_item").length;
	//Init cursor mouvement
	mouse_pos_end = scroll_height;
}


function setNewIndex(index)
{
	var input = selected_index_zone;
	input.value = index;
}

function move_list()
{
	new_pos = (parseInt(first_displayed-first_index)-1)*item_height*-1;
	var odim = moved_zone.getDimensions();
	var height = odim.height;
	var limit = (height-item_height*nbitem_showed)*-1;
	if(new_pos<limit)new_pos=limit;
	moved_zone.style.top = new_pos + "px";
}

function check()
{
	var a = a;
}
function selectline(newIndex)
{
	if(current_index!="" && $("alist_item_" + current_index))
	{
		var oldline = $("alist_item_" + current_index);
		oldline.className = oldline.className.replace(" alist_selected_line","");
	}
	
	if($("alist_item_" + newIndex).className.indexOf("alist_selected_line")==-1)
		$("alist_item_" + newIndex).className+=" alist_selected_line";
	current_index = newIndex;
}

function changeline(newIndex)
{
	if(newIndex<1)
		newIndex=1;
	if(newIndex>=nbmax_item)
		newIndex=nbmax_item;

	//Wait if item is not already arrived
	if($("alist_item_" + newIndex))
	{	
		if(newIndex>=(first_displayed+nbitem_showed))
		{
			first_displayed = newIndex-nbitem_showed+1;
			move_list();
		}
		
		if(newIndex<first_displayed)
		{
			first_displayed = newIndex;
			move_list();
		}
			
		//Unselect item
		selectline(newIndex);
		//Move cursor
		moveCursor(newIndex);
	}
}

function moveCursor(index)
{
	var pos = Math.ceil(index*scroll_height/nbmax_item);
	cursor.style.top=pos + "px";
	tab_pos = cursor.cumulativeOffset();
	cursor_pos = tab_pos[1];
	cursor_rel_pos=pos;
}

function move_selected_byline(down)
{
	if(down)
		newIndex = current_index+1;
	else
		newIndex = current_index-1;

	//Check index
//	if(newIndex>nbmax_item)newIndex=nbmax_item;
//	if(newIndex<1)newIndex=1;

	//Load next list if limit is reach
//	alert(newIndex + "==" +(last_index-ajax_limit));
	if(newIndex==(last_index-ajax_limit))
	{
		get_items('bottom',last_index,ajax_nbget);
		last_index = last_index + ajax_nbget;
	}
	else if(newIndex==(first_index+ajax_limit))
	{
		var start = first_index-ajax_nbget;
		if(start<0)start=0;

		var nb = ajax_nbget;
		if(start + nb >= first_index)nb=first_index - start;

		if(nb>0)
		{
			get_items('top',start,nb);
		}
	}

	changeline(newIndex);
}

function move_selected_bypage(down)
{
	if(down)
		newIndex = current_index+nbitem_showed;
	else
		newIndex = current_index-nbitem_showed;

	//Check index
	if(newIndex>nbmax_item)newIndex=nbmax_item;
	if(newIndex<1)newIndex=1;

	var ff  = (last_index-ajax_limit);
	//Load next list if limit is reach
	if(newIndex>=(last_index-ajax_limit))
	{
		get_items('bottom',last_index,ajax_nbget);
		last_index = last_index + ajax_nbget;
	}
	else if(newIndex<=(first_index+ajax_limit) && newIndex<temp_index)
	{
		var start = first_index-ajax_nbget;
		if(start<0)start=0;

		var nb = ajax_nbget;
		if(start + nb >= first_index)nb=first_index - start;

		if(nb>0)
		{
			
			get_items('top',start,nb);
			temp_index = start-nb;
		}
	}
	changeline(newIndex);
}

function move_selected_bycurseur()
{
	new Effect.Appear(alist_wait, {queue:'end', duration:0.1});
	var first_disp = Math.ceil(cursor_rel_pos*nbmax_item/scroll_height);
	var first_req= Math.ceil(first_disp-nbitem_showed-ajax_limit);
	var nb_req = Math.floor(nbitem_showed+ajax_limit)*2;
	//Check limit
	if(first_req<0)first_req=0;
	if(first_disp<1)first_disp=1;
	if((first_disp + nb_req) >nbmax_item)nb_req=nbmax_item-first_req;
	get_items_cursor(first_req,nb_req,first_disp);
}

function alist_key_handler(event)
{
		var e = event || window.event;
		var ccode = e.keyCode;
		if(ccode==38)
		{
			move_selected_byline(false);
			return false;
		}
		else if(ccode==40)
		{
			move_selected_byline(true);
			return false;
		}
		else if(ccode==33)
		{
			move_selected_bypage(false);
			return false;
		}
		else if(ccode==34)
		{
			move_selected_bypage(true);
			return false;
		}
		return true;
}

function reset_mouse_event()
{
	if(cursor_clicked==true)
	{
		cursor_clicked=false;
		move_selected_bycurseur();
	}
}

var myrules = {
	'body':function(body)
	{
		//Ajouter une condition pour ma demo seulement
		if($('alist_full'))
		{
			//Lose my handler on click why???
			body.onkeydown= function(event)
			{
				return alist_key_handler(event);
			}
			
			body.onmouseup = function(event)
			{
				reset_mouse_event();
			}
	
			body.onmousemove= function(event)
			{
				if(cursor_clicked==true)
				{
					var tabpos = getMousePosition(event);
					var mouse_pos = tabpos[1];
					var cursor_dest = mouse_pos - mouse_move_start + mouse_delta;
					if(cursor_dest<mouse_pos_start)
						return;
					if(cursor_dest>mouse_pos_end)
						return;
					cursor.style.top = cursor_dest + "px";
					tab_pos = cursor.cumulativeOffset();
					cursor_pos = tab_pos[1];
					cursor_rel_pos=cursor_dest;
				}
			}
		}
	},

	'.alist_full':function(zone)
	{
		init_list();
		zone.onmouseout = function(event)
		{
			var tab_pos = zone.cumulativeOffset();
			var tab_dim = zone.getDimensions();
			var min_x = tab_pos[0];
			var max_x= tab_pos[0] + tab_dim.width;
			var min_y = tab_pos[1];
			var max_y = tab_pos[1] + tab_dim.height;
			var tabpos = getMousePosition(event);
			if(tabpos[0]<=min_x||tabpos[0]>max_x||tabpos[1]<min_y||tabpos[1]>max_y)
			{
				reset_mouse_event();
				clearInterval(mouse_interval);
			}
		}
	},
	
	'.alist_scrollbar_up':function(btn)
	{
		clearInterval(mouse_interval);
		btn.onmousedown = function()
		{
			mouse_interval = setInterval("move_selected_byline(false)",repeat_interval);
			return false;
		}
		
		btn.onmouseup = function()
		{
			clearInterval(mouse_interval);
		}
		
		btn.onmouseout = function()
		{
			clearInterval(mouse_interval);
		}
	},

	'.alist_scrollbar_down':function(btn)
	{
		clearInterval(mouse_interval);
		btn.onmousedown = function()
		{
			mouse_interval = setInterval("move_selected_byline(true)",repeat_interval);
			return false;
		}
		
		btn.onmouseup = function()
		{
			clearInterval(mouse_interval);
		}

		btn.onmouseout = function()
		{
			clearInterval(mouse_interval);
		}
	},

	'#alist_scrollbar_middle':function(zone)
	{
		zone.onmousedown = function(event)
		{
			clearInterval(mouse_interval);
			var tabpos = getMousePosition(event);
			if(tabpos[1]>(cursor_pos+cursor_height))			
			{
				mouse_interval = setInterval("move_selected_bypage(true)",(repeat_interval*2));
			}	
			else if(tabpos[1]<cursor_pos)			
			{
				mouse_interval = setInterval("move_selected_bypage(false)",(repeat_interval*2));
			}
			return false;
		}

		zone.onmouseup = function()
		{
			clearInterval(mouse_interval);
		}

		zone.onmouseout = function()
		{
			clearInterval(mouse_interval);
		}
		
	},
	
	'#alist_scrollbar_cursor':function(cursor)
	{
		cursor.onmousedown= function(event)
		{
			var tabpos = getMousePosition(event);
			mouse_move_start = tabpos[1];
			mouse_delta = parseInt(cursor.style.top.replace("px",""));
			cursor_clicked=true;
			return false;
		}
	},
	
	//Zone d'informations
	'.utflist_btn_information' : function(bouton_information){
		bouton_information.onclick=function(){
			new Effect.Grow($('utflist_information'),{
				direction:'top-left'
			});
		}
	},
	'.utflist_btn_fermer' : function(bouton_information){
		bouton_information.onclick=function(){
			new Effect.Fade($('utflist_information'),{
				direction:'top-left'
			});
		}
	}
}
// Enregistrement des regles definies ci dessus dans Behaviour
Behaviour.register(myrules);