﻿var nie = (navigator.appName.indexOf("Microsoft") == -1);
var gc = (navigator.userAgent.toLowerCase().indexOf("chrome") > -1);
var ie5 = document.all && !window.opera
var ns6 = document.getElementById
var msgrepetir = 'Desculpe, ocorreu uma falha técnica durante o atendimento à sua solicitação.\n\nPor favor tente repetir a operação.\n\nSe o erro persistir, tente fechar seu navegador e abrí-lo novamente, ou entre em contato conosco.';

function getel(doc, id) {
    return doc.getElementById(id);
}

function el(id) {
    return getel(document, id);
}

function getElementsById(sId) {
    var outArray = new Array();

    if (typeof (sId) != 'string' || !sId) {
        return outArray;
    };
        if (document.evaluate) {
        var xpathString = "//*[@id='" + sId.toString() + "']"
        var xpathResult = document.evaluate(xpathString, document, null, 0, null);
        while ((outArray[outArray.length] = xpathResult.iterateNext())) { }
        outArray.pop();
    }
    else if (document.all) {

        if (document.all[sId])
            for (var i = 0, j = document.all[sId].length; i < j; i += 1) {
                outArray[i] = document.all[sId][i];
            }

    } else if (document.getElementsByTagName) {

        var aEl = document.getElementsByTagName('*');
        for (var i = 0, j = aEl.length; i < j; i += 1) {

            if (aEl[i].id == sId) {
                outArray.push(aEl[i]);
            };
        };

    };

    if ((outArray.length == 0) && (el(sId)))
        outArray[0] = el(sId);

    return outArray;
}

function escreve(s) {
    document.write(s);
}

function arr(n) {
    this.length = n
    for (var i = 0; i < n; i = i + 1) {
        this[i] = ''
    }
}

function element_top(el) {
    var et = 0
    while (el) {
        et += el.offsetTop
        el = el.offsetParent
    }
    return et
}


function element_left(el) {
    var et = 0
    while (el) {
        et += el.offsetLeft
        el = el.offsetParent
    }
    return et
}

// deteccao flash
var nv = navigator; var isIE = (nv.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (nv.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (nv.userAgent.indexOf("Opera") != -1) ? true : false; function ControlVersion() { var v; var a; var e; try { a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); v = a.GetVariable("$version") } catch (e) { } if (!v) { try { a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); v = "WIN 6,0,21,0"; a.AllowScriptAccess = "always"; v = a.GetVariable("$version") } catch (e) { } } if (!v) { try { a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); v = a.GetVariable("$version") } catch (e) { } } if (!v) { try { a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); v = "WIN 3,0,18,0" } catch (e) { } } if (!v) { try { a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); v = "WIN 2,0,0,11" } catch (e) { v = -1 } } return v } function GetSwfVer() { var a = -1; ua = nv.userAgent.toLowerCase(); if (nv.plugins != null && nv.plugins.length > 0) { if (nv.plugins["Shockwave Flash 2.0"] || nv.plugins["Shockwave Flash"]) { var b = nv.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var c = nv.plugins["Shockwave Flash" + b].description; var d = c.split(" "); var e = d[2].split("."); var f = e[0]; var g = e[1]; if (d[3] != "") { tam = d[3].split("r") } else { tam = d[4].split("r") } var h = tam[1] > 0 ? tam[1] : 0; var a = f + "." + g + "." + h } } else if (ua.indexOf("webtv/2.6") != -1) a = 4; else if (ua.indexOf("webtv/2.5") != -1) a = 3; else if (ua.indexOf("webtv") != -1) a = 2; else if (isIE && isWin && !isOpera) { a = ControlVersion() } return a } function DetectFlashVer(a, b, c) { vStr = GetSwfVer(); if (vStr == -1) { return false } else if (vStr != 0) { if (isIE && isWin && !isOpera) { tempArray = vStr.split(" "); tempString = tempArray[1]; vArray = tempString.split(",") } else { vArray = vStr.split(".") } var d = vArray[0]; var e = vArray[1]; var f = vArray[2]; if (d > parseFloat(a)) { return true } else if (d == parseFloat(a)) { if (e > parseFloat(b)) return true; else if (e == parseFloat(b)) { if (f >= parseFloat(c)) return true } } return false } }

/* 18/01/2010 */
function getFlash(id, src, width, height, align, salign, transparent, mozila, versao, onmouseover, onmouseout, flashVars, opaque) {
    s = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + (versao) + ',0,0,0" width="' +
    (width) + '" height="' + (height) + '" id="' +
    id + '" ' + (align != '' ? 'align="' + align + '"' : '') +
    (onmouseover != '' ? ' onmouseover="' + onmouseover + '"' : '') +
    (onmouseout != '' ? ' onmouseout="' + onmouseout + '"' : '') +
    '><param name="quality" value="high" />' +
    (src != '' ? '<param name="movie" value="' + src + '" />' : '') +
    (salign != '' ? '<param name="salign" value="' + salign + '" />' : '') +
    (transparent ? '<param name="wmode" value="transparent" />' : '') +
    (((typeof (opaque) != "undefined") && (opaque)) ? '<param name="wmode" value="opaque" />' : '') +
    (((typeof (flashVars) != "undefined") && (flashVars != '')) ? '<param name="flashVars" value="' + flashVars + '" />' : '') +
    '<param name="menu" value="false" /><param name="scale" value="noscale" />';
    if (mozila)
        s += '<embed ' +
        (src != '' ? 'src="' + src + '" ' : '') +
        'loop="false" menu="false" quality="high" scale="noscale" width="' +
        (width) + '" height="' + (height) + '" name="' + id + '" ' +
        (align != '' ? 'align="' + align + '" ' : '') +
        (salign != '' ? 'salign="' + salign + '" ' : '') +
        (onmouseover != '' ? 'onmouseover="' + onmouseover + '" ' : '') +
        (onmouseout != '' ? 'onmouseout="' + onmouseout + '" ' : '') +
        (transparent ? 'wmode="transparent" ' : '') +
        (((typeof (opaque) != "undefined") && (opaque)) ? 'wmode="opaque" ' : '') +
        (((typeof (flashVars) != "undefined") && (flashVars != '')) ? 'flashVars="' + flashVars + '" ' : '') +
        'allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" swliveconnect="true" />';
    s += '</object>';
    return s;
}

