String.prototype.trim = function() { return this.replace(/^[\s]+|[\s]+$/g,'') }
String.prototype.numOfCharacters = function(character){
	var rep = 0;
	for(var i=0; i<=this.length-1;i++) if(this.charAt(i) == character) rep++;
	return rep;
}


var fixes={
	modAlertas:function(){
		$("#alertas").append(fixes.fix());
	},
	modInteres:function(){
		$("#interes .title").append(fixes.fix());
	},
	modBuscador:function(){
		$(".columnType2").append($("<div class='sp fixBuscador png'>&nbsp;</div>"));
	},
	modBuscadorPage:function(){
		$(".wrapIframe").append($("<div class='sp fixBuscador png'>&nbsp;</div>"));
	},
	modCandidatos:function(){
		$("#candidatos").append(fixes.fix());
	},
	modAlertasEmpleo:function(){
		$("#alertasEmpleo").append(fixes.fix());
	},
	fix:function(){
		return $("<div class='sp fix png'>&nbsp;</div>");
	},
	setLinkPrint:function(){		
		var obj = $("#pageOptions");		
		var liElement = $("<li class='print'><a href='javascript:window.print()'>"+ literal["imprimir"] +"</a></li>")
		obj.find("li").eq(0).before(liElement);		
	},
	setMsgError:function(){
		var obj = $("#error .msg");
		var divElement = $("<div class='sp fix'>&nbsp;</div>");
		obj.append(divElement);
	},
	setBackRecommend:function(){
		var obj = $("#recommendPage");
		var forms = obj.find("form");
		var parent = obj.parent();
		var hreff = (forms.length != 0) ? "javascript:history.back()" : "javascript:history.go(-2)";
		var spanElement = "<span class='btn'><span><a href='"+hreff+"'>"+literal["volver"]+"</a></span></span>";
		parent.append($(spanElement));
	},
	setBckCompatibilidad:function(){
		var bck = '<span class="shape sp">&nbsp;</span>';
		var fieldsets = $(".compatibilidad").find("fieldset");
		var last = fieldsets.eq(4).parent();
		var _this = parentt = null;
		var  zIndexNumber = 1000;
		fieldsets.each(function(){
			_this = $(this);
			parentt = _this.parent();
			parentt.append($(bck));
			parentt.find(".shape.sp").css("top", parentt.height()+29);
			parentt.css('zIndex', zIndexNumber);
			zIndexNumber -= 10;
		});				
		last.find(".shape.sp").remove();
	}
}

var graphs = {
	setExportOptions:function(){
		var graficas = $("#graficas");
		var wrapGraphs = graficas.find(".wrapGraph");
		var aux = '<ul class="exportOptions">\n';
			aux += '<li><a href="javascript:printChart();"><img src="images/imprimirgrafica.gif" alt="'+literal["exportOptions"][0]+'" /></a></li>\n';
			aux += '<li><a href="javascript:exportCharts("JPG");"><img src="images/exportarjpg.gif" alt="'+literal["exportOptions"][1]+'" /></a></li>\n';
			aux += '<li><a href="javascript:exportCharts("PDF");"><img src="images/pdf.gif" alt="'+literal["exportOptions"][2]+'" /></a></li>\n';
			aux += '<li><a href="javascript:pintaExcel(0);"><img src="images/exportarexcel.gif" alt="'+literal["exportOptions"][3]+'" /></a></li>\n';
			aux += '</ul>';     									        		
		wrapGraphs.each(function(){
			$(this).find("div.clearFix").eq(0).append($(aux));
		})
	}
}

var curves={
	
	createMainCurves:function(){
		var obj = $("#wrapper");
		var obj2 = $("#wrapperFooter");		
		var cTopLeft = $("<div class='sp cLeftTop'>&nbsp;</div>");		
		var cTopRight = $("<div class='sp cRightTop'>&nbsp;</div>");	
		var cBottomLeft = $("<div class='sp cLeftBottom'>&nbsp;</div>");	
		var cBottomRight = $("<div class='sp cRightBottom'>&nbsp;</div>");	
		obj.append(cTopLeft);
		obj.append(cTopRight);
		obj2.append(cBottomLeft);
		obj2.append(cBottomRight);
		obj2.append(cTopLeft.clone());
		obj2.append(cTopRight.clone());
															
	},
	createGeneralCurves:function(obj){
		var cTLeft = cTRight = cBLeft = cBRight = null;
		cTLeft = curves.createElementsCurves("cTLeft");
		cTRight = curves.createElementsCurves("cTRight");
		cBLeft = curves.createElementsCurves("cBLeft");
		cBRight = curves.createElementsCurves("cBRight");
		obj.append(cTLeft);
		obj.append(cTRight);
		obj.append(cBLeft);
		obj.append(cBRight);
	},
	createElementsCurves:function(style){
		return $("<div class='sp " + style + "'>&nbsp;</div>");
	}
}



