/**
 * I18n
 * Objeto para internacionalización
 */
I18n = {};

/**
 * I18n
 * Objeto para internacionalización textos en Español
 */
I18n.es = {};

/**
 * I18n
 * Objeto para internacionalización textos en Catalán
 */
I18n.ca = {};				

/**
 * JsCantvUtils
 */			 
JsCantvUtils = {};

/**
 * JsCantvUtils.SuPath
 * 
 * Contexto del proyecto SU
 */
JsCantvUtils.SuPath = CantvProperties.supath;		

/**
 * JsCantvUtils.Paths
 */
JsCantvUtils.Paths = {
	BasePath: document.location.protocol+"//"+document.location.host+"/",
	LocaleFromPath: document.location.pathname.split('/')[1],
	BasePathLocale: document.location.protocol+"//"+document.location.host+"/"+document.location.pathname.split('/')[1]+"/"
}


/**
 * JsCantvUtils.HasFiles
 */
JsCantvUtils.HasFiles = {
		
	/**
	 * JsCantvUtils.HasFiles.hash
	 * Función que devuelve ruta adecuada en función del identificador
	 * 
	 * @param ID - identificador del contenido
	 */		
	hash: function(id,deep){
		var deep = (typeof(deep) != 'undefined')?deep:2;
		var id = id.toString();
		var size = id.length;
		var stringHash = "";
		var defaultChar = "0";
		
		for (var i=1;i<=deep;i++) { 
			if (size < i){
				stringHash = stringHash+"/"+defaultChar;			
			}else{
				stringHash = stringHash+"/"+id.charAt(size-i);		
			}
		}
		return stringHash+"/";
	}
};


/**
* Selector de elementos por id
* @param {String}  elem -  id del elemento
* @returns {String}  selector del elemento
*/
JsCantvUtils.idSel = function (id_elem){
	return "#"+id_elem;
};

/**
 * JsCantvUtils.timestamp
 */
JsCantvUtils.timestamp = function (){
	return new Date().getTime();
};
/**
* Impide el cacheo de una url
* @param {String}  url - url
* @returns {String} 
*/
JsCantvUtils.urlNoCache = function (url){ 
	return url+"?nocache="+JsCantvUtils.timestamp();
};

/**
 * JsCantvUtils.Messages
 */
JsCantvUtils.Messages = {
	/**
	 * JsCantvUtils.Messages.showMsg
	 * @param msg - mensaje a mostrar
	 */		
	showMsg: function (msg){
		alert(msg);
	}
}

/**
 * JsCantvUtils.Errors
 */
JsCantvUtils.Errors = {
	/**
	 * JsCantvUtils.Errors.showError
	 * @param msg - mensaje de error a mostrar
	 */		
	showError: function (msg){
		alert(msg);
	}
}

/**
 * JsCantvUtils.isUserLogged
 * Devuelve true si el usuario está logado
 */
JsCantvUtils.isUserLogged = function (){
	return ($("#login_access").attr("advanceduser"));
}

/**
 * JsCantvUtils.isIE
 * Devuelve true si se está ejecutando Internet Explorer
 */
JsCantvUtils.isIE = function (){
	return (navigator.appName=="Microsoft Internet Explorer");
}

/**
 * Mensajes para login en Español
 */
I18n.es.login_required_action = "Se necesita estar identificado para realizar esta acción";
I18n.es.login_required_rate = "Veo que quieres votar. Para eso necesitas darte de alta.";

/**
 * Mensajes para login en Catalán
 */
I18n.ca.login_required_action = "Es necessita estar identificat per realitzar aquesta acció";
I18n.ca.login_required_rate = "Veo que quieres votar. Para eso necesitas darte de alta.";

/**
 * JsCantvUtils.showLoginRequired
 * Muestra un mensaje para indicar que se necesita estar identificado en el sistema
 * @param  locale - Idioma
 */
JsCantvUtils.showLoginRequired = function (locale,action){
	if (!action)
	{
		alert(I18n[locale].login_required_action);
	}
	else{
		var textShow="I18n['"+locale+"'].login_required_"+action;
		alert(eval(textShow));
	}
}

var userAgent = navigator.userAgent.toLowerCase();

jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	msie6: (jQuery.browser.msie && jQuery.browser.version =="6.0"),
	msie7: (jQuery.browser.msie && jQuery.browser.version =="7.0"),	
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

/**
 * JsCantvUtils.Player
 * Objeto de configuración para el player
 */
JsCantvUtils.Player = {
	playerId: "ctv_player",
	/**
	 * JsCantvUtils.Player.getFlashObj
	 * Devuelve el objeto flash correspondiente al identificador
	 * @param  swf - identificador del objeto flash
	 */		
	getFlashObj: function (swf) {
		if (jQuery.browser.mozilla){
			return document[swf];
		} else {
			return window[swf];
		}
	}
}

/**
 * Mensajes para clipboard en Español
 */
I18n.es.clipboard_select_text = "Selecciona el texto y presiona Crtl+C para copiar al portapapeles";
I18n.es.clipboard_text_copy = "El texto se ha copiado en el portapapeles."

/**
 * Mensajes para clipboard en Catalán
 */
I18n.ca.clipboard_select_text = "Selecciona el texto y presiona Crtl+C para copiar al portapapeles";
I18n.ca.clipboard_text_copy = "El texto se ha copiado en el portapapeles.";


/**
 * JsCantvUtils.Clipboard
 * Objeto de configuración del portapapeles
 */
JsCantvUtils.Clipboard = {
	playerId: "ctv_player",
	/**
	 * JsCantvUtils.Clipboard.copy
	 * Copia un texto al portapapeles
	 * @param  textToCopy - texto a copiar
	 */		
	copy: function (textToCopy) {
		JsCantvUtils.Player.getFlashObj(JsCantvUtils.Player.playerId).copyToClipboard(textToCopy);
	},
	/**
	 * JsCantvUtils.Clipboard.copyField
	 * Copia el valor de un campo al portapapeles
	 * @param  fieldID - identificador del campo a copiar
	 */		
	copyField: function (fieldID) {
		JsCantvUtils.Player.getFlashObj(JsCantvUtils.Player.playerId).copyToClipboard($("#"+fieldID).val());
	},
	/**
	 * JsCantvUtils.Clipboard.copyTextArea
	 * Copia el valor de una caja de texto al portapapeles
	 * @param  fieldID - identificador de la caja de texto a copiar
	 */		
	copyTextArea: function (textareaID) {
		JsCantvUtils.Player.getFlashObj(JsCantvUtils.Player.playerId).copyToClipboard($("#"+textareaID).text());
	}
}

/**
 * JsCantvUtils.ClipboardOnlyIE
 * Objeto de configuración del portapapeles
 */
JsCantvUtils.ClipboardOnlyIE = {
	/**
	 * JsCantvUtils.ClipboardOnlyIE.copyField
	 * Copia el valor de un campo al portapapeles
	 * @param  fieldID - identificador del campo a copiar
	 */		
	copyField: function (fieldID,locale) {
		if (navigator.appName=="Microsoft Internet Explorer") {
		    window.clipboardData.setData("Text", $("#"+fieldID).val()); 
		    JsCantvUtils.Messages.showMsg(I18n[locale].clipboard_text_copy);
		} 
		else {
			JsCantvUtils.Messages.showMsg(I18n[locale].clipboard_select_text);
		}
	},
	/**
	 * JsCantvUtils.ClipboardOnlyIE.copyTextArea
	 * Copia el valor de una caja de texto al portapapeles
	 * @param  fieldID - identificador de la caja de texto a copiar
	 */		
	copyTextArea: function (textareaID,locale) {
		if (navigator.appName=="Microsoft Internet Explorer") {
		    window.clipboardData.setData("Text", $("#"+textareaID).text()); 
		    JsCantvUtils.Messages.showMsg(I18n[locale].clipboard_text_copy);
		} 
		else {
			JsCantvUtils.Messages.showMsg(I18n[locale].clipboard_select_text);
		}
	}
}