/* 11/05/2011 */
function escreveFlash(id, src, width, height, align, salign, transparent, mozila, versao, onmouseover, onmouseout, flashVars, opaque, altCode) {
    hasFlash = DetectFlashVer(versao, 0, 0);
    s = '';
    if (hasFlash)
        s = getFlash(id, src, width, height, align, salign, transparent, mozila, versao, onmouseover, onmouseout, flashVars, opaque);
    else if (typeof (altCode) != "undefined") {
        s = altCode;
    }
    escreve(s);
}

function loadFlashWithPreload2(id, src, preloadId, paramsStr) {
    preloaded = movieIsLoaded(mv(preloadId));
    loaded = movieIsLoaded(mv(id));

    if ((!loaded) && (preloaded)) {
        cmd = 'loadMovie(\'' + id + '\', \'' + src + '\', [' + paramsStr + '])';
        setTimeout(cmd, 1);
    }

    paramsStr = paramsStr.replace(/\'/g, '\\\'');
    cmd = 'loadFlashWithPreload2(\'' + id + '\', \'' + src + '\', \'' + preloadId + '\', \'' + paramsStr + '\')';

    //if ((loaded) && (nie))
    //    setTimeout(cmd, 1000);
    //else 
    if (!loaded)
        setTimeout(cmd, 100);

}

function mv(movieName) {
    tM = null;
    if (navigator.appName.indexOf("Microsoft") != -1) {
        tM = document.all[movieName];
        if (typeof (tM) != "undefined") {
            if (tM.length && (tM.length > 0))
                tM = tM[0];
            else if (tM.length && (tM.length == 0))
                tM = null;
        }
    }
    else if (document[movieName])
        tM = document[movieName];
    else
        tM = el(movieName);

    return tM;
}

function loadMovie(id, movie, params) {
    mv(id).LoadMovie(0, movie);
    for (p = 0; p < params.length; p += 2)
        mv(id).SetVariable(params[p], params[p + 1]);
}

function loadMovieWithDelay(id, movie, paramsStr) {
    cmd = 'loadMovie(\'' + id + '\', \'' + movie + '\', ' + paramsStr + ')';
    setTimeout(cmd, 500);
}

function movieIsLoaded(theMovie) {
    if (typeof (theMovie) != "undefined") {
        return ((typeof (theMovie.PercentLoaded) != "undefined") && (theMovie.PercentLoaded() == 100));
    } else {
        return false;
    }
}

function movieIsReady(theMovie) {
    return (typeof (theMovie.PercentLoaded) != "undefined");
}

function newImage(arg) {
    if (document.images) {
        rslt = new Image();
        rslt.src = arg;
        return rslt;
    }
}

function imprime() {
    window.focus();
    setTimeout("window.print()", 500);
}

var ie5 = document.all && !window.opera
var lastHeight = 0;
var autoHeight = 1;
var autoHSet = 0;
function adjustIFrameSize() {
    if (!el('divSize'))
        return;
    iframeElement = getel(window.parent.document, 'ifcontent');
    iframeWindow = window.parent.frames[name];
    //if (nie)
    //    iframeElement.style.height = '';
    h = 0;
    hMin = 0;
    h = el('divSize').offsetHeight;
    hMin = 500;
    h = h > hMin ? h : hMin;

    lastHeight = h;

    iframeElement.style.height = (h) + 'px';

    if ((autoHeight) && (!autoHSet)) {
        autoHSet = 1;
        setTimeout('autoH()', 500);
    }
}

function autoH() {
    h = el('divSize').offsetHeight;
    hMin = 300;
    h = h > hMin ? h : hMin;
    if (h != lastHeight) {
        scrollPos = window.parent.document.documentElement.scrollTop;
        adjustIFrameSize();
        window.parent.document.documentElement.scrollTop = scrollPos;
    }
    setTimeout('autoH()', 500);
}

function indica() {
    ifc = window.parent.frames['ifcontent'];
    iurl = 'indique.aspx?1=1';
    if (ifc) {
        if (ifc.idcontent)
            iurl += '&idContent=' + (ifc.idcontent);
        if (ifc.idcontentsection)
            iurl += '&idContentSection=' + (ifc.idcontentsection);
        ifc.location = htmlbase + iurl;
    }
    else
        window.location = iurl;
}

function amplia2(id, pw, ph, text) {
    wp = window.parent;
    wpd = wp.document;
    ov = getel(wpd, 'overlay');
    amp = getel(wpd, 'ampliacao');
    ampi = getel(wpd, 'ampliInner');
    img = getel(wpd, 'imgAmpliar2');
    txt = getel(wpd, 'ampliText');

    ampi.style.width = (pw + 12) + 'px';
    ov.style.height = (wpd.documentElement.scrollHeight > wpd.body.scrollHeight ? wpd.documentElement.scrollHeight : wpd.body.scrollHeight) + 'px';
    img.src = wp.htmlbase + 'images/blank.gif';
    txt.style.display = (text != '' ? 'block' : 'none');
    txt.innerHTML = text;

    th = wpd.documentElement.clientHeight;
    th = ((th - ph - 12 - 18 - 3) / 2) - 20;
    if (th < 0)
        th = 0;
    th = th + (window.parent.document.body.scrollTop > 0 ? window.parent.document.body.scrollTop : window.parent.document.documentElement.scrollTop);
    ampi.style.marginTop = (th) + 'px';

    showHideFlashs(document, 0);

    ov.style.display = 'block';
    amp.style.display = 'block';

    img.src = wp.htmlbase + 'ModuleHandlers/Content/picture.aspx?idContentPicture=' +
        (id) + '&w=' + (pw) + '&h=' + (ph);
}

