
/*-------------------------------------------
  ---  seccion <_common>         -----
  -------------------------------------------*/


function json_stringify (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n];
            t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = json_stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};


//Seteo de proveTrafico
function trackPTrafico(reducedUrl){

    var ptInfo;
    if( GetCookie("pt") != null
        && GetCookie("pt") != "undefined"
        ) {            
        eval("ptInfo="+GetCookie("pt"));
        if (ptInfo['id']!= null) {
            return;
        } 
    }

    var imagenespia='<img src="/utils-SetProveTrafico.php';
    if (location.search) {
        imagenespia += location.search;
    }else{
        imagenespia += "?";
    }

    if(location.search!='') imagenespia+='&';
    else  imagenespia+='';

    if(location.href.indexOf('#')!=-1){

        queryaddword=location.href.split('#')[1];
        imagenespia+=queryaddword+"&";
    }

    if (reducedUrl != null) {
        imagenespia+='ru='+escape(reducedUrl)+'&';
    }
    imagenespia+='r='+document.referrer.replace(new RegExp('&','gi'), '|');
    imagenespia+='&e='+location.href.replace(new RegExp('&','gi'), '|');
    imagenespia+='" width="0" height="0" style="position:absolute;top:-100px">';

    document.write(imagenespia);

}


function setZOrigen(valor) {
    var ptInfo = Object();
    if( GetCookie("pt") != null
        && GetCookie("pt") != "undefined"
        ) {
        eval("ptInfo="+GetCookie("pt"));
    }
    ptInfo['o'] = valor;
    SetCookieSession("pt",json_stringify(ptInfo));  
    return true;
}

function showQuoteLayer(e) {
    common_openLayer(e, '/emp-QuickQuote.php');
}

function common_reloadTop()
{
    top.location.href = top.location;
}


function getPointByAddress(address, fncOk, fncError)
{
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(
        address,
        function(point) {
            if (!point) {
                fncError();
            } else {
                fncOk(point.lat(), point.lng());
            }
        }
    );
}

function IframeConversion(id) {
	var bodyAdw = document.getElementsByTagName('body')[0];
	var conv = document.createElement('iframe');
    id = id+"-"+Math.floor(Math.random()*10000);
	conv.setAttribute('src',"http://"+"www.weddingspot.co.uk"+"/landing-AdwordsSolic.php?id="+id);
	conv.setAttribute('id',id);
	conv.style.display="none";
	bodyAdw.appendChild(conv);
}


function common_layerFrmSolicitud(e,id_empresa) {
	common_openLayer(
        e,
        '/emp-Form.php?id_empresa='+id_empresa,
        null,
        null,
        showContactarEmpCookies
    );
}


/**
 * Mostramos cajita de vendors para presupuestos
 */
function showVendorBox() {
	// Obtenemos los vendors guardados
	var aVendors=getQuotedVendors();

	// Mostramos la caja con el número de empresas a presupuestar
	var htmlVendorBox="<span class='ico calculator'>"+'Quote Request'+"</span>: <a href='http://"+"www.weddingspot.co.uk"+"/emp-QuickQuoteMore.php' class='strong'>"+aVendors.length+" "+'Businesses'+"</a>";
	$('#myQuotes').html(htmlVendorBox);
}


/**
 * Obtenemos array de vendors guardados en presupuestos
 */
function getQuotedVendors() {
	if (GetCookie("USER_QUICKQUOTE_VENDORS")) {
		var quotedVendors=GetCookie("USER_QUICKQUOTE_VENDORS");
		var aVendors=quotedVendors.split(",");
	} else {
		var aVendors=new Array();
	}
	
	return aVendors;
}



/**
 * Comprobación de usduario duplicado
 * 
 * @return true si el mail no exite en BDD
 */
function common_verificaUserUnico(mail){
    
    var idDuplicate = false;
    
    $.ajax({
        url:"/com-VerificaUserDup.php?mail="+mail,
        async:false,
        success:function(res){
            idDuplicate = res != 'OK';
        }
    });
    
	return idDuplicate;
}

function ponerCapaOscura() {
	var coscura = document.createElement("div");
	coscura.setAttribute("id", "shadow");
    coscura.style.zIndex="100";
	coscura.style.height=getPageSize()[1]+"px";
	document.body.appendChild(coscura);
}

function quitarCapaOscura() {
	$("#shadow").remove();

}

function ajaxFormFunc(form,func) {
  // Enviamos el formulario usando AJAX
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: $(form).serialize(),
            success: function(data) {
                func();
            }
        })
        return false;    
}


function ajaxFormFuncPage(form,layer,func) {
  // Enviamos el formulario usando AJAX
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: $(form).serialize(),
            success: function(data) {
                func();
				$(layer).html(data);
            }
        })
        return false;
}



function common_showCapaFormularioSolic(elem, idEmpresa, isLanding, zonaOrigen, url)
{

    if (url == null) {
        url = '/landings/form.php?id_empresa='+idEmpresa+"&isCapaSolicitud=1";
    }
    
    if (isLanding) {
        url += "&isLanding=1";
    }
    
    if (zonaOrigen != null) {
        setZOrigen(zonaOrigen);
    }
    
    
    //si no tenemos el iframe para el submit de solicitud lo creamos
    if ($("#fMultisolicitud").length == 0){

        CrearIframe("fMultisolicitud");
    }
    
    //ñapa!!!!! si encontramos el formulario document.frmContacto lo renombramos a frmContacto2. En onclose lo volvemos a poner
    if (typeof(document.forms["frmContacto"]) != "undefined") {
        var formulario = document.forms["frmContacto"];
        formulario.name="frmContacto2";
    } else {
        var formulario = null;
    }
    
    $.colorbox({
        href: url,
        transition:"none", 
        overlayClose: false,
        width:"660", scrolling:false,maxHeight:false,
/*      onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },*/
        onComplete:function() {
            showContactarEmpCookies();
            $.colorbox.resize();
        },
        onClosed:function(){ 
            if (formulario != null) {
                formulario.name="frmContacto";
            }    
        }
    });
    
    return false;
}

function common_showLayerRedirect(options)
{
	if (document.referrer != ''
        && document.referrer.indexOf('.google.') != -1) {		
		if (typeof(GetCookie) != 'undefined' && navigator.cookieEnabled) {
				cookie_LayerRedirect = GetCookie('layerRedirect');
				if (!cookie_LayerRedirect || cookie_LayerRedirect!='2') {
				$.ajax({
					url:"/utils-LayerRedirect.php?options="+options,
					success:function(res){
						$('#header').append(res);
						setTimeout(function(){$('#layerRedirect').fadeIn(700)},1500);
					}
				});
            }
        }
    } 
}

function common_redirectPost(action, postParams) {
        
    var str = "";
    for (var key in postParams) {
        var val = postParams[key].trim();
        if (val.length>0) {
            str+="<input type='hidden' name='"+key+"' value='"+val+"'/>";
        }
    }
    str = "<form id='gwoRedir' action='"+action+"' method='POST'>"+str+"</form>";
    document.write(str);
    $("#gwoRedir").submit();
}

/*-------------------------------------------
  ---  seccion <lib/AjaxFormManager>         -----
  -------------------------------------------*/


/**
 * Clase para la gestión de formularios
 *
 * @category Emagister
 * @package  Emagister_Common
 * @author   Gregorio Martínez <gmartinez@emagister.com>
 *
 */

/**
 * Constructor
 *
 * @param Object   form           Formulario a validar
 * @param Function onOk           Función a llamar si todo ha ido bien
 * @param Function onError        Función a llamar si ha habido un error
 * @param int      errDisplayMode formato de visualización de errores. Debe ser una constante de la clase
 * @param Function errDisplayFnc  función custom para renderizar errores, si errDisplayMode = ERR_DISPLAY_CUSTOM
 * 
 */
function AjaxFormManager(form, errDisplayMode, errDisplayFnc, onOk, onError, progressFunction){
    
	this.form 	 = $(form);
    this.onOk    = onOk;
    this.onError = onError;
    this.errDisplayMode = errDisplayMode;
    this.errDisplayFnc = errDisplayFnc;
    this.progressFunction = progressFunction;
    var afm = this;
    
    if (this.errDisplayMode == null) {
        this.errDisplayMode = this.ERR_DISPLAY_STANDAR;
    }

    var oldSubmit = form[0].onsubmit;
    form[0].onsubmit = null;

    this.form.submit(
        function(){
            if (typeof(tinyMCE) != "undefined") tinyMCE.triggerSave();
            if (oldSubmit != null) {
                if (oldSubmit.call(this)) {
                    afm.doSubmit();
                }
            } else {
                afm.doSubmit();                
            }
            return false;
        }
    );

        
}

AjaxFormManager.prototype = {

    ERR_DISPLAY_STANDAR: 1,
    ERR_DISPLAY_ALERT:   2,
    ERR_DISPLAY_CUSTOM:  3,

	doSubmit: function(){

        var url = this.form.attr("action");
        var data = this.form.serialize();
        var afm = this;

        document.body.style.cursor = "wait";

        if (this.progressFunction != null) {
            this.progressFunction(true);
        }
        $.post( url,
                data,
                function(response){

                    if (afm.progressFunction != null) {
                        afm.progressFunction(false);
                    }
                    document.body.style.cursor = "default";
                    
                    //para cada elemento que hay en el formulario quitarmos los errores y luego lo marcamos
                    afm.form.find(".mensajeError").remove();
                    afm.form.find(".conError").removeClass("conError");

                    //miramos la respuesta. Si ha ido ok, ejecutamos el resultado, sino maquetamos cada error
                    if (response.errCode == 0){
                        afm.doOk(response);
                    }else{
                        afm.doError(response);
                    }
                },
                "json"
            );
	},


    doOk: function(response){

        var afm = this;
        
        this.form.find(".errors").remove();

        //si tenemos algún mensaje y es global lo mostramos con un alert
        if(response.messages != null) {
            $.each(response.messages,
                function(nameField,message){
                    if (nameField == "global") {
                        alert(message);
                        return false;
                    }
                }
              );
        }


        if(this.onOk){
            this.onOk(response);
        }else if(response.redirect != null){
            //en redirecciones si hay funcion de progreso la volvemos a poner
            if (afm.progressFunction != null) {
                afm.progressFunction(true);
            }
            window.location = response.redirect;
        }else{
            //window.location.reload();
            window.location.href=window.location.href;
        }    
        
    },

    doError: function(response){

        //quitamos los errores antiguos
        this.form.find(".errors").remove();

        var dspFnc = null;
        var afm = this;
        switch(this.errDisplayMode){

            case this.ERR_DISPLAY_CUSTOM:
                $.each(response.messages, this.errDisplayFnc);
                break;

            case this.ERR_DISPLAY_ALERT:
                $.each(response.messages,
                       function(id,msg){
                            alert(msg);
                            return false;
                        }
                      );
                break;

            default:
                $.each(response.messages,
                      function(nameField,message){
                            //si eran campos de un tinymce el item será una tabla
                            //que se llame nameFile_parent
                            var tinyField = $('#'+nameField+'_parent', afm.form);
                            if (tinyField.length>0) {
                                tinyField.parent().append(
                                    "<div class=\"mensajeError\" style='clear:left'>"+message+"</div>"
                                );
                                tinyField.addClass("conError");
                            } else{
                                $('[name='+nameField+']', afm.form).parent().append(
                                    "<p class=\"mensajeError\">"+message+"</p>"
                                );
                                $('[name='+nameField+']', afm.form).addClass("conError");
                            }
                      }
                 );
                     
                 //ponemos el foco en el primer error
                 //TODO: Poner scroll en el primer campo también. Mirar plugin jquery http://plugins.jquery.com/project/ScrollTo
                 $.each(response.messages,
                      function(nameField,message){
                            var elem = $('[name='+nameField+']', afm.form);
                            elem.focus();
                            if(elem && elem.length > 0) {
                                //$.scrollTo(elem, {offset: {top:-200}});
                                return false;
                            }
                      }
                 );
        }

        //si hay alguno que tenga la clave "global" lo mostramos con un alert
        var hayMensajeGlobal = false;
        $.each(response.messages,
                function(nameField,message){
                    if (nameField == "global") {
                        alert(message);
                        hayMensajeGlobal = true;
                        return false;
                    }
                }
        );

        //si no hay mensaje global mostramos el primer error
        if (!hayMensajeGlobal && this.errDisplayMode == this.ERR_DISPLAY_STANDAR) {            
            alert('We found errors processing your form.');
        }

        if (this.onError != null) {
            this.onError(response);
        }
            
    }

};


/*-------------------------------------------
  ---  seccion <lib/jquery.colorbox-min>         -----
  -------------------------------------------*/


