// Según la sección seleccionada, se cambia el menu
function menu(sec) {
  if (navigator.userAgent.indexOf('AppleWebKit') != -1) {
    sub = 'sub-'+sec;
    document.getElementById(sub).style.display = '';
  }
  else {
    if (sec == 'promociones') {
      document.LWjsPagerRef.menu0general.goTo('promocionesenventaresidencial');
    } else {
      document.LWjsPagerRef.menu0general.goTo(sec);
    }
  }

  if (sec == 'promocionesenventa' || sec == 'promocionesenproyecto') {
    document.getElementById('promociones').className = 'on';
    aux = 'menaux-promociones';
  }
  else if (sec == 'serviciosfinancieros' || sec == 'serviciosjuridicos' || sec == 'aplicaciones') {
    document.getElementById('servicios').className = 'on';
    aux = 'menaux-servicios';
  }
  else {
    document.getElementById(sec).className = 'on';
    aux = 'menaux-'+sec;
  }

  var eaux = document.getElementById(aux);
  if (eaux) {
    eaux.className = 'on';
  }
}

/*	sIFR 2.0.2
	Copyright 2004 - 2006 Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben
	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/
var hasFlash=function(){var a=6;if(navigator.appVersion.indexOf("MSIE")!=-1&&navigator.appVersion.indexOf("Windows")>-1){document.write('<script language="VBScript"\> \non error resume next \nhasFlash = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & '+a+'))) \n</script\> \n');if(window.hasFlash!=null)return window.hasFlash}if(navigator.mimeTypes&&navigator.mimeTypes["application/x-shockwave-flash"]&&navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){var b=(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description;return parseInt(b.charAt(b.indexOf(".")-1))>=a}return false}();String.prototype.normalize=function(){return this.replace(/\s+/g," ")};if(Array.prototype.push==null){Array.prototype.push=function(){var i=0,a=this.length,b=arguments.length;while(i<b){this[a++]=arguments[i++]}return this.length}}if(!Function.prototype.apply){Function.prototype.apply=function(a,b){var c=[];var d,e;if(!a)a=window;if(!b)b=[];for(var i=0;i<b.length;i++){c[i]="b["+i+"]"}e="a.__applyTemp__("+c.join(",")+");";a.__applyTemp__=this;d=eval(e);a.__applyTemp__=null;return d}}function named(a){return new named.Arguments(a)}named.Arguments=function(a){this.oArgs=a};named.Arguments.prototype.constructor=named.Arguments;named.extract=function(a,b){var c,d;var i=a.length;while(i--){d=a[i];if(d!=null&&d.constructor!=null&&d.constructor==named.Arguments){c=a[i].oArgs;break}}if(c==null)return;for(e in c)if(b[e]!=null)b[e](c[e]);return};var parseSelector=function(){var a=/^([^#.>`]*)(#|\.|\>|\`)(.+)$/;function r(s,t){var u=s.split(/\s*\,\s*/);var v=[];for(var i=0;i<u.length;i++)v=v.concat(b(u[i],t));return v}function b(c,d,e){c=c.normalize().replace(" ","`");var f=c.match(a);var g,h,i,j,k,n;var l=[];if(f==null)f=[c,c];if(f[1]=="")f[1]="*";if(e==null)e="`";if(d==null)d=document;switch(f[2]){case "#":k=f[3].match(a);if(k==null)k=[null,f[3]];g=document.getElementById(k[1]);if(g==null||(f[1]!="*"&&!o(g,f[1])))return l;if(k.length==2){l.push(g);return l}return b(k[3],g,k[2]);case ".":if(e!=">")h=m(d,f[1]);else h=d.childNodes;for(i=0,n=h.length;i<n;i++){g=h[i];if(g.nodeType!=1)continue;k=f[3].match(a);if(k!=null){if(g.className==null||g.className.match("(\\s|^)"+k[1]+"(\\s|$)")==null)continue;j=b(k[3],g,k[2]);l=l.concat(j)}else if(g.className!=null&&g.className.match("(\\s|^)"+f[3]+"(\\s|$)")!=null)l.push(g)}return l;case ">":if(e!=">")h=m(d,f[1]);else h=d.childNodes;for(i=0,n=h.length;i<n;i++){g=h[i];if(g.nodeType!=1)continue;if(!o(g,f[1]))continue;j=b(f[3],g,">");l=l.concat(j)}return l;case "`":h=m(d,f[1]);for(i=0,n=h.length;i<n;i++){g=h[i];j=b(f[3],g,"`");l=l.concat(j)}return l;default:if(e!=">")h=m(d,f[1]);else h=d.childNodes;for(i=0,n=h.length;i<n;i++){g=h[i];if(g.nodeType!=1)continue;if(!o(g,f[1]))continue;l.push(g)}return l}}function m(d,o){if(o=="*"&&d.all!=null)return d.all;return d.getElementsByTagName(o)}function o(p,q){return q=="*"?true:p.nodeName.toLowerCase().replace("html:", "")==q.toLowerCase()}return r}();var sIFR=function(){var a="http://www.w3.org/1999/xhtml";var b=false;var c=false;var d;var ah=[];var al=document;var ak=al.documentElement;var am=window;var au=al.addEventListener;var av=am.addEventListener;var f=function(){var g=navigator.userAgent.toLowerCase();var f={a:g.indexOf("applewebkit")>-1,b:g.indexOf("safari")>-1,c:navigator.product!=null&&navigator.product.toLowerCase().indexOf("konqueror")>-1,d:g.indexOf("opera")>-1,e:al.contentType!=null&&al.contentType.indexOf("xml")>-1,f:true,g:true,h:null,i:null,j:null,k:null};f.l=f.a||f.c;f.m=!f.a&&navigator.product!=null&&navigator.product.toLowerCase()=="gecko";if(f.m&&g.match(/.*gecko\/(\d{8}).*/))f.j=new Number(g.match(/.*gecko\/(\d{8}).*/)[1]);f.n=g.indexOf("msie")>-1&&!f.d&&!f.l&&!f.m;f.o=f.n&&g.match(/.*mac.*/)!=null;if(f.d&&g.match(/.*opera(\s|\/)(\d+\.\d+)/))f.i=new Number(g.match(/.*opera(\s|\/)(\d+\.\d+)/)[2]);if(f.n||(f.d&&f.i<7.6))f.g=false;if(f.a&&g.match(/.*applewebkit\/(\d+).*/))f.k=new Number(g.match(/.*applewebkit\/(\d+).*/)[1]);if(am.hasFlash&&(!f.n||f.o)){var aj=(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description;f.h=parseInt(aj.charAt(aj.indexOf(".")-1))}if(g.match(/.*(windows|mac).*/)==null||f.o||f.c||(f.d&&(g.match(/.*mac.*/)!=null||f.i<7.6))||(f.b&&f.h<7)||(!f.b&&f.a&&f.k<312)||(f.m&&f.j<20020523))f.f=false;if(!f.o&&!f.m&&al.createElementNS)try{al.createElementNS(a,"i").innerHTML=""}catch(e){f.e=true}f.p=f.c||(f.a&&f.k<312);return f}();function at(){return{bIsWebKit:f.a,bIsSafari:f.b,bIsKonq:f.c,bIsOpera:f.d,bIsXML:f.e,bHasTransparencySupport:f.f,bUseDOM:f.g,nFlashVersion:f.h,nOperaVersion:f.i,nGeckoBuildDate:f.j,nWebKitVersion:f.k,bIsKHTML:f.l,bIsGecko:f.m,bIsIE:f.n,bIsIEMac:f.o,bUseInnerHTMLHack:f.p}}if(am.hasFlash==false||!al.getElementsByTagName||!al.getElementById||(f.e&&(f.p||f.n)))return{UA:at()};function af(e){if((!k.bAutoInit&&(am.event||e)!=null)||!l(e))return;b=true;for(var i=0,h=ah.length;i<h;i++)j.apply(null,ah[i]);ah=[]}var k=af;function l(e){if(c==false||k.bIsDisabled==true||((f.e&&f.m||f.l)&&e==null&&b==false)||(al.body==null||al.getElementsByTagName("body").length==0))return false;return true}function m(n){if(f.n)return n.replace(new RegExp("%\d{0}","g"),"%25");return n.replace(new RegExp("%(?!\d)","g"),"%25")}function as(p,q){return q=="*"?true:p.nodeName.toLowerCase().replace("html:", "")==q.toLowerCase()}function o(p,q,r,s,t){var u="";var v=p.firstChild;var w,x,y,z;if(s==null)s=0;if(t==null)t="";while(v){if(v.nodeType==3){z=v.nodeValue.replace("<","&lt;");switch(r){case "lower":u+=z.toLowerCase();break;case "upper":u+=z.toUpperCase();break;default:u+=z}}else if(v.nodeType==1){if(as(v,"a")&&!v.getAttribute("href")==false){if(v.getAttribute("target"))t+="&sifr_url_"+s+"_target="+v.getAttribute("target");t+="&sifr_url_"+s+"="+m(v.getAttribute("href")).replace(/&/g,"%26");u+='<a href="asfunction:_root.launchURL,'+s+'">';s++}else if(as(v,"br"))u+="<br/>";if(v.hasChildNodes()){y=o(v,null,r,s,t);u+=y.u;s=y.s;t=y.t}if(as(v,"a"))u+="</a>"}w=v;v=v.nextSibling;if(q!=null){x=w.parentNode.removeChild(w);q.appendChild(x)}}return{"u":u,"s":s,"t":t}}function A(B){if(al.createElementNS&&f.g)return al.createElementNS(a,B);return al.createElement(B)}function C(D,E,z){var p=A("param");p.setAttribute("name",E);p.setAttribute("value",z);D.appendChild(p)}function F(p,G){var H=p.className;if(H==null)H=G;else H=H.normalize()+(H==""?"":" ")+G;p.className=H}function aq(ar){var a=ak;if(k.bHideBrowserText==false)a=al.getElementsByTagName("body")[0];if((k.bHideBrowserText==false||ar)&&a)if(a.className==null||a.className.match(/\bsIFR\-hasFlash\b/)==null)F(a, "sIFR-hasFlash")}function j(I,J,K,L,M,N,O,P,Q,R,S,r,T){if(!l())return ah.push(arguments);aq();named.extract(arguments,{sSelector:function(ap){I=ap},sFlashSrc:function(ap){J=ap},sColor:function(ap){K=ap},sLinkColor:function(ap){L=ap},sHoverColor:function(ap){M=ap},sBgColor:function(ap){N=ap},nPaddingTop:function(ap){O=ap},nPaddingRight:function(ap){P=ap},nPaddingBottom:function(ap){Q=ap},nPaddingLeft:function(ap){R=ap},sFlashVars:function(ap){S=ap},sCase:function(ap){r=ap},sWmode:function(ap){T=ap}});var U=parseSelector(I);if(U.length==0)return false;if(S!=null)S="&"+S.normalize();else S="";if(K!=null)S+="&textcolor="+K;if(M!=null)S+="&hovercolor="+M;if(M!=null||L!=null)S+="&linkcolor="+(L||K);if(O==null)O=0;if(P==null)P=0;if(Q==null)Q=0;if(R==null)R=0;if(N==null)N="#FFFFFF";if(T=="transparent")if(!f.f)T="opaque";else N="transparent";if(T==null)T="";var p,V,W,X,Y,Z,aa,ab,ac;var ad=null;for(var i=0,h=U.length;i<h;i++){p=U[i];if(p.className!=null&&p.className.match(/\bsIFR\-replaced\b/)!=null)continue;V=p.offsetWidth-R-P;W=p.offsetHeight-O-Q;aa=A("span");aa.className="sIFR-alternate";ac=o(p,aa,r);Z="txt="+m(ac.u).replace(/\+/g,"%2B").replace(/&/g,"%26").replace(/\"/g, "%22").normalize() + S + "&w=" + V + "&h=" + W + ac.t;F(p,"sIFR-replaced");if(ad==null||!f.g){if(!f.g){if(!f.n)p.innerHTML=['<embed class="sIFR-flash" type="application/x-shockwave-flash" src="',J,'" quality="best" wmode="',T,'" bgcolor="',N,'" flashvars="',Z,'" width="',V,'" height="',W,'" sifr="true"></embed>'].join("");else p.innerHTML=['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" sifr="true" width="',V,'" height="',W,'" class="sIFR-flash"><param name="movie" value="',J,"?",Z,'"></param><param name="quality" value="best"></param><param name="wmode" value="',T,'"></param><param name="bgcolor" value="',N,'"></param> </object>'].join('')}else{if(f.d){ab=A("object");ab.setAttribute("data",J);C(ab,"quality","best");C(ab,"wmode",T);C(ab,"bgcolor",N)}else{ab=A("embed");ab.setAttribute("src",J);ab.setAttribute("quality","best");ab.setAttribute("flashvars",Z);ab.setAttribute("wmode",T);ab.setAttribute("bgcolor",N)}ab.setAttribute("sifr","true");ab.setAttribute("type","application/x-shockwave-flash");ab.className="sIFR-flash";if(!f.l||!f.e)ad=ab.cloneNode(true)}}else ab=ad.cloneNode(true);if(f.g){if(f.d)C(ab,"flashvars",Z);else ab.setAttribute("flashvars",Z);ab.setAttribute("width",V);ab.setAttribute("height",W);ab.style.width=V+"px";ab.style.height=W+"px";p.appendChild(ab)}p.appendChild(aa);if(f.p)p.innerHTML+=""}if(f.n&&k.bFixFragIdBug)setTimeout(function(){al.title=d},0)}function ai(){d=al.title}function ae(){if(k.bIsDisabled==true)return;c=true;if(k.bHideBrowserText)aq(true);if(am.attachEvent)am.attachEvent("onload",af);else if(!f.c&&(al.addEventListener||am.addEventListener)){if(f.a&&f.k>=132&&am.addEventListener)am.addEventListener("load",function(){setTimeout("sIFR({})",1)},false);else{if(al.addEventListener)al.addEventListener("load",af,false);if(am.addEventListener)am.addEventListener("load",af,false)}}else if(typeof am.onload=="function"){var ag=am.onload;am.onload=function(){ag();af()}}else am.onload=af;if(!f.n||am.location.hash=="")k.bFixFragIdBug=false;else ai()}k.UA=at();k.bAutoInit=true;k.bFixFragIdBug=true;k.replaceElement=j;k.updateDocumentTitle=ai;k.appendToClassName=F;k.setup=ae;k.debug=function(){aq(true)};k.debug.replaceNow=function(){ae();k()};k.bIsDisabled=false;k.bHideBrowserText=true;return k}();
if(typeof sIFR == "function" && !sIFR.UA.bIsIEMac){
	sIFR.setup();
};
/*
  h1 -> eslogan Flash (en cursiva)
  h2 -> título de sección Flash
  h3 -> subtítulo de sección
  h3.blanco -> subtítulo de sección (color blanco)
  h3.filete -> subtítulo de sección (con filete)
  h4 -> apartado de seccion
  h4.verde -> apartado de seccion (color verde)
  h5 span -> destacado Flash (fondo gris)
  p.frase -> frase Flash
*/
function sIFRwrite() {
  if(typeof sIFR == "function"){
    sIFR.replaceElement(named({sSelector:"h1", sFlashSrc:"/swf/sifr_themixoffice_italic.swf", sColor:"#c32023", sWmode:"opaque", nPaddingLeft:"0"}));
    sIFR.replaceElement(named({sSelector:"h2", sFlashSrc:"/swf/sifr_themixoffice.swf", sColor:"#bf0a1d", sWmode:"opaque", nPaddingLeft:"0"}));
    sIFR.replaceElement(named({sSelector:"h5 span", sFlashSrc:"/swf/sifr_themixoffice.swf", sColor:"#ffffff", sBgColor:"#8b8b80", sWmode:"opaque", nPaddingLeft:"10"}));
    sIFR.replaceElement(named({sSelector:"p.frase", sFlashSrc:"/swf/sifr_themixoffice.swf", sColor:"#1a171b", sWmode:"opaque", nPaddingLeft:"0"}));
  };
}

// Mostrar contenido emergente (fotos, videos...), Youtube: solo codigo identificador de video, Imagen: ruta absoluta (sin dominio)
function visor(f,m,t) {
  // si hay funcion = on
  if (f) {
    // si es video, reemplaza la ruta
    if (m == 'youtube') {
      fc = f.replace('watch?v=','v/');
      youtube = fc+'&fmt6&color1=0x5d1719&color2=0xcd311b&border=0'; w = 425; h = 355;
      // construye el <object> con los datos reformados
      v = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+w+'" height="'+h+'"><param name="loop" value="false"/><param name="menu" value="false"/><param name="movie" value="'+youtube+'"/><param name="quality" value="high"/><param name="wmode" value="transparent"><embed src="'+youtube+'" loop="false" menu="false" quality="high" width="'+w+'" height="'+h+'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/></object>';
      tit = '';
    }
    // si es foto
    else {
      v = '<img src="'+f+'" onclick="visor()" alt="Cargando imagen..."/>';
      tit = '<tr><td colspan="2" style="background:#8a8a7f;">'+t+'</td></tr>';
    }
    // construye la tabla con el contenido foto|video
    c = '<table class="global"><tr><td class="ali-med" onclick="visor(\'\',\'\')"><table align="center" style="width:200px;height:200px"><tr><td>Grupo Ferlo</td><td align="right"><a href="javascript:;" onclick="visor(\'\',\'\')">Cerrar</a></td></tr><tr><td colspan="2" class="decora">'+v+'</td></tr>'+tit+'</table></td></tr></table>';
    // si es Mac o Linuc muestra el iframe hack para Flah
    if (navigator.userAgent.indexOf('Linux') != -1 || navigator.userAgent.indexOf('Mac') != -1) {
      document.getElementById('iframe').style["display"]='block';
    }
    else document.body.style["overflow"]='hidden';
    document.getElementById('visorbg').style["visibility"]='';
    document.getElementById('visor').style["visibility"]='';
    
    // Fallos del IE cargando imagenes, necesita cachear antes.
    if (m == 'youtube') {
      document.getElementById('visor').innerHTML=c;
    }
    else {
      if (LWjsLib.isIE) {
        var i = new Image;
        top._cc = c;
        i.onload = function() {
          document.getElementById('visor').innerHTML=c;
        }
        i.src = f;
      }
      else {
        document.getElementById('visor').innerHTML=c;
      }
    }
    var st = document.body.scrollTop;
    document.getElementById('visorbg').style["marginTop"]=st;
    document.getElementById('visor').style["marginTop"]=st;
  }
  // si no hay funcion, oculta el contenido
  else {
    // si es Mac o Linuc oculta el iframe hack para Flah
    if (navigator.userAgent.indexOf('Linux') != -1 || navigator.userAgent.indexOf('Mac') != -1) {
      document.getElementById('iframe').style["display"]='none';
    }
    else if (navigator.userAgent.indexOf('AppleWebKit') != -1) {
      document.body.style["overflow"]='scroll';
    }
    else document.body.style["overflow"]='auto';
    document.getElementById('visor').innerHTML='';
    document.getElementById('visor').style["visibility"]='hidden';
    document.getElementById('visorbg').style["visibility"]='hidden';
  }
}

// Enviar formulario
var e = top._toEmail = 'comer'+'cial@grupo'+'ferlo.com';
var em = '<a href="mailto:'+e+'">'+e+'</a>';

function enviar(c, v) {
  if (v) {
    var lang = location.pathname.charAt(3) == '/' ? location.pathname.substr(1,2) : location.search.substr(location.search.indexOf('lang=')+5,2);

    if (!v.checked) {
      if (lang = 'es') {
        alert('Debe aceptar la política de privacidad antes de usar este servicio.');
      } else {
        alert('Data protection policy must be read and accepted first');
      }
      return;
    }
  }

  c.toEmail.value = top._toEmail;
  c.submit();
}

// Corrige la transparencia de los PNG en IE
function correctPNG() {
  var arVersion = navigator.appVersion.split("MSIE");
  var version = parseFloat(arVersion[1]);
  if ((version < 7) && (document.body.filters)) {
    for(var i=0; i<document.images.length; i++) {
      var img = document.images[i];
      var imgName = img.src.toUpperCase();
      if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
        var imgID = (img.id) ? "id='" + img.id + "' " : "";
        var imgClass = (img.className) ? "class='" + img.className + "' " : "";
        var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
        var imgStyle = "display:inline-block;" + img.style.cssText;
        if (img.align == "left") imgStyle = "float:left;" + imgStyle;
        if (img.align == "right") imgStyle = "float:right;" + imgStyle;
        if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
        var strNewHTML = "<span " + imgID + imgClass + imgTitle
          + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
          + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
          + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
        img.outerHTML = strNewHTML;
        i = i-1;
      }
    }
  }    
};
if (navigator.appName == 'Microsoft Internet Explorer') window.attachEvent("onload", correctPNG);

// banner aleatorio
function showbanners() {
  var d = document;
  var cb = d.getElementById('columnabanners');
  if (cb) {
    var nb = 0, e = cb.firstChild, id;
    while (e) {
      if (e.getAttribute) {
        id = e.getAttribute('id');
        if (id && !id.indexOf('banner')) {
          nb++;
        }
      }
      e = e.nextSibling;
    }
    if (nb) {
      e = Math.pow(2,nb)-1;
      var s = 0, y;
      var max = d.getElementById('banner_dossier')? 2 : 3, hi = 1;
      while (s < max && s < nb) {
        var x = e-Math.random()*e, b = 1;
        while (x >= 2) {
          x = x/2;
          b++;
        }
        y = d.getElementById('banner'+b);
        if (y.style.display != '') {
          y.style.display = '';
          s++;
          y.className = 'banner';
          if (b > hi) {
            hi = b;
          }
        }
      }
      
      y = d.getElementById('banner'+hi);
      y.className = 'bannerultimo';
    }
  }
};
top.showbanners = showbanners;

// Login inmobiliaria (i=id, n=name)
function inmobiliarialogin(i, n) {
  var a = document.getElementById('accesoinmobiliarias');
  if (a) {
    var lang = location.pathname.charAt(3) == '/' ? location.pathname.substr(1,2) : location.search.substr(location.search.indexOf('lang=')+5,2), mc, ex;
    
    if (lang == 'es') {
      mc='Mi cuenta';
      ex='Salir';
    }

    if (lang == 'en') {
      mc='My account';
      ex='Exit';
    }
    
    a.innerHTML = n+' · <a href="/user/auth/login?use=web&noanon=on&lang='+lang+'">'+mc+'</a>  · <a href="/user/auth/logout?use=web&noanon=on&lang='+lang+'">'+ex+'</a>';
    
    Set_Cookie('_inmobiliaria', i, 999999, '/', 'grupoferlo.com', '');
    Set_Cookie('_inmobiliarian', n, 999999, '/', 'grupoferlo.com', '');
  }
};
top.inmobiliarialogin = inmobiliarialogin;

function inmobiliarialogout() {
  var a = document.getElementById('accesoinmobiliarias');
  if (a) {
    var lang = location.pathname.charAt(3) == '/' ? location.pathname.substr(1,2) : location.search.substr(location.search.indexOf('lang=')+5,2), ac;

    if (lang == 'es') {
      ac='Acceso inmobiliarias';
    }

    if (lang == 'en') {
      ac='Real state channel';
    }

    a.innerHTML = name+' <a href="/user/auth/login?use=web&noanon=on&lang='+lang+'">'+ac+'</a>';
    Delete_Cookie('_inmobiliaria', '/', 'grupoferlo.com');
  }
};
top.inmobiliarialogout = inmobiliarialogout;

function presentarimporte(v, coneuro) {
  var v = String(v), e, d, r = '', i = 0;
  if (v > 2) {
    e = v.substring(0,v.length-2);
    d = v.substr(v.length-2);
  }
  else {
    e = '0';
    d = ('0'+v).substr(('0'+v).length-2);
  }
  for (var j = e.length-1; j >= 0; j--) {
    if (i == 3) {
      r = '.'+r;
      i = 0;
    }
    r = e.charAt(j)+r;
    i++;
  }
  return(r+','+d+(coneuro? ' &euro;' : ''));
};

function presentarmes(m) {
  switch (m) {
    case 0: return('Enero');
    case 1: return('Febrero');
    case 2: return('Marzo');
    case 3: return('Abril');
    case 4: return('Mayo');
    case 5: return('Junio');
    case 6: return('Julio');
    case 7: return('Agosto');
    case 8: return('Septiembre');
    case 9: return('Octubre');
    case 10: return('Noviembre');
    case 11: return('Diciembre');
  }
};

function verfecha(f) {
  var r;
  return(presentarmes(f.getMonth())+' '+f.getFullYear());
};

function cuota(hipoteca, meses, interes) {
  var tipomes = (interes/100) / 1200.0, y  = 1.0 + tipomes;
  var cuota = Math.round(hipoteca/100) * tipomes * Math.pow(y, meses) / ( Math.pow(y, meses) - 1.0 ); 
  return(Math.round(cuota * 100.00));
};

function simuplazo(q) {
  var d = document, f = d.getElementById('formsimu'), e = f.elements;
  var plazo = parseInt(e.anios.value, 10);
  if (isNaN(plazo) || !plazo) {
    plazo = 30;
    e.anios.value = plazo;
  }
  else {
    if (q) {
      f._as = f._ms = null;
      simuveranomes();
      plazo += q;
      if (plazo < 1) {
        plazo = 1;
      }
      if (plazo > 50) {
        plazo = 50;
      }
      e.anios.value = plazo;
      simu();
    }
  }
  return(plazo);
};

function simumes(m) {
  var d = document, f = d.getElementById('formsimu'), e = f.elements;
  var hoy = new Date(), mi = hoy.getMonth(), ai = hoy.getFullYear(), sc = d.getElementById('simumesesitos');
  var plazo = simuplazo();
  var af = ai + plazo, mf = 11;
  if (f._as) {
    if (f._as == af && mi > 0) {
      mf = mi -1;
    }
    if (f._as > ai) {
      mi = 0;
    }
  }
  var mm = mf-mi > 6? mf-5 : mi;
  if (!m && m != 0) {
    m = mi;
  }
  else {
    if (m == 1 || m == -1) {
      m = f._ma? f._ma + m : mi + m;
    }
    if (m < mi) {
      m = mi;
    }
    if (m > mm) {
      m = mm;
    }
  }
  f._ma = m;
  var j = 1, pm = m, html = '';
  while (j < 7 && pm <= mf) {
    html = html+'<a href="javascript:simuveranomes('+pm+');"'+(f._ms == pm? ' style="background-color:#e5eec1;"' : '')+'>'+presentarmes(pm)+'<\/a>';
    pm++;
    j++;
  }
  sc.innerHTML = html;
};

function simuano(a) {
  var d = document, f = d.getElementById('formsimu'), e = f.elements;
  var hoy = new Date(), ai = hoy.getFullYear(), sc = d.getElementById('simuanios');
  var plazo = simuplazo(); 
  var af = ai + plazo, am = af-ai > 6? af-5 : ai;
  if (!a) {
    a = ai;
  }
  else {
    if (a == 1 || a == -1) {
      a = f._aa? f._aa + a : ai + a;
    }
    if (a < ai) {
      a = ai;
    }
    if (a > am) {
      a = am;
    }
  }
  f._aa = a;
  var j = 1, pa = a, html = '';
  while (j < 7 && pa <= af) {
    html = html+'<a href="javascript:simuveranomes('+pa+');"'+(f._as == pa? ' style="background-color:#e5eec1;"' : '')+'>'+pa+'<\/a>';
    pa++;
    j++;
  }
  sc.innerHTML = html;
  simumes(f._ma || f._ma == 0? f._ma : null);
};

function simuveranomes(c) {
  var d = document, f = d.getElementById('formsimu'), e = f.elements;
  if (c || c == 0) {
    if (c > 12) {
      f._as = c;
      simuano(f._aa? f._aa : null);
    } 
    else {
      f._ms = c;
      simumes(f._ma || f._ma == 0? f._ma : null);
    }
  }
  var rf = d.getElementById('simumesano'), scm = d.getElementById('simucuotamesano'), stm = d.getElementById('simutotalmesano');
  if ((f._ms || f._ms == 0) && f._as) {
    rf.innerHTML = presentarmes(f._ms)+' '+String(f._as);
    var hoy = new Date(), tm = (f._as-hoy.getFullYear()-1)*12 + (12-hoy.getMonth()) + (f._ms);
    scm.innerHTML = presentarimporte(f._almes, true);
    stm.innerHTML = presentarimporte(tm*f._almes, true);
  } 
  else {
    rf.innerHTML = '--';
    scm.innerHTML = stm.innerHTML = '--';
  }
};

/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.1
Last Update: 4 October 2007

Changes:
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks

1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


// Amort
// amt - importe
// mnths - meses
function amortizacion(amt, mnths, interes) {
  var ct=0, ct1=0, ct2=0, ctmnth=0, t0=0, t1=0, t2=0, t3=0, t4=0, arrayct=0, nbal=0;
  var arrayct=240, mnth = new Array();

	var rte = interes/1200;
	var pmt=(rte+(rte/(Math.pow((1+rte),(mnths))-1)))*amt;
	
	var pmtout = pmt*100;
	pmtout=Math.round(pmtout);
	pmtout=pmtout/100;


  var items=mnths*4;
  var payoff=amt;
  var intbal=amt;
  var intbal2=amt;
  var t3=amt;
  var t4=0;

  var yrs=mnths/12;
  
  while (ct1 < yrs) {
    while (ct2 < 12) {
      intrst = (intbal*rte);
      payoff = payoff-pmt+intrst;
      t1 = t1+pmt;
      mnth[ctmnth] = t1;
      ctmnth = ctmnth+1;
      t2 = t2+intrst;
      mnth[ctmnth] = t2;
      ctmnth = ctmnth+1;
      t3 = amt-payoff;
      mnth[ctmnth] = t3;
      ctmnth = ctmnth+1;
      t4 = payoff;
      mnth[ctmnth] = t4;
      ctmnth = ctmnth+1;
      intbal = intbal-pmt+intrst;
      ct2 = ct2+1
    }
    
    ct2 = 0;
    ct1 = ct1+1
  }

  return(mnth);
}

function gastos(p, h) {
  var r = new Object();
  r.precio = p;
  r.totaliva = Math.round(p*0.08);
  r.hipoteca = h;
  
  r.actos = Math.round(p*0.01);
  r.notario = Math.round(p*0.0015);
  r.registro = Math.round(p*0.0008);
  r.gestoria = Math.round(p*0.0012);
  
  r.total = r.actos+r.notario+r.registro+r.gestoria;
  
  // subrogación
  r.s = new Object();
  r.s.comision = Math.round(h*0.006);
  r.s.notario = Math.round(h*0.0015);
  r.s.registro = Math.round(h*0.0008);
  r.s.gestoria = Math.round(h*0.0005);
  r.s.total = r.s.comision+r.s.notario+r.s.registro+r.s.gestoria;
  
  // nuevaconstitucion
  r.o = new Object();
  r.o.notario = Math.round(h*0.0042);
  r.o.registro = Math.round(h*0.0018);
  r.o.gestoria = Math.round(h*0.0014);
  r.o.actos = Math.round(h*1.5*0.01);
  r.o.comision = Math.round(h*0.01);
  r.o.tasacion = Math.round(h*0.002);
  r.o.total = r.o.notario+r.o.registro+r.o.gestoria+r.o.actos+r.o.comision+r.o.tasacion;
  
  // cancelación (oferta vinculante)
  r.c = new Object();
  r.c.notario = Math.round(h*0.0015);
  r.c.registro = Math.round(h*0.0009);
  r.c.gestoria = Math.round(h*0.0005);
  r.c.comision = Math.round(h*0.005);
  //r.c.iva = Math.round(h*0.0035);
  r.c.total = r.c.comision+r.c.notario+r.c.gestoria+r.c.registro;//+r.c.iva;
  
  // subrogación (oferta vinculante)
  //r.sh = new Object();
  //r.sh.notario = Math.round(h*0.0015);
  //r.sh.registro = Math.round(h*0.0009);
  //r.sh.gestoria = Math.round(h*0.0005);
  //r.sh.comisionamortizacion = Math.round(h*0.005);
  //r.sh.comision = Math.round(h*0.001);
  //r.sh.total = r.sh.notario+r.sh.gestoria+r.sh.comisionamortizacion; // comision apertura no
  
  return(r);
}
