var randomSearchClicked = 0;
var tipoRifa = 1;
var tipoSorteo = 1;


function init_general(){
	$("#bajaComoUsuario").click(function(){
		$("#bajaComoUsuarioTexto").toggle("slow");
		return false;
	});
	$("#bajaNewsletter").click(function(){
		$("#bajaNewsletterTexto").toggle("slow");
		return false;
	});
}

function init_sliderHome(){
	if ($("#sliderHome").size() > 0){
		$('#sliderHome').slides({
			preload: true,
			play: 5000
		});
	}
}

function init_msg(){
	if ($("#msg").size() > 0){
		
		$("#msg").fadeIn(100).delay(3000).fadeOut(100);
		$(".msgItem").click(function(){
			$("#msg").hide();			
		})
	}	
}


function init_login(){
	/*
	$(".tuCuenta").hover(function(){
		$("#userLogin").animate({top: -10}, 150);
		
		$("#userLogin").hover(
				function(){},
				function(){
					$("#userLogin").animate({top: -250}, 145);
				}
		)
	});
	*/
}


function init_ficha(){
	if ($("#ficha").size() > 0){
		$("#lbox").hide();
		$(".miniaturas img").click(function(){
			var img = $(this).attr("src");
			$("#foto img").attr("src", img);
		});	
		//$(".miniaturas img:first-child").click();
	}
	
	
	$("#abreLogin").click(function(){
		// mostrar un mensaje?
		location.href=getPathTo('entrar/',1);
	});
	
	$("#abreCompra").click(function(){
		_gaq.push(['_trackPageview', '/sorteo/'+sorteoPurl+'/participando']);
		$("#lbox").show();
	});
	
	$("#closeBox").click(function(){
		$("#lbox").hide();
		return false;
	});
	
	
	if($("#embeddApi").length > 0){
		$("#embeddApi").hide();
		$("textarea#embeddApi").click(function(){
			$(this).select();
			return false;
		});
	}
	
	if($("#apikeyA").length > 0){
		$("#apikeyA").click(function(){
			$("#embeddApi").toggle();
			return false;
		});
	}
}