// ColorBox v1.3.17.2 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
// Copyright (c) 2011 Jack Moore - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function(a,b,c){function bc(b){if(!U){P=b,_(),y=a(P),Q=0,K.rel!=="nofollow"&&(y=a("."+g).filter(function(){var b=a.data(this,e).rel||this.rel;return b===K.rel}),Q=y.index(P),Q===-1&&(y=y.add(P),Q=y.length-1));if(!S){S=T=!0,r.show();if(K.returnFocus)try{P.blur(),a(P).one(l,function(){try{this.focus()}catch(a){}})}catch(c){}q.css({opacity:+K.opacity,cursor:K.overlayClose?"pointer":"auto"}).show(),K.w=Z(K.initialWidth,"x"),K.h=Z(K.initialHeight,"y"),X.position(),o&&z.bind("resize."+p+" scroll."+p,function(){q.css({width:z.width(),height:z.height(),top:z.scrollTop(),left:z.scrollLeft()})}).trigger("resize."+p),ba(h,K.onOpen),J.add(D).hide(),I.html(K.close).show()}X.load(!0)}}function bb(){var a,b=f+"Slideshow_",c="click."+f,d,e,g;K.slideshow&&y[1]?(d=function(){F.text(K.slideshowStop).unbind(c).bind(j,function(){if(Q<y.length-1||K.loop)a=setTimeout(X.next,K.slideshowSpeed)}).bind(i,function(){clearTimeout(a)}).one(c+" "+k,e),r.removeClass(b+"off").addClass(b+"on"),a=setTimeout(X.next,K.slideshowSpeed)},e=function(){clearTimeout(a),F.text(K.slideshowStart).unbind([j,i,k,c].join(" ")).one(c,d),r.removeClass(b+"on").addClass(b+"off")},K.slideshowAuto?d():e()):r.removeClass(b+"off "+b+"on")}function ba(b,c){c&&c.call(P),a.event.trigger(b)}function _(b){K=a.extend({},a.data(P,e));for(b in K)a.isFunction(K[b])&&b.substring(0,2)!=="on"&&(K[b]=K[b].call(P));K.rel=K.rel||P.rel||"nofollow",K.href=K.href||a(P).attr("href"),K.title=K.title||P.title,typeof K.href=="string"&&(K.href=a.trim(K.href))}function $(a){return K.photo||/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(a)}function Z(a,b){return Math.round((/%/.test(a)?(b==="x"?z.width():z.height())/100:1)*parseInt(a,10))}function Y(c,d,e){e=b.createElement("div"),c&&(e.id=f+c),e.style.cssText=d||"";return a(e)}var d={transition:"elastic",speed:300,width:!1,initialWidth:"600",innerWidth:!1,maxWidth:!1,height:!1,initialHeight:"450",innerHeight:!1,maxHeight:!1,scalePhotos:!0,scrolling:!0,inline:!1,html:!1,iframe:!1,fastIframe:!0,photo:!1,href:!1,title:!1,rel:!1,opacity:.9,preloading:!0,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:!1,returnFocus:!0,loop:!0,slideshow:!1,slideshowAuto:!0,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:!1,onLoad:!1,onComplete:!1,onCleanup:!1,onClosed:!1,overlayClose:!0,escKey:!0,arrowKey:!0,top:!1,bottom:!1,left:!1,right:!1,fixed:!1,data:!1},e="colorbox",f="cbox",g=f+"Element",h=f+"_open",i=f+"_load",j=f+"_complete",k=f+"_cleanup",l=f+"_closed",m=f+"_purge",n=a.browser.msie&&!a.support.opacity,o=n&&a.browser.version<7,p=f+"_IE6",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X;X=a.fn[e]=a[e]=function(b,c){var f=this;b=b||{};if(!f[0]){if(f.selector)return f;f=a("<a/>"),b.open=!0}c&&(b.onComplete=c),f.each(function(){a.data(this,e,a.extend({},a.data(this,e)||d,b)),a(this).addClass(g)}),(a.isFunction(b.open)&&b.open.call(f)||b.open)&&bc(f[0]);return f},X.init=function(){z=a(c),r=Y().attr({id:e,"class":n?f+(o?"IE6":"IE"):""}),q=Y("Overlay",o?"position:absolute":"").hide(),s=Y("Wrapper"),t=Y("Content").append(A=Y("LoadedContent","width:0; height:0; overflow:hidden"),C=Y("LoadingOverlay").add(Y("LoadingGraphic")),D=Y("Title"),E=Y("Current"),G=Y("Next"),H=Y("Previous"),F=Y("Slideshow").bind(h,bb),I=Y("Close")),s.append(Y().append(Y("TopLeft"),u=Y("TopCenter"),Y("TopRight")),Y(!1,"clear:left").append(v=Y("MiddleLeft"),t,w=Y("MiddleRight")),Y(!1,"clear:left").append(Y("BottomLeft"),x=Y("BottomCenter"),Y("BottomRight"))).children().children().css({"float":"left"}),B=Y(!1,"position:absolute; width:9999px; visibility:hidden; display:none"),a("body").prepend(q,r.append(s,B)),t.children().hover(function(){a(this).addClass("hover")},function(){a(this).removeClass("hover")}).addClass("hover"),L=u.height()+x.height()+t.outerHeight(!0)-t.height(),M=v.width()+w.width()+t.outerWidth(!0)-t.width(),N=A.outerHeight(!0),O=A.outerWidth(!0),r.css({"padding-bottom":L,"padding-right":M}).hide(),G.click(function(){X.next()}),H.click(function(){X.prev()}),I.click(function(){X.close()}),J=G.add(H).add(E).add(F),t.children().removeClass("hover"),q.click(function(){K.overlayClose&&X.close()}),a(b).bind("keydown."+f,function(a){var b=a.keyCode;S&&K.escKey&&b===27&&(a.preventDefault(),X.close()),S&&K.arrowKey&&y[1]&&(b===37?(a.preventDefault(),H.click()):b===39&&(a.preventDefault(),G.click()))})},X.remove=function(){r.add(q).remove(),a("."+g).removeData(e).removeClass(g)},X.position=function(a,c){function g(a){u[0].style.width=x[0].style.width=t[0].style.width=a.style.width,C[0].style.height=C[1].style.height=t[0].style.height=v[0].style.height=w[0].style.height=a.style.height}var d=0,e=0;z.unbind("resize."+f),r.hide(),K.fixed&&!o?r.css({position:"fixed"}):(d=z.scrollTop(),e=z.scrollLeft(),r.css({position:"absolute"})),K.right!==!1?e+=Math.max(z.width()-K.w-O-M-Z(K.right,"x"),0):K.left!==!1?e+=Z(K.left,"x"):e+=Math.round(Math.max(z.width()-K.w-O-M,0)/2),K.bottom!==!1?d+=Math.max(b.documentElement.clientHeight-K.h-N-L-Z(K.bottom,"y"),0):K.top!==!1?d+=Z(K.top,"y"):d+=Math.round(Math.max(b.documentElement.clientHeight-K.h-N-L,0)/2),r.show(),a=r.width()===K.w+O&&r.height()===K.h+N?0:a||0,s[0].style.width=s[0].style.height="9999px",r.dequeue().animate({width:K.w+O,height:K.h+N,top:d,left:e},{duration:a,complete:function(){g(this),T=!1,s[0].style.width=K.w+O+M+"px",s[0].style.height=K.h+N+L+"px",c&&c(),setTimeout(function(){z.bind("resize."+f,X.position)},1)},step:function(){g(this)}})},X.resize=function(a){if(S){a=a||{},a.width&&(K.w=Z(a.width,"x")-O-M),a.innerWidth&&(K.w=Z(a.innerWidth,"x")),A.css({width:K.w}),a.height&&(K.h=Z(a.height,"y")-N-L),a.innerHeight&&(K.h=Z(a.innerHeight,"y"));if(!a.innerHeight&&!a.height){var b=A.wrapInner("<div style='overflow:auto'></div>").children();K.h=b.height(),b.replaceWith(b.children())}A.css({height:K.h}),X.position(K.transition==="none"?0:K.speed)}},X.prep=function(b){function h(){K.h=K.h||A.height(),K.h=K.mh&&K.mh<K.h?K.mh:K.h;return K.h}function g(){K.w=K.w||A.width(),K.w=K.mw&&K.mw<K.w?K.mw:K.w;return K.w}if(!!S){var c,d=K.transition==="none"?0:K.speed;A.remove(),A=Y("LoadedContent").append(b),A.hide().appendTo(B.show()).css({width:g(),overflow:K.scrolling?"auto":"hidden"}).css({height:h()}).prependTo(t),B.hide(),a(R).css({"float":"none"}),o&&a("select").not(r.find("select")).filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one(k,function(){this.style.visibility="inherit"}),c=function(){function o(){n&&r[0].style.removeAttribute("filter")}var b,c,g,h,i=y.length,k,l;!S||(l=function(){clearTimeout(W),C.hide(),ba(j,K.onComplete)},n&&R&&A.fadeIn(100),D.html(K.title).add(A).show(),i>1?(typeof K.current=="string"&&E.html(K.current.replace("{current}",Q+1).replace("{total}",i)).show(),G[K.loop||Q<i-1?"show":"hide"]().html(K.next),H[K.loop||Q?"show":"hide"]().html(K.previous),b=Q?y[Q-1]:y[i-1],g=Q<i-1?y[Q+1]:y[0],K.slideshow&&F.show(),K.preloading&&(h=a.data(g,e).href||g.href,c=a.data(b,e).href||b.href,h=a.isFunction(h)?h.call(g):h,c=a.isFunction(c)?c.call(b):c,$(h)&&(a("<img/>")[0].src=h),$(c)&&(a("<img/>")[0].src=c))):J.hide(),K.iframe?(k=a("<iframe/>").addClass(f+"Iframe")[0],K.fastIframe?l():a(k).one("load",l),k.name=f+ +(new Date),k.src=K.href,K.scrolling||(k.scrolling="no"),n&&(k.frameBorder=0,k.allowTransparency="true"),a(k).appendTo(A).one(m,function(){k.src="//about:blank"})):l(),K.transition==="fade"?r.fadeTo(d,1,o):o())},K.transition==="fade"?r.fadeTo(d,0,function(){X.position(0,c)}):X.position(d,c)}},X.load=function(b){var c,d,e=X.prep;T=!0,R=!1,P=y[Q],b||_(),ba(m),ba(i,K.onLoad),K.h=K.height?Z(K.height,"y")-N-L:K.innerHeight&&Z(K.innerHeight,"y"),K.w=K.width?Z(K.width,"x")-O-M:K.innerWidth&&Z(K.innerWidth,"x"),K.mw=K.w,K.mh=K.h,K.maxWidth&&(K.mw=Z(K.maxWidth,"x")-O-M,K.mw=K.w&&K.w<K.mw?K.w:K.mw),K.maxHeight&&(K.mh=Z(K.maxHeight,"y")-N-L,K.mh=K.h&&K.h<K.mh?K.h:K.mh),c=K.href,W=setTimeout(function(){C.show()},100),K.inline?(Y().hide().insertBefore(a(c)[0]).one(m,function(){a(this).replaceWith(A.children())}),e(a(c))):K.iframe?e(" "):K.html?e(K.html):$(c)?(a(R=new Image).addClass(f+"Photo").error(function(){K.title=!1,e(Y("Error").text("This image could not be loaded"))}).load(function(){var a;R.onload=null,K.scalePhotos&&(d=function(){R.height-=R.height*a,R.width-=R.width*a},K.mw&&R.width>K.mw&&(a=(R.width-K.mw)/R.width,d()),K.mh&&R.height>K.mh&&(a=(R.height-K.mh)/R.height,d())),K.h&&(R.style.marginTop=Math.max(K.h-R.height,0)/2+"px"),y[1]&&(Q<y.length-1||K.loop)&&(R.style.cursor="pointer",R.onclick=function(){X.next()}),n&&(R.style.msInterpolationMode="bicubic"),setTimeout(function(){e(R)},1)}),setTimeout(function(){R.src=c},1)):c&&B.load(c,K.data,function(b,c,d){e(c==="error"?Y("Error").text("Request unsuccessful: "+d.statusText):a(this).contents())})},X.next=function(){!T&&y[1]&&(Q<y.length-1||K.loop)&&(Q=Q<y.length-1?Q+1:0,X.load())},X.prev=function(){!T&&y[1]&&(Q||K.loop)&&(Q=Q?Q-1:y.length-1,X.load())},X.close=function(){S&&!U&&(U=!0,S=!1,ba(k,K.onCleanup),z.unbind("."+f+" ."+p),q.fadeTo(200,0),r.stop().fadeTo(300,0,function(){r.add(q).css({opacity:1,cursor:"auto"}).hide(),ba(m),A.remove(),setTimeout(function(){U=!1,ba(l,K.onClosed)},1)}))},X.element=function(){return a(P)},X.settings=d,V=function(a){a.button!==0&&typeof a.button!="undefined"||a.ctrlKey||a.shiftKey||a.altKey||(a.preventDefault(),bc(this))},a.fn.delegate?a(b).delegate("."+g,"click",V):a("."+g).live("click",V),a(X.init)})(jQuery,document,this);
/*-------------------------------------------
  ---  seccion <commons>         -----
  -------------------------------------------*/


//-------------------------------------------------------------------------------------------
//  FUNCIONES CARGA DE VENTANAS CON AJAX
//-------------------------------------------------------------------------------------------
var bustcachevar=1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects="";
var rootdomain="http://"+window.location.hostname;
var bustcacheparameter="";
var paisesTipo1="198,";
var paisesTipo2="10,43,47,139,229";

function ajaxpage(url, containerid){
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	} else return false;

	page_request.onreadystatechange=function(){loadpage(page_request, containerid)};

	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	page_request.open('GET', url+bustcacheparameter, true);
	page_request.send(null);
}

function loadpage(page_request, containerid){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
		document.getElementById(containerid).innerHTML=page_request.responseText;
        if (typeof(document.onLayerLoaded) != "undefined" && document.onLayerLoaded != null) {
            document.onLayerLoaded();
        }
	}
}

function loadobjs(){
	if (!document.getElementById)
		return;
	for (i=0; i<arguments.length; i++){
		var file=arguments[i];
		var fileref="";
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
		if (file.indexOf(".js")!=-1){ //If object is a js file
		fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", file);
	} else if (file.indexOf(".css")!=-1){ //If object is a css file
		fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", file);
		}
	}
		if (fileref!=""){
		document.getElementsByTagName("head").item(0).appendChild(fileref);
		loadedobjects+=file+" "; //Remember this object as being already added to page
		}
	}
}

//----------------------------------------------------------------
// Ajaxpage sincrono para funciones...
//------------------------------------------------------------

function ajaxfunc(url, func){	
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	} else return false;

	page_request.onreadystatechange=function(){loadfunc(page_request, func)};

	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	page_request.open('GET', url+bustcacheparameter, true);
	page_request.send(null);
}

function loadfunc(page_request, func){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
	func();
}

//----------------------------------------------------------------
// Ajaxpage sincrono para funciones...
//------------------------------------------------------------

