$().ready(function() {

	// Buscap
	if($("#buscap").length){
		var keywords = $("#ba_keywords").val();
		var email = $("#ba_email").val();
		$.ajax({
			url: '/nomvc/email_buscaptador.php',
			dataType: 'text',
			success: function (htmlresponse) {
			if (htmlresponse) {
				$("#ba_email").val(htmlresponse);
				var email = $("#ba_email").val();
			}
		}
		});
		if (keywords != $("#ba_keywords").attr("title")) {
		    $("#ba_keywords").css('color','black');
		}
		if (email != $("#ba_email").attr("title")) {
		    $("#ba_email").css('color','black');
		}
	}

	// Home
	if($('#acceso_candidato').length){
		$('#acceso_candidato').click(function(){ window.location = ($('#acceso_candidato_a').attr('href'));});
		$('#acceso_empresa').click(function(){ window.location = ($('#acceso_empresa_a').attr('href'));});
	}

	// Ofertas
	if($('#act_subfiltro_1').length){
		$('#act_subfiltro_1').click(function(e){e.preventDefault();$('#subfiltro_1').toggle();});
		$('#act_subfiltro_2').click(function(e){e.preventDefault();$('#subfiltro_2').toggle();});
		$('#act_subfiltro_3').click(function(e){e.preventDefault();$('#subfiltro_3').toggle();});
	}

	// listados para Anterior y siguiente
	if($('#guardar_listado').length){
		$.ajax({  url: '/usuarios/ajaxresultados',
	        type: "POST",
	        dataType: "json",
	        data: "query=" + location.pathname
	    });
	}

	// Oferta
	if($('#enviar_cv').length){
		$('#enviar_cv').click(function(e){$("#ba_email").focus()});
	}
	// Oferta form
	if($('#frmSolicitud').length){

		$("#presentation").click(function(){$("#comentarios").toggle()});

		var errorWrapperHtml = '<fieldset class="marginframe marginstandard back05">' +
		'<legend>' + aMensajes['MSG0001'] + '</legend>' +
		'<ol class="list styleoutside color08 fontmedium"><span id="errorForm"></span></ol>' +
		'</fieldset>';
		$("#errorWrapper").html(errorWrapperHtml);
		$("#errorWrapper").hide();
		$("#frmSolicitud").validate({
			onkeyup: false,
			onfocusout: false,
			rules: {
			email: {
			required: true,
			email: true,
			maxlength: 255
		},
		pass: {
			required: true,
			maxlength: 255
		},
		comentarios: {
			required: false,
			maxlength: 4000
		}
		},
		messages: {
			email: {
			required: aErrores['ERR0001'],
			email: aErrores['ERR0001'],
			maxlength: jQuery.format(aErrores['ERR0003'], $("label[for='email']").attr("title"))
		},
		pass: {
			required: aErrores['ERR0002'],
			maxlength: jQuery.format(aErrores['ERR0003'], $("label[for='pass']").attr("title"))
		},
		comentarios: {
			maxlength: aErrores['ERR0104']
		}
		},
		errorLabelContainer: "#errorForm",
		errorElement: "li",
		submitHandler: function(inscripcion) {
			var sEmail = $("#email").attr("value");
			var sPass = $("#pass").attr("value");
			var iIdOferta = $("#id_oferta").attr("value");
			var sComentarios = $("#comentarios").attr("value");
			var iNumPreguntas = $("#num_preguntas").attr("value");


			// Construimos 2 arrays con las killer radio y text, para validarlas y enviar la informacion via ajax

			var error = false;
			var txt_error = "";
			var KRadio = new Array();
			var KText = new Array();
			var dataKQ = '';

			for(i=0; i<document.getElementById('frmSolicitud').elements.length; i++)
			{
				nombre = document.getElementById('frmSolicitud').elements[i].name;

				//guardamos las killer radio en un array
				if(nombre && nombre.substring(0,4) == "KQ_R")
				{
					if(!in_array(KRadio, nombre))
					{
						KRadio.push(nombre);
					}
				}

				//guardamos las killer text en otro
				if(nombre && nombre.substring(0,4) == "KQ_T")
				{
					if(!in_array(KText, nombre))
					{
						KText.push(nombre);
					}
				}
			}

			for(i=0; i<KRadio.length && !error; i++)
			{
				//miramos los radios a ver si estan chequeados
				if(!$("input[name="+KRadio[i]+"]:checked").val())
				{
					error = true;
					//txt_error = aErrores['ERR0105'];
					txt_error = "te das cuen?"
				}
				else {
					// Para enviar la peticion Ajax
					dataKQ = dataKQ + "& "+ KRadio[i] + "=" + $("input[name="+KRadio[i]+"]:checked").val();
				}
			}

			for(i=0; i<KText.length && !error; i++)
			{
				txtTrim = trim(document.getElementById(KText[i]).value);

				//miramos los textos a ver cumplen al longitud máxima
				if(txtTrim.length > 255)
				{
					error = true;
					txt_error = aErrores['ERR0103'];
				}

				// y la mínima
				if(txtTrim.length < 15)
				{
					error = true;
					txt_error = aErrores['ERR0103'];
				}
				if(! error){
					// Para enviar la peticion Ajax
					dataKQ = dataKQ + "& "+ KText[i] + "=" + txtTrim ;
				}
			}

			if(error) {  // si hubo error mostramos un mensaje
				$("#errorWrapper").show();
				var errores = '';
				if( $("#errorFormWrapper") ){
					$("#errorFormWrapper").hide();
				}
				errores += "<li>" + txt_error + "</li>";
				$("#errorForm").html(errores);
			}
			else {
				inscripcion.submit();
				return false;
			}
			return false;
		},
		showErrors: function(errorMap, errorList) {
			$("#errorForm").html("");
			if( $("#errorFormWrapper") ){
				$("#errorFormWrapper").hide();
			}
			if (this.numberOfInvalids() > 0) {
				$("#errorWrapper").show();
				this.defaultShowErrors();
				window.location.hash="form";
			}
		}
		});
	}
});

