// Focus first element
$.fn.focus_first = function() {
  var elem = $('input:visible', this).get(0);
  var select = $('select:visible', this).get(0);
  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }
  var textarea = $('textarea:visible', this).get(0);
  if (textarea && elem) {
    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }
  
  if (elem) {
    elem.focus();
  }
  
  return this;
}

/*       Popup per a l'audio de catradio.cat         */
function openNewWindowCustom(_url, _title, _options) {
	var bInSame = _title==null;
	myPopup = window.open(_url, _title, _options);
	if (bInSame) {
		myPopup.focus();
	}
}
/*                                                   */


var inc=170;
var inc2=169;
var inc3=268;
var pos=0;
var pos2=0;
var pos3=0;
var tot=0;
var tot2=0;
var tot3=0;
var canal_actual=1;
var user_actual=1;
var stop=true;
var capsalera=false;

$(document).ready(function(){
	/////////////////Calcul de l'scroll de la home/////////////////////////////////////////////////////
	if($("#scroll_home li").length>0){
		tot=$("#scroll_home li").length;
		$("#scroll_home").css("width",parseInt(tot)*inc);
	}
	if($("#slide_canal li").length>0){
		tot2=$("#slide_canal li").length;
		$("#slide_canal").css("width",parseInt(tot2)*inc2);
	}
	if($("#user_list li").length>0){
		tot3=$("#user_list li").length;
		$("#user_list").css("width",parseInt(tot3)*inc3);
	}
	$("#submit_edit_perfil").click( function(){
		check_perfil();
	});
	$("#moderacio_comentaris").click( function(){
		$("#normes_dus_text2").toggle();
		$("#fons_negre").css("height",$(document).height());
		$("#fons_negre").show();
		$("#normes_dus_text2").css("top",$(document).height()-700+"px");
	});
	$("#moderacio_comentaris_normes").click( function(){
		$("#normes_dus_text").css("top", $(document).height()-700+"px"); //1500px
		$("#normes_dus_text").css("overflow", "scroll");
		$("#normes_dus_text").css("height", "400px");
		$("#normes_dus_text").toggle();
		$("#fons_negre").css("height",$(document).height());
		$("#fons_negre").show();
	});
	
	$("#normes_dus_link").click( function(){
		$("#normes_dus_text").css("overflow", "scroll");
		$("#normes_dus_text").css("height", "400px");
		$("#normes_dus_text").toggle();
		$("#fons_negre").css("height",$(document).height());
		$("#fons_negre").show();
	});
	$("#normes_dus_text .close_window a").click( function(){
		$("#normes_dus_text").toggle();
		$("#fons_negre").hide();
	});
	$("#normes_dus_text2 .close_window a").click( function(){
		$("#normes_dus_text2").toggle();
		$("#fons_negre").hide();
	});
	$("#fons_negre").click( function(){
		$("#normes_dus_text").hide();
		$("#normes_dus_text2").hide();
		$("#com_participar_text").hide();
		$("#fons_negre").hide();
	});
	
	$("#com_participar_link").click( function(){
		$("#com_participar_text").css("overflow", "scroll");
		$("#com_participar_text").css("height", "400px");
		$("#com_participar_text").toggle();
		$("#fons_negre").css("height", $(document).height());
		$("#fons_negre").show();
	});
	$("#com_participar_text .close_window a").click( function(){
		$("#com_participar_text").toggle();
		$("#fons_negre").hide();
	});
	
	/////////////////Buidament de camps de input en cerca i login//////////////////////////////////////
	$("#user").blur(function(){
		if($(this).val()=="") $(this).val("usuari");
	});
	$("#user").focus(function(){
		if($(this).val()=="usuari") $(this).val("");
	});
	$("#password").blur(function(){
		if($(this).val()=="") $(this).val("usuari");
	});
	$("#password").focus(function(){
		if($(this).val()=="usuari") $(this).val("");
	});
	$("#cerca_text").blur(function(){
		if($(this).val()=="") $(this).val("Cerca recepta");
	});
	$("#cerca_text").focus(function(){
		if($(this).val()=="Cerca recepta") $(this).val("");
	});
	$("#cerca_text_2").blur(function(){
		if($(this).val()=="") $(this).val("Text / Paraula a cercar");
	});
	$("#cerca_text_2").focus(function(){
		if($(this).val()=="Text / Paraula a cercar") $(this).val("");
	});
	
	/////////////////Buidament de camps de input en login de avis//////////////////////////////////////
	$("#user_avis").blur(function(){
		if($(this).val()=="") $(this).val("usuari");
	});
	$("#user_avis").focus(function(){
		if($(this).val()=="usuari") $(this).val("");
	});
	$("#password_avis").blur(function(){
		if($(this).val()=="") $(this).val("usuari");
	});
	$("#password_avis").focus(function(){
		if($(this).val()=="usuari") $(this).val("");
	});
	
	Growl.init(336,154,2);
});