function init_perfil(){
	var dayNames = new Array(getText('datePicker.dayName.long.sunday'), getText('datePicker.dayName.long.monday'), 
			getText('datePicker.dayName.long.tuesday'), getText('datePicker.dayName.long.wednesday'), 
			getText('datePicker.dayName.long.thursday'), getText('datePicker.dayName.long.friday'), 
			getText('datePicker.dayName.long.saturday'));
	var dayNamesMin = new Array(getText('datePicker.dayName.short.sunday'), getText('datePicker.dayName.short.monday'), 
			getText('datePicker.dayName.short.tuesday'), getText('datePicker.dayName.short.wednesday'), 
			getText('datePicker.dayName.short.thursday'), getText('datePicker.dayName.short.friday'), 
			getText('datePicker.dayName.short.saturday'));
	var monthNamess = new Array(getText('datePicker.monthName.january'), getText('datePicker.monthName.february'), 
			getText('datePicker.monthName.march'), getText('datePicker.monthName.april'), getText('datePicker.monthName.may'), 
			getText('datePicker.monthName.june'), getText('datePicker.monthName.july'), getText('datePicker.monthName.august'), 
			getText('datePicker.monthName.september'), getText('datePicker.monthName.october'), getText('datePicker.monthName.november'), 
			getText('datePicker.monthName.december'));
	$("#birthday").datepicker({
		dayNames: dayNames,
		dayNamesMin: dayNamesMin,
		firstDay: 1,
		monthNames: monthNamess,
		dateFormat: 'dd/mm/yy',
		changeYear: true, 
		yearRange: '-110:+0'
	});
	
	$("#changePasswLink").click(function(){
		if($("#changePassw").is(":hidden")){
			$("#changePassw").show();
		}
		else{
			$("#changePassw").hide();
		}
		$("#changePhoto").hide();
		return false;
	});
	
	$("#changePhotoLink").click(function(){
		if($("#changePhoto").is(":hidden")){
			$("#changePhoto").show();
		}
		else{
			$("#changePhoto").hide();
		}
		$("#changePassw").hide();
		return false;
	});
	
	$("#passwOld, #passw, #passwRe, #firstName, #lastName, #dni, #birthday, #address, #postalCode, #city, #state, #phone, #www, #twitter, #facebook, #description").change(function(){
 		var strInputCode = $(this).val();
 	 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function(strMatch, p1){
 	 		return (p1 == "lt")? "<" : ">";
 		});
 		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
 		$(this).val(strTagStrippedText);
 		//alert("Output text:\n" + strTagStrippedText);
	});

	
	$("#formPerfil").submit(function(){
		/*
		if($("#firstName").val() == ""){
			$("#firstName").focus();
			alert(getText('perfil_usuario_nombre_obligatorio'));
			return false;
		}
		if($("#lastName").val() == ""){
			$("#lastName").focus();
			alert(getText('perfil_usuario_apellidos_obligatorio'));
			return false;
		}
		if($("#dni").val() == ""){
			$("#dni").focus();
			alert(getText('perfil_usuario_dni_obligatorio'));
			return false;
		}
		else{
			if(!checkCorrectDni($("#dni").val())){
				$("#dni").focus();
				alert(getText('perfil_usuario_dni_incorrecto'));
				return false;
			}
		}
		*/
		return true;
	});
	
	var optionsFotoPerf = {success:uploadedFotoPerf};
	$("#formFotoPerfil").ajaxForm(optionsFotoPerf);
}
function init_sorteo(){
	$(".sortear").click(function(){
		if(!confirm('Va a proceder a realizar el sorteo.')){
			return false;
		}
		var lin = $(this);
		var pad = $(this).parent();
		pad.empty();
		pad.append('<img src="'+getPathTo("img/ajax-loader.gif",1)+'" alt="Realizando sorteo" title="Realizando sorteo" style="margin:auto;padding:20px;" />');
		$.post(getPathTo('user/mis-sorteos/sortear',1),{'sorteo':lin.attr("data")},function(datos){
			pad.empty();
			var data = eval('('+datos+')');
			if(data.error){
				alert(data.message);
				pad.append('<a href="#" class="boton verde sortear" data="'+lin.attr("data")+'">Realizar el sorteo</a>');
				init_sorteo();
			}
			else{
				$.each(data.tickets,function(i,item){
					pad.append('<p>Ganador: <span class="winner blinkin">'+item.username+' (N\xB0 de participaci\xF3n: '+item.number+')</span>.</p>');
				});
				setTimeout('stopBlink()',5000);
			}
		});
		return false;
	});
}
function stopBlink(){
	$(".blinkin").removeClass("blinkin");
}
function uploadedFotoPerf(responseText, statusText, xhr, form){
	if(responseText.indexOf("www") == -1){
		alert(responseText);
	}
	else{
		$("#fotoPerfil").attr("src",responseText);
		$("#changePhoto").hide();
		alert(getText('perfil_usuario_foto_actualizada'));
	}
}