function ajaxpagefunc(url, containerid, func){	
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	} else return false;

	page_request.onreadystatechange=function(){loadpagefunc(page_request, containerid, func)};

	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	page_request.open('GET', url+bustcacheparameter, true);
	page_request.send(null);
}

function loadpagefunc(page_request, containerid, func){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
		document.getElementById(containerid).innerHTML=page_request.responseText;
		func();
	}
}

//--------------------------------------------------------------------------------------------
//  UTILIDADES DEL BUSCADOR
//--------------------------------------------------------------------------------------------

function UnloadProvincia() {
	document.frmSearch.id_provincia.value="";
	document.frmSearch.id_poblacion.value="";
	document.frmSearch.submit();
}

function UnloadPoblacion() {
	document.frmSearch.id_poblacion.value="";
	document.frmSearch.submit();
}

function UnloadGrupo() {
	document.frmSearch.id_grupo.value="";
	document.frmSearch.id_sector.value="";
	document.frmSearch.submit();
}

function UnloadSector() {
	document.frmSearch.id_sector.value="";
	document.frmSearch.submit();
}

function LodShowMode(mode) {
	document.frmSearch.showmode.value=mode;
	document.frmSearch.submit();
}

function LoadBuscPage(npage) {
	document.frmSearch.NumPage.value=npage;
	document.frmSearch.submit();
}

function LoadBuscComPage(npage) {
	document.frmSearchCom.NumPage.value=npage;
	document.frmSearchCom.submit();
}


//--------------------------------------------------------------------------------------------
//  METODOS DE VALIDACIÓN DE FORMULARIOS
//--------------------------------------------------------------------------------------------

function getValueRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i < buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return buttonGroup[i].value;
         }
      }
   } else {
      if (buttonGroup.checked) { return buttonGroup.value; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return null;
}

function VerificaContacto(form) {
	if(form.Nombre.value.length<5){alert("Enter your full name.");form.Nombre.focus();return false;}
	var arroba_found=false;var punto_found=false;var i=0;
	while((i < form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
	if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
	while((i < form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}
	if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain an. followed by at least two characters");form.Mail.focus();return false;}
	if(form.Telefono.value.length<6){alert("Please enter a phone number for companies to contact you.");form.Telefono.focus();return false;}
    if(form.Fecha.value.length<1){alert("Approximate date of (your/the) event.");form.Fecha.focus();return false;}
	if(typeof(form.Comensales)!="undefined") {
		if(form.Comensales.value.length<1){alert("Approximate number of guests.");form.Comensales.focus();return false;}
    }
    //si el rol es visible lo validamos
    if (document.getElementById("divRol").style.display=="block") {
        var rol = getValueRadio(form.Rol);
        if(typeof(form.Rol) != "undefined" && rol == null){alert("Let us know your role in the wedding");form.Rol[0].focus();return false;}
    }
	if(form.Comentario.value.length<10){alert("Your comment must contain a minimum of ten characters");form.Comentario.focus();return false;}
	return true;
}	

function ContinuarEnvio() {
	document.frmMultisolic.continuar.value=1;
	document.frmMultisolic.submit();
}


function usuarioRegistradoAndVenue(Mail) {
	usuarioRegistrado(Mail);
	if(verificaVenueSaved(Mail,"")) {
		document.getElementById("divVenueSaved").style.display="none";
	} else {
		document.getElementById("divVenueSaved").style.display="block";
	}
}

function usuarioRegistrado(Mail) {
	if(verificaUserDup(Mail,"")&&(Mail.value!="")) {
		document.getElementById("divRol").style.display="block";
		document.frmContacto.SolicNewMail.value=1;
	} else {
		document.getElementById("divRol").style.display="none";
		document.getElementById("divProvinciaBoda").style.display="none";
		if ((document.frmContacto.Grupo==1)||(document.frmContacto.Grupo==2)) {
			document.getElementById("divFechaBoda").style.display="none";
		}	
		document.getElementById("divOrganizacionBoda").style.display="none";	
		document.frmContacto.SolicNewMail.value=0;				
	}			
    
    //si el formulario es en una capa y hay colorbox los expandimos
    $.colorbox.resize();
}

function usuarioRegistradoVendor(Mail) {
		if(verificaUserDup(Mail,"")&&(Mail.value!="")) {
			document.getElementById("divExtraFields").style.display="block";
			document.getElementById("divRules").style.display="block";		
		}			
}
			
function showCamposNovios(rol) {
	if(verificaUserDup(document.frmContacto.Mail,"")&&(document.frmContacto.Mail.value!="")) {
		if((rol==1)||(rol==2)) {				
			document.getElementById("divProvinciaBoda").style.display="block";
			document.getElementById("divFechaBoda").style.display="block";
			document.getElementById("divOrganizacionBoda").style.display="block";	
		} else {
			document.getElementById("divProvinciaBoda").style.display="none";
			if ((document.frmContacto.Grupo==1)||(document.frmContacto.Grupo==2)) {
				document.getElementById("divFechaBoda").style.display="none";
			}	
			document.getElementById("divOrganizacionBoda").style.display="none";
		}
        //si el formulario es en una capa y hay colorbox los expandimos
        $.colorbox.resize();        
	}
}

function showContactarEmpCookies() {
	// Marcamos Nombre
	if (document.frmContacto.Nombre.value=="") {
		if (GetCookie("pb_name")!=null) {
			document.frmContacto.Nombre.value=GetCookie("pb_name");
			document.getElementById("SolicNombre").className="itext_medium_cookie";
		}
	} else {
		document.getElementById("SolicNombre").className="itext_medium_cookie";
	}
	
	// Marcamos Mail
	if (document.frmContacto.Mail.value=="") {
		if (GetCookie("pb_mail")!=null) {
			document.frmContacto.Mail.value=GetCookie("pb_mail");
			document.getElementById("SolicMail").className="itext_medium_cookie";
		}
	} else {
		document.getElementById("SolicMail").className="itext_medium_cookie";
	}
	
	// Marcamos Telefono
	if (document.frmContacto.Telefono.value=="") {
		if (GetCookie("pb_telefono")!=null) {
			document.frmContacto.Telefono.value=GetCookie("pb_telefono");
			document.getElementById("SolicTelefono").className="itext_medium_cookie";
		}
	} else {
		document.getElementById("SolicTelefono").className="itext_medium_cookie";
	}
	
	// Marcamos fecha en el caso en el que este...
	if (typeof(document.frmContacto.Fecha) != "undefined") {
		if (document.frmContacto.Fecha.value=="") {
			if (GetCookie("pb_fecha")!=null) {
				document.frmContacto.Fecha.value=GetCookie("pb_fecha");
				document.getElementById("SolicFecha").className="itext_medium_cookie";
			}
		} else {
			document.getElementById("SolicFecha").className="itext_medium_cookie";
		}
	}
	
	// Marcamos comensales en el caso en el que este...
	if (typeof(document.frmContacto.Comensales) != "undefined") {
		if (document.frmContacto.Comensales.value=="") {
			if (GetCookie("pb_comensales")!=null) {
				document.frmContacto.Comensales.value=GetCookie("pb_comensales");
				document.getElementById("SolicComensales").className="itext_medium_cookie";
			}
		} else {
			document.getElementById("SolicComensales").className="itext_medium_cookie";
		}
	}
	
	// Mostramos celebración de banquete si toca
	var divVenue = document.getElementById("divVenueSaved");
	if(divVenue) {
		if(verificaVenueSaved(document.frmContacto.Mail,"")) {
			divVenue.style.display="none";
		} else {
			divVenue.style.display="block";
		}
	}
	
	document.frmContacto.Nombre.focus();
}

function showContactarEmp(id_empresa) {
	ajaxpagefunc('/emp-Form.php?id_empresa='+id_empresa,'contact-emp-layer',function(){showContactarEmpCookies();});
	document.getElementById("contact-emp-layer").style.display="block";
	document.getElementById("btnCompany").className="bt-big black";
}

function closeContactarEmp() {
	document.getElementById("contact-emp-layer").style.display="none";
	document.getElementById("btnCompany").className="bt-big mag";
}

//--------------------------------------------------------------------------------------------
//  SLIDE SHOW FOTOS EMPRESA
//--------------------------------------------------------------------------------------------
var ShowFoto=0;
var lock = false;
var delay = 2000;
var play_busy=false;
var crossFadeDuration = 3;
var run;

function slideShowFoto(nfoto) {
	ShowFoto=nfoto;
	foto=document.getElementById("galeria"+ShowFoto);
	fotoprincipal=document.getElementById("fotoPrincipal");
	descfoto=document.getElementById("galeriaDesc"+ShowFoto);
	descfotoprincipal=document.getElementById("descPrincipal");
	if (document.all){
		fotoprincipal.style.filter="blendTrans(duration=2)";
		fotoprincipal.style.filter="blendTrans(duration=crossFadeDuration)";
		fotoprincipal.filters.blendTrans.Apply();
	}	
	fotoprincipal.src=foto.src.replace("tpr_","tb_");

	//ponemos link en foto principal
	try {
		fotoPonLink(fotoprincipal, foto.parentNode.href);
	} catch (err) {}
	
	if (document.all){
		fotoprincipal.filters.blendTrans.Play();
	}
	descfotoprincipal.innerHTML=descfoto.innerHTML+" <i> - "+(ShowFoto+1)+"/"+nFotos+"</i>";

}

function slideNextFoto(direction) {		
	ShowFoto=(ShowFoto+direction);	
	if(ShowFoto>(nFotos-1)) ShowFoto=0;
	else if(ShowFoto<0) ShowFoto=(nFotos-1);
	slideShowFoto(ShowFoto);
}

function slideShow() {	
	window.clearInterval(run); 
	run = setInterval("slideNextFoto(1)", delay);
}

function slidePlay() {
	if(!play_busy) {
		play_busy=true;
		bplay=document.getElementById("PlayButton");
		if(bplay.title=="Pause") {
			bplay.title="Play";
			bplay.src='http://cdn0.weddingspot.co.uk/img/img-play.gif';			
			window.clearInterval(run); 
		} else {
			bplay.title="Pause";	
			bplay.src='http://cdn0.weddingspot.co.uk/img/img-pause.gif';
			slideShow();
		}
		play_busy=false;
	}	
}


function fotoPonLink(obj, url, fnc)
{
	obj.style.cursor = 'pointer';
	obj.onclick = function() {
        if (fnc != null) {
            fnc();
        }
		window.location.href = url;
	}
}

//--------------------------------------------------------------------------------------------

function verificaLoginDup(campo,mensaje){
	var retorno=false;
	var entrajx=false;
	url="/emp-VerificaLogin.php?login="+campo.value;
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='OK'){
			   retorno=true;
			}
			else {
			   alert(mensaje);
			   campo.focus();
			   retorno=false;
			}
	}
	return retorno;
}	

function verificaComSession(){
	var retorno=false;
	var entrajx=false;
	url="/com-VerificaLayerSession.php";
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='OK'){
			   retorno=true;
			}
			else {
			   retorno=false;
			}
	}
	return retorno;
}

function verificaUserValidado(){
	var retorno=false;
	var entrajx=false;
	url="/com-VerificaUserValidado.php";
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='OK'){
			   retorno=true;
			}
			else {
			   retorno=false;
			}
	}
	return retorno;
}

function verificaUserDup(campo,mensaje){
	if(campo.value=="") { 
	   if (mensaje!="") {	
		   alert(mensaje);
		   campo.focus();
	   }
		return false; 
	}
	var retorno=false;
	var entrajx=false;
	url="/com-VerificaUserDup.php?mail="+campo.value;
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='OK'){
			   retorno=true;
			}
			else {
			   if (mensaje!="") {	
				   alert(mensaje);
				   campo.focus();
			   }
			   retorno=false;
			}
	}
	return retorno;
}

function verificaVenueSaved(campo,mensaje){
	if(campo.value=="") { 
	   if (mensaje!="") {	
		   alert(mensaje);
		   campo.focus();
	   }
		return false; 
	}
	var retorno=false;
	var entrajx=false;
	url="/com-VerificaVenueSaved.php?mail="+campo.value;
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='SAVED'){
			   retorno=true;
			}
			else {
			   if (mensaje!="") {	
				   alert(mensaje);
				   campo.focus();
			   }
			   retorno=false;
			}
	}
	return retorno;
}

function verificaUserDup(campo,mensaje){
	if(campo.value=="") { 
	   if (mensaje!="") {	
		   alert(mensaje);
		   campo.focus();
	   }
		return false; 
	}
	var retorno=false;
	var entrajx=false;
	url="/com-VerificaUserDup.php?mail="+campo.value;
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='OK'){
			   retorno=true;
			}
			else {
			   if (mensaje!="") {	
				   alert(mensaje);
				   campo.focus();
			   }
			   retorno=false;
			}
	}
	return retorno;
}
	
function creaXML(){
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	  try {
	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   xmlhttp=false;
	  }
	 }
	@else
	 xmlhttp=false
	 @end @*/
	
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	return xmlhttp;
} 								 

// Linking social
function fSocial() {
	var fsocial='';
	var url=location.href;
	var titulo=document.title;
	fsocial+="<div class='rss'>";
	fsocial+="<a class='delicious' rel='nofollow' href='http://del.icio.us/post?url="+escape(url)+"&title="+escape(titulo)+"'>del.icio.us</a>";
	fsocial+="<a class='yahoo' rel='nofollow' href='http://add.my.yahoo.com/content?.intl=us&url="+escape(url)+"'>My Yahoo</a>";
	fsocial+="<a class='google' rel='nofollow' href='http://fusion.google.com/add?feedurl="+escape(url)+"'>Google Reader</a>";
	fsocial+="<a class='microsoft' rel='nofollow' href='http://www.live.com/?add="+escape(url)+"'>MSN live</a>";
	//fsocial+="<a class='meneame' rel='nofollow' href='http://meneame.net/submit.php?url="+escape(url)+"'>Meneame</a>";
	fsocial+="</div>";
	document.write(fsocial);
}