/**
* Obtiene una imagen nueva del captcha
* @param {String}  id_img_captcha -  id de la imágen
* @param {String}  captcha_src -  ruta de la imagen
*/
JsCantvUtils.captcha = {
	/**
	* Crea la imagen del captcha
	* @param {Object}  properties - objeto con los atributos de la imágen  atributo: valor
	* @param {String}  elem -  id del elemento al que se le añade la imagen 
	*/
	ImageCaptcha: function (properties,elem){
	
		
		var url = properties["src"];
		var id = properties["id"];
		var elem_to_add = JsCantvUtils.idSel(elem);
	
		var img_captcha = $('<img>');
		for ( var i in properties ){
			if (i != "src"){
				img_captcha.attr(i,properties[i]);
			}
		}
		
		var f_reloadCaptcha = function (){
			JsCantvUtils.captcha.reloadCaptcha(id,url);
		};
		
		img_captcha.attr("style","border: 2px solid rgb(75, 74, 77); width: 208px;cursor: pointer;");
		img_captcha.attr("src",JsCantvUtils.urlNoCache(url));    
		img_captcha.bind("click", f_reloadCaptcha);    
		$(elem_to_add).append(img_captcha);
	},
	reloadCaptcha : function  (id_img_captcha,captcha_src) {        
		var url_load_captcha = JsCantvUtils.urlNoCache(captcha_src);
		var img_captcha = JsCantvUtils.idSel(id_img_captcha);
		$(img_captcha).hide("slow",function(){
			$(img_captcha).attr("src", url_load_captcha);
			$(img_captcha).show("slow",function(){
				$(img_captcha).css("display","inline");
			});
		});	
	}
}

/**
 * Mensajes para comentarios en Español
 */
I18n.es.comentarios_campo_nombre = "Nombre";
I18n.es.comentarios_mail_no_valido = "e-Mail no válido";
I18n.es.comentarios_campo_obligatorio = "es obligatorio";
I18n.es.comentarios_web_ko = "Dirección web no válida. Recuerda que debe empezar por http:// o similar.";
I18n.es.comentarios_obligatorio = "Debe escribir un comentario.";
I18n.es.comentarios_name_obli = "Debe escribir un nombre";
I18n.es.comentarios_send_ok= "El comentario se ha enviado correctamente";
I18n.es.comentarios_send_ko= "Se ha producido un error al enviar el comentario";
I18n.es.comentarios_captcha_oblig = "Debe introducir el código de seguridad";
I18n.es.comentarios_captcha_number = "El código de seguridad debe ser numérico";
I18n.es.comentarios_captcha_length = "El código de seguridad debe tener 7 caracteres";
I18n.es.comentarios = "COMENTARIOS";
I18n.es.comentario = "COMENTARIO";
I18n.es.comentario_user_existe = "El nombre corresponde a un usuario registrado";
I18n.es.comentario_email_existe = "El email corresponde a un usuario registrado. Identifícate, por favor";
I18n.es.comentarios_max_cars = "El comentario no puede tener más de 250 caracteres";

/**
 * Mensajes para comentarios en Catalán
 */
I18n.ca.comentarios_campo_nombre = "Nom";
I18n.ca.comentarios_mail_no_valido = "e-Mail no vàlid";
I18n.ca.comentarios_campo_obligatorio = "és obligatori";
I18n.ca.comentarios_web_ko = "Adreça web no vàlida. Recorda que ha de començar per http:// o similar.";
I18n.ca.comentarios_obligatorio = "Escriu un comentari.";
I18n.ca.comentarios_name_obli = "Escriu un nom";
I18n.ca.comentarios_send_ok= "El comentari s'ha enviat correctament";
I18n.ca.comentarios_send_ko= "S'ha produït un error en enviar el comentari";
I18n.ca.comentarios_captcha_oblig = "Cal introduir el codi de seguretat";
I18n.ca.comentarios_captcha_number = "El codi de seguretat ha de ser numèric";
I18n.ca.comentarios_captcha_length = "El codi de seguretat ha de tenir 7 caràcters";
I18n.ca.comentarios = "COMENTARIS";
I18n.ca.comentario = "COMENTARI";
I18n.ca.comentario_user_existe = "El nom correspon a un usuari registrat";
I18n.ca.comentario_email_existe = "L'email correspon a un usuario registrado. Identifica't, si et plau";
I18n.ca.comentarios_max_cars = "El comentari no pot tenir més de 250 caràcters";

/**
 * JsCantvUtils.Commenting
 * Comentarios
 */ 					
JsCantvUtils.Commenting = {};

/**
 * JsCantvUtils.Commenting
 */
JsCantvUtils.Commenting = {};

/**
 * JsCantvUtils.Commenting.comments
 * Objeto para la configuración y funciones de los comentarios
 */