function showHideFlashs(doc, show) {
    objs = doc.getElementsByTagName('OBJECT');
    for (i = 0; i < objs.length; i++)
        objs[i].style.visibility = show ? 'visible' : 'hidden';
    objs = doc.getElementsByTagName('EMBED');
    for (i = 0; i < objs.length; i++)
        objs[i].style.visibility = show ? 'visible' : 'hidden';
}

function fechaAmpliar2() {
    wp = window.parent;
    wpd = wp.document;
    img = getel(wpd, 'imgAmpliar2');
    txt = getel(wpd, 'ampliText');
    ov = getel(wpd, 'overlay');
    amp = getel(wpd, 'ampliacao');

    showHideFlashs(window.top.frames['ifcontent'].document, 1);

    ov.style.display = 'none';
    amp.style.display = 'none';
    img.src = '';
    txt.innerHTML = '';
}



/* ----------------------------------------------- */

function amplia3(list, index) {

    atts = list[index];
    id = atts[0];
    pw = atts[1];
    ph = atts[2];
    text = atts[3];

    wp = window.parent;
    wpd = wp.document;

    wp.activeImgList = list;
    wp.activePicIndex = index;
    
    marginHeight = 60;
    marginWidth = 60;

    dh = wpd.documentElement.clientHeight - marginHeight;
    dw = wpd.documentElement.clientWidth - marginWidth;

    news = calculateNewSize(pw, ph, dw, dh);
    pw = news[0];
    ph = news[1];

    ov = getel(wpd, 'overlay');
    amp = getel(wpd, 'ampliacao');
    ampi = getel(wpd, 'ampliInner');
    img = getel(wpd, 'imgAmpliar2');
    txt = getel(wpd, 'ampliText');
    pl = getel(wpd, 'picleft');
    pr = getel(wpd, 'picright');

    ampi.style.width = (pw + 12) + 'px';
    ov.style.height = (wpd.documentElement.scrollHeight > wpd.body.scrollHeight ? wpd.documentElement.scrollHeight : wpd.body.scrollHeight) + 'px';
    img.style.width = (pw) + 'px';
    img.style.height = (ph) + 'px';
    img.style.visibility = 'hidden';
    txt.style.display = (text != '' ? 'block' : 'none');
    txt.innerHTML = text;

    th = wpd.documentElement.clientHeight;
    th = ((th - ph - 12 - 3) / 2) - 20;
    if (th < 0)
        th = 0;
    th = th + (window.parent.document.body.scrollTop > 0 ? window.parent.document.body.scrollTop : window.parent.document.documentElement.scrollTop);
    ampi.style.marginTop = (th) + 'px';

    showHideFlashs(document, 0);

    pl.style.display = index > 0 ? 'block' : 'none';
    pr.style.display = index < list.length - 1 ? 'block' : 'none';

    ov.style.display = 'block';
    amp.style.display = 'block';

    window.top.theImg = img;
    window.top.theImgLoading = null;
    window.top.theImgLoading = newImage(wp.htmlbase + 'ModuleHandlers/Content/picture.aspx?idContentPicture=' + (id) + '&w=' + (pw) + '&h=' + (ph));
    window.top.theLoading = getel(wpd, 'carregando');
    window.top.theLoading.style.display = 'block';
    setTimeout('showImgOnLoad()', 100);
}

function nextPicture(next) {
    wpd = window.parent.document;
    amp = getel(wpd, 'ampliacao');
    amp.style.display = 'none';
    if (next)
        window.top.activePicIndex++;
    else
        window.top.activePicIndex--;
    amplia3(window.top.activeImgList, window.top.activePicIndex);
    window.top.focus();
}

function showImgOnLoad() {
    img = window.top.theImg;
    imgLoading = window.top.theImgLoading;
    if (imgLoading.complete) {
        img.src = imgLoading.src;
        img.style.visibility = 'visible';
        window.top.theLoading.style.display = 'none';
    }
    else {
        setTimeout('showImgOnLoad()', 100);
    }
}

function calculateNewSize(currentWidth, currentHeight, maxWidth, maxHeight)
{
    newWidth = 0;
    newHeight = 0;
    
    hl = ((currentHeight - maxHeight) / currentHeight);
    wl = ((currentWidth - maxWidth) / currentWidth);

    if ((currentWidth >= maxWidth) || (currentHeight >= maxHeight))
    {
        if (hl >= wl)
        {
            newWidth = currentWidth - Math.round(currentWidth * hl);
            newHeight = maxHeight;
        }
        else
        {
            newWidth = maxWidth;
            newHeight = currentHeight - Math.round(currentHeight * wl);
        }
    }
    else
    {
        newWidth = currentWidth;
        newHeight = currentHeight;
    }
    
    return [newWidth, newHeight];
}

/* ----------------------------------------------- */

var cxAutoGoDelay = 0;

