// Bodaclick
// Funciones diversas
// Kike Valdenebro y Miguel Álvarez
// 21.05.2007
// Redbility

jQuery(document).ready(function($){
   
	$(".tabla_resultados tr").bind("mouseenter mouseleave", function(e){
        $(this).toggleClass("resaltar");
    });


	// CAMBIO DE PAÍS
	// David Balderas

	// revisar la existencia #opencbox-cambio-pais para fines de prueba. Habrá que quitar este if al programar.
	if( $('#opencbox-cambio-pais').length > 0)
		$.colorbox( {
			href: '/templates/script_ajax/cambio_portal-cbox.php',
			height: 360,
			width: 500,
			opacity: 0.3,
			onComplete: function() {
				$('#cbox-cambio-portal .ff-type-radio input').change( function(e) {
					$('#cbox-cambio-portal .ff-type-radio').removeClass('selected');
					if( $(this).is(':checked') )
						$(this).parent('.ff-type-radio').addClass('selected');
				});
			}
		});

	// -- fin cambio de país



});

var desplegadoActual = null;  // Global.  Almacena la capa visible actualmente

function conmuta(objId){
    // Conmuta la visibilidad de una capa
    // objId : Id de la capa a ocultar o mostrar
    
    if(desplegadoActual != null && desplegadoActual != objId){
        var actual = document.getElementById(desplegadoActual);
        actual.style.display="none";        
    }
    var objeto = document.getElementById(objId);
    if(objeto.style.display == "none"){
        objeto.style.display = "block";
    }else{
        objeto.style.display = "none";
    }
    desplegadoActual = objId;
}


//  Scriptlets code written by Jeremy Edmiston
//  The functions have been adapted from various sources
//  and re-written to provide maximum flexibility
//  and compatability with various browsers.

//Global Declarations
var ie = (document.all) ? true : false;

function toggleClass(objClass){
//  This function will toggle obj visibility of an Element
//  based on Element's Class
//  Works with IE and Mozilla based browsers

  if (getElementByClass(objClass).style.display=="none"){
    showClass(objClass)
  }else{
    hideClass(objClass)
  }
}

function hideClass(objClass){
//  This function will hide Elements by object Class
//  Works with IE and Mozilla based browsers

var elements = (ie) ? document.all : document.getElementsByTagName('*');
  for (i=0; i<elements.length; i++){
    if (elements[i].className==objClass){
      elements[i].style.display="none"
    }
  }
}

function showClass(objClass){
//  This function will show Elements by object Class
//  Works with IE and Mozilla based browsers
var elements = (ie) ? document.all : document.getElementsByTagName('*');
  for (i=0; i<elements.length; i++){
    if (elements[i].className==objClass){
      elements[i].style.display="block"
    }
  }
}

function toggleID(objID){
//  This function will toggle obj visibility of an Element
//  based on Element's ID
//  Works with IE and Mozilla based browsers
var element = (ie) ? document.all(objID) : document.getElementById(objID);
  if (element.style.display=="none"){
    showID(objID)
  }else{
    hideID(objID)
  }
}

function hideID(objID){
//  This function will hide Elements by object ID
//  Works with IE and Mozilla based browsers
var element = (ie) ? document.all(objID) : document.getElementById(objID);
  element.style.display="none"
}

function showID(objID){
//  This function will show Elements by object ID
//  Works with IE and Mozilla based browsers
var element = (ie) ? document.all(objID) : document.getElementById(objID);
  element.style.display="block"
}

function getElementByClass(objClass){
//  This function is similar to 'getElementByID' since there
//  is no inherent function to get an element by it's class
//  Works with IE and Mozilla based browsers
var elements = (ie) ? document.all : document.getElementsByTagName('*');
  for (i=0; i<elements.length; i++){
    //alert(elements[i].className)
    //alert(objClass)
    if (elements[i].className==objClass){
    return elements[i]
    }
  }
}

// FUCNIONES QUE HEMOS IDO AÑADIENDO NOSOTROS