JsCantvUtils.Commenting.comments = {		
	/**
	 * JsCantvUtils.Commenting.comments.cfg
	 * Configuración de los comentarios
	 */
	cfg: {
		pagesize: 5,
		target: "/commenting/commenting-system-view.jsp",
		command: JsCantvUtils.SuPath+"commands/getCommentsReal",
		comments_selector_container: "#comentarios",
		comments_selector: "#comentarios",
		form_comments_selector: "#formcommt",
		login_msg_selector:"#loginMSG"
	},
	
	/**
	 * JsCantvUtils.Commenting.comments.cfgMostRated
	 * Configuración comentario más votado
	 */
	cfgMostRated: {
		command: JsCantvUtils.SuPath+"commenting/mostRatedComment.jsp",
		method: "POST",
		most_rated_selector: "#most_rated_comment",
		question_id: CantvProperties.question_id,
		answer_id_votesup: CantvProperties.answer_id_votesup,
		answer_id_votesdown: CantvProperties.answer_id_votesdown		
	},	
	
	/**
	 * JsCantvUtils.Commenting.comments.get
	 * Obtiene los comentarios
	 * 
	 * @param itemid - identificador del contenido
	 * @param itemtype - tipología
	 * @param locale - idioma
	 * @param page - número de página
	 */			
	get: function (itemid,itemtype,locale,page){
		var cfgComments = JsCantvUtils.Commenting.comments.cfg;
		var cfgMR = JsCantvUtils.Commenting.comments.cfgMostRated;
		var params = {ITEMID:itemid, ITEMTYPE:itemtype, LANGUAGE:locale, hiTarget:cfgComments.target, 
				pagesize: cfgComments.pagesize, page:page, question: cfgMR.question_id, 
				answeridup: cfgMR.answer_id_votesup, answeriddown: cfgMR.answer_id_votesdown, nocache:JsCantvUtils.timestamp()
		};
		$.get(cfgComments.command,params,function(data,status){
			if (status == "success"){
				//$(cfgComments.comments_selector+" > *").remove()
				//$(cfgComments.comments_selector).append(data);
				document.getElementById('comentarios').innerHTML = data;
			}
		});
	},
	
	/**
	 * JsCantvUtils.Commenting.comments.getNoCache
	 * Obtiene los comentarios sin utilizar la caché
	 * 
	 * @param itemid - identificador del contenido
	 * @param itemtype - tipología
	 * @param locale - idioma
	 * @param page - número de página
	 */			
	getNoCache: function (itemid,itemtype,locale,page){
		var cfgComments = JsCantvUtils.Commenting.comments.cfg;
		var cfgMR = JsCantvUtils.Commenting.comments.cfgMostRated;
		var params = {ITEMID:itemid, ITEMTYPE:itemtype, LANGUAGE:locale, hiTarget:cfgComments.target, 
				pagesize: cfgComments.pagesize, page:page, question: cfgMR.question_id, 
				answeridup: cfgMR.answer_id_votesup, answeriddown: cfgMR.answer_id_votesdown, cache:"false", nocache:JsCantvUtils.timestamp()
		};
		$.get(cfgComments.command,params,function(data,status){
			if (status == "success"){
				$(cfgComments.comments_selector+" > *").remove()
				$(cfgComments.comments_selector).append(data);
			}
		});
	},	
	
	
	/**
	 * JsCantvUtils.Commenting.comments.numComments
	 * Obtiene el número de comentarios 
	 * 
	 * @param itemid - identificador del contenido
	 * @param itemtype - tipología
	 * @param locale - idioma
	 * @param target - id de la capa en la que se pone el numero de comentarios. Si no se especifica.
	 * La función hace un return con el numero de comentarios
	 */
	 numComments: function (itemid,itemtype,locale,target,span){
	 
	 	var totalret = 0;
	 
	 	$.ajax({
			type: "GET",
			url: "/su/services/getComments?ITEMID=" + itemid + "&ITEMTYPE=" + itemtype + "&LANGUAGE=" + locale + "&page=1&pagesize=0",
			dataType: "xml",
			success: function(xml){
				 $(xml).find('list').each(function(){
					var total = $(this).attr("totalItems");
					
					if(total==1){
						if(span){
							$("#"+target).html("<span class='Negrita'>" + total + "</span> " + I18n[locale].comentario);
						}else{
							$("#"+target).html(total + " " + I18n[locale].comentario);
						}
					}else{
						if(span){
							$("#"+target).html("<span class='Negrita'>" + total + "</span> " + I18n[locale].comentarios);
						}else{
							$("#"+target).html(total + " " + I18n[locale].comentarios);
						}
					}
				 });
			},
			error: function(){
				if(span){
					$("#"+target).html("<span class='Negrita'>0</span> " + I18n[locale].comentarios);
				}else{
					$("#"+target).html("0 " + I18n[locale].comentarios);
				}
			}
		});
	 },
	/**
	 * JsCantvUtils.Commenting.comments.LoginReq
	 * Función que comprueba si el usuario está logado y muestra el formulario de comentarios si es así
	 */			
	LoginReq: function (){
		var cfg = JsCantvUtils.Commenting.comments.cfg;
		//$(cfg.form_comments_selector).hide();	
		$(cfg.login_msg_selector).remove();
	    $.ajax({
	        type: "GET",
	        url: JsCantvUtils.SuPath+"services/getUser",
	        dataType: "xml",
	        success: function(xml){
				 $(xml).find('user ').each(function(){	
	                 var nick = $(this).find('nick').text();
	                 var email = $(this).find('email').text();	                 
	                 var web = $(this).find('web').text();
					 $("#COMMENT_NAME").val(nick);
					 $("#COMMENT_NAME").attr('readonly', true);
					 $("#COMMENT_MAIL").val(email);
					 $("#COMMENT_MAIL").attr('readonly', true);
					 $("#COMMENT_URL").val(web);
				 });
//	    		$(cfg.login_msg_selector).remove();
	    		$(cfg.form_comments_selector).show();	
	        }
	     });
	}
}

/**
 * JsCantvUtils.Commenting.form
 * Formulario de comentarios
 */ 