function init_fichaCreacion(){
	
	$("#formCrearRifa").submit(function(){
		if($("#productName").val()==""){
			alert("El titulo del sorteo no puede estar en blanco.");
			return false;
		}
		if($("#productCategory").val()==""){
			alert("Tiene que seleccionar una categoría de producto.");
			return false;
		}
		if($("#raffleDrawDate").val()==""){
			alert("Tiene que rellenar fecha para el sorteo");
			return false;
		}
		if($("#productPhoto").val()==""){
			alert("Tiene que incluir, al menos, una foto de producto.");
			return false;
		}
		if($("#raffleCloses").val()==""){
			alert("Tiene que rellenar fecha de fin de participaciónpara el sorteo");
			return false;
		}
		if($("#productValue").val()==""){
			alert("Debe introducir el precio de mercado del producto sin IVA");
			return false;
		}
		if($("#productDesc").val()==""){
			alert("Incluya una descripción del producto para poder continuar.");
			return false;
		}
		if($("#promotorSelect").val()==1){
			if($("#promoter_name").val()==""){
				alert("Incluya el nombre del promotor.");
				return false;
			}
			if($("#promoter_logo").val()==""){
				alert("El logo del promotor es un campo obligado.");
				return false;
			}
			if($("#promoter_cif").val()==""){
				alert("El CIF del promotor es un campo obligado.");
				return false;
			}
		}
		
		return true;
	});
	
	
	$("#limitUsersSelect").change(function(){
		if($(this).val()==1)
			$("#limitUsersDiv").show("slow");
		else 
			$("#limitUsersDiv").hide("slow");
	});
	$("#promotorSelect").change(function(){
		if($(this).val()==1)
			$("#promotorDiv").show("slow");
		else 
			$("#promotorDiv").hide("slow");
	});
	
	$("#planLiteBt").click(function(){
		$("#rafflePlan").val("1");
		$("#rafflePlanName").text($("#rafflePlan option:selected").text());
		$("#planUser").hide();
		$("#raffleSegment").hide();
		$("#rifaUser").show();
		return false;
	});
	$("#planProBt").click(function(){
		$("#rafflePlan").val("2");
		$("#rafflePlanName").text($("#rafflePlan option:selected").text());
		$("#planUser").hide();
		$("#raffleSegment").show();
		$("#rifaUser").show();
		return false;
	});
	$("#planCustomBt").click(function(){
		$("#rafflePlan").val("3");
		$("#rafflePlanName").text($("#rafflePlan option:selected").text());
		$("#planUser").hide();
		$("#raffleSegment").show();
		$("#rifaUser").show();
		return false;
	});
	$("#addRequisito").click(function(){
		if($(".raffleCondition").length == 1){
			alert("Utilizar más de un requisito solo está disponible en la modalidad de pago.");
		}
		var r = $("#requisitoFoo").clone();
		r.find(".removeRequisito").show();
		$("#requisitoFoo").parent().append(r);
		
		calculaPrecioTotal()
		return false;
	});
	
	$(".removeRequisito").live('click',function(){
		$(this).parent().remove();
		calculaPrecioTotal();
		return false;
	});

	var params = window.location.href;
	if(params.indexOf("p=") > -1){
		params = params.substring(params.indexOf("p=") + 2);
		if(params == "lite"){
			$("#planLiteBt").click();
		}
		else if(params == "pro"){
			$("#planProBt").click();
		}
		else if(params == "custom"){
			$("#planCustomBt").click();
		}
	}
	
	/*$("#rafflePlan").change(function(){
		$("#rafflePlanName").text($("#rafflePlan option:selected").text());
		if($("#rafflePlan").val() == 1){
			$("#raffleSegment").hide();
		}
		else{
			$("#raffleSegment").show();
		}
	});*/
	
	$("#showPh2").click(function(){
		if($("#productPh2").is(":hidden")){
			$("#productPh2").show();
		}
	});
	$("#showPh3").click(function(){
		if($("#productPh3").is(":hidden")){
			$("#productPh3").show();
		}
	});
	$("#showPh4").click(function(){
		if($("#productPh4").is(":hidden")){
			$("#productPh4").show();
		}
	});
	$("#showPh5").click(function(){
		if($("#productPh5").is(":hidden")){
			$("#productPh5").show();
		}
	});
	
	
	$(".raffleCondition").live('change',function(){
		if($(this).val() == 1){
			$(this).parent().parent().find(".raffCondQue label").text("Pregunta");
			$(this).parent().parent().find(".raffCondQue").show();
			$(this).parent().parent().find(".raffCondFB").hide();
			$(this).parent().parent().find(".raffCondAns1").hide();
			$(this).parent().parent().find(".raffCondAns2").hide();
			$(this).parent().parent().find(".raffCondAns3").hide();
			$(this).parent().parent().find(".raffCondAns4").hide();
		}
		else if(($(this).val() == 2) || ($(this).val() == 3)){
			$(this).parent().parent().find(".raffCondQue label").text("Pregunta");
			$(this).parent().parent().find(".raffCondQue").show();
			$(this).parent().parent().find(".raffCondFB").hide();
			$(this).parent().parent().find(".raffCondAns1").show();
			$(this).parent().parent().find(".raffCondAns2").show();
			$(this).parent().parent().find(".raffCondAns3").show();
			$(this).parent().parent().find(".raffCondAns4").show();
		}
		else if($(this).val() == 4){
			$(this).parent().parent().find(".raffCondAns1").hide();
			$(this).parent().parent().find(".raffCondAns2").hide();
			$(this).parent().parent().find(".raffCondAns3").hide();
			$(this).parent().parent().find(".raffCondAns4").hide();
			$(this).parent().parent().find(".raffCondFB").show();
			$(this).parent().parent().find(".raffCondQue").show();
		}
		else if($(this).val() == 5){
			$(this).parent().parent().find(".raffCondQue label").text("Seguir en twitter");
			$(this).parent().parent().find(".raffCondQue").show();
			$(this).parent().parent().find(".raffCondAns1").hide();
			$(this).parent().parent().find(".raffCondAns2").hide();
			$(this).parent().parent().find(".raffCondAns3").hide();
			$(this).parent().parent().find(".raffCondAns4").hide();
			$(this).parent().parent().find(".raffCondFB").hide();
		}
		else if($(this).val() == 6){
			$(this).parent().parent().find(".raffCondQue label").text("Dirección web");
			$(this).parent().parent().find(".raffCondQue").show();
			$(this).parent().parent().find(".raffCondAns1").hide();
			$(this).parent().parent().find(".raffCondAns2").hide();
			$(this).parent().parent().find(".raffCondAns3").hide();
			$(this).parent().parent().find(".raffCondAns4").hide();
			$(this).parent().parent().find(".raffCondFB").hide();
		}
		else{
			$(this).parent().parent().find(".raffCondQue label").text("Pregunta");
			$(this).parent().parent().find(".raffCondQue").hide();
			$(this).parent().parent().find(".raffCondAns1").hide();
			$(this).parent().parent().find(".raffCondAns2").hide();
			$(this).parent().parent().find(".raffCondAns3").hide();
			$(this).parent().parent().find(".raffCondAns4").hide();
			$(this).parent().parent().find(".raffCondFB").hide();
		}
	});

	
	$("#raffleSegCiudad").click(function(){
		if($(this).is(':checked')){
			$("#raffSegCiudad").show();
		}
		else {
			$("#raffSegCiudad").hide();
		}
		calculaPrecioTotal();
	});
	$("#raffleSegPais").click(function(){
		if($(this).is(':checked')){
			$("#raffSegPais").show();
		}
		else {
			$("#raffSegPais").hide();
		}
		calculaPrecioTotal();
	});
	$("#raffleSegEdad").click(function(){
		if($(this).is(':checked')){
			$("#raffSegEdad1").show();
			$("#raffSegEdad2").show();
		}
		else {
			$("#raffSegEdad1").hide();
			$("#raffSegEdad2").hide();
		}
		calculaPrecioTotal();
	});
	$("#raffleSegSexo").click(function(){
		if($(this).is(':checked')){
			$("#raffSegSexo").show();
		}
		else {
			$("#raffSegSexo").hide();
		}
		calculaPrecioTotal();
	});
	$("#widgetPersonalizado").click(function(){
		calculaPrecioTotal();
	});
	$("#comparticionDatos").click(function(){
		calculaPrecioTotal();
	});
	$("#productValue").blur(function(){
		//calculaPrecioTotal();
		return true;
	})
	
	var dayNames = new Array(getText('datePicker.dayName.long.sunday'), getText('datePicker.dayName.long.monday'), 
			getText('datePicker.dayName.long.tuesday'), getText('datePicker.dayName.long.wednesday'), 
			getText('datePicker.dayName.long.thursday'), getText('datePicker.dayName.long.friday'), 
			getText('datePicker.dayName.long.saturday'));
	var dayNamesMin = new Array(getText('datePicker.dayName.short.sunday'), getText('datePicker.dayName.short.monday'), 
			getText('datePicker.dayName.short.tuesday'), getText('datePicker.dayName.short.wednesday'), 
			getText('datePicker.dayName.short.thursday'), getText('datePicker.dayName.short.friday'), 
			getText('datePicker.dayName.short.saturday'));
	var monthNamess = new Array(getText('datePicker.monthName.january'), getText('datePicker.monthName.february'), 
			getText('datePicker.monthName.march'), getText('datePicker.monthName.april'), getText('datePicker.monthName.may'), 
			getText('datePicker.monthName.june'), getText('datePicker.monthName.july'), getText('datePicker.monthName.august'), 
			getText('datePicker.monthName.september'), getText('datePicker.monthName.october'), getText('datePicker.monthName.november'), 
			getText('datePicker.monthName.december'));
	
	$("#raffleCloses, #raffleDrawDate").datepicker({
		dayNames: dayNames,
		dayNamesMin: dayNamesMin,
		firstDay: 1,
		monthNames: monthNamess,
		dateFormat: 'dd/mm/yy'
	});
	
	
	$("#checkoutTPV").click(function(){
		alert("Forma de pago no disponible todav\xEDa.");
		return false;
	});
	$("#checkoutPayPal").click(function(){
		alert("Forma de pago no disponible todav\xEDa.");
		return false;
	});
	$("#checkoutTB").click(function(){
		$("#checkoutOption").val("1");
		$("#checkoutForm").submit();
		return false;
	});
	
}