function CxCont(varId) {

    this.varid = varId;
    this.outid = varId + '_out';
    this.posid = varId + '_pos';
    this.cts = [];
    this.index = 0;

    this.add = function (id) {
        this.cts.length++;
        i = this.cts.length - 1;
        this.cts[i] = id;
    }

    this.autoGoInterval = 5000;
    this.autoGoTimeId = 0;

    this.go = function (next, fast) {

        if (this.autoGoTimeId)
            clearTimeout(this.autoGoTimeId);

        if (this.cts.length == 0)
            return;

        old = this.index;

        if (next)
            this.index++;
        else
            this.index--;

        if (this.index == -1)
            this.index = this.cts.length - 1;
        else if (this.index >= this.cts.length)
            this.index = 0;

        this.blend(old, this.index, fast);
        el(this.posid).innerHTML = this.index + 1;

        this.ajusta();

        this.autoGoTimeId = setTimeout(this.varid + '.go(1, 0)', this.autoGoInterval);
    }

    this.init = function () {

        if (this.cts.length == 0)
            return;

        el(this.cts[0]).style.visibility = 'visible';
        this.ajusta();

        setInterval(this.varid + '.ajusta()', 1000);

        this.autoGoTimeId = setTimeout(this.varid + '.go(1, 0)', cxAutoGoDelay + this.autoGoInterval);
        cxAutoGoDelay += 1000;
    }

    this.ajusta = function () {
        if (el(this.outid).offsetHeight < el(this.cts[this.index]).offsetHeight)
            el(this.outid).style.height = (el(this.cts[this.index]).offsetHeight) + 'px';
    }

    this.blendInterval = 100;
    this.blendSteps = 10;

    this.ctBlendTimeId = 0;

    this.blend = function (oldIndex, newIndex, fast) {

        if (this.ctBlendTimeId)
            clearTimeout(this.ctBlendTimeId);

        od = el(this.cts[oldIndex]);
        nw = el(this.cts[newIndex]);

        for (i = 0; i < this.cts.length; i++) {
            if ((i != oldIndex) && (i != newIndex)) {
                if (el(this.cts[i]))
                    el(this.cts[i]).style.visibility = 'hidden';
            }
        }

        nw.style.opacity = '0';
        nw.style.filter = 'filter: alpha(opacity=0)';
        nw.style.zIndex = '12';
        nw.style.visibility = 'visible';
        if (od) {
            od.style.zIndex = '11';
            od.style.opacity = '1';
            od.style.filter = 'filter: alpha(opacity=100)';
            od.style.visibility = 'visible';
        }

        if (!fast)
            this.ctBlendTimeId = setTimeout(this.varid + '.blend2(' + (oldIndex) + ',' + (newIndex) + ',1)', this.blendInterval);
        else
            this.blend2(oldIndex, newIndex, this.blendSteps);
    }

    this.blend2 = function (oldIndex, newIndex, step) {

        od = el(this.cts[oldIndex]);
        nw = el(this.cts[newIndex]);

        opn = (1 / this.blendSteps) * step;
        opo = 1 - opn;

        nw.style.opacity = (opn);
        nw.style.filter = 'filter: alpha(opacity=' + (opn * 100) + ')';
        od.style.opacity = (opo);
        od.style.filter = 'filter: alpha(opacity=' + (opo * 100) + ')';

        step++;
        if (step <= this.blendSteps)
            this.ctBlendTimeId = setTimeout(this.varid + '.blend2(' + (oldIndex) + ',' + (newIndex) + ',' + (step) + ')', this.blendInterval);
        else {
            od.style.visibility = 'hidden';
        }
    }
}

/* ----------------------------------------------- */