JsCantvUtils.Commenting.form = {
	/**
	 * JsCantvUtils.Commenting.form.cfg
	 * Configuración del formulario de comentarios
	 */ 		
	cfg: {
		id: "form_comments",
		id_personal_data: "comments_userdates",
		action: JsCantvUtils.SuPath+"commands/addComment",
		method: "POST",
		fields_validate: [
			["COMMENT_CONTENTTYPE"],
			["COMMENT_CONTENTID"],
			["LANGUAGE"],
			["COMMENT_NAME","validaName"],
			["COMMENT_MAIL","validaMail"],
			["COMMENT_URL","validaWeb"],
			["COMMENT_TEXT","commentNotEmpty"],
			["CAPTCHA_RESPONSE","validaCaptcha"]
		],
		fields_clean: [ "COMMENT_TEXT",
						"CAPTCHA_RESPONSE"
					   ],
		validate_funcs_namespace: "JsCantvUtils.Commenting.form.validate_functions.",
		textAreaClicked: false
	},
	/**
	 * JsCantvUtils.Commenting.form.validate_functions
	 * Funciones de validación para el formulario de comentarios
	 */ 			
	validate_functions: {
		validaName: function(field_value,locale){
			if ((field_value)!=""){
				if (JsCantvUtils.Commenting.form.validate_functions.validaNoVacio(field_value)){
					return false;
				}
			}
			return I18n[locale].comentarios_name_obli;
		},		
		commentNotEmpty: function(field_value,locale){
			if ((field_value)!=""){
				if (JsCantvUtils.Commenting.form.validate_functions.validaNoVacio(field_value)){
					if(JsCantvUtils.Commenting.form.cfg.textAreaClicked){
						if (field_value.length > 250){
							return I18n[locale].comentarios_max_cars;
						}
						return false;
					}
				}
			}
			return I18n[locale].comentarios_obligatorio;
		},
		validaMail: function(field_value,locale){
			if ((field_value)!=""){
				if(field_value.indexOf(".") <= 2 || field_value.indexOf("@") <= 0){
					return I18n[locale].comentarios_mail_no_valido;
				}
				return false;
			}
			return I18n[locale].comentarios_mail_no_valido;	
		},
		validaCaptcha: function(field_value,locale){		
			if(field_value.length < 1 ){
				return I18n[locale].comentarios_captcha_oblig;
			}
			if (!/^([0-9])*$/.test(field_value)){
				return I18n[locale].comentarios_captcha_number;
			}	
			if (field_value.length != 7){		
				return I18n[locale].comentarios_captcha_length;
			}			
			return false;	
		},
		validaWeb : function(field_value,locale){
			if ((field_value)!=""){
				var webaddrvalidator= /http:\/\/|https:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
				if (!webaddrvalidator.test(field_value))
				{
					return I18n[locale].comentarios_web_ko;
				}
			}
			return false;
		},
		validaNoVacio: function (field_value) {
			 var field = field_value.replace(new RegExp('\\n','g'),' ').replace(new RegExp('\\r','g'),' ');
			 for (i = 0; i < field.length; i++ ) {  
		         if ( field.charAt(i) != " ") {  
		                 return true;
		         }
			 }
			 return false;
		 }
	},
	/**
	 * JsCantvUtils.Commenting.form.send
	 * Envío del formulario de comentarios
	 */ 			
	send: function (locale,itemid,itemtype,page){
		var cfg = JsCantvUtils.Commenting.form.cfg;
		var valid = true;
		var data = "";
		for (i in cfg.fields_validate){
			if (valid){
				var field_name = cfg.fields_validate[i][0];
				var field_value = $("#"+field_name).val();
				var sep_param = (cfg.fields_validate.length==parseInt(i)+1)?"":"&";
				data = data+field_name+"="+field_value+sep_param;
				if (typeof cfg.fields_validate[i][1] != 'undefined'){
					var validate_func = eval(cfg.validate_funcs_namespace+cfg.fields_validate[i][1]);
					var error = validate_func(field_value,locale);
					if (error)
					{
						valid = false;
						alert(error);
					}
				}			
			}
		}
		if (valid){
			JsCantvUtils.Commenting.form.submit(data,cfg,locale,itemid,itemtype,page);
		}
		return false;
	},
	/**
	 * JsCantvUtils.Commenting.form.submit
	 * Submit del formulario de comentarios
	 */ 			
	submit:function(data,cfg,locale,itemid,itemtype,page){
		$.ajax({
			type: cfg.method,
			url: cfg.action,
			data: data,
			contentType: "application/x-www-form-urlencoded;charset=utf-8",	
			success: function(){
				alert(I18n[locale].comentarios_send_ok);
				JsCantvUtils.Commenting.comments.getNoCache(itemid,itemtype,locale,page);
				JsCantvUtils.Commenting.form.clean();
				JsCantvUtils.captcha.reloadCaptcha("img_captcha","/su/captcha");
			},
			error: function(data){
				var errorsMsgs = new Array()
				var errorCode= $("#exception_code",data.responseText).val();
				if (errorCode == 'ERR_NICK_ALREADY_IN_USE'){
					errorsMsgs.push(I18n[locale].comentario_user_existe);
				}
				else if (errorCode == 'ERR_EMAIL_ALREADY_IN_USE'){
					errorsMsgs.push(I18n[locale].comentario_email_existe);
				}	
				else{
					errorsMsgs.push(I18n[locale].comentarios_send_ko);
				}	
				JsCantvUtils.Messages.showMsg(errorsMsgs);
			}
		});
	},
	/**
	 * JsCantvUtils.Commenting.form.clean
	 * Limpia los campos del formulario de comentarios
	 */ 				
	clean: function(){
		var cfg = JsCantvUtils.Commenting.form.cfg;
		for (i in cfg.fields_clean){
			var field_name = cfg.fields_clean[i];
			$("#"+field_name).val("");
		}
		return false;
	},
	/**
	 * JsCantvUtils.Commenting.form.cleanTextArea
	 * Habilita los campos para los datos personales del formulario de comentarios
	 */
	cleanTextArea: function (){
		$("#COMMENT_TEXT").val("");
		$("#COMMENT_TEXT").attr("onclick","");
		JsCantvUtils.Commenting.form.cfg.textAreaClicked = true;
	},
	
	/**
	 * JsCantvUtils.Commenting.form.showForm
	 * Muestra el formulario de comentarios
	 */
	show: function (cont_id){
		JsCantvUtils.Show(cont_id);
	},
	
	/**
	 * JsCantvUtils.Commenting.form.initForm
	 * Inicia el formulario
	 */
	initForm: function (){
		$("#COMMENT_TEXT").val("");
		$("#COMMENT_TEXT").attr("onclick","");
	}						
}

/**
 * Mensajes para votaciones en Español
 */
I18n.es.voting_vote_ok = "Su voto se ha computado correctamente";
I18n.es.voting_vote_ko = "No se ha podido computar el voto";
I18n.es.voting_vote_ko_alredy_vote = " ya se ha registrado un voto para el contenido desde esta dirección.";

/**
 * Mensajes para votaciones en Catalán
 */
I18n.ca.voting_vote_ok = "El seu vot s'ha computat correctament";
I18n.ca.voting_vote_ko = "No s'ha pogut computar el vot";
I18n.ca.voting_vote_ko_alredy_vote = " ja s'ha registrat un vot per al contingut des d'aquesta direcció.";

/**
 * JsCantvUtils.Voting
 */
JsCantvUtils.Voting = {
	cfg:{
		getVotesCommand: JsCantvUtils.SuPath+"services/interactive/votes",
		getVotesCommentsCommand: JsCantvUtils.SuPath+"services/interactive/ranking",
		addVoteCommand: JsCantvUtils.SuPath+"commands/interactive/participate",
		getVotesCommentCommand: JsCantvUtils.SuPath+"commenting/getRateComment.jsp",
		method: "POST",
		interactive_id: CantvProperties.interactive_id,
		question_id: CantvProperties.question_id,
		votesup_id: "votesup",
		votesdown_id: "votesdown",
		votesup_comm_id: "votesupcomm",
		votesdown_comm_id: "votesdowncomm",		
		answer_id_votesup: CantvProperties.answer_id_votesup,
		answer_id_votesdown: CantvProperties.answer_id_votesdown,
		offensive_id_votes: CantvProperties.offensive_id_votes,
		alredy_vote_error_code: "ERR_INTERACTIVE_ALREADY_VOTE",
		exception_code_id: "exception_code",
		itemTypeComments: "T_SRVD_COMMENTIN"
	}
};

/**
 * JsCantvUtils.Voting.getVotes
 */
JsCantvUtils.Voting.getVotes = function (cfg,itemid,itemtype){
	$.ajax({
		type: cfg.method,
		url: cfg.getVotesCommand,
		data: { interactive:cfg.interactive_id, question:cfg.question_id, itemid:itemid, itemtype:itemtype},
		dataType: "xml",
		success: function(xml){
			 $(xml).find('answer').each(function(){
                 var answer_id = $(this).find('id').text();
                 var numVotes = $(this).find('votes').text();
                 if (answer_id == cfg.answer_id_votesup){
                	 $("#"+cfg.votesup_id+itemid+" > span").text("+"+numVotes);
                 } 
                 if (answer_id == cfg.answer_id_votesdown){
                	 $("#"+cfg.votesdown_id+itemid+" > span").text("-"+numVotes);
                 } 
			 });
		},
		error: function(){}
	});
}

/**
 * JsCantvUtils.Voting.addVote
 */
JsCantvUtils.Voting.addVote = function (cfg,itemid,itemtype,up,locale){
	$.ajax({
		type: cfg.method,
		url: cfg.addVoteCommand,
		data: { interactive:cfg.interactive_id, question:cfg.question_id, itemid:itemid, itemtype:itemtype, 
				answer:up?cfg.answer_id_votesup:cfg.answer_id_votesdown
		},
		success: function(){
			JsCantvUtils.Messages.showMsg(I18n[locale].voting_vote_ok);
			JsCantvUtils.Voting.getVotes(cfg, itemid, itemtype);	
		},
		error: function(data){
			var errorsMsgs = new Array()
			errorsMsgs.push(I18n[locale].voting_vote_ko);
			var errorCode= $("#"+cfg.exception_code_id,data.responseText).val();
			if (errorCode == cfg.alredy_vote_error_code){
				errorsMsgs.push(I18n[locale].voting_vote_ko_alredy_vote);
			}	
			JsCantvUtils.Messages.showMsg(errorsMsgs);
		}
	});
}

/**
 * JsCantvUtils.Voting.getVotesComments
 */
