/* --- Menu --- */
jQuery(function(){
	var points = new Array();
	var elem1 = jQuery("#showcanales").offset();
	var elem2 = jQuery("#capa_menu").offset();
	points["x1"]=elem1.left;
	points["y1"]=elem1.top;
	points["x2"]=elem1.left + jQuery("#showcanales").outerWidth();
	points["y2"]=elem2.top;
	points["x3"] = elem2.left + jQuery("#capa_menu").outerWidth();
	points["y3"]=points["y2"] + jQuery("#capa_menu").outerHeight();
	//console.dir(points);
	jQuery("#capa_menu").css({"display":"none","visibility":"visible"});
	jQuery("#showcanales").hover(function(e){
		jQuery("#capa_menu").show();
		jQuery("#showcanales").removeClass("pleg").addClass("despleg");
	}, function(e){
		if(e.pageX <= points["x1"] || e.pageY <= points["y1"] || (e.pageX > points["x2"] && e.pageY < points["y2"])){
			jQuery("#capa_menu").hide();
			jQuery("#showcanales").removeClass("despleg").addClass("pleg");
		}
	})

	jQuery("#capa_menu").hover(function(e){
		jQuery("#capa_menu").show();}, function(e){
			if(e.pageX <= points["x1"] || e.pageX >= points["x3"] || e.pageY>= points["y3"] || (e.pageX >= points["x2"] && e.pageY<= points["y2"])){
				jQuery("#capa_menu").hide();
				jQuery("#showcanales").removeClass("despleg").addClass("pleg");
			}
		}
	)

	/* --- Buscador amigable --- */
	jQuery("#globalsearch").submit(function(){
		var keyword = jQuery("#palabraClave").val()
		if(keyword.length == 0) keyword = 'all';
		keyword = keyword.toLowerCase();
		keyword = keyword.replace(/\s+/g,"_");
		keyword = keyword.replace(/\/\/+/g,"");
		keyword = keyword.replace(/\\+/g,"");
		keyword = keyword.replace(/[àáâãäå]/g,"a");
		keyword = keyword.replace(/[èéêë]/g,"e");
		keyword = keyword.replace(/[ìíîï]/g,"i");
		keyword = keyword.replace(/[òóôõö]/g,"o");
		keyword = keyword.replace(/[ùúûü]/g,"u");
		keyword = keyword.replace(/[ýÿ]/g,"u");
		keyword = keyword.replace(/ñ+/g,"n");
		keyword = keyword.replace(/ç+/g,"c");
		keyword = keyword.replace(/&+/g,"");
		keyword = keyword.replace(/'+/g,"");
		keyword = keyword.replace(/"+/g,"");
		keyword = keyword.replace(/\.+/g,"_");
		jQuery(this).attr('action', jQuery(this).attr('action') + keyword);
		return true;
	})
})

/* -- Evento click sobre el thumbnail de un video -- */
jQuery(".video_imagen_cont, .cont_img").live("click",function(){
	if(jQuery(this).children("a").length > 0) return true;
	var idvideo = jQuery(this).attr("id").split("_")[1];
	var idsectionplayer = "947";
	jQuery.getJSON("/theNEXTBIGthing/utils.encrypturl",{idvideo:idvideo, idsection:idsectionplayer,auto:false},function(json){
		jQuery.get("/_ajax/Section.show" + json.res,function(data){
			var res = data.getElementsByTagName("body")[0].firstChild.nodeValue;
			jQuery("#theplayer").replaceWith(res);
//			jQuery("#theplayer").html(res);
			jQuery(document).scrollTop(0);
			videos_relacionados(idvideo);
			hide_elempest();
		})
	})
	return false;
})

/* -- ver los relacionados -- */
function videos_relacionados(idvideo){
	jQuery.post("/videosRelacionados.getUrl",{idVideo: idvideo},function(json){
		var element = json;
		var url = element.url;
		if (url != '') {
			eBDSection.show(url, reemplazar_videos_relacionados );
		} else {
			$("#relacionados").css("display", "none");
		}
	});
}

function reemplazar_videos_relacionados(html){
	$("#relacionados").html( html ).css("display", "block");
}

/* --- esconder bloque de datos de las pestanyas en canales --- */
function hide_elempest(){
	if(jQuery("#box_videospest").length > 0){
		jQuery("#box_videospest").hide();
		jQuery("div[class=p_on]").attr("class","p_off");
	}
}

/* --- Pintar contenidos estaticos en una capa --- */
function verestatic(idcont, ididioma){
	jQuery.post("/estaticos.contents",{idcontenido:idcont, ididioma:ididioma}, function(json){
		//var res = eval("(" + json + ")");
		var res = json;

		jQuery("body").prepend("<div id='pop_estatic'><div class='close_pop'></div><div class='barita'>" + res.titulo + "</div><div class='cont_estatic'>" + res.texto + "</div></div>");
		jQuery("#capa").height(jQuery(document).height());
		jQuery("#capa").width(jQuery(document).width());
		jQuery("#capa").show();
		jQuery("#capa").click(function(){jQuery("#capa").hide();jQuery("#pop_estatic").remove();});

		var popw = jQuery('#pop_estatic').outerWidth();
		var poph = jQuery('#pop_estatic').outerHeight();
		var docw = jQuery(window).width();
		var doch = jQuery(window).height();
		var posx = (docw - popw)/2;
		var posy = (doch - poph)/3;

		if (jQuery.browser.msie==true && parseInt(jQuery.browser.version)<7) { var scroll=jQuery(window).scrollTop();posy=posy+scroll;}

		jQuery("#pop_estatic").css({"left":posx, "top":posy}).show();
		jQuery(".cont_estatic").css({"height":"400px"});
		jQuery("#pop_estatic div[class=close_pop]").click(function(){jQuery("#pop_estatic").remove(); jQuery("#capa").hide();})
	})
}
/** Formulario contactar **/

function contactar(){
	var url=jQuery("#contact_form_reload").val();
	jQuery.post("/_ajax/Section.show"+url,{},function(data){
		var res = data.getElementsByTagName("body")[0].firstChild.nodeValue;

		jQuery("body").prepend("<div id='pop_estatic'><div class='close_pop'></div><div class='barita'>Formulario de contacto</div><div class='cont_estatic'><p class='login_titulo' style='padding:5px 15px;'>Para ponerse en contacto con nosotros rellene el siguiente formulario con sus datos. Tenga en cuenta que le enviaremos la respuesta al email que nos indique:<br></p>"+res+"</div></div>");
		jQuery("#capa").height(jQuery(document).height());
		jQuery("#capa").width(jQuery(document).width());
		jQuery("#capa").show();
		jQuery("#capa").click(function(){jQuery("#capa").hide();jQuery("#pop_estatic").remove();});

		var popw = jQuery('#pop_estatic').outerWidth();
		var poph = jQuery('#pop_estatic').outerHeight();
		var docw = jQuery(window).width();
		var doch = jQuery(window).height();
		var posx = (docw - popw)/2;
		var posy = ((doch - poph)/3)-50;

		if (jQuery.browser.msie==true && parseInt(jQuery.browser.version)<7) { var scroll=jQuery(window).scrollTop();posy=posy+scroll;}

		jQuery("#pop_estatic").css({"left":posx+"px", "top":posy}).show();
		jQuery("#pop_estatic div.cont_estatic").css({"height":"auto"});
		jQuery("#pop_estatic div[class=close_pop]").click(function(){jQuery("#pop_estatic").remove();jQuery("#capa").hide();})
		contact_validate();
	})
}
function contact_validate(){
	jQuery.validator.addMethod('validCaptcha', function(value, element){
		var illegalChars = /\W/;
		var ret=false;

		if (illegalChars.test(value))
		{
			ret=false;
		}
		else{
			var capcha=jQuery('#capcha').val();
			jQuery.ajax({
				type: 'POST',
				url: '/v2/contact.captcha',
				async: false,
				data: 'captcha='+capcha,
				success: function(json){
					var resp=json;
					if (resp.res == 'KO'){ ret=false; }
					else { ret=true; }
				}
			});
		}
		return ret;
	}, '<br><span style="color:red">El código es incorrecto</span>');

	jQuery("#contact_form").validate(
	{
		rules: {
			nombre: 'required',
			email: {
				required:true,
				email : true
			},
			titulo: 'required',
			contact_detalle:'required',
			capcha: {
				required:true,
				validCaptcha : true
			}
		},
		messages: {
			nombre: '<br><span style="color:red">No puede estar vacío</span>',
			titulo: '<br><span style="color:red">No puede estar vacío</span>',
			contact_detalle: '<br><span style="color:red">No puede estar vacío</span>',
			email:
			{
				required : '<br><span style="color:red">No puede estar vacío</span>',
				email : '<br><span style="color:red">Introduce un email válido</span>'
			},
			capcha:
			{
				required : '<br><span style="color:red">No puede estar vacío</span>',
				validCaptcha : '<br><span style="color:red">El código es incorrecto</span>'
			}
		},
			submitHandler: function(form) {
			// do other stuff for a valid form
			save_contact();
		}
	})
}

function save_contact(){
	var capcha=jQuery('#capcha').val();
	var nombre=jQuery("#nombre").val();
	var titulo=jQuery("#titulo").val();
	var email=jQuery("#email").val();
	var contact_detalle=jQuery("#contact_detalle").val();

	jQuery.ajax({
		type: 'POST',
		url: '/v2/contact.save',
		async: false,
		data: 'nombre='+nombre+'&titulo='+titulo+'&contact_detalle='+contact_detalle+'&email='+email,
		success: function(json){
			//var resp=eval('('+json+')');
			var resp=json;
			jQuery("#pop_estatic div.cont_estatic").html("<p class='login_titulo' style='text-align:center;'>"+resp.res+"</p>");
		}
	})
}

/* --- funciones telefonica --- */
/* -- imagenes ir por detras -- */
function chane(idlk){
	var idprog = idlk.split("_")[1];
	var counter=jQuery("#cspan_"+idprog).attr('title');
	var total=counter.split("/")[1];
	var count=counter.split("/")[0];
	count=parseInt(count)-3;
	var aux=parseInt(count)-3;
	if(count<total){
		//jQuery("#imglinkr_"+idprog).attr('style','display:block;');
		jQuery("#imglinkr_"+idprog).show();
		//jQuery("#imgsolar_"+idprog).attr('style','display:none;');
		jQuery("#imgsolar_"+idprog).hide();
	}
	if(aux==0){
		//jQuery("#imglinkl_"+idprog).attr('style','display:none;');
		jQuery("#imglinkl_"+idprog).hide();
		//jQuery("#imgsolal_"+idprog).attr('style','display:block;');
		jQuery("#imgsolal_"+idprog).show();
		//jQuery("#imgsolal_"+idprog+" span").attr('style','display:block;margin-top:80px;');
		jQuery("#imgsolal_"+idprog+" span").show();
	}

	var newv=count+"/"+total;
	jQuery("#cspan_"+idprog).attr('title',newv);
	var value=jQuery("#nexttel_"+idprog).val();
	var clss=value;
	var after=parseInt(clss)-100;
	jQuery("."+clss).hide();//attr('style','display:none;');
	jQuery("."+after).fadeIn("fast");
	jQuery("#nexttel_"+idprog).attr('value',after);
	jQuery("#prevtel_"+idprog).attr('value',clss);
	jQuery("#cspan_" + idprog).text(newv);
}
/* -- imagenes ir por adelante -- */

function changeimgtel(idlk){
	var idprog = idlk.split("_")[1];
	var counter=jQuery("#cspan_"+idprog).attr('title');
	var total=counter.split("/")[1];
	var count=counter.split("/")[0];
	count=parseInt(count)+3;
	var aux=parseInt(count)-3;
	if(count>=total){
		//jQuery("#imglinkr_"+idprog).attr('style','display:none;');
		jQuery("#imglinkr_"+idprog).hide();
		//jQuery("#imgsolar_"+idprog).attr('style','display:block;');
		jQuery("#imgsolar_"+idprog).show();
	}
	if(aux!=0){
		//jQuery("#imglinkl_"+idprog).attr('style','display:block;');
		jQuery("#imglinkl_"+idprog).show();
		//jQuery("#imgsolal_"+idprog).attr('style','display:none;');
		jQuery("#imgsolal_"+idprog).hide();
	}
	var newv=count+"/"+total;
	jQuery("#cspan_"+idprog).attr('title',newv);

	var value=jQuery("#nexttel_"+idprog).val();
	var clss=value;
	var after=parseInt(clss)+100;
	jQuery("."+clss).hide();//attr('style','display:none;');
	jQuery("."+after).fadeIn("fast");
	jQuery("#nexttel_"+idprog).attr('value',after);
	jQuery("#prevtel_"+idprog).attr('value',clss);

	if(count>total){
		newv=total+"/"+total;
	}
	jQuery("#cspan_" + idprog).text(newv);
}

/* galeria canal evento --> programas videos */
function changeimg(idlk){
	var sentido = idlk.split("_")[0];
	var idprog = idlk.split("_")[1];
	var numimg = (jQuery("#celda_" + idprog + " input[type=hidden]").length) / 6;

	if(sentido == 'prec') var increm = -1; else var increm = 1;
	var idimgactual = jQuery("#celda_" + idprog + " img").attr("id");
	var counterimg = idimgactual.split("_")[2];
	/* definir imagen que pintar */
	var nextcounter = parseInt(counterimg) + increm;
	if(nextcounter == 0) var newcounter = numimg;
	else if(nextcounter > numimg) var newcounter = 1;
	else var newcounter = nextcounter;
	/* pintar los datos nuevos */
	jQuery("#contimgprg_" + idprog + " div").fadeOut("fast", function(){
		jQuery("#contimgprg_" + idprog).empty();
		var newtxt=jQuery("#txtprg_" + idprog + "_" + newcounter).val();
		var newimg=jQuery("#imgprg_" + idprog + "_" + newcounter).val();
		var newhd = jQuery("#hd_" + idprog + "_" + newcounter).val();
		var newidvideo = jQuery("#idvideo_" + idprog + "_" + newcounter).val();
		var elemid = "thumb" + idprog + "_" + newidvideo;

		jQuery("#contimgprg_" + idprog).html("<div class='cont_img' id='" + elemid + "'>" + newhd + "<img id='img_" + idprog + "_" + newcounter + "' src='" + newimg + "' alt='" + newtxt + "' title='" + newtxt + "'></div><div class='leyendaimg' id='txt_" + idprog + "_" + newcounter + "'>" + newtxt + "</div>")
		jQuery("#counter_" + idprog).text(newcounter + " / " + numimg);
		jQuery("#contimgprg_" + idprog + " div").fadeIn();
	});
}