// Validación del formulario de búsqueda
function VerificaSearch(form) {
	if ((form.id_grupo.value=="")||(form.id_sector.value=="")) {
		if(form.txtStrSearch.value.length<2){alert("You must specify your criterea");form.txtStrSearch.focus();return false;}
	}
	return true;
}

// Validación del formulario de búsqueda
function VerificaSearchHome(form) {
	if((form.id_sector.value=="")&&(form.id_provincia.value=="")) {alert('You must select a sector or a city.'); form.id_sector.focus(); return false;}
	return true;
}

// Enviamos solicitud de información
function SendSolic(tipo) {
	document.frmContacto.tipo.value=tipo;
}


function LoadPromoWidget(id_region, id_provincia, id_sector, id_grupo) {	
	if (window.attachEvent)
	   window.attachEvent("onload", function(){ajaxpage('/promos-Widget.php?id_region='+id_region+'&id_provincia='+id_provincia+'&id_sector='+id_sector+'&id_grupo='+id_grupo,'PromoWidget');});
	else if (window.addEventListener)
	   window.addEventListener("load", function(){ajaxpage('/promos-Widget.php?id_region='+id_region+'&id_provincia='+id_provincia+'&id_sector='+id_sector+'&id_grupo='+id_grupo,'PromoWidget');},false);	
}

function onLoadPromoSky() {
	document.getElementById('PromoSky').innerHTML=document.getElementById('FramePromoSky').contentWindow.document.body.innerHTML;
}
function LoadPromoSky(key,zona,bannerCliente) {
	if (window.attachEvent)
	   window.attachEvent("onload", function(){document.getElementById('FramePromoSky').src="/promo-SkyInline.php?key="+key+"&zona="+zona+"&bannerCliente="+bannerCliente;});
	else if (window.addEventListener)
   	   window.addEventListener("load", function(){document.getElementById('FramePromoSky').src="/promo-SkyInline.php?key="+key+"&zona="+zona+"&bannerCliente="+bannerCliente;},false);
}

function LoadEmpSkyCercade(id_provincia, id_poblacion, id_sector, id_grupo) {	
	if (window.attachEvent)
	   window.attachEvent("onload", function(){ajaxpage('/busc-ShowListadoCercadeThumb.php?id_provincia='+id_provincia+'&id_poblacion='+id_poblacion+'&id_sector='+id_sector+'&id_grupo='+id_grupo,'EmpSky');});
	else if (window.addEventListener)
	   window.addEventListener("load", function(){ajaxpage('/busc-ShowListadoCercadeThumb.php?id_provincia='+id_provincia+'&id_poblacion='+id_poblacion+'&id_sector='+id_sector+'&id_grupo='+id_grupo,'EmpSky');},false);	
}

function onLoadPromoRobaPaginas() {
	document.getElementById('PromoRobaPaginas').innerHTML=document.getElementById('FramePromoRobaPaginas').contentWindow.document.body.innerHTML;
}
function LoadPromoRobaPaginas(key,zona) {
	if (window.attachEvent)
	   window.attachEvent("onload", function(){document.getElementById('FramePromoRobaPaginas').src="/promo-RobaPaginasInline.php?key="+key+"&zona="+zona;});
	else if (window.addEventListener)
   	   window.addEventListener("load", function(){document.getElementById('FramePromoRobaPaginas').src="/promo-RobaPaginasInline.php?key="+key+"&zona="+zona;},false);
}

function onLoadPromoMiniRobaPaginas() {
	document.getElementById('PromoMiniRobaPaginas').innerHTML=document.getElementById('FramePromoMiniRobaPaginas').contentWindow.document.body.innerHTML;
}

function LoadPromoMiniRobaPaginas(key,zona) {
	if (window.attachEvent)
	   window.attachEvent("onload", function(){document.getElementById('FramePromoMiniRobaPaginas').src="/promo-MiniRobaPaginasInline.php?key="+key+"&zona="+zona;});
	else if (window.addEventListener)
   	   window.addEventListener("load", function(){document.getElementById('FramePromoMiniRobaPaginas').src="/promo-MiniRobaPaginasInline.php?key="+key+"&zona="+zona;},false);
}

function showPrometido(rol) {
	if((rol==1)||(rol==2)) {
		document.getElementById("divPrometido").style.display="inline";
		document.getElementById("divCelebracion").style.display="inline";
	} else if ((rol==3)||(rol==4)) {	
		document.getElementById("divPrometido").style.display="none";
		document.getElementById("divCelebracion").style.display="inline";
	} else {
		document.getElementById("divPrometido").style.display="none";
		document.getElementById("divCelebracion").style.display="none";
	}
}

function showAltaLayerCalendario(rol) {
	if((rol==1)||(rol==2)) {
		document.getElementById("divPrometido").style.display="inline";
	} else if ((rol==3)||(rol==4)) {	
		document.getElementById("divPrometido").style.display="none";
	} else {
		document.getElementById("divPrometido").style.display="none";
	}
}

function showPrometidoModif(rol) {
	if((rol==1)||(rol==2)) {
		document.getElementById("divNombrePrometido").style.display="block";
		document.getElementById("divMailPrometido").style.display="block";
		document.getElementById("divFechaBoda").style.display="block";
		document.getElementById("divInvitados").style.display="block";
		document.getElementById("divSobreMiBoda").style.display="block";				
	} else if ((rol==3)||(rol==4)) {	
		document.getElementById("divNombrePrometido").style.display="none";
		document.getElementById("divMailPrometido").style.display="none";
		document.getElementById("divFechaBoda").style.display="block";
		document.getElementById("divInvitados").style.display="none";
		document.getElementById("divSobreMiBoda").style.display="none";				
	} else {
		document.getElementById("divNombrePrometido").style.display="none";
        document.getElementById("divMailPrometido").style.display="none";
        document.getElementById("divFechaBoda").style.display="none";
        document.getElementById("divInvitados").style.display="none";
        document.getElementById("divSobreMiBoda").style.display="none";				
	}
}

function changePais(idPais) {
	if(paisesTipo1.indexOf(idPais+",")!=-1) {
		document.frmComunidad.tipoPais.value=1;
		document.getElementById("divPais").style.display="inline";		
		document.getElementById("divPaisTipo2").style.display="none";
		document.getElementById("divPaisTipo3").style.display="none";
		document.frmComunidad.CodigoPostal.value="";
		document.frmComunidad.Direccion.value="";				
	} else if(paisesTipo2.indexOf(idPais+",")!=-1) {
		document.frmComunidad.tipoPais.value=2;
		LoadProvinciasCom();
		document.getElementById("divPais").style.display="none";
		document.getElementById("divPaisTipo2").style.display="inline";
		document.getElementById("divPaisTipo3").style.display="none";
		document.frmComunidad.Ciudad2.value="";
		document.frmComunidad.CodigoPostal2.value="";
		document.frmComunidad.Direccion2.value="";
	} else {
		document.frmComunidad.tipoPais.value=3;
		document.getElementById("divPais").style.display="none";
		document.getElementById("divPaisTipo2").style.display="none";
		document.getElementById("divPaisTipo3").style.display="inline";
		document.frmComunidad.Provincia3.value="";		
		document.frmComunidad.Ciudad3.value="";
		document.frmComunidad.CodigoPostal3.value="";
		document.frmComunidad.Direccion3.value="";		
	}
}

function showPais(idPais,idProvUser) {
	if(paisesTipo1.indexOf(idPais+",")!=-1) {
		document.frmComunidad.tipoPais.value=1;
		document.getElementById("divPais").style.display="inline";		
		document.getElementById("divPaisTipo2").style.display="none";
		document.getElementById("divPaisTipo3").style.display="none";
	} else if(paisesTipo2.indexOf(idPais+",")!=-1) {
		document.frmComunidad.tipoPais.value=2;
		LoadProvinciasCom(idProvUser);
		document.getElementById("divPais").style.display="none";
		document.getElementById("divPaisTipo2").style.display="inline";
		document.getElementById("divPaisTipo3").style.display="none";
	} else {
		document.frmComunidad.tipoPais.value=3;
		document.getElementById("divPais").style.display="none";
		document.getElementById("divPaisTipo2").style.display="none";
		document.getElementById("divPaisTipo3").style.display="inline";
	}
}
			
			
function ResponderTema(id_tema) {
	window.location='/foro-ResponderTema.php?id_tema='+id_tema;
}
function ResponderMensaje(id_mensaje) {
	window.location='/foro-ResponderMensaje.php?id_mensaje='+id_mensaje;
}
function NuevoTema(id_seccion) {
	window.location='/foro-NuevoTema.php?id_seccion='+id_seccion;
}
function BanMensaje(id_mensaje) {
	window.location='/foro-BanMensaje.php?id_mensaje='+id_mensaje;
}
function BanTema(id_tema) {
	window.location='/foro-BanTema.php?id_tema='+id_tema;
}