// Funcion para los popups de los escaparates
function pop(nom_popup,ancho,alto,imagen,desc) {
    alto=(alto*1)+15;
    if (imagen.toUpperCase().indexOf(".PDF")!=-1){
        window.open(imagen,'','directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=yes');   
    }else{
        nom_vent=window.open ('/templates/moll_escaparate_popup.php?desc='+desc+'&imagen='+imagen,nom_popup,'height='+alto+',width='+ancho+',location=no,menubar=no,personalbar=no,scrollbars=no,status=no,titlebar=no,toolbar=no');    
    }
}

function popupGenerico(fuente, ancho, alto, scroll){ 
    window.open(fuente, '_blank', 'width='+ancho+', height='+alto+', top=1px, left=1px, status=yes, scrollbars='+scroll); 
}

function quitaAcentos(texto){
    texto=texto.replace("á", "a");
    texto=texto.replace("é", "e");
    texto=texto.replace("í", "i");
    texto=texto.replace("ó", "o");
    texto=texto.replace("ú", "u");
    return texto;
}

function censuraTexto(texto){
    texto=quitaAcentos(texto.toLowerCase());
    for(i=0; i<arrayPalabras.length; i++){ 
        if (texto.indexOf(arrayPalabras[i])>-1){
            if (texto.indexOf(arrayPalabras[i])!=0 && ((texto.charCodeAt(texto.indexOf(arrayPalabras[i])-1)>=65 && texto.charCodeAt(texto.indexOf(arrayPalabras[i])-1)<=90) || (texto.charCodeAt(texto.indexOf(arrayPalabras[i])-1)>=97 && texto.charCodeAt(texto.indexOf(arrayPalabras[i])-1)<=122))) return false;
            if (texto.substring(texto.indexOf(arrayPalabras[i])+arrayPalabras[i].length, 1)!='' && ((texto.charCodeAt(texto.indexOf(arrayPalabras[i])+arrayPalabras[i].length)>=65 && texto.charCodeAt(texto.indexOf(arrayPalabras[i])+arrayPalabras[i].length)<=90) || (texto.charCodeAt(texto.indexOf(arrayPalabras[i])+arrayPalabras[i].length)>=97 && texto.charCodeAt(texto.indexOf(arrayPalabras[i])+arrayPalabras[i].length)<=122))) return false;
            return arrayPalabras[i];
        }
    }
    return false;
}

function abreRevista(webroot,sec_id) {
    if (sec_id>0) lin=webroot+'revista/seccion.htm?id='+sec_id;
    else lin=webroot+'revista/revistaBodaclick/novias_revista_marcos.htm';
    window.open(lin,'revistanovias_' + sec_id, 'screenX=0,left=0,screenY=0,top=0,width=' + screen.width + ',height=' + screen.height + ',menubar=no,resizable=no,titlebar=no,alwaysRaised=yes,status=no,fullscreen=1,scrollbars=NO');
}

function imprimir(idReportaje,webroot,logo)
{
  window.open (webroot+"templates/versionImpresaReportaje.php?idReportaje="+idReportaje+"&logo="+logo,"Version_Impresa","top=0,left=0,width=700,height=700");
}

function strpos(str, ch) {
    for (var i = 0; i < str.length; i++)
    if (str.substring(i, i+ch.length) == ch) return i;
    return -1;
}

// Combo de las secciones para ir a una planta
function irPlanta(bdMollNacional) {
    var f=document.getElementById("selectIrPlanta");
    //Miro si ha seleccionado o no alguna opción
    if (f.selectedIndex == 0){
        location.href= "/?moll=" + bdMollNacional;
    }else{
        location.href=f.options[f.selectedIndex].value;
    }
    
}

//Carga dinamica de archivos AJAX
function ajaxpage(url, containerid){
    partes_url=url.split("?");
    url=partes_url[0];
    parametros=partes_url[1];
    //alert("URL: "+url);
    //alert("PARAMETROS: "+parametros);
    //alert("CONTENEDOR: "+containerid);
    jQuery("div#"+containerid).html("<center><img src='http://media.bodaclick.com/img/bd-loader.gif' border='0' />");
        jQuery.ajax( {
            type:"POST", url:url,
            data:parametros,
            success: function (msg) {
                    jQuery("div#"+containerid).html(msg);
            }
        } )
    jQuery("div#"+containerid).ajaxStop(function(){})
}