function left_scroll()
{
	if(stop && pos<0){
		stop=false;
		pos+=inc;
		$("#scroll_home").animate({marginLeft:pos},250,function(){
			stop=true;
		});
	}
}

function intercambiar(){
	$("#normes_dus_text2").toggle();
	$("#normes_dus_text").css("top", $(document).height()-700+"px"); //1500px
	$("#normes_dus_text").css("overflow", "scroll");
	$("#normes_dus_text").css("height", "400px");
	$("#normes_dus_text").toggle();
	$("#fons_negre").css("height",$(document).height());
	$("#fons_negre").show();
}

function right_scroll()
{
	if(stop && pos>-(inc*(tot-3))){
		stop=false;
		pos-=inc;
		$("#scroll_home").animate({marginLeft:pos},250,function(){
			stop=true;
		});
	}
}

function left_canal()
{
	if(stop && pos2<0){
		stop=false;
		pos2+=2*inc2;
		$("#slide_canal").animate({marginLeft:pos2},250,function(){
			canal_actual--;
			$("#canal_actual").html(canal_actual);
			stop=true;
		});
	}
}

function right_canal()
{
	if(stop && pos2>-(inc2*(tot2-2))){
		stop=false;
		pos2-=2*inc2;
		$("#slide_canal").animate({marginLeft:pos2},250,function(){
			canal_actual++;
			$("#canal_actual").html(canal_actual);
			stop=true;
		});
	}
}

function left_user()
{
	//console.log(pos3);
	if(stop && pos3<0){
		stop=false;
		pos3+=inc3;
		$("#user_list").animate({marginLeft:pos3},250,function(){
			user_actual--;
			$("#user_actual").html(user_actual);
			stop=true;
		});
	}
}

function right_user()
{
	//console.log(-inc3*(tot3-1));
	if(stop && pos3>-inc3*(tot3-1)){
		stop=false;
		pos3-=inc3;
		$("#user_list").animate({marginLeft:pos3},250,function(){
			user_actual++;
			$("#user_actual").html(user_actual);
			stop=true;
		});
	}
}

function show_acordio(i)
{
	$("div[id*=popup-]").slideUp();
	$(".show_hide .hide").hide();
	$(".show_hide .show").show();
	
	$("#popup-"+i).slideDown();
	$("#acordio-"+i+" .show").hide();
	$("#acordio-"+i+" .hide").show();
}

function show_promo(i)
{
	$("div[id*=popup_promo-]").slideUp();
	$(".show_hide .hide").hide();
	$(".show_hide .show").show();
	
	$("#popup_promo-"+i).slideDown();
	$("#promo-"+i+" .show").hide();
	$("#promo-"+i+" .hide").show();
}

