/*
 * FILMIN 2010
 */
 
$(document).ready(function(){
	/* Funcion para borrar el contenido de los inputs al recibir el foco.*/
	$("input:text").focus(function(){
		//$(this).val();
		if ($(this).val()==$(this).attr("title")) {
			$(this).val("");
		}
	});
	/* Funcion para evitar el reborde punteado en los enlaces*/
	$("a").focus(function(){
		$(this).blur();
	});
	$(".main_select_two a").click(function(event){
		event.preventDefault();
	});
	
	//Funcion para reducir los textos grandes.
	$(".strR").each(function(){
		var content=this;
		var container=$(this).parents().find(".strC");
		var limit=$(this).parents().find(".ie_str_limit");
		var container_pos=$(container).position();
		var container_w=container_pos.left+parseInt($(container).css("width").replace("px",""));

		var limit_pos=$(limit).position();
		
		var content_w=limit_pos.left-container_pos.left;

		var font_size=$(this).css("font-size").replace("px","");
		var i=0;
		while(content_w>0 && i<20){
			font_size-=1;
			$(this).css("font-size",font_size+"px");
			container_w=container_pos.left+parseInt($(container).css("width").replace("px",""));
			var limit_pos=$(limit).position();
			content_w=limit_pos.left-container_w;
			i++;
		}
	});
	imageAlternative();
	
	addEvent($("body"),"load",allLoad(),false);

		$(".filmin_film").live("mouseenter",function(){
			var addView='<a class="addViewLater" style="position:absolute;margin:148px 0 0 -112px;background-image:url(http://contenido.s3.amazonaws.com/img/addView.png);display:none;width:26px;height:20px;" href="#"></a>';
			var addFavo='<a class="addFavorites" style="position:absolute;margin:148px 0 0 -84px;background-image:url(http://contenido.s3.amazonaws.com/img/addFavorites.png);display:none;width:26px;height:20px;" href="#"></a>';
			$(this).append(addView);
			$(this).append(addFavo);
			$(this).find(".addViewLater,.addFavorites").fadeTo("normal",0.3);
		});
		$(".filmin_film").live("mouseleave",function(){
			$(this).find(".addViewLater,.addFavorites").fadeOut("normal",function(){
				$(this).remove();
			});
		});
		$(".filmin_episode").live("mouseenter",function(){
			var addView='<a class="addViewLater" style="position:absolute;margin:145px 0 0 -110px;background-image:url(http://contenido.s3.amazonaws.com/img/addView.png);display:none;width:26px;height:20px;" href="#"></a>';
			//var addFavo='<a class="addFavorites" style="position:absolute;margin:148px 0 0 -84px;background-image:url(http://contenido.s3.amazonaws.com/img/addFavorites.png);display:none;width:26px;height:20px;" href="#"></a>';
			$(this).append(addView);
			//$(this).append(addFavo);
			$(this).find(".addViewLater,.addFavorites").fadeTo("normal",0.3);
		});
		$(".filmin_episode").live("mouseleave",function(){
			$(this).find(".addViewLater,.addFavorites").fadeOut("normal",function(){
				$(this).remove();
			});
		});
		
		$(".filmin_serie").live("mouseenter",function(){
			//var addView='<a class="addViewLater" style="position:absolute;margin:148px 0 0 -112px;background-image:url(http://contenido.s3.amazonaws.com/img/addView.png);display:none;width:26px;height:20px;" href="#"></a>';
			var addFavo='<a class="addFavorites" style="position:absolute;margin:148px 0 0 -112px;background-image:url(http://contenido.s3.amazonaws.com/img/addFavorites.png);display:none;width:26px;height:20px;" href="#"></a>';
			//$(this).append(addView);
			$(this).append(addFavo);
			$(this).find(".addFavorites").fadeTo("normal",0.3);
		});
		$(".filmin_serie").live("mouseleave",function(){
			$(this).find(".addFavorites").fadeOut("normal",function(){
				$(this).remove();
			});
		});
		/*$(".filmin_serie").live("mouseenter",function(){
			var addFavo='<a class="addFavorites" style="position:absolute;margin:148px 0 0 -110px;background-image:url(http://contenido.s3.amazonaws.com/img/addFavorites.png);display:none;width:26px;height:20px;" href="#"></a>';
			$(this).append(addFavo);
			$(this).find(".addFavorites").fadeTo("normal",0.3);
		});
		$(".filmin_serie").live("mouseleave",function(){
			$(this).find(".addFavorites").fadeOut("normal",function(){
				$(this).remove();
			});
		});*/
		/********/		
		$(".addViewLater,.addFavorites").live("mouseenter",function(){
			$(this).fadeTo("normal",0.7);
		});
		$(".addViewLater,.addFavorites").live("mouseleave",function(){
			$(this).fadeTo("normal",0.3);
		});
		
		$(".addViewLater").live("click",function(event){
			event.preventDefault();
			var values=$(this).parents().attr("id").split("_");
			id=values[1];
			addViewLater(id,$(this));
			$(this).blur();
		});
		$(".addFavorites").live("click",function(event){
			event.preventDefault();
			var values=$(this).parents().attr("id").split("_");
			id=values[1];
			type=values[2];
			addFavorites(id,type,$(this));
			$(this).blur();
		});

		$(".filminToolTip").live("click",function(event){
			event.preventDefault();
			$(this).fadeOut("fast");
		});
		
		$("#alias").focus(function(){
			$(".filminToolTip").fadeOut("fast");
		});
function addViewLater(id,div){
	$.ajax({
		type: 	'POST',
		data: {'id': id},
		url:	'/ws/viewlater.php',
		success:  	function(code){
						code = code.replace(/^\s*|\s*$/g,"");
						if(code=="add"){
							$(div).css("background-image","url(http://contenido.s3.amazonaws.com/img/addViewAdd.png)");
						}else{ 
							if(code=="nologin"){
								$("#lb_log").click();
							}else{						
								$(div).css("background-image","url(http://contenido.s3.amazonaws.com/img/addViewDel.png)");
							}
						}
					}
	});			
}

function addFavorites(id,type,div){
	$.ajax({
		type: 	'POST',
		data: {'id': id,'type':type},
		url:	'/ws/favorites.php',
		success:  	function(code){
						code = code.replace(/^\s*|\s*$/g,"");
						if(code=="add"){
							$(div).css("background-image","url(http://contenido.s3.amazonaws.com/img/addFavoritesAdd.png)");
						}else{ 
							if(code=="nologin"){
								$("#lb_log").click();
							}else{						
								$(div).css("background-image","url(http://contenido.s3.amazonaws.com/img/addFavoritesDel.png)");
							}
						}
					}
	});			
}
		
});