//Función redireccion por javascript
function setUrl(url){
    //alert(url);
    document.location.href=url;
}

//Función de desplegado y plegado de listados por ajax
function despliegaListado(contanerid){
    jQuery("div#"+contanerid).slideToggle("slow");
}

//Carga dinamica de enlaces sobre imagenes
function getByClassName(className, parentElement) {
    if (typeof parentElement == 'string'){
        parentElement = document.getElementById(parentElement);
    } else if (typeof parentElement != 'object' || typeof parentElement.tagName != 'string') {
        parentElement = document.body;
    }

    var children = parentElement.getElementsByTagName('*');
    var re = new RegExp(className);
    var element, elements = [];
    var i = 0;
    while ( (element = children[i++]) ){
        if ( element.className && re.test(element.className)){
          elements.push(element);
        }
    }
    return elements;
}

function fncImgL(imgObj,lnk)
{
    imgObj.style.cursor = 'pointer';
    imgObj.onclick = function() {
        window.location.href = lnk;
    }

}
function fnLnkImg()
{

    var imgs = getByClassName('imgProv_');

    for(i=0;i<imgs.length;i++) {
        var imgObj = imgs[i];
        var parts = imgObj.className.split(' '); //Elimina espacios
        for (j=0;j<parts.length;j++) {
            var pos =parts[j].indexOf('imgProv_');
            if (pos!=-1) {
                var idEmpresa = parts[j].substr(pos+8);
                var lnkObj = document.getElementById('linkProv_'+idEmpresa);
                if (typeof(lnkObj)!="undefined") {
                    fncImgL(imgObj, lnkObj.href);
                    break;
                }
            }
        }
    }
}

function portales(portalactual, web_root){
        var items = [];
        $.ajax({
			url: web_root+"templates/script_ajax/ajaxArrayPaises.php",
            type: "POST",
            data: ({portal : portalactual}),
            dataType: "json",
            async: false,
            success: function(msg){
                $.each(msg, function(key, val){
                    items[key]=val;
                });
            }
        });
        return items;
}

function cambioportal(portal, geoip_country_code, web_root){
        var items = [];
        $.ajax({
            url: web_root+"templates/script_ajax/ajaxArrayPaises.php",
            type: "POST",
            data: ({portal : null}),
            dataType: "json",
            success: function(msg){
                $.each(msg, function(key, val){
                    items[key]=val;
                });
                cambioportal_interno(portal, geoip_country_code,items, web_root);
            }
        });
}

function cambioportal_interno(portal, geoip_country_code,arrayPaises, web_root){
    encontrado = false;
    for(var i in arrayPaises){
        if((geoip_country_code=='PT' || geoip_country_code=='BR') && arrayPaises[i][0]==geoip_country_code){
            //if(arrayPaises[i][0]==geoip_country_code){
            encontrado = true;
        }
    }
    //si existe algo que se le pueda sugerir

    if(encontrado== true && arrayPaises[portal][0]!=geoip_country_code){
    $.ajax({
       url: web_root+'templates/script_ajax/ajax_cambio_portal.php',
        dataType: "html",
        success: function(msg){
            $('#cambio-portal').html(msg);
        }
        });
    }
}

function redireccion(geoip_country_code, portal, web_root){
		// CAPAMOS TEMPORALMENTE LA CANALIZACION DEL TRAFICO HASTA QUE MKT ONLINE SE PRONUNCIE
		//return true;
        var items = [];
        $.ajax({
            url: web_root+"templates/script_ajax/ajaxArrayPaises.php",
            type: "POST",
            data: ({portal : null}),
            dataType: "json",
            success: function(msg){
                $.each(msg, function(key, val){
                    items[key]=val;
                });
                
                redireccion_interno(geoip_country_code,portal, items, web_root);
            }
        });
}