function init_misRifas(){
	
	$("#tabs").tabs();
	
	$(".verStats").click(function(){
		var v = $(this).attr("data");
		$("#table"+v).toggle("slow");
		return false;
	});
	$(".showStatsSources").click(function(){
		var v = $(this).attr("data");
		$("#tableSources"+v).toggle("slow");
		return false;
	});
	
	$(".modificarWidget").click(function(){
		var v = $(this).attr("data");
		$("#widgetCustom"+v).toggle("slow");
		return false;
	});
	
	$(".bgColor").focus(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker").show("slow");
	});
	
	$(".bgColor").blur(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker").hide("slow");
	});
	
	$(".fontColor").focus(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker2").show("slow");
	});
	$(".fontColor").blur(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker2").hide("slow");
	});
	$(".lineColor").focus(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker3").show("slow");
	});
	$(".lineColor").blur(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker3").hide("slow");
	});
	$(".buttonColor").focus(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker4").show("slow");
	});
	$(".buttonColor").blur(function(){
		$("#widgetCustom"+$(this).attr("data")).find(".colorpicker4").hide("slow");
	});
	
	if($(".embeddApi").length > 0){
		$("textarea.embeddApi").click(function(){
			$(this).select();
			return false;
		});
	}
	
	if($('.colorpicker').length > 0){
		var colorPickers = $('.colorpicker');
		$.each(colorPickers,function(ind,val){
			$(this).farbtastic('#bgColor'+$(this).attr("data"));	
		});
	}
	if($('.colorpicker2').length > 0){
		var colorPickers2 = $('.colorpicker2');
		$.each(colorPickers2,function(ind,val){
			$(this).farbtastic('#fontColor'+$(this).attr("data"));	
		});
	}
	if($('.colorpicker3').length > 0){
		var colorPickers3 = $('.colorpicker3');
		$.each(colorPickers3,function(ind,val){
			$(this).farbtastic('#lineColor'+$(this).attr("data"));	
		});
	}
	if($('.colorpicker4').length > 0){
		var colorPickers4 = $('.colorpicker4');
		$.each(colorPickers4,function(ind,val){
			$(this).farbtastic('#buttonColor'+$(this).attr("data"));	
		});
	}
	if($('.colorpicker5').length > 0){
		var colorPickers5 = $('.colorpicker5');
		$.each(colorPickers5,function(ind,val){
			$(this).farbtastic('#buttonTextColor'+$(this).attr("data"));	
		});
	}
	
	$(".configuracionWidget").ajaxForm({
		beforeSubmit:function(arr, xhr){
			xhr.find(".loaderWidget").show();
			return true;
		},
		success:function(responseText,statusText,xhr){
			var valueSuper = xhr.find("input.addr").val();
			var script = document.createElement('script');
			var t = new Date();
			script.type = "text/javascript";
			script.defer = true;
			script.src = valueSuper+"&time="+t.getTime();
			
			// lo meto al final para que sea el último script cargado 
			// y params tenga el valor que toca en script!
		    var hook = document.getElementById('mainFooter')
		    hook.appendChild(script);
		    xhr.find(".loaderWidget").delay(2500).hide("fast");
		}
	});
	
	$(".todaviaNoSortear").click(function(){
		$("#todaviaNoSorteo"+$(this).attr("data")).toggle("slow");
		return false;
	});
	
}