// Gafs
function google_afs_request_done(google_ads)
{
    /*
     * Verify that there are actually ads to display.
     */
    var google_num_ads = google_ads.length;
    if (google_num_ads <= 0)
    {
        return;
    }

    var wideAdsTop = '<ul class="listnone">';   // texto html de bloque de anuncios superiores
    var wideAdsBottom  = '<ul class="listnone">';   // texto html de bloque de anuncios inferiores
    var wideAdsCnt_0 = "";   // texto html de bloque de anuncios en contenido
    var wideAdsCnt_1 = "";   // texto html de bloque de anuncios en contenido

    for(i = 0; i < google_num_ads; i++)
    {
        if (google_ads[i].type=="text/wide")
        {
            if (i < l1) {
                // render a top ad
                wideAdsTop += '<li><h4><a rel="external" href="' + google_ads[i].url + '">' + google_ads[i].line1 +
                '</a></h4><p><arel="external" href="' + google_ads[i].url + '">' + google_ads[i].visible_url +
                '</a> ' + google_ads[i].line2 + '</p></li>';
            } else if ( i < l2 ) {
                // render a top ad
                wideAdsCnt_0 += printContent(google_ads[i]);
            } else if ( i < l3 ) {
                // render a content ad
                wideAdsCnt_1 += printContent(google_ads[i]);
            } else if ( i < l4 ) {
                // render a bottom ad
                wideAdsBottom += '<li><h4><a rel="external" href="' + google_ads[i].url + '">' + google_ads[i].line1 +
                '</a></h4><p><a rel="external" href="' + google_ads[i].url + '">' + google_ads[i].visible_url +
                '</a> ' + google_ads[i].line2 + '</p></li>';
            }
        }
    }

    if (wideAdsTop != '<ul class="listnone">')
    {
        wideAdsTop = '<div><p><a rel="external" ' +
        'href="http://services.google.com/feedback/online_hws_feedback">' + aVarios['VAR0119'] + '</a>' + wideAdsTop + '</ul></div>';
    }

    if (wideAdsCnt_0 != '')
    {
        wideAdsCnt_0 = printTable(wideAdsCnt_0);
    }

    if (wideAdsCnt_1 != '')
    {
        wideAdsCnt_1 = printTable(wideAdsCnt_1);
    }

    if (wideAdsBottom != '<ul class="listnone">')
    {
        wideAdsBottom = '<div><p><a rel="external" ' +
        'href="http://services.google.com/feedback/online_hws_feedback">' + aVarios['VAR0119'] + '</a>' + wideAdsBottom + '</ul></div>';
    }
    // Bloque superior
    if (document.getElementById("wide_ad_top_unit")) {
        document.getElementById("wide_ad_top_unit").innerHTML = wideAdsTop;
    }
    // Bloques de ofertas
    if (document.getElementById("adsense")) {
        document.getElementById("adsense").innerHTML = wideAdsCnt_0;
    }
    if (document.getElementById("wide_ad_cnt_unit_1")) {
        document.getElementById("wide_ad_cnt_unit_1").innerHTML = wideAdsCnt_1;
    }
    // Bloque inferior
    if (document.getElementById("wide_ad_bottom_unit")) {
        document.getElementById("wide_ad_bottom_unit").innerHTML = wideAdsBottom;
    }
}