function Menu(varId) {

    this.varid = varId;

    this.activeMenu = 0;
    this.timeid = 0;
    this.isOverButton = 0;
    this.isOverMenu = 0;
    this.menuobj = 0;
    this.delayhide = 0;

    this.showmenu_src = 0;
    this.showmenu_id = 0;

    this.abreMenu = function (e, id) {

        if ((this.isOverButton == id) &&
            (this.menuobj))
            return;

        this.isOverButton = id;
        this.isOverMenu = 0;

        this.showmenu_src = el(this.varid + '_m' + id);
        this.showmenu_id = id;

        this.hidemenu();
        this.clearhidemenu()

        clearTimeout(this.timeid);
        this.timeid = setTimeout(this.varid + '.showmenu()', 200);
    }

    this.fechaMenu = function (id) {

        if (id == this.isOverButton) {
            clearTimeout(this.timeid);
            this.timeid = setTimeout(this.varid + '.fechaMenu2()', 200);
        }
    }

    this.fechaMenu2 = function () {
        this.isOverButton = 0;
        this.delayhidemenu();
    }

    this.showmenu = function () {

        src = this.showmenu_src;
        id = this.showmenu_id;

        this.mudaBotao(this.varid + '_m' + (id), 1);

        this.activeMenu = id;
        this.clearhidemenu()

        this.menuobj = el(this.varid + '_ms' + (id));

        lnks = getElementsById(this.varid + '_sub' + (id));
        for (i = 0; i < lnks.length; i++)
            lnks[i].style.width = '';

        if (this.varid == 'menu1') {

            this.menuobj.style.left = element_left(src) + 'px';

            this.menuobj.style.width = '';
            if (this.menuobj.offsetWidth < src.offsetWidth)
                this.menuobj.style.width = (src.offsetWidth) + 'px';

            w_item = (this.menuobj.offsetWidth - 20 - 2);

            this.menuobj.style.top = (element_top(src) + src.offsetHeight) + 'px';

        }
        else if (this.varid == 'menu2') {

            if (id != '0') {
                td1 = el('menu2_td1_' + (id));
                td2 = el('menu2_td2_' + (id));
                img = el('menu2_img_' + (id));
                bgext = el('menu2_bgext_' + (id));
                td1.style.width = ((img.offsetWidth > 120 ? 120 : (img.offsetWidth < 60 ? 60 : img.offsetWidth)) + 30) + 'px';
                this.menuobj.style.left = (element_left(src) - td1.offsetWidth - 6) + 'px';
                w_item = (td2.offsetWidth - 35);
                // bgext.style.left = (element_left(src) - 4) + 'px';
                // bgext.style.top = (element_top(src) + src.offsetHeight + 2) + 'px';
                bgext.style.height = (td1.offsetHeight) + 'px';
            }
            else {
                this.menuobj.style.left = element_left(src) + 'px';
                w_item = 10;
            }

            this.menuobj.style.top = (element_top(src) + src.offsetHeight) + 'px';
        }

        if (id != '0') {
            for (i = 0; i < lnks.length; i++) {
                lnks[i].style.width = (w_item) + 'px';
            }
        }
        else {
            for (i = 0; i < lnks.length; i++) {
                lnks[i].style.width = (el('menu2_tdAZ_' + (lnks[i].getAttribute('ids'))).offsetWidth - 20) + 'px';
            }
        }

        return false;
    }

    this.subover = function (event) {
        this.clearhidemenu();
        this.isOverMenu = 1;
    }

    this.subout = function (event) {
        this.isOverMenu = 0;
        this.dynamichide(event);
    }

    this.contains_ns6 = function (a, b) {
        while (b.parentNode)
            if ((b = b.parentNode) == a)
                return true;
        return false;
    }

    this.hidemenu = function () {
        if (this.menuobj) {
            this.mudaBotao(this.varid + '_m' + (this.activeMenu), 0);
            this.menuobj.style.top = '-5000px';
            this.activeMenu = 0;
            this.menuobj = 0;
        }
    }

    this.dynamichide = function (e) {
        if (!this.menuobj)
            return;
        if (!this.isOverButton) {
            if (ie5 && !this.menuobj.contains(e.toElement))
                this.hidemenu()
            else if (ns6 && e.currentTarget != e.relatedTarget && !this.contains_ns6(e.currentTarget, e.relatedTarget))
                this.hidemenu()
        }
    }

    this.delayhidemenu = function () {
        if (!this.isOverMenu)
            this.delayhide = setTimeout(this.varid + ".hidemenu()", 500)
    }

    this.clearhidemenu = function () {
        if (this.delayhide)
            clearTimeout(this.delayhide)
    }

    this.mudaBotao = function (id, ativo) {
        if (!el(id))
            return;

        if (this.varid == 'menu1')
            el(id).className = ativo ? 'but-menu-inst-active' : 'but-menu-inst';
        else if (this.varid == 'menu2')
            el(id).className = ativo ? 'but-menu left ativo' : 'but-menu left';
    }

    this.legenda = function (idmaster, mostrar, prod, texto) {
        pp = el('menu2_desc' + (idmaster));
        pp.style.width = '';
        td1 = el('menu2_td1_' + (idmaster));
        bgext = el('menu2_bgext_' + (id));
        w = td1.offsetWidth;
        if (mostrar) {
            if ((pp.getAttribute('bck_texto') == null) ||
                (pp.getAttribute('bck_texto') == '')) {
                pp.setAttribute('bck_texto', pp.innerHTML);
            }
            pp.innerHTML = '<B>' + prod + '</B><BR>' + texto;
            if (td1.offsetWidth > w) {
                pp.style.width = (w - 30) + 'px';
            }
        }
        else {
            pp.innerHTML = pp.getAttribute('bck_texto');
        }
        bgext.style.height = (td1.offsetHeight) + 'px';
    }
}

// *********************************************************************************************************************

/* ********** */
var bannerIndex = -1;
var allBannersCreated = 0;
var bannerAutoChangeDelay = 7000;
var loadAllBannersIndex = 1;
var loadBannersCalled = 0;
var blendInterval = 50;
var blendSteps = 20;

function iniciaOutdoor() {

    if (banners.length == 0)
        return;

    if (!loadBannersCalled) {
        loadBanners();
        loadBannersCalled = 1;
    }
    else {
        vaiParaBanner(0);
    }
}

function loadBanners() {

    if (banners.length == 0)
        return;

    criaBanner(banners[0], 'banner0');

    setTimeout('loadAllBanners()', 500);

    trocaBanner(1, 1, -1);
}

function criaBanner(html, id) {
    el('bannerBanner').innerHTML += html;
    el('div' + id).style.visibility = 'hidden';
    el('div' + id).style.position = 'absolute';
}

function loadAllBanners() {

    if (bannerIsLoaded('banner0')) {
        if (banners.length > 1) {
            criaBanner(banners[loadAllBannersIndex], 'banner' + (loadAllBannersIndex));
        }
        if (loadAllBannersIndex < banners.length - 1) {
            loadAllBannersIndex++;
            setTimeout('loadAllBanners()', 100);
        }
        else {
            el('bannerCarregando').style.display = 'none';
            allBannersCreated = 1;
        }
    }
    else
        setTimeout('loadAllBanners()', 500);
}


function bannerIsLoaded(id) {
    if ((mv(id).tagName == 'EMBED') || (mv(id).tagName == 'OBJECT'))
        return movieIsLoaded(mv(id));
    else if (mv(id).tagName == 'IMG')
        return el(id).complete;
}

var oldBannerIndex;
function trocaBanner(avanca, fast, novoIndice) {
    if ((!allBannersCreated) && (bannerIndex != -1))
        return;

    oldBannerIndex = bannerIndex;

    if (avanca > -1) {
        if (avanca)
            bannerIndex++;
        else
            bannerIndex--;

        if (bannerIndex == -1)
            bannerIndex = banners.length - 1;
        else if (bannerIndex >= banners.length)
            bannerIndex = 0;
    }
    else if (novoIndice > -1) {
        bannerIndex = novoIndice;
    }

    if (bannerIndex > -1) {
        if (!bannerIsLoaded('banner' + (bannerIndex)) && (oldBannerIndex > -1))
            el('divbanner' + (oldBannerIndex)).style.visibility = 'hidden';
    }

    mostraBanner(fast);
}

