function MySwapImgRestore()
{
    var i, x, a;

    a = document.MM_sr;
    for (i=0; a && i<a.length && (x=a[i]) && x.oSrc; i++)
        x.src = x.oSrc;
    return;
}

function MyPreloadImages()
{
    var i, j, a, d;

    d = document;
    if (d.images) {
        if (!d.MM_p)
            d.MM_p = new Array();
        j = d.MM_p.length;
        a = MyPreloadImages.arguments;
        for (i=0; i<a.length; i++) {
            //if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            //}
        }
    }
    return;
}

function MySwapImage()
{
    var i, j, x, a;

    j = 0;
    a = MySwapImage.arguments;
    document.MM_sr = new Array;
    for (i=0; i<(a.length-2); i+=3) {
        if ((x=MyFindObj(a[i])) != null) {
            document.MM_sr[j++] = x;
            if (!x.oSrc)
                x.oSrc = x.src;
            x.src = a[i+2];
        }
    }
    return;
}

function MyFindObj(n, d)
{
    var p, i, x;

    if (!d)
        d = document;
    if ((p=n.indexOf("?"))>0 && parent.frames.length) {
        d = parent.frames[n.substring(p+1)].document;
        n = n.substring(0,p);
    }
    if (!(x=d[n]) && d.all)
        x = d.all[n];
    for (i=0; !x && i<d.forms.length; i++)
        x = d.forms[i][n];
    for (i=0; !x && d.layers && i<d.layers.length; i++)
        x = MyFindObj(n,d.layers[i].document);
    if (!x && document.getElementById)
        x = document.getElementById(n);
    return x;
}

function MyReloadPage(init)
{ //reloads the window if Nav4 resized
    if (init != false) { 
        with (navigator) {
            if ((appName=="Netscape") && (parseInt(appVersion)==4)) {
                document.MM_pgW = innerWidth;
                document.MM_pgH = innerHeight;
                onresize = MyReloadPage;
            }
        }
    }
    else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH)
        location.reload();
    return;
}

//Functiones extra
function IsValidEMail(s)
{
    var i, l, lastwasdot, atfound, atpos;
    
    l = s.length;
    if (l < 1)
        return false;
    lastwasdot = true;
    atfound = false;
    atpos = -1;
    for (i=0; i<l; i++) {
        if (s.charCodeAt(i) < 33)
            return false;
        if (s.charAt(i) == '.') {
            if (lastwasdot != false)
                return false;
            if (atfound!=false && atpos==i-1)
                return false;
            lastwasdot = true;
        }
        else if (s.charAt(i) == '@') {
            if (i==0 || lastwasdot!=false || atfound!=false)
                return false;
            atfound = true;
            atpos = i;
        }
        else
            lastwasdot = false;
    }
    if (lastwasdot!=false || atfound==false || atpos==l-1)
        return false;
    return true;
}

function IsJavaAvailable()
{
    if (navigator.appName=='Microsoft Internet Explorer' && navigator.appVersionindexOf('MSIE 3'))
        return false;
    return (navigator.javaEnabled && navigator.javaEnabled());
}

function MyGetElementPosition(elem, relativeWindow)
{
    var pos = {x:0, y:0};
    var oWindow = relativeWindow || window;

    while (elem) {
        pos.x += elem.offsetLeft;
        pos.y += elem.offsetTop;
        if (elem.offsetParent == null) {
            var oDocument = elem.ownerDocument || elem.document;
            var oOwnerWindow = oDocument.parentWindow || oDocument.defaultView;
            if (oOwnerWindow != oWindow)
                elem = oOwnerWindow.frameElement;
            else
                break;
        }
        else
            elem = elem.offsetParent;
    }
    return pos;
}

function MyScrollToElement(n)
{
    var pos;

    if ((elem=MyFindObj(n)) == null)
        return;
    pos = MyGetElementPosition(elem);
    if (pos.y > 200)
        pos.y -= 20;
    window.scrollTo(pos.x, pos.y);
    return;
}

function MyResizeToObject(s)
{
    var x, w, h, w2, h2, pw, ph, d, b;

    if ((x=MyFindObj(s)) == null)
        return;
    window.resizeTo(screen.availWidth, screen.availHeight);
    w = x.clip ? x.clip.width : x.offsetWidth;
    h = x.clip ? x.clip.height : x.offsetHeight;
    if (!h)
        return;
    window.resizeTo(w+200, h+200);
    pw = 0; ph = 0;
    d = window.document.documentElement;
    b = window.document.body;
    if (window.innerWidth) {
        pw = window.innerWidth;
        ph = window.innerHeight;
    }
    else if (d && d.clientWidth) {
        pw = d.clientWidth;
        ph = d.clientHeight;
    }
    else if (b && b.clientWidth) {
        pw = b.clientWidth;
        ph = b.clientHeight;
    }
    if (window.opera && !document.childNodes)
        pw += 16;
    x = MyFindObj(s);
    w2 = x.clip ? x.clip.width : x.offsetWidth;
    h2 = x.clip ? x.clip.height : x.offsetHeight;
    w2 = w2+((w+200)-pw);
    h2 = h2+((h+200)-ph);
    if (w2 > screen.availWidth)
        w2 = screen.availWidth;
    if (h2 > screen.availHeight)
        h2 = screen.availHeight;
    window.resizeTo(w2, h2);
    w2 = (screen.width-w2) / 2;
    h2 = (screen.height-h2) / 2;
    window.moveTo(w2, h2);
    return;
}