function cambioPlan(){
	
	if($("#raffleSegSexo").is(':checked') || 
			$("#raffleSegPais").is(':checked') || 
			$("#raffleSegCiudad").is(':checked') ||
			$("#raffleSegEdad").is(':checked') ||
			$("#widgetPersonalizado").is(':checked') ||
			$("#comparticionDatos").is(':checked') ||
			$(".raffleCondition").length > 1){
		$("#rafflePlan").val(2);
		$("#widgetPersonalizado").attr("checked","checked");
		$(".precioRifa").text("99");
		return 99;
	}
	else {
		$("#widgetPersonalizado").removeAttr("checked");
		$("#rafflePlan").val(1);
		$(".precioRifa").text("0");
		return 0;
	}
	
}
function calculaTasa(v){
	if(v!=""){
		v = Math.round(parseFloat(v)/10*100)/100;
	}
	else {
		v = 0;
	}
	$("#tasaValue").text(v);
	
	return v;
}

function calculaPrecioTotal(){
	var p = 0;
	p += cambioPlan();
	//p += calculaTasa($("#productValue").val());
	
	$(".precioTotal").text(p);
}


function getText(key){
	if((key != null) && (key != "") && (key != "undefined")){
		if((_[key] != null) &&(_[key] != "") && (_[key] != "undefined")){
			return _[key];
		}
	}
	return "";
}
/*
function init_ficha_rifa(){
	if($('#compra').size() > 0){
		if(carrico == 0){
			$("#compra").hide();
		}
		
		if($("#numCompradosContainer li").size() > 0){
			$("#borrarBoletos").show();
		}
	
		$('#abreCompra').click(function(){
			if(!$("#resultadosBusqueda").is(":hidden")){
				$("#resultadosBusqueda").hide();
			}
			$("#compra").slideToggle();
			return false;
		});
	
		$('#precioTick').click(function(){
			if($('#abreCompra').size() > 0){
				if(!$("#resultadosBusqueda").is(":hidden")){
					$("#resultadosBusqueda").hide();
				}
				$("#compra").slideToggle();
			}
			return false;
		});
		
		$("#emptyCarroButt").click(function(){
			if(!$("#resultadosBusqueda").is(":hidden")){
				$("#resultadosBusqueda").hide();
			}
			if(confirm(getText('ficha_rifa_tickets_carro_borrar_todos_aviso'))){
				$.post(window.location.href,{'act':'removeAllNumbers'},function(data){
					var datos = eval('('+data+')');
					if(datos.objec == 1){
						$("#numCompradosContainer li").remove();
						$("#numerosComprar").val("");
						$("#borrarBoletos").hide();
						$("#captTotal").text("0" + getText('ficha_rifa_tickets_carro_numeros_label'));
						$("#captPrecio").text("0€");
					}
					else{
						alert(datos.messages);
					}
				});
			}
			return false;
		});
		
		$("#desiredNumber, #numBoletos").focus(function(){
			if(!$("#resultadosBusqueda").is(":hidden")){
				$("#resultadosBusqueda").hide();
			}
		});
		
		resultsBusq();
		optionsFicha();
	
		var optionsBusq = {beforeSubmit:loadAjaxImg, success:successBusqueda, dataType:'json'};
		$("#buscaNumsForm").ajaxForm(optionsBusq);
		
		var optionsRandom = {beforeSubmit:loadAjaxImg, success:successRandom, dataType:'json'};
		$("#randomForm").ajaxForm(optionsRandom);
		
		$("#botCompraBolsRifa").click(function(){
			if(usLogged != 1){
				alert(getText('ficha_rifa_comprar_no_login'));
				return false;
			}
			if(tipoRifa != 1){
				if(confirm(getText('ficha_rifa_aviso_datos_compartidos'))){
					return true;
				}
				else{
					return false;
				}
			}
			return true;
		});
	}
	else{
		$("#rifaPollForm").ajaxForm(votedRafflePoll);
	}
	
	$("a[rel=gallery]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
	});
}
function loadAjaxImg(formData, jqForm, options){
	if(randomSearchClicked == 0){
		randomSearchClicked = 1;
		$("#loaderContent").show();
	}
	else{
		return false;
	}
}
function successBusqueda(responseText, statusText, xhr, form){
	if(responseText.messages != ""){
		alert(responseText.messages);
	}
	
	if((responseText.objec != undefined) && (responseText.objec.length > 0)){
		$("#resultadosBusqueda ul").empty();
		if($("#resultadosBusqueda").is(":hidden")){
			$("#resultadosBusqueda").show();
		}
		$.each(responseText.objec,function(i,item){
			if(item == $("#desiredNumber").val()){
				$("#resultadosBusqueda ul").append(
					$('<li class="checkbox"></li>').append(
						'<label for="b'+item+'" style="font-weight:bold;">'+item+'</label><input type="checkbox" id="b'+item+'" />'
					)
				);
			}
			else{
				$("#resultadosBusqueda ul").append(
					$('<li class="checkbox"></li>').append(
						'<label for="b'+item+'">'+item+'</label><input type="checkbox" id="b'+item+'" />'
					)
				);
			}
		});
	
		resultsBusq();
	}
	
	randomSearchClicked = 0;
	$("#loaderContent").hide();
}
function successRandom(responseText, statusText, xhr, form){
	if(responseText.messages != ""){
		alert(responseText.messages);
	}
	else{
		if(!$("#resultadosBusqueda").is(":hidden")){
			$("#resultadosBusqueda").hide();
		}
		$.each(responseText.objec,function(i,item){
			$("#numCompradosContainer").append('<li id="rifTick-'+item+'">'+item+'<a href="#">'+getText("ficha_rifa_tickets_carro_borrar_boton")+'</a></li>');
			if($("#numerosComprar").val() != ""){
				$("#numerosComprar").val($("#numerosComprar").val()+","+item);
			}
			else{
				$("#numerosComprar").val(item);
			}
		});

		if($("#numCompradosContainer li").size() == 0){
			$("#borrarBoletos").hide();
		}
		else{
			$("#borrarBoletos").show();
		}
		actualizaCompra();
		optionsFicha();
	}
	
	randomSearchClicked = 0;
	$("#loaderContent").hide();
}
function optionsFicha(){
	$("#numCompradosContainer li a").click(function(){
		if(!$("#resultadosBusqueda").is(":hidden")){
			$("#resultadosBusqueda").hide();
		}
		if(confirm(getText('ficha_rifa_tickets_carro_borrar_aviso'))){
			var idParent = $(this).parent().attr("id");
			var numero = $("#"+idParent).text().substring(0,$("#"+idParent).text().indexOf(getText('ficha_rifa_tickets_carro_borrar_boton')));
			$.post(window.location.href,{'act':'removeNumber','number':numero},function(data){
				var datos = eval('('+data+')');
				if(datos.objec == 1){
					$("#"+idParent).remove();
					var nums = removeFromArray(convertToArray($("#numerosComprar").val()),numero);
					$("#numerosComprar").val(nums.toString());
					if($("#numCompradosContainer li").size() == 0){
						$("#borrarBoletos").hide();
					}
					else{
						$("#borrarBoletos").show();
					}
					actualizaCompra();
				}
				else{
					alert(datos.messages);
				}
			});
		}
		return false;
	});
}
function actualizaCompra(){
	var contad = $("#numCompradosContainer li").size();
	if(contad == 1){
		$("#captTotal").text("1" + getText('ficha_rifa_tickets_carro_numero_label'));
	}
	else{
		$("#captTotal").text(contad + getText('ficha_rifa_tickets_carro_numeros_label'));
	}
	var precioTick = $("#precioTick").text().substring(0,$("#precioTick").text().length-1);
	$("#captPrecio").text((precioTick * contad) + "€");
}
function resultsBusq(){
	$("#resultadosBusqueda ul li input").click(function(){
		var number = $(this).siblings().text();
		if(!isInArray(convertToArray($("#numerosComprar").val()),number)){
			// if(confirm(getText('ficha_rifa_tickets_buscados_anyadir_aviso'))){
			$.post(window.location.href,{'act':'addNumber','number':number},function(data){
				if(data.messages != ""){
					alert(data.messages);
				}
			},'json');
			$("#numCompradosContainer").append('<li id="rifTick-'+number+'">'+number+'<a href="#">'+getText("ficha_rifa_tickets_carro_borrar_boton")+'</a></li>');
			if($("#numerosComprar").val() != ""){
				$("#numerosComprar").val($("#numerosComprar").val()+","+number);
			}
			else{
				$("#numerosComprar").val(number);
			}
			$(this).parent().remove();
			if($("#resultadosBusqueda ul li").size() < 1){
				if(!$("#resultadosBusqueda").is(":hidden")){
					$("#resultadosBusqueda").hide();
				}
			}
			if($("#numCompradosContainer li").size() == 0){
				$("#borrarBoletos").hide();
			}
			else{
				$("#borrarBoletos").show();
			}
			actualizaCompra();
			optionsFicha();
			// }
		}
		else{
			alert(getText('ficha_rifa_tickets_buscados_anyadir_already'));
		}
	});
}
function votedRafflePoll(responseText, statusText, xhr, form){
	var data = eval('('+responseText+')');
	alert(data.message);
}

function init_index(){
	if($('.content').size() > 0){
		pulsado = false;
		pos =  $('.content').css("top");
		posIni = pos;
		altura = $('.content').innerHeight();
		fin = pos.length - 2;
		pos = pos.substr(0,fin);
		
		altoCollapsable = $("#collapsable").innerHeight();
		altoBoton = $(".masInfo").innerHeight();
		
		pos = pos - (altoCollapsable)-10; // alto+ margen del boton
		
		$("#collapsable").hide();
		
		$(".content").hover(				
			function(){
				if(pulsado != true){
					$("#collapsable").slideDown();
					$('.content').animate({top: pos-1, height: -pos}, 500, function(){
						pulsado = true;
					});
					return false;
				}
			},
			function(){
				if(pulsado == true){
					$("#collapsable").hide("fast");
					$('.content').animate({top: posIni, height: altura}, 180, function(){
						pulsado = false;
					});
					return false;
				}
			}
		);
	}
}

function init_login(){
	$("#user").focus(function(){
		if($("#user").val() == "Usuario"){
			$("#user").val("");
			$("#pass").val("");
		}
	});
	$("#pass").focus(function(){
		if($("#user").val() == "Usuario"){
			$("#user").val("");
			$("#pass").val("");
		}
	});
}

function init_encuestas(){
	$("#pollForm").ajaxForm(votedPoll);
}
function votedPoll(responseText, statusText, xhr, form){
	var data = eval('('+responseText+')');
	if(!data.error){
		var porcentVotos = "";
		var pintarVotos = 0;
		var idOpt = "";
		$.each(data.objec.options,function(i,item){
			pintarVotos = ((item.obtainedVotes*100)/data.objec.totalVotes);
			porcentVotos = new String(pintarVotos);
			porcentVotos = porcentVotos.substr(0,5);
			pintarVotos = pintarVotos - 100;
			idOpt = item.idOption;
			$("#percent-"+idOpt).text("("+porcentVotos+"%)");
			$("#barrRest-"+idOpt).css("background-position",pintarVotos+"px 0");
		});
	}
	alert(data.message);
}

function letraDni(dni){
	var lockup = 'TRWAGMYFPDXBNJZSQVHLCKE';
	return lockup.charAt(parseInt(dni) % 23);
}
function checkCorrectDni(dni){
	if(dni.length < 8){
		return false;
	}
	if(dni.length > 11){
		return false;
	}
	var letra = "";
	var caracs = dni.split("");
	var num = "";
	var i = 0;
	while((letra == "") && (i < dni.length)){
		if(isNaN(caracs[i])){
			var re = new RegExp("[A-Za-z]");
			if(caracs[i].match(re)){ 
				letra = caracs[i];
			}
			else{
				i++;
			}
		}
		else{
			num += caracs[i];
			i++;
		}
	}

	if(letra == ""){
		return false;
	}
	else{
		if(letraDni(num) != letra){
			return false;
		}
	}
	return true;
}

function isInArray(array, value){
	var parar = false;
	var i = 0;
	while((i < array.length) && !parar){
		if(value == array[i]){
			parar = true;
		}
		i++;
	}
	return parar;
}
function removeFromArray(array,value){
	var parar = false;
	var i = 0;
	while((i < array.length) && !parar){
		if(value == array[i]){
			parar = true;
			i++;
		}
		else{
			i++;
		}
	}
	if(i < array.length){
		while(i < array.length){
			array[i-1] = array[i];
			i++;
		}
		array.pop();
	}
	return array;
}
function convertToArray(values){
	var parts = values.split(",");
	var newArray = new Array();
	for(i = 0; i < parts.length; i++){
		newArray[i] = $.trim(parts[i]);
	}
	return newArray;
}
function convertToString(arr){
	var newString = "";
	for(i = 0; i < arr.length; i++){
		if(i != 0){
			newString += ",";
		}
		newString += $.trim(arr[i]);
	}
	return newString;
}
*/
function init_tooltips(){
	$.fn.qtip.styles.rifalia = { // Last part is the name of the style
	   width: 200,
	   background: '#005420',
	   color: 'white',
	   border: {
	      width: 2,
	      radius: 3,
	      color: '#005420'
	   },
	   tip: 'leftTop',
	   name: 'dark' // Inherit the rest of the attributes from the preset dark style
	}
	
	if ($("#planUser").size() > 0){
		$(".segmentacion").qtip({
			content: 'Tooltip de segmentación',
			style: 'rifalia'
		});	
		
		$(".widget").qtip({
			content: 'Tooltip del widget',
			style: 'rifalia'
		});	
	}
}