function printContent(google_ads_row){
    var wideAdsCnt = '';
    var long  = google_ads_row.line2.length;
    if (long > 10 ) {
        var cutC  = Math.floor(long / 2);
        //var line = wordWrap(google_ads_row.line2,cutC,'<br/>',false,2);
        var line = google_ads_row.line2;
    }
    wideAdsCnt += '<li><div class="adcontent"><h4><a rel="external" href="' + google_ads_row.url + '">' + google_ads_row.line1 +
    '</a></h4>' + line + '</div><div class="adlink"><h4>&nbsp;</h4><a rel="external" href="' + google_ads_row.url +
    '">' + google_ads_row.visible_url + '</a></div><div class="clear"></div></li>';
    return wideAdsCnt;
}

function printTable(wideAdsCnt){
    var wideAdsCntTable = '';
    wideAdsCntTable = '<ul><li id="adheader"><a rel="external" href="http://services.google.com/feedback/online_hws_feedback">' +aVarios['VAR0119'] + '</a></li>' + wideAdsCnt + '</ul>' ;
    return wideAdsCntTable;
}

function wordWrap(str, m, b, c, maxLine){

    var i, j, s, r = str.split("\n");
    var nLines = 1, auxRuptura;
    if(m > 0) for(i in r){
        for(s = r[i], r[i] = ""; s.length > m;
        j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length
                || m,
                r[i] += s.substr(0, j) + ( auxRuptura = ((s = s.substr(j)).length ? b : "")),
                nLines = nLines + 1,
                m = ( maxLine && ( auxRuptura == b ) && nLines >= maxLine)? str.length : m
        ){}
        r[i] += s;
    }
    var debug = r.join("\n");
    return r.join("\n");
}

//cbe: clase para obtener los parámetros de la url
function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

function writeLogin() {
    $.getJSON('/usuarios/ajaxlogin', function(htmlresponse) {
    	var sHtml = '';
    	// Pintamos login
        if (htmlresponse.tipo == 'E') {
            sHtml = '<strong>' + htmlresponse.data.empresa.EMAIL_LOGIN + '</strong>' +
            '<a class="acceso accesoempresa" href="'+htmlresponse.urls.empresas_acceso+'" title="'+aVarios['VAR0006']+'">'+aVarios['VAR0003']+'</a>' +
            '<a class="acceso logoutempresa" href="'+htmlresponse.urls.empresas_logout+'" title="'+aVarios['VAR0007']+'">'+aVarios['VAR0005']+'</a>';
            $('#enlaces').html(sHtml);
        } else if (htmlresponse.tipo == 'C') {
            sHtml = '<li><strong>' + htmlresponse.data.usuario.EMAIL + '</strong></li>' +
            '<li><a class="acceso" href="'+htmlresponse.urls.candidatos_acceso+'" title="'+aVarios['VAR0002']+'">'+aVarios['VAR0003']+'</a></li>' +
            '<li><a class="acceso logout" href="'+htmlresponse.urls.candidatos_logout+'" title="'+aVarios['VAR0004']+'">'+aVarios['VAR0005']+'</a></li>';
            $('#accesos').html(sHtml);
        }

        // Pintamos frase home
        var myURL = parseURL(document.URL);
        if (myURL.path == '/' || myURL.path == '') {
        	var sHtml = '';
        	if (htmlresponse.tipo == 'E') {
        		sHtml = '';
        		$('#ruta').html(sHtml);
        	} else if (htmlresponse.tipo == 'C') {
        		sHtml = aVarios['VAR0192'].replace('{0}', htmlresponse.urls.candidatos_actualiza_cv);
        		sHtml = sHtml.replace('{1}', htmlresponse.urls.candidatos_destaca_cv);
        		$('#ruta').html(sHtml);
        	}
        }
    });
}