function MyFetchOffset(obj)
{
    var l, t, C;

    if (obj.getBoundingClientRect) {
      C = obj.getBoundingClientRect();
      t = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
      l = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
      if (document.documentElement.dir == "rtl") {
        l = l+document.documentElement.clientWidth - document.documentElement.scrollWidth;
      }
      return {left:C.left+l, top:C.top+t};
    }
    l = obj.offsetLeft;
    t = obj.offsetTop;
    while ((obj=obj.offsetParent)!=null) {
      l += obj.offsetLeft;
      t += obj.offsetTop
    }
    return {left:l, top:t};
}

function MyRepositionMenu(obj, menu_obj)
{
    var p;

    p = MyFetchOffset(obj);
    p.top = p.top + obj.offsetHeight;
    if (p.left+menu_obj.offsetWidth >= document.body.clientWidth &&
        p.left+obj.offsetWidth-menu_obj.offsetWidth > 0)
      p.left = p.left + obj.offsetWidth - menu_obj.offsetWidth;
    menu_obj.style.left = p.left.toString() + "px";
    menu_obj.style.top = p.top.toString() + "px";
    return;
}

function MyCreateElement(tag_type, attributes)
{
    var bIsIE, elem, s;

    bIsIE = (typeof(window.opera) == 'undefined' &&
             navigator.userAgent.indexOf('MSIE') >= 0) ? true : false;
    if (bIsIE != false) {
        s = '<' + tag_type;
        for (var _key in attributes) {
            if (_key == 'name') {
                s = s + ' name="' + attributes[_key] + '"';
            }
        }
        s = s + ' />';
    }
    else {
        s = tag_type;
    }
    elem = document.createElement(s);
    if (elem == null)
        return null;
    for (var _key in attributes) {
        if (bIsIE != false && _key == 'name')
            continue;
        elem.setAttribute(_key, attributes[_key]);
    }
    return elem;
}

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