var behaviours = {
	headerSearch:function(){
		$("#termino").focus(function(){ $(this).attr("value","");})
	},
	invita:function(){
		$("#emailInvita").focus(function(){ $(this).attr("value","");})
		$("#emailAmigo").focus(function(){ $(this).attr("value","");})
	},
	faq:{
		init:function(){
			var obj = $("#listFormatFAQ");
			var wysiwygs = obj.find(".wysiwyg");
			var openBlock = text = "";
			var _this = null;
			wysiwygs.each(function(){
				_this = $(this);
				_this.hide();
				text = _this.prev().text();
				openBlock = '<span class="openBlock"><a href="javascript:void(null)" onclick="behaviours.faq.action(this); return false;" onkeypress="behaviours.faq.action(this); return false;" title="'+literal["faq"][0]+': '+text+'">'+literal["faq"][0]+'</a></span>';
				$(openBlock).insertBefore(_this);
			})
		},
		action:function(obj){
			var wysiwyg = $(obj).parent().parent().find(".wysiwyg");
			var span = $(obj).parent();
			if (span.attr("class") == "openBlock") {
				$(wysiwyg).show("normal");
				$(wysiwyg).attr("tabIndex", "-1");
				$(wysiwyg).focus();
				$(obj).text(literal["faq"][1]);
				$(obj).attr("title", literal["faq"][1] + " : " + $(span).prev().text());
				span.removeClass("openBlock");
				span.addClass("closeBlock");
			}else{
				$(wysiwyg).hide("normal");
				$(obj).text(literal["faq"][0]);
				$(obj).attr("title", literal["faq"][0] + " : " + $(span).prev().text());
				span.removeClass("closeBlock");
				span.addClass("openBlock");				
			}
		}
	},
	commentsList:{
		init:function(){
		
			var obj = $("#commentsList");
			var wraps = obj.find(".wrap.clearFix");
			var formsComments = obj.find(".blockFormBlog");
			var aux = textAux = "";
			formsComments.each(function(){ 
		
				aux = '<span class="close"><a href="javascript:void(null)" onclick="behaviours.commentsList.close(this);return false" onkeypress="behaviours.commentsList.close(this);return false">X Cerrar</a></span>';
				$(this).hide() 
				$(this).find("fieldset").before($(aux));
				$(this).find("form").append($("<div class='sp fix'>&nbsp;</div>")) 
			}) 
			/*wraps.each(function(){
				textAux = $(this).find(".title a").text();
				aux = '<span class="answer"><a href="javascript:void(null)" onclick="behaviours.commentsList.open(this);return false" onkeypress="behaviours.commentsList.open(this);return false" title="'+literal["responder"]+': '+textAux+' ">'+literal["responder"]+'</a></span>';
				$(this).append($(aux));
			})*/
		},
		open:function(obj){						
			$(obj).parent().parent().parent().find(".blockFormBlog").show("normal");
			
		},
		close:function(obj){
			$(obj).parent().parent().parent().hide("normal");
		}
	}
	
}

var Valoracion = {
    starInit: function(){
        $('.auto-submit-star').rating({
            callback: function(value, link){
                $(".star1",
$(this).parent()).removeClass("star-rating-live");
                $(".star1",
$(this).parent()).addClass("star-rating-readonly");
                $(".star1 a", $(this).parent()).click(function(){return
false;});
                $(".star1 a",
$(this).parent()).mouseout(function(){return false;});
                $(".star1 a",
$(this).parent()).mouseover(function(){return false;});

                
$.getJSON("/votes/puntuar/"+($("#contentObject").val())+'/'+value+'/'+($("#clasevoto").val()),
function(data){
                    // si data.valido recibe 0 es que la votación no se ha produccido, porque el usuario ya voto una vez
                    alert(data.valido);
                    if(data.valido)
                    {
                        alert(data.total);
                        alert(data.media);
                        alert(data.puntos);
                        $('#votostotales1').text('('+data.total+' votos)');
                        $('#votostotales2').text('('+data.total+' votos)');
                    }
                    //$(".tuNota .ranking span").fadeIn("slow");
                })
            }
        });   
    }
}