function writeStatusListado() {
	$.getJSON('/usuarios/ajaxlogin', function(htmlresponse) {
        // Pintamos en verde las ofertas activas
        if (htmlresponse.tipo == 'C') {
            var ofertas = htmlresponse.ofertas;
            for (i=0; i < ofertas.length; i++) {
            	
            	var ofertaNueva = $("li[id$=" + ofertas[i] + "]"); 
            	
                // Pintamos el formulario indicando que está inscrito
                if (ofertaNueva.length > 0) {
                	$("#" + 'ofertaid-' + ofertas[i]).addClass("active");
                	$("#" + 'ofertadestacadaid-' + ofertas[i]).addClass("active");

                	var a = $("#" + 'ofertaid-' + ofertas[i]).children('.col1').html();
                	var b = $("#" + 'ofertadestacadaid-' + ofertas[i]).children('.col1').html();
            		sHtmla = '<strong>'+aVarios['VAR0197']+'</strong> '+a;
            		sHtmlb = '<strong>'+aVarios['VAR0197']+'</strong> '+b;
            		$("#" + 'ofertaid-'+ofertas[i]).children('.col1').html(sHtmla);
            		$("#" + 'ofertadestacadaid-'+ofertas[i]).children('.col1').html(sHtmlb);

            		var n = htmlresponse.estado_oferta[i];
            		var state = '';

            		switch(n)
            		{
            		case htmlresponse.state.id.recibidos:
            			state = htmlresponse.state.translate.recibidos;
            			break;
            		case htmlresponse.state.id.proceso:
            			state = htmlresponse.state.translate.proceso;
            			break;
            		case htmlresponse.state.id.descartados:
            			state = htmlresponse.state.translate.descartados;
            			break;
            		case htmlresponse.state.id.finalistas:
            			state = htmlresponse.state.translate.finalistas;
            		  break;
            		}

            		sHtml = "<a href=\""+htmlresponse.urls.candidatos_listado_solicitudes+"\">"+aVarios['VAR0193']+" <strong>"+state+"</strong></a>";
            		$("#"+'ofertaid-'+ofertas[i]).children('.col3').html(sHtml);
            		$("#"+'ofertadestacadaid-'+ofertas[i]).children('.col3').html(sHtml);
                }
            }
        }
	});
}

function writeStatusOferta(id_oferta){
	$.getJSON('/usuarios/ajaxoferta/id/'+id_oferta, function(htmlresponse) {
    	// Pintamos el navegador anterior <> siguiente
    	if (htmlresponse.html_antsig) {
    		$("#antsig").html(htmlresponse.html_antsig);
        }
        // Si el candidato está logeado
        if (htmlresponse.tipo == 'C') {
            var inscrito = false;
            var ofertas = htmlresponse.ofertas;
            for (i=0; i < ofertas.length; i++) {
                var oferta = $("#" + 'col-inscribete_' + ofertas[i]);
                // Pintamos el formulario indicando que está inscrito
                if (oferta.length > 0) {
                    oferta.html('<div class=\"blockform back01\">' +
                    '<h1 class="cv" style="font-size:14px">' + aVarios['VAR0194'] + '</h1>' +
                    '<br/>' +
                    '<p class="normal">' + aVarios['VAR0195'] + ' <strong>' + htmlresponse.estado + '</strong></p>' +
                    '<p>' + aVarios['VAR0202'] +'</p>' +
                    '</div>');
                 
                    $(".blockform").parent().addClass("active");
                    $(".blockform").parent().parent().addClass("active");
                    $(".sup_izq").addClass("sup_izq_active");
                    $(".sup_der").addClass("sup_der_active");
                    $(".inf_izq").addClass("inf_izq_active");
                    $(".inf_der").addClass("inf_der_active");
                    
                    //enlace inscribirse debajo del listado
                    $("#" + 'enlace-inscribete_' + ofertas[i]).html('<a href="' + htmlresponse.urls.candidatos_listado_solicitudes + '" title="' + aVarios['VAR0196'] + '">' + aVarios['VAR0196'] + '</a>');
                    //$("#" + 'enlace-inscribete_' + ofertas[i]).html('');
                    inscrito = true;
                }
            }

            // En caso de no estar inscrito en la oferta pintamos sus datos de acceso en el formulario
            if (inscrito == false) {
                $("#form_oferta_login_form").html("<p class=\"normal\">"+aVarios['VAR0101']+" <br/><br /> <a href=\""+htmlresponse.urls.candidatos_acceso+"\" style=\"font-size:12px;font-weight:bold;color:#000;text-decoration:none;\">"+htmlresponse.data.usuario.EMAIL+"</a> "+
                        "<a href=\""+htmlresponse.urls.candidatos_logout+"/" +id_oferta +"\" style=\"font-size:11px;\">"+aVarios['VAR0103']+"</a></p>");
            }
        }
    });
}