function allLoad(){ 
	$("#lb_log").addClass("vallk_box");
	$("#lb_log").attr("href","/acceder.php?w=543&h=367");
	$("#lb_log").attr("rel","#vContainer");
	$("#lb_reg").addClass("vallk_box");
	$("#lb_reg").attr("href","/registro.html?w=566&h=534");
	$("#lb_reg").attr("rel","#vContainer");
}

function addEvent(elem, evType, func, useCapture){
	if(elem.addEventListener){
		elem.addEventListener(evType, func, useCapture);
		return true;
	}else if(elem.attachEvent){
		var r = elem.attachEvent('on' + evType, func);
		return r;
	}else{
		elem['on' + evType] = func;
	}
}

function utf8_encode(s){
	return unescape(encodeURIComponent(s));
}

function utf8_decode(s){
	return decodeURIComponent(escape(s));
}

function goToAnchor(anchor){
	destination = $("#"+anchor).offset().top;
	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 800 );
}



function addToNewsletter(email){
	if(validEmail($("#"+email).val())==true){
	$.ajax({ 
		type: 	'POST',
		data: {'email': $("#"+email).val()},
		url:	'/ws/newsletter.php',
		success:  	function(code){
						alert(code);
					}
	});
	}else{
		alert("El email '" + $("#"+email).val() +"' no es válido");
	}
}

function embedVideo(width,height,idDiv,type,id){
	$.ajax({ 
		type: 	'POST',
		data: {'width': width,'height': height,'id': id, 'type':type},
		url:	'/ws/embed.php',
		success:  	function(code){
						$("#"+idDiv).html(code);
						
						document.location.href="javascript:d=document,e=d.createElement('script');e.src='http://www.filmin.es/js/airplay.js?'+(new%20Date()*1);void(d.body.appendChild(e));";
					}
	});
}

function newembedVideo(width,height,idDiv,type,id){
	$.ajax({ 
		type: 	'POST',
		data: {'width': width,'height': height,'id': id, 'type':type},
		url:	'/ws/newembed.php',
		success:  	function(code){
						$("#"+idDiv).html(code);
					}
	});
}
function paginarComentario(fuente,id,limite,actual,div){
	gFuente=fuente;
	div=div || "film_user_container";
	$.ajax({
		type: 	'POST',
		data: {'fuente':fuente,'id': id,'limite':limite,'actual':actual},
		url:	'/ws/comments.php',
		success:  	function(code){
						$("#"+div+" .main_user_comments").fadeOut('normal', function (){
						$("#"+div).html(code);
						$("#"+div+" .main_pagination_one").css("float","left");
						$("#"+div+" .main_write_comment").css("float","left");
						$("#"+div+" .main_user_comments").fadeIn('normal');
						imageAlternative();
						});
					}
	});
}