/* validaciones de formularios */
var formsValidations = {
	setMsgError:function(txt, form){
		var parentForm = form.parent();
		var msgError = parentForm.find(".msgError");
		var divElement = (msgError.length != 0) ? msgError.eq(0) : document.createElement("div");		
		var ulElement = document.createElement("ul");
		var liElement = null;		
		var errors = txt.split("|");				
		$(divElement).attr("class", "msgError");
		$(divElement).attr("tabIndex","-1");
		if($(divElement).find("ul").length != 0) $(divElement).empty();
		for(var i = 0; i < errors.length - 1; i++){
			liElement = document.createElement("li");
			liElement.appendChild(document.createTextNode(errors[i]));
			ulElement.appendChild(liElement);
		}
		$(divElement).append(ulElement);		
		if(msgError.length == 0) form.before($(divElement));
		$(divElement).focus();
	},
	validaInvitaForm:function(obj){
		var errorTxt = "";
		var f = jQuery(obj);					
		if (!f.find("input[@id='emailInvita']").attr("value")) errorTxt += literal["alerta"][0];
		else {
			if (!regularExpressions.isValidEmail(f.find("input[@id='emailInvita']").attr("value"))) {				
				errorTxt += literal["alerta"][1];
			}
		}
		if (!f.find("input[@id='emailAmigo']").attr("value")) errorTxt += literal["alerta"][2];
		else {
			if (!regularExpressions.isValidEmail(f.find("input[@id='emailAmigo']").attr("value"))) {				
				errorTxt += literal["alerta"][3];
			}
		}
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, f);
			return false;
		}else return true;
	},
	validaFormAlertasEmpleo:function(obj){
		var errorTxt = "";
		var f = jQuery(obj);					
		if (!f.find("input[@id='email']").attr("value")) errorTxt += literal["alerta"][0];
		else {
			if (!regularExpressions.isValidEmail(f.find("input[@id='email']").attr("value"))) {				
				errorTxt += literal["alerta"][1];
			}
		}		
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, f);
			return false;
		}else return true;
	},
	validaBlogForm:function(obj){
		var errorTxt = "";
		var f = jQuery(obj);		
		if (!f.find("input.nombreInput").attr("value")) errorTxt += literal["blogForm"][0];			
		if (!f.find("input.emailInput").attr("value")) errorTxt += literal["blogForm"][1];
		else {
			if (!regularExpressions.isValidEmail(f.find("input.emailInput").attr("value"))) {				
				errorTxt += literal["blogForm"][2];
			}
		}		
		if (!f.find("textarea.comentarioInput").attr("value")) errorTxt += literal["blogForm"][3];
		//if (!f.find("input.captchaInput").attr("value")) errorTxt += literal["blogForm"][4];			
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, f);
			return false;
		}else return true;
	},
	validaFormCompatibilidad:function(obj){
		var errorTxt = "";
		var f = jQuery(obj);		
		
		//if (f.find(":radio:checked").length < 5) errorTxt += literal["compatibilidadForm"][0];			
		var bRespuestas = true;
		var bloques = f.find("fieldset");
		//var respuestas = f.find("input[@type='radio']:not(:checked)");		
		var respuestas = null;
		$(bloques).each(function(){
			respuestas = $(this).find("input[@type='radio']:checked");
			if (respuestas.length == 0) {
				bRespuestas = false;
				return false;
			}
		})
		if(!bRespuestas) errorTxt += literal["compatibilidadForm"][0];	
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, f);
			return false;
		}else return true;
	},
	validaFormPercepcion:function(obj){
		var errorTxt = "";
        var f = jQuery(obj);                        
        var bloques = f.find("tbody tr");
        var bRespuestas = true;
        var respuestas = null;      
        $(bloques).each(function(){             
            respuestas = $(this).find(":checked");
            if (respuestas.length == 0) {
                bRespuestas = false;        
                return false;       
            }
        })      
        if(!bRespuestas) errorTxt += literal["percepcionForm"][0];
        if(errorTxt != ""){ 
            formsValidations.setMsgError(errorTxt, f);
            return false;
        }else return true;          
	},
	validaFormRecommend:function(obj){
		var f = jQuery(obj);		
		var errorTxt = aux = "";
		var okMailsAmigo = true;
		var destino = f.find("input[@id='destino']").attr("value");
		if(f.find("input[@id='nombre']").attr("value") == "") errorTxt += literal["recommend"][0];
		if(f.find("input[@id='mail']").attr("value") == "") errorTxt += literal["recommend"][1];
		else{
			if(!regularExpressions.isValidEmail(f.find("input[@id='mail']").attr("value"))) errorTxt += literal["recommend"][4];		
		}
		if(destino == "") errorTxt += literal["recommend"][2];		
		if (destino.numOfCharacters("@") == 0 && destino != "") errorTxt += literal["recommend"][5];
		else {			
			aux = destino.replace(/,/g, " ");
			mailsAmigo = aux.split(" ");
			for (i = 0; i < mailsAmigo.length && okMailsAmigo; i++) {				
				if (mailsAmigo[i].trim() == "") {
					okMailsAmigo = true;
					continue;
				}
				okMailsAmigo = regularExpressions.isValidEmail(mailsAmigo[i]);
			}
			if (!okMailsAmigo) errorTxt += literal["recommend"][5];
			else {
				if (aux.numOfCharacters("@") > 1 && destino.numOfCharacters(",") != destino.numOfCharacters("@") - 1) errorTxt += literal["recommend"][6];
			}
		}
		if(f.find("textarea[@id='comentarios']").attr("value") == "") errorTxt += literal["recommend"][3];	
		else{
			if(f.find("textarea[@id='comentarios']").attr("value").length > 250)  errorTxt += literal["recommend"][7];	
		}	
		if(errorTxt != ""){	
			formsValidations.setMsgError(errorTxt, f);
			return false;
		}else return true;
	},
	CambiaBuscador:function(obj)
	{
		if (obj.value !="147") //si es distinto de españa
		{
			ciudad = $("#ciudad");
			texto = $('#pais :selected').text();
			
			 $("#ciudad option").each(function(i){
					if ($(this).text() == texto)
					{
						$(this).attr("selected","selected"); //esto solo vale si los combos tienen los mismos nombres
					}
			 });
		}
		
	}
}