function writeAcceso() {
	$.getJSON('/usuarios/ajaxacceso', function(htmlresponse) {
		// Solo si el usuario esta logueado modificamos el bloque
		if (htmlresponse.tipo){
			$('#accesos .acceso_candidatos').remove();
			$('#accesos .caja .contenido').remove();
			$('#accesos .caja').addClass('nocursor');

			var sHtml = '';
			if (htmlresponse.tipo == 'C') {
				sHtml = '<div class="sup_izq"></div><div class="sup_der"></div><div class="clear"></div>'+
				'<div class="contenido">'+
				'<ul class="menuprivado">'+
				'<h1>' + htmlresponse.translate.candidatos + ':</h1>'+
				'<li><a title="' + htmlresponse.translate.alertas + '" class="bt_empresas" href="' + htmlresponse.urls.alertas + '">' + htmlresponse.translate.alertas + '</a></li>'+
				'<li><a title="' + htmlresponse.translate.visualizar + '" class="bt_empresas" href="' + htmlresponse.urls.visualizar + '">' + htmlresponse.translate.visualizar + '</a></li>'+
				'<li><a title="' + htmlresponse.translate.modifica + '" class="bt_empresas" href="' + htmlresponse.urls.modifica + '">' + htmlresponse.translate.modifica + '</a></li>'+
				'<li><a title="' + htmlresponse.translate.visualizar_pdf + '" class="bt_empresas" href="' + htmlresponse.urls.visualizar_pdf + '">' + htmlresponse.translate.visualizar_pdf + '</a></li>';
				if (htmlresponse.pago_candidato) {
					sHtml += '<li><a title="' + htmlresponse.translate.destaca + '" class="bt_empresas" href="' + htmlresponse.urls.destaca + '">' + htmlresponse.translate.destaca + '</a></li>';
				}
				sHtml += '</ul>'+
				'</div>'+
				'<div class="inf_izq"></div><div class="inf_der"></div><div class="clear"></div>';
			}
			if (htmlresponse.tipo == 'E') {
				sHtml = '<div class="sup_izq"></div><div class="sup_der"></div><div class="clear"></div>'+
				'<div class="contenido">'+
				'<ul class="menuprivado">'+
				'<h1>' + htmlresponse.translate.empresas + ':</h1>'+
				'<li><a title="' + htmlresponse.translate.empresas_gestiona + '" class="bt_empresas" href="' + htmlresponse.urls.empresas_gestiona + '">' + htmlresponse.translate.empresas_gestiona + '</a></li>'+
				'<li><a title="' + htmlresponse.translate.empresas_busca + '" class="bt_empresas" href="' + htmlresponse.urls.empresas_busca + '">' + htmlresponse.translate.empresas_busca + '</a></li>'+
				'<li><a title="' + htmlresponse.translate.empresas_publica + '" class="bt_empresas" href="' + htmlresponse.urls.empresas_publica + '">' + htmlresponse.translate.empresas_publica + '</a></li>'+
				//'<br />' +
				//'<li><a title="' + htmlresponse.translate.empresas_saldoyfacturas + '" class="bt_empresas" href="' + htmlresponse.urls.empresas_saldoyfacturas + '">' + htmlresponse.translate.empresas_saldoyfacturas + '</a></li>'+
				'</ul>'+
				'</div>'+
				'<div class="inf_izq"></div><div class="inf_der"></div><div class="clear"></div>';
			}
			$('#accesos .caja').html(sHtml);
		}
	});

}

function writeUltimas() {
    $.ajax({
      url: "/usuarios/ajaxultimas",
      cache: false,
      dataType: "json",
      success: function(htmlresponse) {
        var sHtml = '';
        if (htmlresponse) {
        	sHtml = '<h1>' + htmlresponse.ultimas.title + ':</h1>' +
        	'<ul class="menuprivado">' +
        	htmlresponse.ultimas.lista +
        	'</ul>';
        }
        $('#ultimas').html(sHtml);
      }
    });
}

function deleteUltimas(name) {
    $.ajax({
      url: "/usuarios/ajaxultimas/?name="+name,
      cache: false,
      dataType: "json",
      success: function(htmlresponse) {
        var sHtml = '';
        if (htmlresponse) {
        	sHtml = '<h1>' + htmlresponse.ultimas.title + ':</h1>' +
        	'<ul class="menuprivado">' +
        	htmlresponse.ultimas.lista +
        	'</ul>';
        }
		$('#ultimas').html(sHtml);
		$('#'+name).remove(); //borra esa oferta de la lista
		if ($('.ultimas_busquedas').size() < 1) {
            $('#ultimas').remove();
		}
      }
    });
}