//google.load("language", "1");

function preTranslate(){
	$(".translate").each(function(){
		var language;
		var trans=this;
		google.language.detect($(this).html(), function(result) {
			if (!result.error) {
				if(result.language!="es"){
					$(trans).after("<a style='color:#0087D4;font-weight:bold;' class='go_translate' title='"+result.language+"' onclick='' href='#'>Traducir cr&iacute;tica</a>");
				}
			}
		});
	});
}
	
$(document).ready(function(){
	preTranslate();
});
	$(".main_tab_one li").live("click",function(event){
		$(this).parents('ul').find('li').removeClass("selected");
		$(this).addClass("selected");
		event.preventDefault();
	});
$(".go_translate").live("click",function(event){
	text=$(this).parents('li').find('.translate');
	$(this).fadeOut("normal");
	google.language.translate($(text).html(), $(this).attr("title"), 'ES', function(result){
		$(text).html(result.translation);
	});
	event.preventDefault();
});


var pos;
var med;
	$(".valuable").live("mousemove",function(e){
		pos = $(this).offset();
		val=e.pageX - pos.left;
		if (val <= 72) {
			med=((val*100)/71)/10;
			med = Math.round(med*10)/10;
			if(med>9.6){
				med=10;
			}else if(med<0.6){
				med=0;
			}
			med = Math.round(med * 2) / 2
			id=$(this).attr("id");
			posx=71-val;
			newPos="-"+posx+"px 0";
			$("#"+id+" .bar").css("background-position",newPos);
			$("#"+id+" span").html(med);
		}
   });
   
	$(".valuable").live("click",function(){
		tipo=$(this).attr("class");
		tipo=tipo.replace("main_progress_bar valuable ","");
		$.ajax({
			type: 	'POST',
			async: false,
			data: {'rank':med,'type':tipo,'id': rank_id},
			url:	'/ws/vote.php',
			success:  	function(code){
							code = code.replace(/^\s*|\s*$/g,"");
							if(code=="0"){
								target=$("#lb_log").attr("href");
								show_vallk_box($("#lb_log"));
								return 0;
							}							
							if(code=="1"){
								alert("Ya has votado este vídeo");
								return 0;
							}
							if(code=="2"){
								alert("Debes activar tu cuenta para poder votar un corto");
								return 0;
							}	
							if(code=="3"){
								target=$("#confirm_email").attr("href");
								show_vallk_box($("#confirm_email"));
								return 0;
							}
							$(this).removeClass("valuable");
							$("#rank_vote").fadeOut('normal',function(){
								$("#rank_vote").html(code);
							});
							$("#rank_vote").fadeIn("normal");
						}
		});	
	});
	
	function addFavorites(type,id,div){
		$.ajax({
			type: 	'POST',
			data: {'type':type,'id': id},
			url:	'/ws/favorites.php',
			success:  	function(code){
							code = code.replace(/^\s*|\s*$/g,"");
							if(code=="del"){
								$("#"+div).fadeOut('normal',function(){
									$("#"+div).html("Borrada de favoritos");
								});
								$("#"+div).fadeIn("normal");
							}else{ 
								if(code=="nologin"){
									$("#lb_log").click();
								}else{						
									$("#"+div).fadeOut('normal',function(){
										$("#"+div).html("Añadida a favoritos");
									});
									$("#"+div).fadeIn("normal");
								}
							}
						}
		});			
	}

	function addLikeView(type,id,div){
		$.ajax({
			type: 	'POST',
			data: {'type':type,'id': id},
			url:	'/ws/viewlater.php',
			success:  	function(code){
							code = code.replace(/^\s*|\s*$/g,"");
							if(code=="del"){
								/*$("#"+div).fadeOut('normal',function(){
									$("#"+div).html("Eliminada de favoritos");
								});*/
								$("#"+div).fadeOut('normal',function(){
									$("#"+div).html("No quieres verla");
								});
								$("#"+div).fadeIn("normal");
							}else{ 
								if(code=="nologin"){
									$("#lb_log").click();
								}else{						
									$("#"+div).fadeOut('normal',function(){
										$("#"+div).html("Quieres verla");
									});
									$("#"+div).fadeIn("normal");
								}
							}
						}
		});			
	}
	
	function writeComment(fuente,id,comentario,div,limite){
		div=div || "film_user_container";
		limite=limite || "4";
		$("#"+div+" .loading").fadeIn("fast");
		$.ajax({
			type: 	'POST',
			data: {'fuente':fuente,'id': id,'comentario':comentario,'limite':limite},
			url:	'/ws/comments.php',
			success:  	function(code){
							code = code.replace(/^\s*|\s*$/g,"");
							if(code!=""){
								datos=code.split("|");
								if(datos[0]=="OK"){
									$("#"+div+" .main_user_comments").fadeOut('normal', function (){
									$("#"+div).html(code.replace("OK|",""));
									$("#"+div+" .main_pagination_one").css("float","left");
									$("#"+div+" .main_write_comment").css("float","left");
									$("#"+div+" .main_user_comments").fadeIn('normal');
									});
									imageAlternative();
								}else{
									if(datos[0]=="EXIST"){
										$("#"+div+" .loading").fadeOut("fast");
									}
									if(datos[0]=="REG"){
										$("#lb_log").click();
									}
								}
							}
						}
		});		
	}
	
	function validEmail(email) {
		//val = document.getElementById('email').value;
		//val=$("#"+email).val();
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email)){
			return true;
		} else {
			//alert("Please insert valid email address");
			return false;
		}
	}
	
	function loginWindow(){
		$("#lb_log").click();
	}

	function imageAlternative(){
		$('img').error(function() {
			$(this).attr({
				src: getImgAlternative($(this).attr("src")),
				alt: ''
			});
		});
	}
	function getImgAlternative(t){
		t=dirname(t)
		switch(t){
			case "http://contenido.s3.amazonaws.com/resources/posters_films/resized":
				return "http://contenido.s3.amazonaws.com/img/alternatives/portada.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/users":
				return "http://d6xicjbjo3rov.cloudfront.net/img/alternatives/user.jpg";
			break;
			case "http://contenido.s3.amazonaws.com/resources/medios":
				return "http://contenido.s3.amazonaws.com/img/alternatives/medio.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/posters_films/70x47":
				return "http://contenido.s3.amazonaws.com/img/alternatives/mini-poster.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/Directores/Twitter48x48":
				return "http://contenido.s3.amazonaws.com/img/alternatives/dir_twitter.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/Directores/275x125":
				return "http://contenido.s3.amazonaws.com/img/alternatives/director-mini.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/Directores/316x180":
				return "http://contenido.s3.amazonaws.com/img/alternatives/250x142.png";
			break;
			case "http://contenido.s3.amazonaws.com/resources/Directores/634x300":
				return "http://contenido.s3.amazonaws.com/img/alternatives/director.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/poster_films/70x47":
				return "http://contenido.s3.amazonaws.com/img/alternatives/mini-poster.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/users/director":
				return "http://contenido.s3.amazonaws.com/img/alternatives/director-mini.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/uploads/shorts/poster":
				return "http://contenido.s3.amazonaws.com/img/alternatives/mini-poster.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/destacado_film/633x269":
				return "http://contenido.s3.amazonaws.com/img/alternatives/director.gif";
			break;
			case "http://contenido.s3.amazonaws.com/resources/destacado_film/250x142":
				return "http://contenido.s3.amazonaws.com/img/alternatives/250x142.png";
			break;
			case "http://contenido.s3.amazonaws.com/resources/poster_films/resized":
				return "http://contenido.s3.amazonaws.com/img/alternatives/portada.gif";
			break;
		}
	}
	function simulateAjax(){
		$("body").append('<img class="imgAlt" src="http://multimedia.filmin.es/sections/newfilmin/resources/uploads/shorts/poster/cakita.jpg" alt="Yaka" />');
		imageAlternative();
	}
	function basename(path) {
		return path.replace(/\\/g,'/').replace( /.*\//, '' );
	}
	function dirname(path) {
		return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');;
	}
	
	/*function login(){
	jQuery.ajax({ 
		type: 	'POST',
		data: 	{'user':hex_sha1($("#user").val().toLowerCase()),'pass':hex_sha1($("#pass").val()),'remember':$("#remember").attr("checked")},
		url:	'/ws/login.php',
		success:  	function(msg){
						msg = msg.replace(/^\s*|\s*$/g,"");
						if(msg=="true"){
							location.reload();
						}else{
							alert("Usuario y/o pass incorrecto");
						}
					}
	});
	}*/

	function close_combo(){
	}