JsCantvUtils.Voting.getVotesComments = function (cfg,interactiveType,interactive){
	$.ajax({
		type: cfg.method,
		url: cfg.getVotesCommentsCommand,
		data: { itemtype:cfg.itemTypeComments, question:cfg.question_id, interactiveType:interactiveType, interactive:interactive},
		dataType: "xml",
		success: function(xml){
			 $(xml).find('participant').each(function(){
				 var item_id = $(this).find('item').find('id').text();		 
				 if ($("#"+cfg.votesup_comm_id+item_id).length > 0){
					 $(this).find('answer').each(function(){
						 var answer_id = $(this).find('id').text();
						 var numVotes = $(this).find('votes').text();
		                 if (answer_id == cfg.answer_id_votesup){
		                	 $("#"+cfg.votesup_comm_id+item_id+" > span").text("(+"+numVotes);
		                 } 
		                 if (answer_id == cfg.answer_id_votesdown){
		                	 $("#"+cfg.votesdown_comm_id+item_id+" > span").text("-"+numVotes);
		                 }				 
					 });
				 }
			 });
		},
		error: function(){}
	});
}

/**
 * JsCantvUtils.Voting.getVotesComment
 */
JsCantvUtils.Voting.getVotesComment = function (cfg, locale, comment, interactive, up){
	
	var answer = up?cfg.answer_id_votesup:cfg.answer_id_votesdown;
	
	$.ajax({
		type: cfg.method,
		url: cfg.getVotesCommentCommand,
		data: {LANGUAGE:locale, comment:comment, interactive:interactive, question:cfg.question_id, answer:answer},
		dataType: "text/plain",
		success: function(text){
			var numVotes = $.trim(text);
            if (answer == cfg.answer_id_votesup){
            	var votesUp = $("#"+cfg.votesup_comm_id+comment+" > span");
        		if (votesUp.text()[0]== "("){
        			votesUp.text("(+"+numVotes);
        		}
        		else{
        			votesUp.text("+ "+numVotes+" ");
        		}
            } 
            if (answer == cfg.answer_id_votesdown){
            	var votesDown = $("#"+cfg.votesdown_comm_id+comment+" > span");
        		if (votesDown.text()[0]== "-"){
        			votesDown.text("-"+numVotes);
        		}
        		else{
        			votesDown.text(numVotes);
        		}
            }
		},
		error: function(){}
	});
}


/**
 * JsCantvUtils.Voting.addVoteComment
 */
JsCantvUtils.Voting.addVoteComment = function (cfg,interactive,interactiveType,itemid,up,locale){

	if (JsCantvUtils.isUserLogged())
	{
		$.ajax({
			type: cfg.method,
			url: cfg.addVoteCommand,
			data: { interactive:interactive, interactiveType:interactiveType, question:cfg.question_id, itemid:itemid, itemtype:cfg.itemTypeComments, 
					answer:up?cfg.answer_id_votesup:cfg.answer_id_votesdown
			},
			success: function(){
				JsCantvUtils.Messages.showMsg(I18n[locale].voting_vote_ok);	
				JsCantvUtils.Voting.getVotesComment(cfg, locale, itemid, interactive, up);							
				//JsCantvUtils.Voting.getVotesComments(cfg, interactiveType, interactive );	
			},
			error: function(data){
				var errorsMsgs = new Array()
				errorsMsgs.push(I18n[locale].voting_vote_ko);
				var errorCode= $("#"+cfg.exception_code_id,data.responseText).val();
				if (errorCode == cfg.alredy_vote_error_code){
					errorsMsgs.push(I18n[locale].voting_vote_ko_alredy_vote);
				}	
				JsCantvUtils.Messages.showMsg(errorsMsgs);
			}
		});
	}
	else {
		JsCantvUtils.showLoginRequired(locale);
	}
}

/**
 * JsCantvUtils.Voting.addOffensiveVoteComment
 */
JsCantvUtils.Voting.addOffensiveVoteComment = function (cfg,interactive,interactiveType,itemid,locale){
	
	if (JsCantvUtils.isUserLogged())
	{
		$.ajax({
			type: cfg.method,
			url: cfg.addVoteCommand,
			data: { interactive:interactive, interactiveType:interactiveType, question:cfg.question_id, itemid:itemid, itemtype:cfg.itemTypeComments, 
					answer:cfg.offensive_id_votes
			},
			success: function(){
				JsCantvUtils.Messages.showMsg(I18n[locale].voting_vote_ok);
			},
			error: function(data){
				var errorsMsgs = new Array()
				errorsMsgs.push(I18n[locale].voting_vote_ko);
				var errorCode= $("#"+cfg.exception_code_id,data.responseText).val();
				if (errorCode == cfg.alredy_vote_error_code){
					errorsMsgs.push(I18n[locale].voting_vote_ko_alredy_vote);
				}	
				JsCantvUtils.Messages.showMsg(errorsMsgs);
			}
		});
	}
	else {
		JsCantvUtils.showLoginRequired(locale);
	}
}

/**
 * JsCantvUtils.ReplaceDOMElement
 * Función para reemplazar un elemento del DOM
 * 
 * @param elemID - identificador del elemento a reemplazar
 * @param elemPath - ruta desde la que se obtiene el nuevo elemento
 */
JsCantvUtils.ReplaceDOMElement = function (elemID, elemPath){
	
	$.ajax({
			type: "GET",
			url: elemPath,
			success: function(data){
				$("#"+elemID).replaceWith(data);
			}
		});
}

/**
 * JsCantvUtils.ReplaceHTML
 * Función para reemplazar html de una capa
 * 
 * @param elemID - identificador del elemento a reemplazar
 * @param elemPath - ruta desde la que se obtiene el nuevo elemento
 */
JsCantvUtils.ReplaceHTML = function (elemID, elemPath){
	if($.browser.msie){
		$.ajax({
			type: "GET",
			url: elemPath,
			success: function(data){
				document.getElementById(elemID).innerHTML = data;
				$("#"+elemID).html(data);
			}
		});
	}else{
		$.ajax({
			type: "GET",
			url: elemPath,
			success: function(data){
				$("#"+elemID).html(data);
			}
		});
	}
}

/**
 * JsCantvUtils.ChangeTab
 * Función para cambiar de pestaña en mediateca
 * 
 * @param elemID - identificador del elemento a reemplazar
 * @param elemPath - ruta desde la que se obtiene el nuevo elemento
 */
JsCantvUtils.ChangeTab = function (elemID, elemPath, submenuID, submenuPath){
	
	if(typeof(elemID)!= 'undefined' && typeof(elemPath)!= 'undefined'){
		$.ajax({
			type: "GET",
			url: elemPath,
			success: function(data){
				$("#"+elemID).html(data);
			},
			error: function(){
				$("#"+elemID).html("<div class='listado'><div class='controlbar'><hr/></div></div>");
			}
		});
	}
	
	if(typeof(submenuID)!= 'undefined' && typeof(submenuPath)!= 'undefined'){
		$.ajax({
			type: "GET",
			url: submenuPath,
			success: function(data){
				$("#"+submenuID).html(data);
			}
		});
	}
}


JsCantvUtils.SelectTab = function (tabId){
	$("#menu_mediateca > ul > li[id]").attr("class","");
	$("#menu_mediateca > ul > li#"+tabId).attr("class","selected");
}