function avancaBanner(avanca) {
    trocaBanner(avanca, 0, -1);
}

function vaiParaBanner(indice) {
    trocaBanner(-1, 0, indice);
    window.focus();
}

var timeoutid;
var timeoutid2;
function mostraBanner(fast) {
    if (bannerIsLoaded('banner' + (bannerIndex))) {
        blend(oldBannerIndex, bannerIndex, fast);
        acertaBullets(oldBannerIndex, bannerIndex);
        if (timeoutid)
            clearTimeout(timeoutid);
        timeoutid = setTimeout('trocaBanner(1, 0, -1)', bannerAutoChangeDelay);
    }
    else {
        setTimeout('mostraBanner(' + (fast) + ')', 100);
    }
}

var blendTimeId = 0;

function blend(oldIndex, newIndex, fast) {

    if (blendTimeId)
        clearTimeout(blendTimeId);

    od = el('divbanner' + (oldIndex));
    nw = el('divbanner' + (newIndex));

    for (i=0; i<banners.length; i++) {
        if ((i != oldIndex) && (i != newIndex)) {
            if (el('divbanner' + (i)))
                el('divbanner' + (i)).style.visibility = 'hidden';
        }
    }

    nw.style.opacity = '0';
    nw.style.filter = 'filter: alpha(opacity=0)';
    nw.style.zIndex = '12';
    nw.style.visibility = 'visible';
    if (od) {
        od.style.zIndex = '11';
        od.style.opacity = '1';
        od.style.filter = 'filter: alpha(opacity=100)';
        od.style.visibility = 'visible';
    }

    if (!fast)
        blendTimeId = setTimeout('blend2(' + (oldIndex) + ',' + (newIndex) + ',1)', blendInterval);
    else
        blend2(oldIndex, newIndex, blendSteps);
}

function blend2(oldIndex, newIndex, step) {

    od = el('divbanner' + (oldIndex));
    nw = el('divbanner' + (newIndex));

    opn = (1 / blendSteps) * step;
    opo = 1 - opn;

    nw.style.opacity = (opn);
    nw.style.filter = 'filter: alpha(opacity=' + (opn * 100) + ')';
    if (od) {
        od.style.opacity = (opo);
        od.style.filter = 'filter: alpha(opacity=' + (opo * 100) + ')';
    }

    step++;
    if (step <= blendSteps)
        blendTimeId = setTimeout('blend2(' + (oldIndex) + ',' + (newIndex) + ',' + (step) + ')', blendInterval);
    else {
        if (od)
            od.style.visibility = 'hidden';
    }

}

function acertaBullets(oldindex, newindex) {
    if (el('bl' + (oldindex)))
        el('bl' + (oldindex)).className = 'hidden otb' + (oldindex);
    if (el('bl' + (newindex)))
        el('bl' + (newindex)).className = 'hidden otb' + (newindex) + 'sel';
}

/* ----------------------------------------------- */

var gTime = 0;
var gSpeed = 0;
var gPics = [];
var gPicWidth = 0;
var gPicHeight = 0;
var gTimeid = 0;

function iniciaGaleria(time, speed, picWidth, picHeight) {
    gTime = time;
    gSpeed = speed;
    gPicWidth = picWidth;
    gPicHeight = picHeight;
}

function iniciaGaleria2() {
    setTimeout('loadPictures()', 100);
    setTimeout('changePicture(1, false)', 100);
}

function addPic(idp) {
    gPics.length++;
    gPics[gPics.length - 1] = [];
    gPics[gPics.length - 1].idp = idp;
    gPics[gPics.length - 1].ok = 0;
    gPics[gPics.length - 1].img = 0;
}

function loadPictures() {
    for (i = 0; i < gPics.length; i++) {
        if (!(gPics[i].ok)) {
            // verifica se a imagem anterior já foi carregada
            if ((i > 0) && !(gPics[i - 1].img.complete)) {
                setTimeout('loadPictures()', 100);
                break;
            }
            else {
                gPics[i].img = newImage('ModuleHandlers/content/picture.aspx?idContentPicture=' + (gPics[i].idp) + '&w=' + (gPicWidth) + '&h=' + (gPicHeight));
                gPics[i].ok = 1;
            }
        }
    }
}

var automatic = 1;
var outItemIndex = -1;
var newIndex = -1;

function changePicture(forward, byUser, destindex) {

    if (gTimeid)
        clearTimeout(gTimeid);

    if (byUser) {
        automatic = 0;
    }

    img = el('outPicture');

    if (newIndex == outItemIndex) {
        newIndex = outItemIndex;
        if (forward) {
            newIndex++;
            if (newIndex >= gPics.length)
                newIndex = 0;
        }
        else if (typeof (destindex) != "undefined") {
            newIndex = destindex;
        }
        else {
            newIndex--;
            if (newIndex < 0)
                newIndex = gPics.length - 1;
        }
    }

    if ((gPics[newIndex].ok) && (gPics[newIndex].img.complete)) {

        if ((!byUser) && (outItemIndex > -1))
            slowChange(1);
        else
            show(newIndex);

        outItemIndex = newIndex;

        if (automatic)
            gTimeid = setTimeout('changeSlide()', gTime);
    }
    else {

        img.src = "images/blank.gif";
        s = 'changePicture(' + (forward) + ', ' + (byUser) + (typeof (destindex) != "undefined" ? ', ' + (destindex) : '') + ')';
        setTimeout(s, 100);
    }
}

function changeSlide() {
    if (automatic)
        changePicture(1, 0);
}