function login(special)
{
	if( special == false )
	{
		user_val = $("#user").val();
		pass_val = $("#password").val();
		portal_val= $("#portal").val();
	}
	else
	{
		user_val = $("#user_avis").val();
		pass_val = $("#password_avis").val();
		portal_val= $("#portal_avis").val();
	}
	
	if ( portal_val == "blank" )
  {
		Growl.show("Recorda que també has de seleccionar un dels portals: tv3.cat o catradio.cat");
	}
  else
  {
		/*$("#waiting-off").hide();
		$("#waiting-on").show();
		*/
		$.post("/ajax/login",{user: user_val, password: pass_val, portal: portal_val }, function(data){
			if( data != "OK" )
			{
				document.location = data+"?loginId="+Math.floor(Math.random()*10000);
			}
			else
			{
				//Todo OK
				if( (location.href).indexOf("avis") != -1 )
        {
					document.location = "/home?loginId="+Math.floor(Math.random()*10000);
				}
				else
        {
					//location.reload();
					if( (location.href).indexOf("?") != -1 )
					{
            document.location = "/home?loginId="+Math.floor(Math.random()*10000);
          }
          else
          {
            document.location = document.location+"?loginId="+Math.floor(Math.random()*10000);
          }
				}
			}
		});
	}
}

function show_tab(tab){
	$("#"+tab).parent().parent().find(".users_list").hide();
	$("#"+tab).show();
	$("#"+tab).parent().parent().children("li").removeClass("select");
	$("#"+tab).parent().addClass("select");
}

function add_ingredient(){
	//console.log($("#ingredients").val());
	val=$("#ingredients").val();
	if(val!="") $("#list_ingredients").append("<li><strong>"+val+"</strong> <span><a href='javascript://' onclick='remove_ingredient(this);'>X</a></span></li>");
	$("#ingredients").val("");
	$("#ingredients").focus();
}

function remove_ingredient(item){
	$(item).parent().parent().remove();
}

function publica_recepta()
{
	error =0;
	//titol
	if($("#titol").val()==""){ error++; $("#titol").css("background-color","#ffffcc");}
	else{ $("#titol").css("background-color","#ffffff");}
	
	//ingredients
	if($("#list_ingredients li").length==0){
		error++; $("#ingredients").css("background-color","#ffffcc");
	}
	else
	{
		val="";
		$("#list_ingredients li").each(function(){
			val+="&$"+$(this).children("strong").html();
		});
		$("#cu_ingredients").val(val);
		
		$("#ingredients").css("background-color","#ffffff");
	}
	
	//Elaboracio
	if($("#cu_elaboracio").val()==""){ error++; $("#cu_elaboracio").css("background-color","#ffffcc");}
	else{ $("#cu_elaboracio").css("background-color","#ffffff");}
	
	//categoria
	if($("input:checked[@rel='cu_categories_id']").length==0){
		error++;
	}
	
	if(error==0){
		 document.nova_recepta_1.submit();
	}
	else
	{
		alert("Hi han "+error+" camps obligatoris buits");
		return false;
	}
}

function publica_recepta2()
{
	error =0;
	//titol
	if($("#titol").val()==""){ error++; $("#titol").css("background-color","#ffffcc");}
	else{ $("#titol").css("background-color","#ffffff");}
	
	//ingredients
	if($("#list_ingredients li").length==0){
		error++; $("#ingredients").css("background-color","#ffffcc");
	}
	else{
		val="";
		$("#list_ingredients li").each(function(){
			val+="&$"+$(this).children("strong").html();
		});
		$("#cu_ingredients").val(val);
		//alert($("#cu_ingredients").val());
		$("#ingredients").css("background-color","#ffffff");
	}
	
	//Elaboracio
	if($("#cu_elaboracio").val()==""){ error++; $("#cu_elaboracio").css("background-color","#ffffcc");}
	else{ $("#cu_elaboracio").css("background-color","#ffffff");}
	
	//categoria
	if($("input:checked[@rel='cu_categories_id']").length==0){
		error++;
	}
	
	
	if(error==0){
		 document.nova_recepta_1.submit();
	}
	else
	{
		alert("Hi han "+error+" camps obligatoris buits");
		return false;
	}
}

function enter(e)
{
  tecla = (document.all) ? e.keyCode : e.which;
  if (tecla==13) add_ingredient();
}

// Votació estrelletes
function punts(punt)
{
	i=0;
	$("#star_list li").each(function(){
		if(i<punt) $(this).removeClass("star_off").addClass("star_on");
		else $(this).removeClass("star_on").addClass("star_off");
		i++;
	});
}