JsCantvUtils.SelectSubTab = function (subtabId){
	$("#submenu_mediatec > ul > li[id]").attr("class","");
	$("#submenu_mediatec > ul > li#"+subtabId).attr("class","selected");
}

JsCantvUtils.SelectSubTabHSV = function (subtabId){
	$("#submenu_hsv > ul > li[id]").attr("class","");
	$("#submenu_hsv > ul > li#"+subtabId).attr("class","selected");
}

JsCantvUtils.showPopup = function (id_popup,locale){
	var popups = CantvProperties.popups_no_login_required;
	var need_login = true;
	for (var i=0; i < popups.length; i++) {
		if (popups[i] == id_popup) {
			need_login = false;
		}
	}
	if (need_login){
		if (JsCantvUtils.isUserLogged())
		{
			document.getElementById(id_popup).style.display='inline';
		}
		else {
			JsCantvUtils.showLoginRequired(locale);
		}		
	}else {
		document.getElementById(id_popup).style.display='inline';
	}
}

JsCantvUtils.share = function(service, locale){

	var shareURL = "";
	var URL = window.document.location.href;
	var doShare = true;

	//eliminar # del final
	if (URL.charAt(URL.length-1) == "#")
	{
		URL = URL.substring(0,URL.length-1);
	}
	
	var titleURL = encodeURIComponent(window.document.title);

	if (service == 'facebook') {
		shareURL = 'http://www.facebook.com/sharer.php?u='+URL;	
	}
	else if (service == 'google') {
		shareURL = 'http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk='+ URL +'&title=' + titleURL;
	}
	else if (service == 'netvibes') {
		shareURL = 'http://www.netvibes.com/subscribe.php?url='+URL;	
	}
	else if (service == 'digg') {
		shareURL = 'http://digg.com/submit?phase=2&url='+URL+'&title='+titleURL;
	}
	else if (service == 'delicious') {
		shareURL = 'http://del.icio.us/post?title='+titleURL+'&url='+URL;
	}
	else if (service == 'meneame') {
		shareURL = 'http://meneame.net/submit.php?url='+URL;
	}
	else if (service == 'twitter') {
		shareURL = 'http://twitter.com/home?status='+URL;
	}
	/*	
	else if (service == 'myspace') {
		shareURL = 'http://www.myspace.com/Modules/PostTo/Pages/?u='+URL;		
	} 	
	} else if (service == 'furl') {
		shareURL = 'http://www.furl.net/storeIt.jsp?u='+URL;
	} 
	} 
	} else if (service == 'technorati') {
		shareURL = 'http://www.technorati.com/faves?add='+URL;
	}*/

	//if (JsCantvUtils.isUserLogged())
	//{
		if (shareURL != "") {
			window.open(shareURL);
		}
	//}
	//else {
		//JsCantvUtils.showLoginRequired(locale);
	//}
}


JsCantvUtils.Rating = {};


/**
 * Mensajes votos ESPAÑOL
 */
I18n.es.puntua_ok = "Tu puntuación ha sido registrada";
I18n.es.puntua_ko = "No ha sido posible registrar tu votación";
I18n.es.puntua_max = "No se puede votar más de una vez";

/**
 * Mensajes votos CATALAN
 */
I18n.ca.puntua_ok = "Tu puntuación ha sido registrada[falta traducir]";
I18n.ca.puntua_ko = "No ha sido posible registrar tu votación [falta traducir]";
I18n.ca.puntua_max = "No se puede votar más de una vez [falta traducir]";


JsCantvUtils.Rating.getRating = function(itemtype, itemid, locale, target){

	$.ajax({
			type: "GET",
			url: "/su/services/getRating?ITEMID=" + itemid + "&ITEMTYPE=" + itemtype + "&LANGUAGE=" + locale,
			dataType: "xml",
			success: function(xml){
				 $(xml).find('float').each(function(){
					var total = $(this).text();
				
					var result = JsCantvUtils.Rating.convert(Math.round(total));		
				
					var elemento = document.getElementById(target);
					elemento.className = "actualrating " + result;
						 				 
				 });
			},
			error: function(){
				//no cargar
			}
		});
}

JsCantvUtils.Rating.rates = [];
JsCantvUtils.Rating.regVote = function(locale,itemid,itemtype){
	JsCantvUtils.Rating.rates[locale+itemid+itemtype] = true;
}

JsCantvUtils.Rating.voted = function(locale,itemid,itemtype){
	if (JsCantvUtils.Rating.rates[locale+itemid+itemtype]){
		JsCantvUtils.Messages.showMsg(I18n[locale].puntua_max);
		return false
	}
	return true;
}

//http://dev-tvcan.communi.tv/su/services/addVote?ITEMID=20&ITEMTYPE=CONTENT&ITEMRATE=1
JsCantvUtils.Rating.rate = function(itemtype, itemid, locale, target, stars){
	if (JsCantvUtils.isUserLogged())
	{
		if (JsCantvUtils.Rating.voted(locale,itemid,itemtype))
		{
			$.ajax({
				type: "GET",
				url: "/su/services/addVote?ITEMID=" + itemid + "&ITEMTYPE=" + itemtype + "&LANGUAGE=" + locale + "&ITEMRATE=" + stars,
				dataType: "xml",
				success: function(){
				 	 JsCantvUtils.Rating.regVote(locale,itemid,itemtype);
					 JsCantvUtils.Messages.showMsg(I18n[locale].puntua_ok);
					 JsCantvUtils.Rating.getRating(itemtype,itemid,locale,target);
				},
				error: function(data){
					var errorCode = "";
					 $(data.responseXML).find('code').each(function(){
							errorCode = $(this).text();
					 });
					if (errorCode == "ERR_VOTE_ALREADY_VOTE"){
						JsCantvUtils.Messages.showMsg(I18n[locale].puntua_max);
					}
					else{
						JsCantvUtils.Messages.showMsg(I18n[locale].puntua_ko);
					}
				}
			});
		}
	}
	else {
		JsCantvUtils.showLoginRequired(locale,"rate");
	}
}

JsCantvUtils.Rating.convert = function(valor){
	
	if(valor==1)
		return "uno";
	else if(valor==2)
		return "dos";
	else if(valor==3)
		return "tres";
	else if(valor==4)
		return "cuatro";
	else if(valor==5)
		return "cinco";
		
	return "cero";
}


/**
 * JsCantvUtils.Stats
 * para sacar el numero de reproducciones
 */

I18n.es.reproducciones = "REPRODUCCIONES";
I18n.es.reproduccion = "REPRODUCCION";

JsCantvUtils.Stats = {};


JsCantvUtils.Stats.getStarts = function(mmId,capaId,text,locale){
	
	$.ajax({
		type: "GET",
		url: "/stats/services/getCounter?refContentId=" + mmId + "&type=NUM_STARTS",
		dataType: "xml",
		success: function(xml){
			 $(xml).find('long').each(function(){
				var total = $(this).text();
				
				if(text){
					if(total==1){
						$("#"+capaId).html(total + " " + I18n[locale].reproduccion);
					}else{
						$("#"+capaId).html(total + " " + I18n[locale].reproducciones);
					}
				}
				else{
					if(total==1){
						$("#"+capaId).html(total);
					}else{
						$("#"+capaId).html(total);
					}
				}
			 });
		},
		error: function(){
			
			if(text){
				$("#"+capaId).html("0 " + I18n[locale].reproducciones);
			}
			else{
				$("#"+capaId).html("0");
			}
			
		}
	});
	
}

