function start_ressources(vari_wood,vari_stone,vari_iron,vari_sp)
{
	start_ressource("wood",vari_wood);
	start_ressource("stone",vari_stone);
	start_ressource("iron",vari_iron);
	start_ressource("sp",vari_sp);
};

function start_ressource(arg,vari)
{
	myElement = document.getElementById(arg);
	if(myElement != null)
	{
		current = myElement.innerHTML;
		if (parseFloat(vari) == 0)
		{
			timeo = 3600000;
		}
		else if (current == 0 && vari < 0)
		{
			timeo = 3600000;
		}
		else
		{
			variposi = Math.abs(vari);
			timeo = 3600000 / variposi;
		}
		
		setTimeout("increase_ressource('"+ arg +"',"+vari+")", timeo);
	}
};

function increase_ressource(arg,vari)
{
	myElement = document.getElementById(arg);
	if(myElement != null)
	{
		current = myElement.innerHTML;
		/*Replace every occurence of space by nothing in order to have an integer*/
		current = current.replace(/ /g,'');
		if (vari == 0)
		{
			total = parseInt(current);
		}
		if (vari < 0 && current != 0)
		{
			total = parseInt(current) - 1;
		}
		if (vari > 0)
		{
			total = parseInt(current) + 1;
		}
		if (total != 0)
		{
			total = separeMilliers(total);
		}
		myElement.innerHTML = total.replace(/^\s+/g,'').replace(/\s+$/g,'');
	}
	
	if (parseFloat(vari) == 0)
	{
		timeo = 3600000;
	}
	else if (current == 0 && vari < 0)
	{
		timeo = 3600000;
	}
	else
	{
		variposi = Math.abs(vari);
		timeo = 3600000 / variposi;
	}
	setTimeout("increase_ressource('"+ arg +"',"+vari+")", timeo);
	
};

function separeMilliers (sNombre) 
{
	var sRetour = "";
	var separateurMilliers = " ";
	while (sNombre.length % 3 != 0) 
	{
		sNombre = "0"+sNombre;
	}
	for (i = 0; i < sNombre.length; i += 3) 
	{
		if (i ==  sNombre.length-1) separateurMilliers = '';
		sRetour += sNombre.substr(i, 3)+separateurMilliers;
	}
	while (sRetour.substr(0, 1) == "0") 
	{
		sRetour = sRetour.substr(1);
	}
	return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
}


function start_count_down()
{
	$(".time_min").each(function()
	{
		//alert(1);
		sek1 = t_format1(this)-1;
		//alert(3);
		if (sek1 < 0)
		{
			//alert(4);
			setTimeout("document.location.reload();", 1000);
		}
		else
		{
			//alert(5);
			sek2 = t_format2(sek1); 
			this.innerHTML=sek2;
		}
		//alert(6);
	});
	setTimeout("start_count_down()", 1000);
};


function t_format1(ele) 
{
	p = ele.innerHTML.split(":");
	if (p.length == 3)
	{
		s1 = p[0]*3600+p[1]*60+p[2]*1;
	}
	else
	{
		s1 = p[0]*60+p[1]*1;
	}
	return s1;
}

function t_format2(s) 
{
	if (s > -1)
	{
		heure = Math.floor(s/3600);
		minute = Math.floor(s/60) % 60;
		seconde = s % 60; 
		if(heure == 0 ){t = "";}
		else if(heure < 10 ){t = "0"+heure+":";}
		else{t = heure + ":";}
		if(minute < 10){t += "0";} t += minute + ":";
		if(seconde < 10){t += "0";} t += seconde;
	}
	else
	{
		t = "0:00:0?";
	}
	return t;
}


function set_max_value()
{
	$(".as_item > td").click(function () { 
		if ($(this).is(":not(':last-child')"))
		{
		tr = $(this).parent();
		maxi = ((tr.attr('id')).split(":"))[1];
		if(maxi == ''){maxi=1;}
		targetid = ((tr.attr('id')).split(":"))[0];
      $("#"+targetid).val(maxi);
   	}
    });
    
    $(".as_item > td").dblclick(function () { 
		tr = $(this).parent();
		img_td = tr.children()[0];
		unique_id = $(img_td).attr('class');
		$('.'+unique_id).click();
   	
    });
}

function verify_max_value()
{
	$(".maxed").change(function()
	{
		parent_id_info = $(this).parent().parent().attr('id');
		maxi = (parent_id_info.split(":"))[1];
		var valu=parseInt($(this).val()); 
   	if (isNaN(valu)) {valu = 0;}
		valu = Math.max(valu,0);
		valu = Math.min(valu,maxi);
		$(this).val(valu);
	});
}