/* expresiones regulares para validar formularios */
var regularExpressions = {	
	isValidEmail:function (str){
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		return (filter.test(str));
	},
	esCadena:function(c) { return /^[0-9A-Za-z-\/Ññ?É?ÓÚáéíóúÜüÄäËë?ïÖö´,'/\\t\n\r\s]+$/.test(c); },
	esAlfabetico:function(c){return /^([a-zA-Z])+$/.test(c);},
	esNumero:function(c){return /^[0-9]+$/.test(c);},
	esTelefono:function(c){return /^[0-9\s\+\-)(]+$/.test(c)},
	esCif:function(c){
		if (!/^[A-Za-z0-9]{9}$/.test(c) || !/^[ABCDEFGHKLMNPQS]/.test(c)) return false;
		var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
		var digCrtl=c.charAt(c.length-1);
		var temp = 0;
		for(i=2;i<=6;i+=2 ) {
		      temp = temp + v1[ parseInt(c.substr(i-1,1)) ];
		      temp = temp + parseInt(c.substr(i,1));
		};
		temp = temp + v1[ parseInt(c.substr(7,1)) ];                   
		temp = (10 - ( temp % 10));
		if( temp == 10 ){if(!(digCrtl=="J" || digCrtl=="0")) return false;
		}else{if(digCrtl!=temp) return false; }
		return true;
	}
}



jQuery(document).ready(function() {	
	curves.createMainCurves();
	behaviours.headerSearch();
	if($("#consejos .valoracionUsuarios .dataStars").length != 0)Valoracion.starInit(); 
	if($("#pageOptions").length != 0) fixes.setLinkPrint();
	if($("#alertas").length != 0) fixes.modAlertas();
	//if($("#graficas").length != 0) graphs.setExportOptions();
	if($("#interes").length != 0) fixes.modInteres();
	if($("#candidatos").length != 0) fixes.modCandidatos();
	if($("#alertasEmpleo").length != 0){
		 fixes.modAlertasEmpleo();
		$("#alertasEmpleo form").submit(function(){return formsValidations.validaFormAlertasEmpleo( jQuery(this))});
	}
	if($("#recommendPage").length != 0) fixes.setBackRecommend();
	if($("#formRecommend").length != 0){		
		$("#formRecommend").submit(function(){return formsValidations.validaFormRecommend( jQuery(this))}); 		
	}
		
	if($("#home").length != 0) fixes.modBuscador();
	if($(".wrapIframe").length != 0)  fixes.modBuscadorPage();
	if($("#invita").length != 0){
		$("#invita form").submit(function(){return formsValidations.validaInvitaForm( jQuery(this))});
		behaviours.invita();
	}
	if ($("#commentsList").length != 0) behaviours.commentsList.init()
	
	if ($("#pais").length != 0) $("#pais").bind('change',function(){formsValidations.CambiaBuscador(this)});
	
	if ($("#blog").length != 0 || $("#consejos").length != 0) {		
		$(".blockFormBlog form").each(function(){
			$(this).submit(function(){return formsValidations.validaBlogForm( jQuery(this))});	
		})
		
	}
	if($("#listFormatFAQ").length != 0) behaviours.faq.init();
	if($("#error").length != 0){
		curves.createGeneralCurves($("#error .msg"));
		fixes.setMsgError();
	}
	if($(".compatibilidad").length != 0) fixes.setBckCompatibilidad();
	if($("#formCompatibilidad").length != 0){		
		$("#formCompatibilidad").submit(function(){return formsValidations.validaFormCompatibilidad( jQuery(this))}); 		
	}
	if($("#formPercepcion").length != 0){		
		$("#formPercepcion").submit(function(){return formsValidations.validaFormPercepcion( jQuery(this))}); 		
	}
	
});
		
/*
$("pais").change(function () 
{
	alert ("dsfasdf");
});
*/