/**
 * JsCantvUtils.Popups
 * Funciones para popups
 */
JsCantvUtils.Popups = {
	ShowEmbed: function (){
		try
		  {
			JsCantvUtils.Player.getFlashObj(JsCantvUtils.Player.playerId).getEmbed();
		  }
		catch(err){}
			document.getElementById('popembedall').style.display='inline';
			if (jQuery.browser.msie6){
				$("#popembedall").show();
			}
		if (jQuery.browser.mozilla || jQuery.browser.safari || jQuery.browser.opera || jQuery.browser.chrome){
			JsCantvUtils.clipboardCopiarInit();
		}
	},
	ShowPopupUrl: function(){
		$("#ENLAZAR_VIDEO").text(document.location.href);
		document.getElementById('popurlall').style.display='inline';
		if (jQuery.browser.msie6){
			$("#popurlall").show();
		}
		if (jQuery.browser.mozilla || jQuery.browser.safari || jQuery.browser.opera || jQuery.browser.chrome){
			JsCantvUtils.clipboardEnlazarInit();
		}
	}
}

/**
 * JsCantvUtils.AdjustAdemasCan
 * Funcion para adaptar el módulo de además en CAN cuando tenga menos de n elementos
 */
JsCantvUtils.AdjustAdemasCan = function (id_ademas_can,num_elements){	
	if ($("#"+id_ademas_can+" .video").length < num_elements) {
		$("#"+id_ademas_can).css("height","100%");
		$("#"+id_ademas_can).css("height","100%");
		$("#"+id_ademas_can).css("max-height","250px");
		$("#"+id_ademas_can).css("margin-bottom","10px");
		$("#"+id_ademas_can+" .jScrollPaneContainer").css("height","100%");
		$("#"+id_ademas_can+" .jScrollPaneContainer").css("max-height","193px");
		$("#"+id_ademas_can+" #scrollable2").css("height","100%");
		$("#"+id_ademas_can+" #scrollable2").css("max-height","193px");
		$("#"+id_ademas_can+" #scrollable2 .video").removeClass("video").addClass("videomin");
	}
}

/**
 * setEmbed
 * Copia el código del embed en la caja de texto
 * (Se llama desde el player)
 */
function setEmbed(embedTxt)
{
	$("#COPIAR_VIDEO").text(embedTxt);
}

/**
 * setHD
 * Función que abre el lightbox con 
 * el player y el presset de HD
 * (Se llama desde el player)
 */
function setHD(videoID, locale)
{	
	var urlPlayerHD = "/"+locale+"/hd_video"+JsCantvUtils.HasFiles.hash(videoID,2)+"hd-"+videoID+".shtml";
	
	$("<a href='"+urlPlayerHD+"'></a>").fancybox(
			{
				'frameWidth'			: 970,
				'frameHeight'			: 550,
				'overlayShow'			: true,
				'hideOnContentClick'	: false			
			}
		).trigger('click');	
	
	$("#fancy_overlay").css("opacity","0.75");
	$("#fancy_overlay").css("background-color","#000000");
	$("#fancy_overlay").css("display","block");
}
JsCantvUtils.search = function (w,campo){	
	
	
	if (w == undefined || w == null || w == ""){
		where = "form1s";
	}else{
		where = w;
	}
	
	if(campo == undefined || campo == null || campo == ""){
		campo = "q";
	}
	
	valor_campo=$('#'+campo).val();
	
	if (valor_campo.indexOf("...")>0){
		$("#"+campo).val('')
	}
	
	$("#"+where).submit();
}

/**
 * JsCantvUtils.addRelatedElement
 * Añade un elemento a la lista de relacionados
 */
JsCantvUtils.addRelatedElement = function (element,locale){
	var relatedHtml = "<div class=\"video orange\">"
			+"<a href=\""+element.url+"\" rel=\"nofollow\">"
			+"<img src=\""+element.image+"\" alt=\""+element.alt+"\"></a>"
			+"<p class=\"title\"><a href=\""+element.url+"\" title=\""+element.seo_title+"\">"+element.title+"</a></p>"
			+"<p id=\""+element.id_content+"_conPlay_"+element.id_asset+"\">0 "+I18n[locale].reproducciones+"</p>"
			+"<span>"+element.date+"&nbsp; |</span>"
			+"<div class=\"rating\"><div class=\"actualrating cero\" id=\"related_"+element.id_content+"\"></div></div>";
	$("#scrollable").append(relatedHtml);
	JsCantvUtils.Stats.getStarts(element.id_asset,element.id_content+"_conPlay_"+element.id_asset,true,element.locale);
	JsCantvUtils.Rating.getRating('CONTENT',element.id_content,element.locale,"related_"+element.id_content,1);
}

/**
 * JsCantvUtils.addRelatedElementChannel
 * Añade un elemento a la lista de relacionados
 */
JsCantvUtils.addRelatedElementChannel = function (element,locale){
	var relatedHtml = "<div class=\"video new\">"
			+"<a href=\""+element.url+"\" rel=\"nofollow\">"
			+"<img src=\""+element.image+"\" alt=\""+element.alt+"\"></a>"
			+"<p class=\"title\"><a href=\""+element.url+"\" title=\""+element.seo_title+"\">"+element.title+"</a></p>"
			+"</div>";
	$("#scrollable2").append(relatedHtml);
}

/**
 * JsCantvUtils.addRelatedContent
 * Busca contenidos en los ficheros de categorías y los añade a la lista de relacionados
 * hasta llegar al número indicado
 */
JsCantvUtils.addRelatedContent = function (id_content,categ_list,manual_contents_list,num_elements_to_add,num_categ,elements_to_add,locale,related_contents_categ_list_path,related_position){
	if ((num_elements_to_add > 0) && (num_categ < categ_list.length)){
		var categNameFile = categ_list[num_categ]+".inc";
		var related_contents_categ_list_file = related_contents_categ_list_path+categNameFile;
		$.ajax({
			type: "GET",
			url: related_contents_categ_list_file,
			dataType: "json",
			success: function (categ_file){	
				var i = 0;
				while ((num_elements_to_add > 0) && (i<categ_file.length)){
					var element = categ_file[i];
					if ((element.id_content != id_content)  && ($.inArray(element.id_content,manual_contents_list) == -1)){
						elements_to_add[elements_to_add.length] = element;
						manual_contents_list[manual_contents_list.length] = element.id_content;
						num_elements_to_add--;
					}
					i++;
				}	
				var numCat = num_categ + 1;
				JsCantvUtils.addRelatedContent(id_content,categ_list,manual_contents_list,num_elements_to_add,numCat,elements_to_add,locale,related_contents_categ_list_path,related_position);
			},
			error: function (){
				var numCat = num_categ + 1;
				JsCantvUtils.addRelatedContent(id_content,categ_list,manual_contents_list,num_elements_to_add,numCat,elements_to_add,locale,related_contents_categ_list_path,related_position);
			}
		 });
	}
	else{
		var related_scroll="scrollable_relateds";
		var scroll_id="scrollable";
		if (related_position == "channel"){
			related_scroll="scrollable2_relateds";
			scroll_id="scrollable2";
		}
		
		for (var j=0;j<elements_to_add.length;j++){
			if (related_position == "channel")
				JsCantvUtils.addRelatedElementChannel(elements_to_add[j],locale);
			else
				JsCantvUtils.addRelatedElement(elements_to_add[j],locale);
		}
		
		if (elements_to_add.length > 0){
			if ($("#"+related_scroll).css("display") == "none")
			{
				$("#"+related_scroll).show("fast",function () {					
					if (!jQuery.browser.msie6){
						$("#"+scroll_id).jScrollPane({scrollbarWidth:17});
					}
					if (related_position == "channel"){
						JsCantvUtils.AdjustAdemasCan("scrollable2_relateds",3); 
					}
				});
			}		
			else {
				if (!jQuery.browser.msie6){
					$("#"+scroll_id).jScrollPane({scrollbarWidth:17});
				}	
				if (related_position == "channel"){
					JsCantvUtils.AdjustAdemasCan("scrollable2_relateds",3); 
				}
			}
		}
	}
}
/**
 * JsCantvUtils.addRelatedContents
 * Añade contenidos a la lista de relacionados
 * @param id_content - identificador del contenido
 * @param categ_list - lista de categorías
 * @param manual_contents_list - lista de contenidos relacionados manuales
 * @param num_elements - número total de contenidos relacionados a mostrar
 * @param locale - idioma
 */