function redireccion_interno(geoip_country_code,portal, arrayPaises, web_root){
            var portalActual = parseInt(portal);
            
            if(!$.cookie("localizacionBC")){ //Si no hay cookie, preguntamos
                  
         //       var cookieLocalizacion = $.cookie("localizacionBC").split(' ');
         //       
         //       if(cookieLocalizacion[2]==portalActual){
         //       }
         //       else{
         //           if(cookieLocalizacion[3]==null || cookieLocalizacion[3]==""){
         //               encontrado = false;
         //               for(var i in arrayPaises){
         //                   if((geoip_country_code=='PT' || geoip_country_code=='BR') && arrayPaises[i][0]==geoip_country_code){
         //                       encontrado = true;
         //                   }
         //               }
         //               
         //               if(encontrado == true){
         //                   jQuery(document).ready(function($){
         //                       $.colorbox({
         //                           href:web_root+'templates/script_ajax/cambio_portal-cbox2.php?pt='+arrayPaises[portalActual][0]+'&tg='+geoip_country_code,
         //                           height: 440,
         //                           width: 550,
         //                           top: "150px",
         //                           opacity: 0.3,
         //                           onComplete: function() {
         //                               $('#cbox-cambio-portal .ff-type-radio input').change( function(e) {
         //                                   $('#cbox-cambio-portal .ff-type-radio').removeClass('selected');
         //                                   if( $(this).is(':checked') )
         //                                       $(this).parent('.ff-type-radio').addClass('selected');
         //                               });
         //                           }
         //                       });
         //                   });
         //               }
         //               else{
         //               }
         //           }
         //           else{
         //           }
         //       }
           // }
           // else{
                //if((geoip_country_code=='PT' || geoip_country_code=='BR') && arrayPaises[portalActual][0] == geoip_country_code){
                //}
                //else{
                    encontrado = false;
                    for(var i in arrayPaises){
                        if((geoip_country_code=='PT' || geoip_country_code=='BR') && arrayPaises[i][0]==geoip_country_code){
                            encontrado = true;
                        }
                    }
                    
                    //if(encontrado == true){
                    if(encontrado== true && arrayPaises[portalActual][0]!=geoip_country_code){
                                                                       
                        jQuery(document).ready(function($){
                            $.colorbox({
                                href:web_root+'templates/script_ajax/cambio_portal-cbox.php?pt='+arrayPaises[portalActual][0]+'&tg='+geoip_country_code,
                                height: 440,
                                width: 550,
                                top: "150px",
                                opacity: 0.3,
                                onComplete: function() {
                                        $('#cbox-cambio-portal .ff-type-radio input').change( 
                                        function(e) {
                                        
                                        $('#cbox-cambio-portal .ff-type-radio').removeClass('selected');
                                        if( $(this).is(':checked') ){
                                            $(this).parent('.ff-type-radio').addClass('selected');
                                        }
                                    });
                                },
                                onClosed: function() {
					//Incluimos codigo seguimiento Google Analytics como evento "Continuar en cerrando ventana  ..." 07-11-2011
                                        if (arrayPaises[portalActual][0]=='PT') //Elegir seguir en Portugal desde Portugal: 
                                               _gaq.push(['_trackEvent', 'Formulario de Seleccion de Pais', 'http://www.casamentoclick.com','Continuar en Portugal desde Casamentoclick.com cerrando Popup']);
                                        else if (arrayPaises[portalActual][0]=='BR') //Elegir seguir en Brasil desde Brasil: 
                                               _gaq.push(['_trackEvent','Formulario de Seleccion de Pais','http://www.casamentoclick.com.br','Continuar en Brasil desde Casamentoclick.com.br cerrando Popup']);
                                                
                                        $.cookie("localizacionBC", arrayPaises[portalActual][0]+" "+arrayPaises[portalActual][1]+" "+arrayPaises[portalActual][2],{ expires: 1 });
                                        
                                    }
                            });
                        });
                    }  
               // }
            }
}