function star_on(punt)
{
	i=0;
	$("#star_list li").each(function(){
		if(i<punt) $(this).removeClass("star_off").addClass("star_on");
		else $(this).removeClass("star_on").addClass("star_off");
		i++;
	});
}

function star_off(punt)
{
	punts(puntuacio);
}

function votar_recepta(recepta_id_value, punts_value, vots_value)
{
	// desapareix el missatge
	$("#vote_response").remove();
	
	$.post("/ajax/votar-recepta", 
		{recepta_id: recepta_id_value, punts_a_enviar: punts_value}, 
		
		function(data){
			// imprimim les dades
			Growl.show(data);
						
			// si la resposta és correcta actualitza puntuacio i vots
			if( data.indexOf('id="hidden_data"') >= 0 )
			{
				puntuacio = $.trim($("#hidden_data").html());
				rounded = Math.round(puntuacio);
				
				$("div.recipe_votes").fadeOut("slow", function(){
					if( (vots_value+1) == 1 )
					{
						counter_label = "vot";
					}
					else
					{
						counter_label = "vots";
					}
					
					$("div.recipe_votes p").html('Puntua (<strong>'+(vots_value+1)+' '+counter_label+'</strong>)');
					star_on(rounded);
					$("div.recipe_votes").fadeIn("slow");
				});
				
				$("div.recipe_score p").fadeOut("slow", function(){
					// Si no té decimals
					if( puntuacio.length < 2 )
					{
						puntuacio = puntuacio+",00";
					}
					// Si té decimals
					if( puntuacio.length > 4 )
					{
						puntuacio = puntuacio.substring(0, puntuacio.indexOf(".")+3);
						puntuacio = puntuacio.replace(".", ",");
					}
					// Escrivim la info al HTML i la mostrem
					$("div.recipe_score p").html('<strong>'+puntuacio+'</strong> / 5');
					$("div.recipe_score p").fadeIn("slow");
				});
				
				// Mostrem les estrelles correctes
				punts(rounded);
			}
		}
	);
}

// Altres
function predeterminar(elem)
{
	$("#imatges ul li").each(function(){
		//console.log(this);
		$(this).removeClass("select");
		$("#predeterminat").val($(elem).attr("rel"));
		$(elem).parent().addClass("select");
	});
}

function check_perfil()
{
	if( $('#condicions').is(':checked') )
	{
		url_value = $("#web").val();
		
		$.post("/ajax/check-url", 
			{url: url_value}, 
			
			function(data)
			{
				if( data == "OK" )
				{
					$("#form_edit_perfil").submit();
				}
				else
				{
					Growl.show(data);
					return false;
				}
			}
		);
	}
	else
	{
		Growl.show("Has d'acceptar les normes d'ús");
		return false;
	}
}




function toogle_capsalera(){

	if(!capsalera)
	{
		total=$(".programs_box .programs_window").length;
		width1=242+(40*(total-1));
		width2=(40*total);
		$(".programes_tv3").animate({height:width2},500);
		
		$("#header_holder").animate({height:width1},500);
		$(".show_all p").removeClass('show_programs').addClass('hide_programs');
		
		capsalera=true;
	}
	else
	{
		$(".programes_tv3").animate({height:40},500);
		$("#header_holder").animate({height:242},500);
		$(".show_all p").removeClass('hide_programs').addClass('show_programs');
		
		capsalera = false;
	}
}



function borrar_foto(id_foto, elem, id_recepta)
{
	switch_default = false;
	
	$.post("/ajax/borrar-foto/"+id_foto+"/"+id_recepta, {}, function(data){
		if( data == "OK" )
		{
			// Si era la predeterminada, sel·leccionem la primera de la llista
			if( $(elem).parent().attr("class") == "select" )
			{
				switch_default = true;
			}
			
			$(elem).parent().remove();
			
			if( switch_default )
			{
				predeterminar($("#imatges ul li:first img"));
			}
		}
	});
	
	return false;
}



function borrar_videos(id_video)
{
	$.post("/ajax/borrar-video/"+id_video,{},function(data){
		if(data=="OK")	$("#video_content").html("");
	});
	
	return false;
}