JsCantvUtils.addRelatedContents = function (id_content,categ_list,manual_contents_list,num_elements,locale){
	var num_categ = 0;
	var elements_to_add = [];
	var num_elements_to_add = num_elements - manual_contents_list.length;
	var related_contents_categ_list_path = "/"+locale+"/listados_tag/";
	
	if (num_elements_to_add > 0){
		JsCantvUtils.addRelatedContent(id_content,categ_list,manual_contents_list,num_elements_to_add,num_categ,elements_to_add,locale,related_contents_categ_list_path,"other");
		
	}
}

/**
 * JsCantvUtils.addRelatedContentsCANChannel
 * Añade contenidos a la lista de relacionados
 * @param id_content - identificador del contenido
 * @param categ_list - lista de categorías
 * @param manual_contents_list - lista de contenidos relacionados manuales
 * @param num_elements - número total de contenidos relacionados a mostrar
 * @param locale - idioma
 */
JsCantvUtils.addRelatedContentsCANChannel = function (id_content,channel_list,manual_contents_list,num_elements,locale){
	var num_categ = 0;
	var elements_to_add = [];
	var num_elements_to_add = num_elements - manual_contents_list.length;
	var related_contents_categ_list_path = "/"+locale+"/listados_channel_can/";
	if (num_elements_to_add > 0){
		JsCantvUtils.addRelatedContent(id_content,channel_list,manual_contents_list,num_elements_to_add,num_categ,elements_to_add,locale,related_contents_categ_list_path,"channel");	
	}else{
		JsCantvUtils.AdjustAdemasCan("scrollable2_relateds",3);
	}
}

JsCantvUtils.getURLParam = function (strParamName){
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("&") > -1 ){
	var strQueryString = strHref.substr(strHref.indexOf("&")).toLowerCase();
	var aQueryString = strQueryString.split("&");
	for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
		if (
			aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}

/**
 * JsCantvUtils.fileExplore
 * Cambia la apariencia del campo file
 */
JsCantvUtils.fileExplore = {
		/**
		 * JsCantvUtils.fileExplore.avatar
		 * Cambia la apariencia del campo file para el avatar
		 */
		avatar: function (){
			var image = "/css/imgs/explora.jpg";
			var imageheight = 23;
			if (jQuery.browser.msie6 || jQuery.browser.msie7){
				imageheight = 30;
			}
			var imagewidth = 528;
			if (jQuery.browser.opera){
				imagewidth = 634;
			}			
			var width = 168;
			
			$(".fileExplore").filestyle({ 
				 image: image,
				 imageheight : imageheight,
				 imagewidth : imagewidth,
				 width : width
			});
			$(".file.fileExplore").css("margin-right","75px");
		},
		/**
		 * JsCantvUtils.fileExplore.uploadVideo
		 * Cambia la apariencia del campo file para el video
		 */	
		uploadVideo: function (){

				var image = "/css/imgs/explora.jpg";
				var imageheight = 30;
				var imagewidth = 75;
				if (jQuery.browser.opera){
					imagewidth = 290;
				}
				var width = 200;	
				 $(".fileExplore").filestyle({ 
					 image: image,
					 imageheight : imageheight,
					 imagewidth : imagewidth,
					 width : width
				 });
		}
}

JsCantvUtils.isClipboardEnlazarInit = false;
JsCantvUtils.isClipboardCopiarInit = false;
JsCantvUtils.clipboardEnlazar = null;
JsCantvUtils.clipboardCopiar = null;

JsCantvUtils.clipboardEnlazarInit = function () {
    ZeroClipboard.setMoviePath(JsCantvUtils.Paths.BasePath+'swf/ZeroClipboard.swf' );	
	if (!JsCantvUtils.isClipboardEnlazarInit){
		JsCantvUtils.isClipboardEnlazarInit = true;
		var id = JsCantvUtils.isClipboardCopiarInit?"2":"1";
		JsCantvUtils.clipboardEnlazar= new ZeroClipboard.Client();
		JsCantvUtils.clipboardEnlazar.setHandCursor(true);
		JsCantvUtils.clipboardEnlazar.addEventListener('mouseOver', function (client) {
			JsCantvUtils.clipboardEnlazar.setText(document.getElementById('ENLAZAR_VIDEO').value);
		});
		JsCantvUtils.clipboardEnlazar.addEventListener('complete', function (client, text) {
			JsCantvUtils.Messages.showMsg(I18n["es"].clipboard_text_copy);			
		});		
		JsCantvUtils.clipboardEnlazar.glue('boton_enlazar_video');
		$("<div id='clipboard_enlazar_video' style='position: absolute; left: 0px; top: 0px; width: 231px; height: 24px; z-index: 99;' >").appendTo("#boton_enlazar_video");
		$("div > embed#ZeroClipboardMovie_"+id).appendTo("#clipboard_enlazar_video");	
	}
}

JsCantvUtils.clipboardCopiarInit = function () {
    ZeroClipboard.setMoviePath(JsCantvUtils.Paths.BasePath+'swf/ZeroClipboard.swf' );	
    if (!JsCantvUtils.isClipboardCopiarInit){
		JsCantvUtils.isClipboardCopiarInit = true;
		var id = JsCantvUtils.isClipboardEnlazarInit?"2":"1";
		JsCantvUtils.clipboardCopiar  = new ZeroClipboard.Client();
		JsCantvUtils.clipboardCopiar.setHandCursor(true);
		JsCantvUtils.clipboardCopiar.addEventListener('mouseOver', function (client) {
			JsCantvUtils.clipboardCopiar.setText(document.getElementById('COPIAR_VIDEO').value);
		});
		JsCantvUtils.clipboardCopiar.addEventListener('complete', function (client, text) {
			JsCantvUtils.Messages.showMsg(I18n["es"].clipboard_text_copy);			
		});				
		JsCantvUtils.clipboardCopiar.glue('boton_copiar_video');
		$("<div id='clipboard_copiar_video' style='position: absolute; left: 220px; top: 190px; width: 231px; height: 24px; z-index: 99;' >").appendTo("#boton_copiar_video");
		$("div > embed#ZeroClipboardMovie_"+id).appendTo("#clipboard_copiar_video");
    }
}