function auto_sum(rate_b_rss,rate_b_sp,rate_s_rss,rate_s_sp)
{
	$(":text").keyup(function()
	{
		rss_type = $(this).attr('name');
		act = $(this).attr('act');
		if (act == 'b')
		{
			rate_rss = 	rate_b_rss;
			rate_sp = rate_b_sp;
		}
		else
		{
			rate_rss = 	rate_s_rss;
			rate_sp = rate_s_sp;
		}
		
		switch (rss_type) 
		{ 
			case 'wood': 
				rate = rate_rss;
				numRss = 1;
				break; 
			case 'stone': 
				rate = rate_rss;
				numRss = 2;
				break; 
			case 'iron': 
				rate = rate_rss;
				numRss = 3;
				break; 
			case 'sp': 
				rate = rate_sp;
				numRss = 4;
				break; 
		}
		newval = Math.round($(this).val()*rate);
		targetid = "#"+act+numRss;
		$("#"+act+numRss).html(newval);
		total = parseFloat($("#"+act+'1').html()) + parseFloat($("#"+act+'2').html()) + parseFloat($("#"+act+'3').html()) + parseFloat($("#"+act+'4').html());
		$("#"+act+"t").html(total);
	});
}

function domain_cell_calc(worker_prod)
{
	var wc = $('#wc').val();
	if(!isInt(wc)){wc = 0;}
	$('#prod_tot').html(Math.round(worker_prod*wc*100)/100) ;
	$('#consow').html(wc*4);
}

function isInt(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) return false; 
	return x==y && x.toString()==y.toString(); 
} 

function addDraggableSkill(el)
{
	el.draggable
	(
		{
			revert: 'invalid',
			zIndex: 1000,
			helper: 'clone',
			containment: '.centrecontainer',
			cursor: 'pointer',
			opacity: 0.8
		}
	);
};

function activateSkillsDrag(el)
{
	addDraggableSkill($('.dragskill'));
	$('.equipskillsdrop').droppable(
		{
			/*accept : '[eq="1"]',*/
			tolerance: 'pointer',
			drop: function (ev,ui)
			{			
				drag = ui.draggable;

				id = $(this).attr('id');
				
				// Check if skill already present on this slot.
				if ($($('#'+id).children(".droppedSkill")).attr('id') == null)
				{
					// Fill default max level
					//alert(drag.attr('id'));
					dragged_skill = ((drag.attr('id')).split("-"))[0];
					dragged_lvl = ((drag.attr('id')).split("-"))[1];
					$('#skill_lvl').val(dragged_lvl);
					$('#max_level').val(dragged_lvl);
					$('#cur_slot').val(id);
					$('#cur_skill').val(dragged_skill);
					
					// Ask level
					$('.centrecontainer').block({ message: $('#skill_lvl_dialog'), 
						css: { 
							padding:        '10px', 
							margin:         '0', 
							width:          '200px',  
							textAlign:      'left', 
							color:          '#000', 
							border:         '4px solid #C9AB00', 
							backgroundColor:'#fff', 
							cursor:         'wait' 
						},
						overlayCSS:  { 
							backgroundColor: '#000', 
							opacity:         0.3
						},
						centerX: true,
						centerY: true
					});
					// Show the skill control panel 
					$("#"+id+'_panel').show();		
					// Fill the skill into the slot
					drag_clone = drag.clone();
					drag_clone.toggleClass( 'droppedSkill', true );
					$(this).append(drag_clone);
				}
			},
			fit: true,
			accept : function (drag)
			{
				return ($($(this).children(".droppedSkill")).attr('id') == null)
			}
		});
		
	$('.dropsclose').click(function () {
      id = $(this).attr('id');
      id = (id.split("_"))[0]; 
      // Remove the control panel
      $(this).parent().hide();
      // Remove the skills
      $($('#'+id).children(".droppedSkill")).remove();
      // Empty level
      $('#'+id+'_lvl').html('');
      // Get hero id
      hero_id = $('#hero_id').val();
      slot = id.charAt(5);
      $.ajax({
					type: "POST",
					url: "ajax_gen.php",
					data: "a=uesk&ss="+slot+"&hid="+hero_id,
					success: function(data, msg)
					{
						//alert('skill equip :'+data);
					}
			});
      
    });
    
    $('#vali_lvl').click(function () 
    {
      
      lvl_to_modify = $('#cur_slot').val()+'_lvl';
      selectedLvl = parseInt($('#skill_lvl').val());
      max_level = parseInt($('#max_level').val());
      if (!isInt(selectedLvl) || selectedLvl < 1 ||  selectedLvl >  max_level)
      {
      	selectedLvl = 1;
      }
      skill = $('#cur_skill').val();
      slot =  ($('#cur_slot').val()).charAt(5);
      hero_id = $('#hero_id').val();
      $('#'+lvl_to_modify).html(selectedLvl);
      $('.centrecontainer').unblock();
      $.ajax({
					type: "POST",
					url: "ajax_gen.php",
					data: "a=esk&sl="+selectedLvl+"&sk="+skill+"&ss="+slot+"&hid="+hero_id,
					success: function(data, msg)
					{
						//alert('skill equip :'+data);
					}
			});
			return false;
    });
    
    $('#hid_form').submit(function(){
    	return false;
    });
}