function slowChange(start) {
    try {
        oDiv = el('divSlide');
        oDiv.style.filter = "blendTrans(duration=0.5)";
        oDiv.filters.blendTrans.apply();
        oDiv.filters.blendTrans.play();
        show(newIndex);
    }
    catch (e) {
        show(newIndex);
    }
}

function changeSlide() {
    if (automatic)
        changePicture(1, 0);
}

var oldmini = 0;

function show(index) {
    if (oldmini != 0)
        oldmini.className = '';
    mini = el('mini' + (gPics[index].idp));
    if (mini) {
        mini.className = 'ativo';
        oldmini = mini;
    }

    el('divSlide').style.height = (gPics[index].img.height > el('divSlide').offsetHeight ? gPics[index].img.height : el('divSlide').offsetHeight) + 'px';
    el('outPicture').src = gPics[index].img.src;
    el('outPicture').style.display = 'block';
}

/* ----------------------------------------------- */

function getAjax() {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            // http_request.overrideMimeType("text/html; charset=windows-1252");
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!http_request) {
        alert('Desculpe, seu navegador é incompatível com este recurso.');
        return false;
    }
    return http_request;
}

var reqs = [];

function saveReqObjs(req, objs) {
    reqs.length++;
    i = reqs.length - 1;
    reqs[i] = [0, 0];
    reqs[i].req = req;
    reqs[i].objects = objs;
}

function loadReqObjs(req) {
    for (i = 0; i < reqs.length; i++)
        if (req == reqs[i].req)
            return reqs[i].objects;
}

var elementosFonte = '';
function fonte(aumenta) {
    // default
    dif = Number(readCookie('fonteSanavita'));

    els = elementosFonte.split(',');

    for (i = 0; i < els.length; i++) {

        if (els[i].substr(0, 1) == '_') {
            dfs = getElementsById(els[i].substr(1, els[i].length - 1));
        }
        else
            dfs = [el(els[i])];

        for (xx = 0; xx < dfs.length; xx++) {
            df = dfs[xx];
            if (!df)
                continue;
            def = Number(df.getAttribute('default-font', 0));
            if (aumenta > -1) {
                size = Number(df.style.fontSize.substr(0, df.style.fontSize.length - 2));
                dif = size - def;
            }
            else {
                dif = Number(readCookie('fonteSanavita'));
                size = def + dif;
            }
            //alert(els[i] + ' default: ' + (def) + ' atual: ' + (size));

            if (aumenta > -1) {
                if ((dif <= 0) && !aumenta) {
                    alert(fonteMinTxt);
                    return;
                }
                if ((dif >= 4) && aumenta) {
                    alert(fonteMaxTxt);
                    return;
                }
                if (aumenta)
                    size++;
                else
                    size--;
            }

            dif = size - def;

            df.style.fontSize = (size) + "px";
        }
    }

    var expire = new Date();
    expire.setTime(new Date().getTime() + 3600000 * 24 * 5000);
    document.cookie = 'fonteSanavita' + "=" + escape((dif) + '') + ";expires=" + expire.toGMTString() + ";path=/";

    adjustIFrameSize();
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

isHome = 1;

function busca(ifc) {
    s = htmlbase + 'busca.aspx?p=' + document.forms['fbusca'].p.value;
    abre(s, ifc);
    setTimeout('el(\'input-busca\').value = \'\'', 100);
}

function abre(url, ifc) {
    if (ifc)
        window.parent.frames['ifcontent'].location = url;
    else
        window.location = 'padrao.aspx?' + url;
}

function pHash() {
    if ((!window.parent) || (!window.parent.location.hash))
        return "";
    h = window.parent.location.hash;
    if (h.substr(0, 1) == '#')
        h = h.substr(1);
    return h;
}

function iframeLoading(loc) {

    if ((loc == null) || (!loc.length)) {
        alert(loc);
        loc = '';
    }
    if ((!window.parent.imain) && (window.parent.location == window.location)) {
        window.top.location.replace(htmlbase + '#' + loc);
    }
    else if (window.parent.imain) {
        ph = pHash();
        bs = (window.parent.location.href.substr(0, window.parent.location.href.length - ph.length));
        bs = bs.substr(bs.length - 1) == '#' ? bs.substr(0, bs.length - 1) : bs;

        if (loc.toLowerCase() == 'home.aspx') {
            if (ph.length > 0) {
                window.parent.location.replace(bs + '#');
            }
        } else {
            window.parent.location.replace(bs + '#' + loc);
        }
        window.parent.activeHash = window.parent.location.hash;

        if (window.parent.menu1)
            window.parent.menu1.hidemenu();
        if (window.parent.menu2)
            window.parent.menu2.hidemenu();
        window.parent.document.documentElement.scrollTop = 0;
        window.parent.document.body.scrollTop = 0;
        window.top.document.title = window.document.title;
    }

}

function adjust1(ishome, itens, logado, texto, email, temPedidos, ar) {
    if (!document.body)
        return;
    
    document.body.className = ishome && (itens == 0) && (!temPedidos) ? 'bodyIsHome' : 'bodyIsInterna';
    el('but-cart').innerHTML = itens > 0 ? '<u>(' + (itens) + ' ite' + (itens != 1 ? 'ns' : 'm') + ')</u>' : '(vazio)';
    sec = window.location.href.substr(0, 8) == 'https://';
    el('but-cart').href = itens > 0 ? (sec ? 'loja/cesta.aspx' : 'https://' + htmlbase.substr(7) + '#loja/cesta.aspx') : 'loja/';
    el('but-cart').target = ((itens > 0) && sec) ? 'ifcontent' : '_self';
    el('box-sair').style.display = logado ? 'block' : 'none';
    el('pLogin').innerHTML = !logado ?
        texto.replace('#linkcad#', '<a href="cadastro.aspx" target="ifcontent">').replace('#linklogin#', '<a href="#" onclick="mostraLogin(1); return false">') :
        '<a href="restrita.aspx" target="ifcontent">' + texto + "</a>";
    el('txtEmail').value = email;
    el('txtSenha').value = '';
    el('box-pedidos').style.display = (!ar && temPedidos) ? 'block' : 'none';
    el('box-ar').style.display = ar ? 'block' : 'none';
    
    window.top.AR = ar;
}

var activeHash = '';

function writeIframe(ishome, wnd) {

    s = '<iframe src="' + getIframeUrl() + '" name="ifcontent" id="ifcontent" class="ifcontent" width="100%" height="100%" scrolling="no" frameborder="0"  marginheight="0" marginwidth="0" allowtransparency="true"></iframe>';
    escreve(s);

    activeHash = window.location.hash;
    checkHash();

}

function checkHash() {
    if ((activeHash != window.location.hash) && (window.frames['ifcontent'])) {
        activeHash = window.location.hash;
        window.frames['ifcontent'].window.location = getIframeUrl();
    }
    setTimeout('checkHash()', 500);
}

function getIframeUrl() {

    loc = 'home.aspx';
    h = window.location.hash;
    if ((h != null) && (h.length > 1))
        loc = h.substr(1);
    return loc;

}

function showTwitters() {
    loadjscssfile("http://platform.twitter.com/widgets.js", "js");
}

function showXIframes() {
    ifrs = document.getElementsByTagName('IFRAME');
    for (i = 0; i < ifrs.length; i++) {
        ifr = ifrs[i];
        xsrc = ifr.getAttribute('xsrc', 0);
        if (ifr.getAttribute('src', 0) == 'about:blank')
            ifr.src = xsrc;
    }
}

function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

pLoginHTML = '';
function mostraLogin(mostrar) {
    if (mostrar) {
        el('txtSenha').value = '';
        pLoginHTML = el('pLogin').innerHTML;
        el('pLogin').innerHTML = '';
        setTimeout('el(\'txtEmail\').focus(); el(\'txtEmail\').select();', 100);
    }
    else {
        el('pLogin').innerHTML = pLoginHTML;
    }
    el('form-login').style.display = mostrar ? 'block' : 'none';
}

function showProgressImage(id) {
    pimg = el(id);
    pimg.style.display = 'block';
    pimg.src = pimg.src;
}

function loga() {

    eml = el('txtEmail').value;
    pss = el('txtSenha').value;

    tid = setTimeout('showProgressImage(\'imgLogando\')', 100);

    url = htmlbase + 'controles/loginAjax.aspx';
    poststr = "acao=login&eml=" + encodeURIComponent(eml) + "&pss=" + encodeURIComponent(pss);

    req = getAjax();
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            clearTimeout(tid);
            el('imgLogando').style.display = 'none';
            if (req.status == 200) {
                if (req.responseText.substr(0, 2) != "ok")
                    alert(req.responseText)
                else {
                    mostraLogin(0);
                    eval(req.responseText.substr(3));
                    if (window.top.AR) {
                        ifc = window.top.frames['ifcontent'];
                        if (ifc)
                            ifc.location = htmlbase + 'restrita.aspx';
                    }
                }
            }
            else {
                alert(msgrepetir);
            }
        }
    }

    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    http_request.setRequestHeader("Connection", "close");
    http_request.send(poststr);
}