/*--------------------------------------------------------------------------------*/
/* Funciones Cookies  */
/*--------------------------------------------------------------------------------*/
function SetCookieSession (name, value) {  
	var argv = SetCookieSession.arguments;  
	var argc = SetCookieSession.arguments.length; 
	var path = (argc > 3) ? argv[3] : "/";  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;  
	document.cookie = name + "=" + escape (value) + 
	((path == null || !path) ? "/" : ("; path=" + path)) +  
	((domain == null) ? "; domain=weddingspot.co.uk" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

function SetCookie (name, value) {  
	var argv = SetCookie.arguments;  
	var argc = SetCookie.arguments.length;  
	// Expires never
	//var expires = (argc > 2) ? argv[2] : null; 
	var expires= new Date(); 
	expires.setYear(9999);
	var path = (argc > 3) ? argv[3] : "/";  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) + 
	"; expires=" + expires.toGMTString() +
	((path == null) ? "/" : ("; path=" + path)) +  
	((domain == null) ? "; domain=weddingspot.co.uk" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

function SetCookieIt (name, value, domain) {  
	var argv = SetCookieIt.arguments;  
	var argc = SetCookieIt.arguments.length;  
	// Expires never
	//var expires = (argc > 2) ? argv[2] : null; 
	var expires= new Date(); 
	expires.setYear(9999);
	var path = (argc > 3) ? argv[3] : "/";  
	//var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;	
	document.cookie = name + "=" + escape (value) + 
	"; expires=" + expires.toGMTString() +
	((path == null) ? "/" : ("; path=" + path)) +  
	((domain == null) ? "; domain=bodas.net" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

function GetCookie (name) {  
	var arg = name + "=";  
	var alen = arg.length;  
	var clen = document.cookie.length;  
	var i = 0;  
	while (i < clen) {    
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg)      
			return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	}  
	return null;
}

function getCookieVal (offset) {  
	var endstr = document.cookie.indexOf (";", offset);  
	if (endstr == -1)    
	endstr = document.cookie.length;  
	return unescape(document.cookie.substring(offset, endstr));
}

function deleteCookie(name,value){
	var argv = deleteCookie.arguments;  
	var argc = deleteCookie.arguments.length; 
	var expires= new Date();
	var path = (argc > 3) ? argv[3] : "/";  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;  
	document.cookie = name + "=" + escape (value) + 
	"; expires=" + expires.toGMTString() +
	((path == null) ? "/" : ("; path=" + path)) +  
	((domain == null) ? "; domain=weddingspot.co.uk" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

//-------------------------------------------------------
// Carga dinámica de paises 
//-------------------------------------------------------
function ajLoadRegions(form) {
	ajaxpage('/utils-ShowLoading.php','divAdm1');
	if (typeof(form.oldRegion)!="undefined" ) {
		ajaxpage('/utils-LoadRegions.php?country='+form.Pais.value+'&region='+form.oldRegion.value,'divAdm1');
	} else {
		ajaxpage('/utils-LoadRegions.php?country='+form.Pais.value,'divAdm1');
	}
}
function ajLoadCities(country_code,adm,postalcode) {
	ajaxpage('/utils-LoadCities.php','divCity');
}
function ajChangePostalCode(form,postalcode) {	
	ajLoadCities(form.Pais.value,form.Provincia.value,postalcode);
}
function ajChangeRegion(form,region) {	
	ajLoadCities(form.Pais.value,region,'');
	form.CodigoPostal.value="";
	form.CodigoPostal.disabled=false;
	form.Poblacion.disabled=false;
}
function ajChangePais(form) {	
	ajLoadCities();
}
function ajLoadLocation(form) {
	ajaxpage('/utils-ShowLoading.php','divAdm1');
	ajaxpage('/utils-LoadRegions.php?country='+form.Pais.value+'&region='+form.oldRegion.value+'&subregion='+form.oldSubRegion.value,'divAdm1');	
	ajaxpage('/utils-ShowLoading.php','divCity');
	ajaxpage('/utils-LoadCities.php?country='+form.Pais.value+'&region='+form.oldRegion.value+'&subregion='+form.oldSubRegion.value+'&city='+form.oldPoblacion.value,'divCity');
	form.CodigoPostal.disabled=false;
	form.Poblacion.disabled=false;	
}

//---------------------------------------------------------------
// Funciones para filtros de promos
//---------------------------------------------------------------
function ShowFiltersPromos(id_region,id_provincia, id_grupo, id_sector, TipoPromocion) {	
	ajaxpage('/promos-buscFilters.php?id_region='+id_region+'&id_provincia='+id_provincia+'&id_grupo='+id_grupo+'&id_sector='+id_sector+'&TipoPromocion='+TipoPromocion,'buscFilters');
}

function LoadProvinciaPromos() {
	document.frmPromos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmPromos.id_grupo.value="";
	document.frmPromos.id_sector.value="";
	document.frmPromos.TipoPromocion.value="";
	document.frmPromos.id_region.value="";
	document.frmPromos.NumPage.value="1";
	document.frmPromos.submit();
}	
function LoadGrupoPromos() {
	document.frmPromos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmPromos.id_grupo.value=document.frmBusc.Grupo.value;
	document.frmPromos.id_sector.value="";
	document.frmPromos.TipoPromocion.value="";
	document.frmPromos.NumPage.value="1";
	document.frmPromos.submit();
}	
function LoadSectorPromos() {
	document.frmPromos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmPromos.id_grupo.value=document.frmBusc.Grupo.value;
	document.frmPromos.id_sector.value=document.frmBusc.Sector.value;
	document.frmPromos.TipoPromocion.value="";
	document.frmPromos.NumPage.value="1";
	document.frmPromos.submit();
}

function LoadTipoPromos() {
	document.frmPromos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmPromos.id_grupo.value=document.frmBusc.Grupo.value;
	document.frmPromos.id_sector.value=document.frmBusc.Sector.value;
	document.frmPromos.TipoPromocion.value=document.frmBusc.TipoPromocion.value;
	document.frmPromos.NumPage.value="1";
	document.frmPromos.submit();
}

function LoadBuscPagePromos(npage) {
	document.frmPromos.NumPage.value=npage;
	document.frmPromos.submit();
}

//---------------------------------------------------------------
// Funciones para filtros de eventos
//---------------------------------------------------------------

function ShowFiltersEventos(id_region,id_provincia, tipo, FechaEvento) {	
	ajaxpage('/eventos-buscFilters.php?id_region='+id_region+'&id_provincia='+id_provincia+'&TipoEvento='+tipo+'&FechaEvento='+FechaEvento,'buscFilters');
}

function LoadProvinciaEventos() {
	document.frmEventos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmEventos.TipoEvento.value=document.frmBusc.TipoEvento.value;
	document.frmEventos.FechaEvento.value=document.getElementById('datepicker').value;
	document.frmEventos.id_region.value="";
	document.frmEventos.NumPage.value="1";
	document.frmEventos.submit();
}

function LoadTipoEventos() {
	document.frmEventos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmEventos.TipoEvento.value=document.frmBusc.TipoEvento.value;
	document.frmEventos.FechaEvento.value=document.getElementById('datepicker').value;
	document.frmEventos.NumPage.value="1";
	document.frmEventos.submit();
}	

function LoadFechaEventos() {
	document.frmEventos.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmEventos.TipoEvento.value=document.frmBusc.TipoEvento.value;
	document.frmEventos.FechaEvento.value=document.getElementById('datepicker').value;
	document.frmEventos.NumPage.value="1";
	document.frmEventos.submit();
}	

function LoadBuscPageEventos(npage) {
	document.frmEventos.NumPage.value=npage;
	document.frmEventos.submit();
}
//---------------------------------------------------------------
// Funciones para filtros de busqueda
//---------------------------------------------------------------
function ShowFilters(id_region,id_provincia, id_grupo, id_sector, id_poblacion) {	
	ajaxpage('/busc-Filters.php?id_region='+id_region+'&id_provincia='+id_provincia+'&id_grupo='+id_grupo+'&id_sector='+id_sector+'&id_poblacion='+id_poblacion,'buscFilters');
}

function LoadProvincia() {
	document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
	//document.frmSearch.id_grupo.value="";
	//document.frmSearch.id_sector.value="";
	document.frmSearch.id_poblacion.value="";
	document.frmSearch.id_region.value="";
	document.frmSearch.NumPage.value="1";
	document.frmSearch.txtStrSearch.value="";
	document.frmSearch.txtLocSearch.value="";	
	document.frmSearch.submit();
}	
function LoadGrupo() {
	document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmSearch.id_grupo.value=document.frmBusc.Grupo.value;
	document.frmSearch.id_sector.value="";
	document.frmSearch.id_poblacion.value="";
	document.frmSearch.NumPage.value="1";
	document.frmSearch.txtStrSearch.value="";
	document.frmSearch.txtLocSearch.value="";	
	document.frmSearch.submit();
}	
function LoadSector() {
	document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmSearch.id_grupo.value=document.frmBusc.Grupo.value;
	document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
	document.frmSearch.id_poblacion.value="";
	document.frmSearch.NumPage.value="1";
	document.frmSearch.txtStrSearch.value="";
	document.frmSearch.txtLocSearch.value="";	
	document.frmSearch.submit();
}	
function LoadPoblacion() {
	document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
	document.frmSearch.id_grupo.value=document.frmBusc.Grupo.value;
	document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
	document.frmSearch.id_poblacion.value=document.frmBusc.Poblacion.value;
	document.frmSearch.NumPage.value="1";
	document.frmSearch.txtStrSearch.value="";
	document.frmSearch.txtLocSearch.value="";	
	document.frmSearch.submit();
}	

function ShowFotoEmp(foto) {		
	destino=document.location+"\/fotos\/"+foto;
	window.location=destino;
}


//---------------------------------------------------------------
// Funciones para la comunidad
//---------------------------------------------------------------
function clickbpdown (boton) {
	boton.style.paddingTop=6;		
	boton.style.paddingLeft=11;
} 
function clickbpup (boton) {
	boton.style.paddingTop=5;		
	boton.style.paddingLeft=10;
} 

function clickbgdown (boton) {
	boton.style.paddingTop=4;		
	boton.style.paddingLeft=12;
} 
function clickbgup (boton) {
	boton.style.paddingTop=3;		
	boton.style.paddingLeft=10;
} 

function ComDebateMensajeValidar(id_mensaje,valid) {		
	ajaxpage("/com-DebatesMensajeValidar.php?id_mensaje="+id_mensaje+"&valid="+valid,"comDebateMensaje"+id_mensaje);	
}

function ComDebateValidar(id_tema,valid) {		
	ajaxpage("/com-DebatesValidar.php?id_tema="+id_tema+"&valid="+valid,"comDebate"+id_tema);	
}

function ComDebateNews(id_tema,status) {      
    ajaxpage("/com-DebatesNews.php?id_tema="+id_tema+"&status="+status,"comDebateNews");   
}

function ComMailAdmin(id_user, id_mail) {
	document.getElementById("AdminMail" + id_mail + "_" + id_user).className="gris";
	ajaxpage("/com-UsuariosMailAdmin.php?id_user="+id_user+"&id_mail="+id_mail,"comUser"+id_user);	
}

function ComUserValidar(id_user,valid) {		
	ajaxpage("/com-UsuariosValidar.php?id_user="+id_user+"&valid="+valid,"comUser"+id_user);	
}

function ComVideosComentarioValidar(id_comentario,valid) {	
	ajaxpage("/com-VideosComentarioValidar.php?id_comentario="+id_comentario+"&valid="+valid,"comVideoComentario"+id_comentario);	
}

function ComVideosValidar(id_video,valid) {		
	ajaxpage("/com-VideosValidar.php?id_video="+id_video+"&valid="+valid,"comVideo"+id_video);	
}

function ComVideosNew(event, id_grupo) {
    return common_goEnsureLogged(event, "/com-VideosNew.php?id_group="+id_grupo);
}

function ComVideosModif(id_video) {		
	window.location="/com-VideosModif.php?id_video="+id_video;
}
function ComVideosDelete(id_video) {		
	window.location="/com-VideosDelete.php?id_video="+id_video;
}

function ComFotosComentarioValidar(id_comentario,valid) {	
	ajaxpage("/com-FotosComentarioValidar.php?id_comentario="+id_comentario+"&valid="+valid,"comFotoComentario"+id_comentario);	
}

function ComFotosValidar(id_foto,valid) {		
	ajaxpage("/com-FotosValidar.php?id_foto="+id_foto+"&valid="+valid,"comFoto"+id_foto);	
}

function ComFotosNew(event, id_grupo) {
	return common_goEnsureLogged(event, "/com-AdminFotosNew.php?id_group="+id_grupo);
}

function ComFotosModif(id_foto) {		
	window.location="/com-AdminFotosModif.php?id_foto="+id_foto;
}
function ComFotosDelete(id_foto) {		
	window.location="/com-AdminFotosDelete.php?id_foto="+id_foto;
}
function ComFotosComentarioNew(id_foto) {	
	if(document.frmComunidad.Comentario.value.length<10){alert("El comentario tiene que tener como mínimo diez caracteres.");document.frmComunidad.Comentario.focus();return false;}
	window.location="/com-FotoComentarioNew.php?id_foto="+id_foto;
}
function ComPeticionAmigo(id_amigo) {		
	window.location="/com-AmigosPeticionRun.php?id_amigo="+id_amigo;
}

function UnirseGrupo(event, id_group) {
	return common_goEnsureLogged(event, "/com-GruposUnirse.php?id_group="+id_group);
}

function NuevoDebate(event, id_group) {
    return common_goEnsureLogged(event, "/com-DebateNuevo.php?id_group="+id_group);
}

function ComAceptarAmigo(id_amigo) {		
	window.location="/com-AmigosAceptarRun.php?id_amigo="+id_amigo;
}
function ComRechazarAmigo(id_amigo) {		
	window.location="/com-AmigosRechazarRun.php?id_amigo="+id_amigo;
}
function ComBlogNewPost() {
	window.location="/com-BlogNewPost.php";	
}
function ComBlogModifPost(id_post) {
	window.location="/com-BlogModifPost.php?id_post="+id_post;	
}
function ComBlogDeletePost(id_post) {
	window.location="/com-BlogDeletePostRun.php?id_post="+id_post;	
}
function ComFotosVotar(id_foto){
	ajaxpage('/com-FotosVotarRun.php?id_foto='+id_foto,'divVotos'+id_foto);
}

function comMuroAddComentario(event, id_user) {
    common_callEnsureLogged(
        event,
        function () {
            openToolsLayer(this.event,'/com-PerfilMuroComentarioAdd.php?id_user='+id_user);
        }
    );

}

function ComEnviarMensaje(id_user){
	window.location="/com-Buzon.php?action=new&id_destinatario="+id_user;	
}


function ComDeleteMensajes() {
	document.frmComunidad.action="com-BuzonDelete.php";
	document.frmComunidad.submit();
}

function checkAllMensajes(status)
{
	/* Selecciona/deselecciona todas las solicitudes */
	var formulari;
	var i;
	var chkbox;
	var tr;
	formulari=document.getElementById("frmComunidad");	
	var el = document.getElementsByName('id_mensaje[]');
	if(el.length) {
		for (i=0; i < el.length; i++)
		{
			chkbox=el[i];
			chkbox.checked=status;	
		}
	}
}

//---------------------------------------------------------------------
// Capas 
//---------------------------------------------------------------------
function VerificaCapaLogin(form) {
	var arroba_found=false;var punto_found=false;var i=0;
 	while((i<form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
 	if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
 	while((i<form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
 	if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain an. followed by at least two characters");form.Mail.focus();return false;}								
 	if(form.Password.value.length<4){alert("The password must contain a minimum of four characters");form.Password.focus();return false;}
	return true;
}	

function VerificaCapaAlta(form) {	
 	if(form.Nombre.value.length<4){alert("Your name must have a minimum of four characters");form.Nombre.focus();return false;}
	var arroba_found=false;var punto_found=false;var i=0;
 	while((i<form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
 	if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
 	while((i<form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
 	if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain an. followed by at least two characters");form.Mail.focus();return false;}										
	if(!verificaUserDup(form.Mail,"A user registered with this email address already exists")) {return false;}
	if(form.Password.value.length<4){alert("The password must contain a minimum of four characters");form.Password.focus();return false;}
	if(form.Password.value!=form.ConfirmPassword.value){alert("The confirmation of the password does not match with the initial password");form.ConfirmPassword.focus();return false;}
	//if(form.Pais.value==-1){alert("Please select the country of residence.");form.Pais.focus();return false;}
	//if((form.Poblacion.value==-1)||(form.Poblacion.value=="")){alert("Please select the city in which you live.");form.Pais.focus();return false;}
	if((form.Provincia.value==-1)||(form.Provincia.value=="")){alert("You must select the county in which you live.");form.Pais.focus();return false;}	
 	if(form.Rol.value==0){alert("You must select your role in this event.");form.Rol.focus();return false;}
	if((form.Rol.value==1)||(form.Rol.value==2)||(form.Rol.value==3)||(form.Rol.value==4)) {
		if((form.bodaDia.value!=0)||(form.bodaMes.value!=0)||(form.bodaAno.value!=0)) {
			if(form.bodaDia.value==0){alert("Please select the day of your wedding.");form.bodaDia.focus();return false;}
			if(form.bodaMes.value==0){alert("Please select the month of your wedding.");form.bodaMes.focus();return false;}
			if(form.bodaAno.value==0){alert("Please select the year of your wedding.");form.bodaAno.focus();return false;}
		}
	}
 	return true;	
}	

function VerificaCapaAltaVendor(form) {	
 	if(!isFullfilField(form.Nombre)||(form.Nombre.value.length<4)){alert("Your name must have a minimum of four characters");form.Nombre.focus();return false;}
	var arroba_found=false;var punto_found=false;var i=0;
 	while((i<form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
 	if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
 	while((i<form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
 	if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain an. followed by at least two characters");form.Mail.focus();return false;}										
	if(!verificaUserDup(form.Mail,"A user registered with this email address already exists")) {return false;}
	if(!isFullfilField(form.Password)||(form.Password.value.length<4)){alert("The password must contain a minimum of four characters");form.Password.focus();return false;}
	//if(form.Pais.value==-1){alert("Please select the country of residence.");form.Pais.focus();return false;}
	//if((form.Poblacion.value==-1)||(form.Poblacion.value=="")){alert("Please select the city in which you live.");form.Pais.focus();return false;}
	if((form.Provincia.value==-1)||(form.Provincia.value=="")){alert("You must select the county in which you live.");form.Pais.focus();return false;}	
 	if(form.Rol.value==0){alert("You must select your role in this event.");form.Rol.focus();return false;}
	if((form.Rol.value==1)||(form.Rol.value==2)||(form.Rol.value==3)||(form.Rol.value==4)) {
		if(!isFullfilField(form.Fecha)||(form.Fecha.value=="")) {alert("You must select a wedding date.");form.Fecha.focus();return false;}
	}
 	return true;	
}	

// Cerramos la capa de login
function closeCapaLogin() {
	var obj = document.getElementById("capaLogin");	
	obj.parentNode.removeChild(obj);
	var obj = document.getElementById("overlay");	
	obj.parentNode.removeChild(obj);	
}

// Cerramos la capa de login
function closeCapaMultisolic() {
	var obj = document.getElementById("capaMultisolicitud");	
	obj.parentNode.removeChild(obj);
	var obj = document.getElementById("overlay");	
	obj.parentNode.removeChild(obj);	
}

// Cargamos la capa de Login
function loadCapaLogin() {
	// Mostramos capa de logado
	ajaxpage("/com-CapaLogin.php","capaLogado");
}

// Cargamos la capa de alta
function loadCapaAlta() {
	// Mostramos capa de alta
	ajaxpage("/com-CapaAlta.php","capaLogado");
}

// Creación dinámica de iframe
function CrearIframe(pid) {
	var _navegador = navigator.userAgent;
	var op = /opera/i.test(_navegador);
	var mo = /gecko/i.test(_navegador);
	if (!(op || mo)) {
    
        if (isIE6() || isIE7()) { 
            var FrameLogin = document.createElement('<IFRAME name='+pid+'>');    
            FrameLogin.id=pid;
            FrameLogin.style.display='none';
        } else {    
            // FIX IE9
            var FrameLogin = document.createElement("iframe");
            FrameLogin.setAttribute("name",pid);
            FrameLogin.setAttribute("id",pid);
            FrameLogin.setAttribute("style","display:none;");
        }    
		document.body.appendChild(FrameLogin);
	} else {
		var FrameLogin = document.createElement("iframe");    
		FrameLogin.id=pid;
		FrameLogin.name=pid;
		FrameLogin.style.display='none';
		document.body.appendChild(FrameLogin);		
	}
}
		
function ValoraItem(id,tipo,valor,capa,evento) {
	if(!CompruebaLogin(evento)) {return false;}
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','capaValoracion');
	objLightbox.style.display = 'none';	
	ajaxpage("/com-ValoraItem.php?tipo="+tipo+"&id="+id+"&valor="+valor,capa);	
}		

// Comprobación de user logado		
function CompruebaLoginUserValid(e)  {
	if (CompruebaLogin(e)) {
		if (verificaUserValidado()) {
			return true; 	
		} else {
			// Creamos el layer para cvisualizar el Alta o Login			
			var objBody = document.getElementsByTagName("body").item(0);		
				
			CrearIframe('frameCapaLogin');				
			var objLightbox = document.createElement("div");
			objLightbox.setAttribute('id','capaLogin');
			objLightbox.style.display = 'none';
			objBody.appendChild(objLightbox);		
			ajaxpage("/com-UserNoValidado.php","capaLogin");
								
			// Posicionamos el layer y lo mostramos
			//pos=getPosition(e);
			var arrayPageSize = getPageSize();
			var arrayPageScroll = getPageScroll();
			var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);	
			var lightboxLeft= ((arrayPageSize[2] / 2)-300);	
			objLightbox.style.top = lightboxTop +"px";
			objLightbox.style.left = lightboxLeft +"px";
			objLightbox.style.display = '';
			
			var arrayPageSize = getPageSize();
			var objOverlay = document.createElement("div");
			objOverlay.setAttribute('id','overlay');	
			document.body.appendChild(objOverlay);		
			objOverlay.style.height=arrayPageSize[1]+200;			
		}
	}
}

// Comprobación de user logado		
function ShowMultisolicitud()  {
	// Creamos el layer para cvisualizar el Alta o Login			
	var objBody = document.getElementsByTagName("body").item(0);				
	CrearIframe('frameCapaLogin');	
	
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','capaMultisolicitud');
	objLightbox.style.display = 'none';
	objBody.appendChild(objLightbox);		
	
	document.getElementById('capaMultisolicitud').innerHTML=document.getElementById('fMultisolicitud').contentWindow.document.body.innerHTML;
						
	// Posicionamos el layer y lo mostramos
	//pos=getPosition(e);
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var lightboxTop = parseInt(arrayPageScroll[1] + 10);	
	var lightboxLeft= parseInt(((arrayPageSize[2] / 2)-300));	
	
	objLightbox.style.top = lightboxTop +"px";
	objLightbox.style.left = lightboxLeft +"px";
	objLightbox.style.display = '';
	
	var arrayPageSize = getPageSize();
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id','shadow');
    objOverlay.style.zIndex="1";
    //objOverlay.style.display = 'none';
    document.body.appendChild(objOverlay);
    objOverlay.style.height=arrayPageSize[1]+"px";    		
}

// Comprobación de user logado		
function CompruebaLogin(e, defaultLogin, redirect)  {

	// Comprobamos si esta en session
	if(verificaComSession()) {
		return true; 
	} else {
		// Creamos el layer para cvisualizar el Alta o Login			
		var objBody = document.getElementsByTagName("body").item(0);		
			
		/*
		CrearIframe('frameCapaLogin');				
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','capaLogin');
		objLightbox.style.display = 'none';
		objBody.appendChild(objLightbox);		
		ajaxpage("/com-CompruebaLogin.php","capaLogin");
							
		// Posicionamos el layer y lo mostramos
		//pos=getPosition(e);
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);	
		var lightboxLeft= ((arrayPageSize[2] / 2)-300);	
		objLightbox.style.top = lightboxTop +"px";
		objLightbox.style.left = lightboxLeft +"px";
		objLightbox.style.display = '';
		
		var arrayPageSize = getPageSize();
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');	
		document.body.appendChild(objOverlay);		
		objOverlay.style.height=arrayPageSize[1]+200;
		*/
		
        var url = "/com-CompruebaLogin.php?a";
        if (defaultLogin != null) {
            url += "&defaultLogin="+defaultLogin;
        }
        if (redirect != null) {
            url += "&redirect="+redirect;
        }
		openToolsLayer(e, url, 1);
		
	}
}


// -----------------------------------------------------------------------------------
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight); 
	return arrayPageSize;
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll); 
	return arrayPageScroll;
}

function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

// Cargamos el administrador
function LoginAdmin(idUser) {
	ajaxpage('/com-LoginAdmin.php?id_user='+idUser,'user-logat');	
}

// Marcamos vendors
function vendorSavedZona(event, id_empresa,zona_vendor) {
    common_callEnsureLogged(
        event,
        function () {
            LayerLoading('vendorSaved'+id_empresa);
            ajaxpage("/tools/VendorsSave?id_empresa="+id_empresa+'&zona_vendor='+zona_vendor, 'vendorSaved'+id_empresa);
        }
    );
}

function vendorSaved(id_empresa) {
    LayerLoading('vendorSaved'+id_empresa);  
    ajaxpage("/tools/VendorsSave?id_empresa="+id_empresa, 'vendorSaved'+id_empresa);
}

function LayerLoading(capa) {
	document.getElementById(capa).innerHTML="<img src='http://cdn0.weddingspot.co.uk/images/indicator.gif'>";
}

//Articulos
function cambiarCatAjax(id_cat,categoria) {
	ajaxpagefunc("http://www.weddingspot.co.uk/contenido-MenuSubcategorias.php?id_categ="+id_cat,"categ_"+categoria,function(){cambiarCat(categoria)});
}

function cambiarCat(categoria) {	
	categdiv = document.getElementById("categ_" + categoria);
	botondiv = document.getElementById("botoncat_" + categoria);
	if(categdiv.style.display=="none"){
		categdiv.style.display="inline";
		botondiv.src="http://cdn0.weddingspot.co.uk/img/contraer.gif";
	} else {
		categdiv.style.display="none";
		botondiv.src="http://cdn0.weddingspot.co.uk/img/expandir.gif";
	}
}

function guardarContenido(url){
	if(!CompruebaLogin(this.event)) {return false;}
	window.location='/contenido-Guardar.php?urlGuardar='+url;
	return true;
}

function validarMail(form){	
	var arroba_found=false;var punto_found=false;var i=0;
	while((i<form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
	if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
	while((i<form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
	if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain an. followed by at least two characters");form.Mail.focus();return false;}										
	
	return true;	
}

function validarComentario(id_comentario,valid) {
	var r=confirm("Está seguro?");
	if (r==true){
    	ajaxpage("/contenido-ComentariosValidar.php?id_comentario="+id_comentario+"&valid="+valid,"comComentario"+id_comentario);
    }  
}

function VerificaComentario(event, form){
    if(form.Comentario.value.length<5){
		alert("El comentario debe tener más de 5 carácteres.");
		return false;
	}
    common_callEnsureLogged(
        event,
        function () {
            form.submit();
        }
	);
	return false;
}

function VerificaBuscarContenido(form){	
	if(form.txtSearch.value.length<1){
		alert("You have still not inserted any search topic");
		return false;
	}
	return true;	
}

//--------------------------------------------------------
//--------------------------------------------------------
// Mostramos la capa perfil
//--------------------------------------------------------
//--------------------------------------------------------
CapaPerfil = function (parent,idUsuario){
    this.idUsuario = idUsuario;
    this.parent = parent;
    this.obj = null;
    this.activo = false; //se est‡ caragndo contenido
    this.visible = false; //capa visible, no se puede abrir otra capa
    this.timeout = null;
    this.right   = false;
};

CapaPerfil.prototype = {

    show: function(){
        //creamos capa

        if (cp.activo == true){
            clearTimeout(cp.timeout);
            if (cp.visible){
                cp.hide();
            }
        }

        var ajaxHelper =  new ajaxEdit_AjaxHelper('/com-CapaPerfil.php?id_user='+cp.idUsuario,
                                    function (result,content) {
                                        cp.obj = document.createElement("DIV");
                                        cp.obj.innerHTML = content;
                                        cp.obj.style.zIndex= 100;

                                        if (cp.right){
                                            cp.obj.className="capaPerfil capaPerfilRight";
                                        }else{
                                            cp.obj.className="capaPerfil capaPerfilLeft";
                                        }

                                        //bot—n de cerrar
                                        var cerrar = document.createElement("DIV");
                                        cerrar.className="cerrar";
                                        //cerrar.innerHTML="x";

                                        cerrar.onclick = function(){
                                            cp.hide();
                                        };
                                                                               
                                        //Crea el cierre inferior de la caja
                                        var cajaBot = document.createElement("DIV");
                                        cajaBot.className="capaPerfilBot";
                                        cp.obj.appendChild(cajaBot);


                                        fncMostrar = function(){
                                                        clearTimeout(cp.timeout);
                                                        cp.timeout = null;
                                                };

                                        cp.obj.onmouseover = fncMostrar;

                                        cp.obj.onmouseout = function(){
                                                hideCapaPerfil();
                                        };


                                        aChilds=cp.obj.childNodes;

                                        var nItems =0;
                                        for(var i=0;i<aChilds.length;i++){
                                                nItems++;
                                                if(aChilds[i].nodeType==1){
                                                    aChilds[i].onmouseover = fncMostrar;
                                                }
                                        }

                                        if (cp.obj.hasChildNodes())
                                        {
                                            cp.obj.insertBefore(cerrar, cp.obj.childNodes[0]);

                                        }

                                        cp.parent.appendChild(cp.obj);
                                        cp.visible = true;
                                    }
                            );
        ajaxHelper.send();

    } ,

    hide: function(){
        if (cp.visible == true && cp.activo == true) {
            cp.parent.removeChild(cp.obj);
            cp.activo = false;
            cp.visible = false;
            cp.obj = null;
            cp.timeout = null;
        }

    }
};


var cp = new CapaPerfil(null,null);
function showCapaPerfil(obj,event,idUsuario) {
    if ( cp.visible == false){
        cp.parent = obj;
        var pos = getPosition(event);
        cp.right = pos.x<700;
        cp.idUsuario = idUsuario;
        cp.activo = true;
        clearTimeout(cp.timeout);
        cp.timeout = setTimeout("cp.show();",300);		
    }
    obj.onmouseout = hideCapaPerfil;
}

function hideCapaPerfil() {
    clearTimeout(cp.timeout);
    cp.timeout = setTimeout("cp.hide();",100);	
}


//----------------------------------------------------------------------------------
//funciones de manejo ajax.

//Clase base
//   metodo send para realizar la llamada
function ajaxEdit_getXmlHttp(){
	 if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }	
}


function ajaxEdit_AjaxHelper(url,callbackFnc){

	if (arguments.length>2 && arguments[2] != null)
		this.method = arguments[2];
	else
		this.method = "GET";	

	if (arguments.length>3 && arguments[3] != null)
		this.parameters = arguments[3];
	else
		this.parameters = "";				
		
	if (arguments.length>4 && arguments[4] != null)
		this.noModal = arguments[4];
	else
		this.noModal = true;	

    
	this.url 		 = url;
    this.callbackFnc = callbackFnc;
    this.yaProcesado = false;
   
}


ajaxEdit_AjaxHelper.prototype = {	
	
	send: function(){
		
		this.xmlHttp = ajaxEdit_getXmlHttp();	
		var obj = this;
		
		this.xmlHttp.onreadystatechange = function(){
			obj.ajaxEdit_handleStateChange();
		};

		this.xmlHttp.open(this.method, this.url, this.noModal);
    	
		if (this.method == "GET") {
	   		this.xmlHttp.send(null);
    	}else{
		    this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      		this.xmlHttp.setRequestHeader("Content-length", this.parameters.length);
      		this.xmlHttp.setRequestHeader("Connection", "close");
      		this.xmlHttp.send(this.parameters);
    	}
	},
	
	ajaxEdit_handleStateChange: function(){
		if(!this.yaProcesado &&
			this.xmlHttp.readyState == 4) {
				
			var ok = (this.xmlHttp.status == 200);	        
        	//hacer accion
        	this.callbackFnc(ok,this.xmlHttp.responseText,this.xmlHttp);
        	this.yaProcesado = true;
		}
	}
};

function ajaxEdit_moveElement(elemento,contenedorDestino){			
		insertarInicio = (arguments.length > 2 && arguments[2] == true);	
		clonedElemento=parent.document.createElement(elemento.tagName);
		clonedElemento.id = elemento.id;
		clonedElemento.className = elemento.className + " elemento_nuevo";
		clonedElemento.innerHTML=elemento.innerHTML; 
		//TODO:Falta añadir todo lo demás del elemento que estamos copiando
		
		//añadimos el nodo
		if (contenedorDestino != null){
			if (insertarInicio && contenedorDestino.childNodes.length >0){
				contenedorDestino.insertBefore(clonedElemento,contenedorDestino.childNodes[0]);
			}else{
				contenedorDestino.appendChild(clonedElemento);
			}
		}else{
			alert("Tu opinión ha sido guardada.");
		}
}		

// url-loading object and a request queue built on top of it
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


//--- content loader object for cross-browser requests ---
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
};


net.ContentLoader.prototype={

	loadXMLDoc:function(url,method,params,contentType){
		  if (!method){
		    method="GET";
		  }
		  if (!contentType && method=="POST"){
		    contentType='application/x-www-form-urlencoded';
		  }
		  if (window.XMLHttpRequest){
		    this.req=new XMLHttpRequest();
		  } else if (window.ActiveXObject){
		    this.req=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		  if (this.req){
		    try{
		      var loader=this;
		      this.req.onreadystatechange=function(){
		        loader.onReadyState.call(loader);
		      };
		      this.req.open(method,url,true);
		      if (contentType){
		        this.req.setRequestHeader('Content-Type', contentType);
		      }
		      this.req.send(params);
		    }catch (err){
		      this.onerror.call(this);
		    }
		  }
		 },
		
 onReadyState:function(){
		  var req=this.req;
		  var ready=req.readyState;
		  if (ready==net.READY_STATE_COMPLETE){
		  	var httpStatus=req.status;
		    if (httpStatus==200 || httpStatus==0){
		      this.onload.call(this);
		    }else{
		      this.onerror.call(this);
		    }
		  }
		 },

 defaultError:function(){
		  alert("error fetching data!"
		    +"\n\nreadyState:"+this.req.readyState
		    +"\nstatus: "+this.req.status
		    +"\nheaders: "+this.req.getAllResponseHeaders());
		 }
};


net.AjaxResponse = function(responseTxt){
	this.errorCode = 0;
	this.errorMsg  ="";
	this.content = "";
	
	//parseamos el resultado de la forma Codigo|Mensaje|contenido
	var posCode = responseTxt.indexOf('|');
	
	if (posCode != -1){
		
		this.errorCode = responseTxt.substring(1,posCode);
		
		posMsg = responseTxt.indexOf('|',posCode+1);		

		if(posMsg != -1){			
			this.errorMsg =  responseTxt.substring(posCode+1,posMsg);
			this.content = responseTxt.substring(posMsg+1);
		}
		
	}
};

//--------------------------------------------------------
//--------------------------------------------------------

         var showComboPais=false;
         function selectPais() {
            if (showComboPais) {
    			document.getElementById("select_combo").style.display="none";
    			showComboPais=false;
            } else {
    			html="<ul>";
    			    				html+="<li><a href='http://www.bodas.net/'><img src='http://cdn0.weddingspot.co.uk/flags/es.png'><span>Spain</span></a></li>";
    			    			    				html+="<li><a href='http://www.matrimonio.com'><img src='http://cdn0.weddingspot.co.uk/flags/it.png'><span>Italy</span></a></li>";
    			    			    				html+="<li><a href='http://www.mariages.net'><img src='http://cdn0.weddingspot.co.uk/flags/fr.png'><span>France</span></a></li>";
    			    			    			    				html+="<li><a href='http://www.bodas.com.mx'><img src='http://cdn0.weddingspot.co.uk/flags/mx.png'><span>Mexico</span></a></li>";
    			   
    			    				html+="<li><a href='http://www.casamentos.pt'><img src='http://cdn0.weddingspot.co.uk/flags/pt.png'><span>Portugal</span></a></li>";
    			   			
    			    				html+="<li><a href='http://www.casamientos.com.ar'><img src='/flags/ar.png'><span>Argentina</span></a></li>";
    			   			                                        
    			    				html+="<li><a href='http://www.matrimonios.cl'><img src='http://cdn0.weddingspot.co.uk/flags/cl.png'><span>Chile</span></a></li>";
    			   			                    
    			    				html+="<li><a href='http://www.casamentos.com.br'><img src='http://cdn0.weddingspot.co.uk/flags/br.png'><span>Brazil</span></a></li>";
    			   			                    
                    
    			html+="</ul>";
    			document.getElementById("select_combo").innerHTML=html;
    			document.getElementById("select_combo").style.display="";
    			showComboPais=true;
            } 
         }
         
function openLayerFunc(url,capa,func, posx, posy) {

	// Creamos el layer para cvisualizar el Alta o Login
	var objBody = document.getElementsByTagName("body").item(0);
	CrearIframe('frameLayer');

	// Eliminamos capa si duplicada
	if(document.getElementById(capa)!=null) {
		capaOld=document.getElementById(capa);
		document.body.removeChild(capaOld);
	}

	// Creamos el lightbox	
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id',capa);
	objLightbox.style.display = 'none';
	objBody.appendChild(objLightbox);
	ajaxpagefunc(url,capa,func);
	
	//Posicionamos en el centro
    objLightbox.style.top = (posy)+"px";
    objLightbox.style.left = (posx)+"px";
    objLightbox.style.zIndex=1000;
    objLightbox.style.position="absolute";
    objLightbox.style.display = '';	
}  

// Cerramos ventanas
function closeLayer(capa) {
	var obj = document.getElementById(capa);
	obj.parentNode.removeChild(obj);
	var obj = document.getElementById("overlay");
	if(obj) obj.parentNode.removeChild(obj);
	showByTagName("object");
}     
         
function  leLoadMap(id_empresa) {
    obj=document.getElementById("esl_"+id_empresa);
    obj2=document.getElementById("main");
	posx=parseInt(findPosX(obj2)+230);
	posy=parseInt(findPosY(obj)-50);
	//alert("x:"+posx+"-y:"+posy);
	openLayerFunc('/list-EmpMap.php?id_empresa='+id_empresa,'capaListEmp',function(){leShowMap()},posx,posy);
}      

function leShowMap() {
	GShowMiniEmp(document.frmMiniMap.longitude.value,document.frmMiniMap.latitude.value,14) ;
} 

function  leEventLoadMap(id_evento) {
    obj=document.getElementById("evento_"+id_evento);
    obj2=document.getElementById("main");
	posx=parseInt(findPosX(obj2)+230);
	posy=parseInt(findPosY(obj)-100);
	//alert("x:"+posx+"-y:"+posy);
	openLayerFunc('/emp-ShowEventosMap.php?id_evento='+id_evento,'capaListEmp',function(){leEventShowMap()},posx,posy);
}      

function leEventShowMap() {
	GShowMiniEmp(document.frmMiniMap.longitude.value,document.frmMiniMap.latitude.value,14) ;
}

leselected="";         
function leh(el) {
	if(leselected.id!=el.id) {
		if(leselected!="") {lenh(leselected);}
		leselected=el;
		id_empresa=el.id.replace("esl_","");
		if (el.className.indexOf("highlight")>=0) {
			el.className='empresa_HL2';
		} else {
			el.className='empresa_HL';
		}
		if (document.getElementById("snp_"+el.id)) {
			htmlLinks="<a href='/list-Redirect.php?type=data&id="+id_empresa+"' class='small fright strong'>View details &raquo;</a>";
		    htmlLinks+="<a href='/list-Redirect.php?type=photos&id="+id_empresa+"' class='ico mas-fotos small'>Photos</a>";
		    htmlLinks+="&nbsp;&nbsp;&nbsp;";
		    htmlLinks+="<a href='javascript:void(0);' onclick='leLoadMap("+id_empresa+")' class='ico mas-mapa small'>Map</a>";
		    htmlLinks+="&nbsp;&nbsp;&nbsp;";
		    htmlLinks+="<a href='/list-Redirect.php?type=contact&id="+id_empresa+"' class='ico mas-contactar small'>Contact us</a>";
		    htmlLinks+="&nbsp;&nbsp;&nbsp;";
		    document.getElementById("snp_"+el.id).innerHTML=htmlLinks; 
	  	}
	}
}     
   
function lenh(el) {
	if (el.className.indexOf("empresa_HL2")>=0) {
		el.className='empresa_N highlight';
	} else {
		el.className='empresa_N';
	}
	if (document.getElementById("snp_"+el.id)) {
		document.getElementById("snp_"+el.id).innerHTML='&nbsp;'; 
	}
}   
 
function lehbasic() {
	if(leselected!="") {lenh(leselected);}
	leselected="";   
}

 function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
         
function VerificaLoginUser(form) {
	var arroba_found=false;var punto_found=false;var i=0;
 	while((i<form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
 	if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
 	while((i<form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
 	if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain a . followed by at least two characters.");form.Mail.focus();return false;}								
 	if(form.Password.value.length<4){alert("The password must contain a minimum of four characters.");form.Password.focus();return false;}
	return true;
}         

function showToolsInfo(page) {
	if(page!='') {
		window.location='/tools/Info?page='+page;
	} else {
		window.location='/tools/Info';
	}
}

/**
* Returns an XMLHttp instance to use for asynchronous
* downloading. This method will never throw an exception, but will
* return NULL if the browser does not support XmlHttp for any reason.
* @return {XMLHttpRequest|Null}
*/
function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

/**
* This functions wraps XMLHttpRequest open/send function.
* It lets you specify a URL and will call the callback if
* it gets a status code of 200.
* @param {String} url The URL to retrieve
* @param {Function} callback The function to call once retrieved.
*/
function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if (status == 200) {
       callback(request.responseXML, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

/**
 * Appends a JavaScript file to the page.
 * @param {string} url
 */
function downloadScript(url) {
  var script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
}


function checkMail(campo,mensaje){
	var retorno=false;
	var entrajx=false;
	url="/utils-CheckMail.php?mail="+campo;
	xmlhttpa=creaXML();
	/*peticion sincrona (se espera una respuesta antes de continuar ejecutando)*/
	xmlhttpa.open("GET",url,false);
	xmlhttpa.setRequestHeader('Accept','message/x-jl-formresult');
	xmlhttpa.send(null);	
	if (xmlhttpa.readyState==4) {
			if((xmlhttpa.responseText).replace(/^\s*|\s*$/g,"")=='OK'){
			   retorno=true;
			}
			else {
			   if (mensaje!="") {	
				   alert(mensaje);
			   }
			   retorno=false;
			}
	}
	return retorno;
}


function VerficaEmailSolic(mail) {
	email = mail.value;
	if(mail.value!=""){
		var emails = email.split(",");
		
		for(var i=0;i < emails.length;i++) {
			if(checkMail(emails[i].replace(/^\s+/g,'').replace(/\s+$/g,''),"Wrong e-mail address.")==false) {
				mail.focus();
				return false;
			}
		}
	}
	return true;
}



function loadPoblacionesCombo(campo,limite) {
	var id_provincia=campo.value;
	document.getElementById('fldPoblacion').innerHTML='<img src="http://cdn0.weddingspot.co.uk/images/ajax-loader-circle.gif" style="padding:0px 68px;" />';
    ajaxpagefunc('/utils-LoadComboPoblaciones.php?limite='+ limite +'&id_pais='+ document.getElementsByName('Pais')[0].value +'&id_provincia='+document.getElementById('Provincia').value,'fldPoblacion',function(){
	    var indiceProv = document.getElementById('Provincia').selectedIndex;
	    document.getElementById('txtStrPoblacion').value= unescape(document.getElementById('Provincia').options[indiceProv].text);
	});
}

function loadPaisCombo(campo,limite) {
	id_pais=campo.value;
	document.getElementById('fldPoblacion').innerHTML='<img src="http://cdn0.weddingspot.co.uk/images/ajax-loader-circle.gif" style="padding:0px 68px;" />';
	document.getElementById('fldProvincia').innerHTML='<img src="http://cdn0.weddingspot.co.uk/images/ajax-loader-circle.gif" style="padding:0px 68px;" />';
	ajaxpagefunc('/utils-LoadComboProvincias.php?limite='+ limite +'&id_pais='+ document.getElementsByName('Pais')[0].value ,'fldProvincia',function(){});
	ajaxpagefunc('/utils-LoadComboPoblaciones.php?limite='+ limite,'fldPoblacion',function(){});
}

function setTextoLocalizacion(campo) {
	document.getElementById('txtStrPoblacion').value=campo;
}


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
};

function getHtmlContentLength(str) {
	return str.replace(/&#?[a-zA-Z0-9]+;/g,' ').replace(/<.*?>/g,'').trim().length;
}

//----------------------------
// Funciones para las pestañas
//----------------------------
var tabs="";
function wct(tab) {
	if(!esIE6()) {
		document.getElementById('wt_'+tab).style.display='none';
		document.getElementById('tab_'+tab).className=document.getElementById('tab_'+tab).className.replace("on-sub","");
	}
}
function wst(tab) {
	if(!esIE6()) {
		wtab=document.getElementById('wt_'+tab);
		if(wtab.innerHTML=="") {
			ajaxpage('/utils-Tabs.php?tab='+tab,'wt_'+tab);
		}
		document.getElementById('wt_'+tab).style.display='';
		document.getElementById('tab_'+tab).className=document.getElementById('tab_'+tab).className+" on-sub";
	}
}

var slayersnippet=false;
function cwpr(id_empresa) {
	document.getElementById('capapromos_'+id_empresa).style.display='none';
	if (document.getElementById('tagpromos_'+id_empresa)) {
		document.getElementById('tagpromos_'+id_empresa).style.zIndex='';
	}
	slayersnippet=false;
} 
function swpr(id_empresa) {
	if(!slayersnippet) {
		slayersnippet=true;
		ajaxpage('/promos-LayerList.php?id_empresa='+id_empresa,'capapromos_'+id_empresa);
		document.getElementById('capapromos_'+id_empresa).style.display='block';
		if (document.getElementById('tagpromos_'+id_empresa)) {
			document.getElementById('tagpromos_'+id_empresa).style.zIndex='10000';
			document.getElementById('capapromos_'+id_empresa).onmouseover= function () { swpr(id_empresa); };
			document.getElementById('capapromos_'+id_empresa).onmouseout=function () { cwpr(id_empresa); };
		}
	}
} 

function cwev(id_empresa) {
	document.getElementById('capaeventos_'+id_empresa).style.display='none';
	if (document.getElementById('tageventos_'+id_empresa)) {
		document.getElementById('tageventos_'+id_empresa).style.zIndex='';
	}
	slayersnippet=false;
} 
function swev(id_empresa) {
	if(!slayersnippet) {
		slayersnippet=true;
		ajaxpage('/eventos-LayerList.php?id_empresa='+id_empresa,'capaeventos_'+id_empresa);
		document.getElementById('capaeventos_'+id_empresa).style.display='block';
		if (document.getElementById('tageventos_'+id_empresa)) {
			document.getElementById('tageventos_'+id_empresa).style.zIndex='10000';
			document.getElementById('capaeventos_'+id_empresa).onmouseover= function () { swev(id_empresa); };
			document.getElementById('capaeventos_'+id_empresa).onmouseout=function () { cwev(id_empresa); };
		}
	}		
} 

function cwvi(id_empresa) {
	document.getElementById('capavideo_'+id_empresa).style.display='none';
	if (document.getElementById('tagvideo_'+id_empresa)) {
		document.getElementById('tagvideo_'+id_empresa).style.zIndex='';
	}
	slayersnippet=false;
} 
function swvi(id_empresa) {
	if(!slayersnippet) {
		slayersnippet=true;
		ajaxpage('/videos-LayerList.php?id_empresa='+id_empresa,'capavideo_'+id_empresa);
		document.getElementById('capavideo_'+id_empresa).style.display='block';
		if (document.getElementById('tagvideo_'+id_empresa)) {
			document.getElementById('tagvideo_'+id_empresa).style.zIndex='10000';
			document.getElementById('capavideo_'+id_empresa).onmouseover= function () { swvi(id_empresa); };
			document.getElementById('capavideo_'+id_empresa).onmouseout=function () { cwvi(id_empresa); };
		}
	}		
} 


//---------------------------------
// Funciones para detectar navegar
//---------------------------------
function esIE6(){
    return getBrowserInfo().appVersion.indexOf("MSIE 6")>0;
};
function esIE(){
    return getBrowserInfo().appVersion.indexOf("MSIE")>0;
};
function esFireFox(){
    return getBrowserInfo().appVersion.indexOf("Netscape")>0;
};

function getBrowserInfo(){
    var browser=navigator.appName;
    var b_version=navigator.appVersion;
    var version=parseFloat(b_version);
    return {
        "name":browser,
        "appVersion":b_version,
        "version":version
    };
};
	

//---------------------------------
// Funciones linkado de imágenes empresa
//---------------------------------
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 fncEmpL()
{

	var imgs = getByClassName('app_imgEmp_');

	for(i=0;i<imgs.length;i++) {
		var imgObj = imgs[i];
		var parts = imgObj.className.split(' ');
		for (j=0;j<parts.length;j++) {
			var pos =parts[j].indexOf('app_imgEmp_');
			if (pos!=-1) {
				var idEmpresa = parts[j].substr(pos+11);
				var lnkObj = document.getElementById('app_lnkEmp_'+idEmpresa);
				if (typeof(lnkObj)!="undefined") {
					fncImgL(imgObj, lnkObj.href);
					break;
				}
			}
		}
	}
}

function fncEmpLNL()
{
	var imgs = $('*[id*=app_imgEmp]');
	imgs.each(function(i, imgObj) {
		var idEmpresa = imgObj.id.substr(11);
		var lnkObj = $('#app_lnkEmp_'+idEmpresa);
		if (lnkObj.length > 0) {
			fncImgL(imgObj, lnkObj.attr('href'));
		}		
    });	
}
function isAppleMobileDevice()
{
    if (
        (navigator.userAgent.indexOf('iPhone') != -1) ||
        (navigator.userAgent.indexOf('iPod') != -1) ||
        (navigator.userAgent.indexOf('iPad') != -1) ||
        (navigator.userAgent.indexOf('symbian') != -1) ||
        (navigator.userAgent.indexOf('android') != -1) ||
        (navigator.userAgent.indexOf('Android') != -1) ||                
        (navigator.userAgent.indexOf('windows ce') != -1) ||
        (navigator.userAgent.indexOf('blackberry') != -1) ||
        (navigator.userAgent.indexOf('palm') != -1)                
    ) {
        return true;
    } else {
        return false;
    }
}

function validateAltaFoot(form) {

	if((!isFullfilField(form.Nombre))||(form.Nombre.value.length<4)){alert("Your name must have a minimum of four characters.");form.Nombre.focus();return false;}
	
	if(!isFullfilField(form.Mail)) {
		alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;
	} else {
		var arroba_found=false;var punto_found=false;var i=0;
		while((i<form.Mail.value.length)&&(!arroba_found)){if(form.Mail.value.charAt(i)=="@"){arroba_found=true;}else{i++;}}
		if((i==0)||(!arroba_found)){alert("The format of your email is incorrect, check that it contains the characters @ and.");form.Mail.focus();return false;}
		while((i<form.Mail.value.length)&&(!punto_found)){if(form.Mail.value.charAt(i)=="."){punto_found=true;}else{i++;}}		
		if((i>form.Mail.value.length-3)||(!arroba_found)){alert("The format of your e-mail is incorrect. It must contain a . followed by at least two characters.");form.Mail.focus();return false;}										
		if(!checkMail(form.Mail.value,"Wrong e-mail address.")) {form.Mail.focus();return false;}
		if(!verificaUserDup(form.Mail,"A user registered with this email address already exists.")) {return false;}
	}
	return true;
}

function resetDirtyFlags()
{
    document["df"] = new Array();
}

function getDirtyFlagsArray(){
    if (typeof(document["df"]) == "undefined" || document["df"] == null) {
        document["df"] = new Array();
    }
    return document["df"];
}

function isFullfilField(campo) {
	var dirtyFlag = "df_"+campo.form.name+"_"+campo.name;
	return (getDirtyFlagsArray()[dirtyFlag] != null);
}

function fullfilField(campo) {
	var dirtyFlag = "df_"+campo.form.name+"_"+campo.name;
	if (document[dirtyFlag] == null) {
		campo.value = "";
		getDirtyFlagsArray()[dirtyFlag] = true;
	}
}

function fullfilFieldPassword(campo) {
	var dirtyFlag = "df_"+campo.form.name+"_"+campo.name;
	if (getDirtyFlagsArray()[dirtyFlag] == null) {
		campo.value = "";
		getDirtyFlagsArray()[dirtyFlag] = true;
	}
	campo.type="Password";
}

function closeAltaFoot() {
	document.getElementById("alta-layer").style.display='none';
	SetCookieSession('NotShowAltaFoot','1');
}

function showAltaFoot() {
	// No mostramos el footer en dispositivos mobiles
	if(!isAppleMobileDevice()) {
		if (GetCookie('NotShowAltaFoot')==1) return;
		var oldUnload = window.onload;
		addToOnLoad(
			function () {
				ajaxpage('/com-AltaFoot.php','comAltaFoot');
			}
		);
	}
}

function addToOnLoad(func) {
	var oldUnload = window.onload;
	window.onload=function () {
		if(oldUnload!=null) oldUnload();
		func();
	}
}





/***********************************************************************/
/* Funciones mostrar capa logado                                       */
/***********************************************************************/

function common_goEnsureLogged(event, url, accion){

    if (url.indexOf("http://") == -1) {
        url = rootdomain +url;
    }
    
    common_callEnsureLogged(
         event,
         function (){
            window.location.href = url;
         },
         accion
    );
    
    return false;
}



function common_callEnsureLogged(event, callfnc, accion, paramAdicionalCapa){
    
    var logado = verificaComSession();

    //si no logado
    if ( !logado){
        //mostramos capa de logado
        common_showLoginLayer(event, callfnc, accion, null, null, paramAdicionalCapa);
    } else {
        callfnc();
    }

    //siempre devolvemos false para poder poner un return en la llamada y poner # en el href del link (problema IE6
    return false;
}


function common_showLoginLayer(event, callfnc, accion, defaultLogin, redirect, paramAdicionalCapa){

	//Función callback que luego se llamar si todo ha ido ok
	document.onLoginOk = function() {
        //var oldhref= window.location.href;
        
        if (!callfnc()) {
            //si no se ha cambiado la url recargamos para que se vea el login
            /*if (oldhref != window.location.href){
                window.location.reload();
            }*/
        }

    };
    
    var url = "/com-CompruebaLogin.php?a";
    if (defaultLogin != null) {
        url += "&defaultLogin="+defaultLogin;
    }
    if (redirect != null) {
        url += "&redirect="+redirect;
    }
   	if (accion != null){
		url +="&accion="+accion;
	}
    
    if (paramAdicionalCapa != null) {
        url += "&"+paramAdicionalCapa;
    }
    
    common_openLayer(event, url, 1);

}


function common_doLoginOkAction()
{
    common_closeLayer('',true);

    if (typeof(document.onLoginOk) != "undefined" &&
        document.onLoginOk != null
    ) {
        document.onLoginOk();
        return true;
    } else {
        return false;
    }
}

// Abrir ventanas
function common_openLayer(e,url,fondo,capa, onLoaded)  {

    document.onLayerLoaded = onLoaded;
    
    if(isIE6()) {
        hideByTagName("select");
    }
    
	if((capa==null)||(capa=='')) {
		capa='capaToolLayer';
		px='';
		py='';
	} else {
		cpl=document.getElementById('capaToolLayer');
		px=cpl.style.top.replace("px","");
		py=cpl.style.left.replace("px","");
	}
	// Creamos el layer para cvisualizar el Alta o Login
	var objBody = document.getElementsByTagName("body").item(0);
	CrearIframe('frameToolLayer');
	if(typeof(fondo)=='undefined') {
		fondo=false;
	}

	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id',capa);
	objLightbox.style.display = 'none';
	//fadeOut(capa);
	objBody.appendChild(objLightbox);
	ajaxpage(url,capa);

	hideByTagName("object");

	// Posicionamos el layer y lo mostramos
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
    var top = (arrayPageSize[3] / 3);
    if (top<10) {
        top = 10;
    }
    top += 40;
	var lightboxTop = arrayPageScroll[1] + top;
	var lightboxLeft= ((arrayPageSize[2] / 2)-200);
	if(px=='') {
        objLightbox.style.top = lightboxTop +"px";
        objLightbox.style.left = lightboxLeft +"px";
        objLightbox.style.zIndex=1000;
    } else {

        objLightbox.style.top = (parseInt(px)+40)+"px";
        objLightbox.style.left = (parseInt(py)+40)+"px";
        objLightbox.style.zIndex=1000;
        objLightbox.style.position="absolute";

    }
    
    objLightbox.style.display = '';
    
    if(fondo) {
        var arrayPageSize = getPageSize();
        var objOverlay = document.createElement("div");
        objOverlay.setAttribute('id','shadow');
        objOverlay.style.zIndex="100";
        //objOverlay.style.display = 'none';
        document.body.appendChild(objOverlay);
        objOverlay.style.height=arrayPageSize[1]+"px";
    }
    
    //reseteamos los dirty flags
    resetDirtyFlags();
}

// Cerramos ventanas
function common_closeLayer(capa,fondo) {
	if((capa==null)||(capa=='')) {
		capa='capaToolLayer';
		if(isIE6()) {
		  showByTagName("select");
		}
	} else  {
	   if(isIE6()) {
	       if(capa!='capaToolLayer') {
	       showByTagNameLayer("select","capaToolLayer");
	       } else {
	           showByTagName("select");
	       }
	   }
	}
	var obj = document.getElementById(capa);
    if (obj != null ) {
        obj.parentNode.removeChild(obj);
        var obj = document.getElementById("overlay");
        if(obj) obj.parentNode.removeChild(obj);
        showByTagName("object");
    }
    var shadow=document.getElementById("shadow");
    if (shadow != null) {
        shadow.parentNode.removeChild(shadow);
    }
}


function isIE6() {
    return window.external && typeof window.XMLHttpRequest == "undefined";
}

function isIE7() {
    return (navigator.appVersion.indexOf("MSIE 7.")==-1) ? false : true;
}

// Mostramos Objetos
function showByTagName(tagName)
{
    var objs = document.getElementsByTagName(tagName);
    for (var i=0; i < objs.length; i++) {
        objs[i].style.display = "";
    }
}

// Ocultamos Objetos
function hideByTagName(tagName)
{
    var objs = document.getElementsByTagName(tagName);
    for (var i=0; i < objs.length; i++) {
        objs[i].style.display = "none";
    }
}

//------------------------------------
// Funciones de traceo de eventos en analytics
//------------------------------------
function trackEvent(categoria, evento) {
	getPageTrackerReduced()._trackEvent(categoria, evento);
}
function teDIR (evento) {
	trackEvent("Directorio", evento);
}
function teME (evento) {
	trackEvent("Menu Proveedor", evento);
}
function teAR (evento) {
	trackEvent("Articulos", evento);
}
function teCOM (evento) {
	trackEvent("Comunidad", evento);
}
function teTOOL (evento) {
	trackEvent("Tools", evento);
}
function teCAT (evento) {
	trackEvent("Catalogo", evento);
}

function getPageTrackerReduced() {
	if(typeof(pageTrackerReduced)=="undefined") {
		pageTrackerReduced = _gat._getTracker("UA-23302538-2");
		pageTrackerReduced._initData();
	}
	return pageTrackerReduced;
}	