var UserHashFormElem = null;
function UserHashInitialize(form_obj)
{
    var elem, sub_elem, subsub_elem;

    UserHashFormElem = MyCreateElement('input', {
                            'id' : "user_hashcode",
                            'name' : "user_hashcode",
                            'type' : "hidden",
                            'value' : ""
                          } );
    form_obj.appendChild(UserHashFormElem);

    document.writeln('<div id="div_mx_DuplUserCookie" style="display:block;">');
    document.writeln('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="mx_UserHash_" name="mx_UserHash_" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="1" height="1" id="mx_UserHash_" align="middle">');
    document.writeln('<param name="allowScriptAccess" value="sameDomain" />');
    document.writeln('<param name="movie" value="' + BASE_URL + 'js/mxCookieMovie.swf" />');
    document.writeln('<param name="quality" value="high" />');
    document.writeln('<param name="bgcolor" value="#0000ff" />');
    document.writeln('<embed src="' + BASE_URL + 'js/mxCookieMovie.swf" id="mx_UserHash_" name="mx_UserHash_" quality="high" bgcolor="#0000ff" width="1" height="1" id="mx_UserHash_" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.writeln('</object></div>');
    return;
}

function myCookieCallback(args)
{
    if (UserHashFormElem != null)
        UserHashFormElem.setAttribute("value", args);
    return;
}

function MyCreateCookie(name, value, days, hours, minutes)
{
    var expires, date, k;

    if (days>0 || hours>0 || minutes>0) {
        date = new Date();
        k = days * 86400 + hours * 3600 + minutes*60;
        date.setTime(date.getTime() + (k*1000));
        expires = "; expires=" + date.toGMTString();
    }
    else
        expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
    return;
}

function MyReadCookie(name)
{
    var i, c, ca, nameEQ;

    nameEQ = name + "=";
    ca = document.cookie.split(';');
    for(i=0; i<ca.length; i++) {
        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;
}

function MyEraseCookie(name)
{
    MyCreateCookie(name, "", -1, 0, 0);
    return;
}

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

function DoLimitText()
{
    var l, x;

    x = MyFindObj('scr_texto');
    l = x.value.length;
    if (l > 420) {
        x.value = x.value.substring(0, 420);
        l = 420;
    }
    x = MyFindObj('scr_contador');
    x.value = (420 - l).toString();
    return;
}

function DoAddSecret()
{
    var _texto, _edad, _sexo, _hash;

    $("#form_error").hide();
    $("#form_ok").hide();
    $("#scr_sexo_txt").removeClass('error');
    $("#scr_edad_txt").removeClass('error');

    _texto = $("#scr_texto").val();
    if (_texto == '') {
        $("#form_error").html('Ingres&aacute; el secreto que deseas compartir');
        $("#form_error").show();
        $("#scr_texto").focus();
        return false;
    }

    if ($("#scr_sexo1").attr("checked") != 0)
        _sexo = 1;
    else if ($("#scr_sexo2").attr("checked") != 0)
        _sexo = 2;
    else {
        $("#scr_sexo_txt").addClass('error');
        $("#form_error").html('Por favor ingresa tu sexo');
        $("#form_error").show();
        $("#scr_sexo1").focus();
        return false;
    }
    _edad = $("#scr_edad").val();
    if (_edad == '') {
        $("#scr_edad_txt").addClass('error');
        $("#form_error").html('Por favor ingresa tu edad');
        $("#form_error").show();
        $("#scr_edad").focus();
        return false;
    }
    _edad = parseInt(_edad);
    if (isNaN(_edad )!=false || _edad<1 || _edad>199) {
        $("#scr_edad_txt").addClass('error');
        $("#form_error").html('La edad ingresada es incorrecta');
        $("#form_error").show();
        $("#scr_edad").focus();
        return false;
    }

    _hash = $("#user_hashcode");
    if (_hash.length > 0)
        _hash = _hash.val();
    else
        _hash = '';

    $("#scr_submit_btn").hide();
    $('#scr_submit_btn').attr('disabled', true);
    $("#scr_submit_ajax").show();

    $.ajax({
        url: BASE_URL + 'action.php',
        cache: false,
        data: {
            'do': 'add_secret',
            'texto': _texto,
            'sexo': _sexo,
            'edad': _edad,
            'hash': _hash,
            'key' : SS_KEY
        },
        dataType: 'xml',
        type: 'post',
        error: function (xhr, ajaxOptions, thrownError) {
            $('#scr_submit_btn').removeAttr('disabled');
            $("#scr_submit_btn").show();
            $("#scr_submit_ajax").hide();
            $("#form_error").html('Hubo un problema al querer enviar tu secreto. Reintenta en 5 minutos.');
            $("#form_error").show();
            $("#scr_text").focus();
        },
        success: function (xml_resp) {
            var code, elem;

            code = 0;
            elem = $(xml_resp).find('code:first');
            if (elem.length > 0)
                code = parseInt(elem.text());

            $('#scr_submit_btn').removeAttr('disabled');
            $("#scr_submit_btn").show();
            $("#scr_submit_ajax").hide();
            if (code <= 0) {
                if (code == -1)
                    $("#form_error").html('No puedes enviar muchos secretos en tan poco tiempo.');
                else
                    $("#form_error").html('Hubo un problema al querer registrar tu secreto. Reintenta en 5 minutos.');
                $("#form_error").show();
            }
            else {
                $("#form_ok").show();
                $("#scr_texto").val('');
                DoLimitText();
            }
            $("#scr_text").focus();
        }
    });
    return false;
}

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

var bMainSendingRating = false;
function DoRatingExec(_obj, _id, _voteVal)
{
    var div_obj, _hash;

    if (_voteVal<1 || _voteVal>5)
        return;
    if (bMainSendingRating != false)
        return;
    bMainSendingRating = true;

    _hash = $("#user_hashcode");
    if (_hash.length > 0)
        _hash = _hash.val();
    else
        _hash = '';

    div_obj = $('#rating_submit_ajax_' + _id.toString());

    div_obj.show();
    $.ajax({
        url: BASE_URL + 'action.php',
        cache: false,
        data: {
            'do': 'add_vote',
            'id': _id,
            'vote': _voteVal,
            'hash': _hash,
            'key' : SS_KEY
        },
        dataType: 'xml',
        type: 'post',
        error: function (xhr, ajaxOptions, thrownError) {
            bMainSendingRating = false;
            div_obj.hide();
        },
        success: function (xml_resp) {
            var s, code, xvotos, xtotalvotos, elem;

            bMainSendingRating = false;
            div_obj.hide();

            code = 0;
            elem = $(xml_resp).find('code:first');
            if (elem.length > 0)
                code = parseInt(elem.text());

            xvotos = -1;
            xtotalvotos = -1;
            if (code > 0) {
                elem = $(xml_resp).find('votos:first');
                if (elem.length > 0)
                    xvotos = parseInt(elem.text());
                elem = $(xml_resp).find('total_votos:first');
                if (elem.length > 0)
                    xtotalvotos = parseInt(elem.text());
            }
            if (xvotos>=0 && xtotalvotos>=0) {
                xvotos = (xtotalvotos > 0) ? ((1.0 * xvotos) / xtotalvotos) : 0.0;
                xvotos = Math.round(xvotos * 10) / 10.0;
                s = "<strong>" + xvotos.toFixed(1) + "</strong> [" +
                    xtotalvotos.toString() + " voto";
                if (xtotalvotos != 1)
                    s = s + "s";
                s = s + "]";
                $('#votados_' + _id.toString()).html(s);
                _obj.setVal(xvotos);
            }
        }
    });
    return;
}

function DoIrA()
{
    $("#filtrar").hide();
    MyRepositionMenu($('#menu_ir_a')[0], $('#ir_a')[0]);
    $('#ir_a').show();
    $("#id").focus();
    return false;
}

function DoIrAExec()
{
    var s = $("#id").val();
    if (s!=null && s!='')
        $("#ir_a_form").trigger('submit');
    return false;
}

function DoFiltrar()
{
    $("#ir_a").hide();
    MyRepositionMenu($('#menu_filtrar')[0], $('#filtrar')[0]);
    $('#filtrar').show();
    $("#filtrar_sexo0").focus();
    return false;
}

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

var bModSendingVote = false;
var nModCurrentSecretId = -1;
function DoGetNewSecretImgShow()
{    $(".secret_loader").css("display", "block");
    return;
}

function DoGetNewSecret()
{
    var s, _hash;

    $("#secreto_div").fadeOut(400);
    DoGetNewSecretImgShow();

    _hash = $("#user_hashcode");
    if (_hash.length > 0)
        _hash = _hash.val();
    else
        _hash = '';
    nModCurrentSecretId = -1;

    $.ajax({
        url: BASE_URL + 'action.php',
        cache: false,
        data: {
            'do': 'mod_getsecret',
            'hash': _hash,
            'key' : SS_KEY
        },
        dataType: 'xml',
        type: 'post',
        error: function (xhr, ajaxOptions, thrownError) {
            $(".secret_loader").css("display", "none");
            $("#secreto_div").html('<p>Hubo un problema al querer buscar un secreto para moderar. Reintenta en 5 minutos.</p>');
            $("#secreto_div").fadeIn(400);
        },
        success: function (xml_resp) {
            DoVotationProcessResponse(xml_resp, 1);
        }
    });
    return;
}

function DoModeraSecretoExec(_voteVal)
{
    var _hash;

    if (nModCurrentSecretId<0 || _voteVal<1 || _voteVal>2)
        return false;
    if (bModSendingVote != false)
        return false;
    bModSendingVote = true;

    _hash = $("#user_hashcode");
    if (_hash.length > 0)
        _hash = _hash.val();
    else
        _hash = '';

    div_obj = $('#vote_submit_ajax_mod');

    div_obj.show();
    $.ajax({
        url: BASE_URL + 'action.php',
        cache: false,
        data: {
            'do': 'mod_addvote',
            'id': nModCurrentSecretId,
            'vote': _voteVal,
            'hash': _hash,
            'key' : SS_KEY
        },
        dataType: 'xml',
        type: 'post',
        error: function (xhr, ajaxOptions, thrownError) {
            bModSendingVote = false;
            div_obj.hide();
        },
        success: function (xml_resp) {
            bModSendingVote = false;
            div_obj.hide();
            $("#secreto_div").fadeOut(400, function() {
                DoVotationProcessResponse(xml_resp, 2);
            });
        }
    });
    return false;
}

function DoVotationProcessResponse(xml_resp, _type)
{
    var code, _id, _html, elem;

    code = 0;
    elem = $(xml_resp).find('code:first');
    if (elem.length > 0)
        code = parseInt(elem.text());

    _id = -1;
    _html = '';
    if (code > 0) {
        elem = $(xml_resp).find('secreto_id:first');
        if (elem.length > 0)
            _id = parseInt(elem.text());
        elem = $(xml_resp).find('secreto_html:first');
        if (elem.length > 0)
            _html = elem.text();
    }

    if (code==1 && _id>0 && _html!='') {
        nModCurrentSecretId = _id;
        $("#secreto_div").html(_html);
    }
    else if (_type==2 && code==-2) {
        $("#secreto_div").html('<p>Hubo un problema procesar su voto. Por favor reintenta en 5 minutos.</p>');
    }
    else {
        $("#secreto_div").html('<p>¡Pucha! No hay m&aacute;s secretos para moderar.</p>');
    }

    $(".secret_loader").css("display", "none");
    $("#secreto_div").fadeIn(400);
    return;
}