function desloga() {

    url = htmlbase + 'controles/loginAjax.aspx?acao=encerrar';

    req = getAjax();
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                if (req.responseText.substr(0, 2) != "ok")
                    alert(req.responseText)
                else {
                    mostraLogin(0);
                    eval(req.responseText.substr(3));
                }
            }
            else {
                alert(msgrepetir);
            }
        }
    }

    req.open('GET', url, true);
    req.send(null);

}

var preBuscaTid = 0;
var ultimaBusca = '';

function preBusca(p) {
    window.clearTimeout(preBuscaTid);
    preBusca2(p.toLowerCase());
}

function preBusca2(p) {
    url = htmlbase + 'controles/buscaAjax.aspx?p=' + encodeURIComponent(p);

    req = getAjax();
    saveReqObjs(req, [p]);

    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                if (req.responseText.substr(0, 2) == "ok") {
                    objs = loadReqObjs(req);
                    p = objs[0];
                    preBusca3(req.responseText.substr(3));
                }
                else
                    el('buscaResult').style.display = 'none';
            }
        }
    }

    req.open('GET', url, true);
    req.send(null);
}

function preBusca3(r) {

    // paramsStr = paramsStr.replace(/\'/g, '\\\'');

    r = r.replace(/#head#/g, '<table id="sub-busca" cellpadding="0" cellspacing="0" border="0"">');
    r = r.replace(/#p1#/g, '<td class="border" width="50" height="50" align="center" valign="middle">');
    r = r.replace(/#img1#/g, '<img src="ModuleHandlers/Content/picture.aspx?idContentPicture=');
    r = r.replace(/#p2#/g, '<td align="left" valign="top" class="txt">');
    r = r.replace(/#txt1#/g, '<tr><td align="left" valign="top" colspan="2" class="txt">');
    r = r.replace(/#clear#/g, '<div class="clear2"></div>');
    r = r.replace(/#f1#/g, '<tr><td class="txt cinza" align="right" valign="top"colspan="2">');

    el('buscaResult').innerHTML = r;
    el('buscaResult').style.display = 'block';
    document.onclick = fechaBusca;
    if ((window.frames['ifcontent']) && (window.frames['ifcontent'].document))
        window.frames['ifcontent'].document.onclick = fechaBusca;
}

function fechaBusca() {
    if (window.top.el('buscaResult')) {
        window.top.el('buscaResult').style.display = 'none';
        window.top.ultimaBusca = '';
        window.top.el('input-busca').value = '';
    }
}
