﻿// LOAD PAGE
$(document).ready(function() {
    //window.onbeforeunload = blockui;

    $("#lnk_crearTuReceta").click(function() {
        Ajax_popup("Home", "PopUP_Crea");
    });

    $("#lnk_ComparteTuReceta").click(function() {
        Ajax_popup("Home", "PopUP_Comparte");
    });

    $("#lnk_GanaConTuReceta").click(function() {
        Ajax_popup("Home", "PopUP_Gana");
    });

    $("#lnk_verVideo").click(function() {
        Ajax_popup("Home", "PopUP_VerVideo");
    });

    $("#dropBusquedaRecetas").change(function() {
        if (this.selectedIndex > 0) {
            document.location = ServidorURl + "recetas/Busqueda/" + this.options[this.selectedIndex].value;
        }
    });


    $("[RequireAuthentication=true]").click(function() {
        RequireAuthentication(this);
    });

});

function RequireAuthentication(element) {
    blockui();
    if (UserName != "") {
        unblockui();
        return true;
    }
    else {
        var href = element.href;
        if (!href)
            href = ServidorURl;
        Ajax_popup("Account", "userLoginRegistro", "?returnurl=" + href);
        return false;
    }
}

function showhide(e) {
    var els = document.getElementById(e).style;
    if (els.display == 'none') {
        els.display = 'block';
    } else {
        els.display = 'none';
    }
}

function validarCamposOblig(formId) {
    var ret = true;
    $("#" + formId + " [obligatorio=true]").each(function() {        
        if (this.value == "") {
            $("[rel=" + this.name + "]").addClass("txtError");
            ret = false;
        } else
            $("[rel=" + this.name + "]").removeClass("txtError");
    });

    $("#" + formId + " [igualCon]").each(function() {
        var valor = document.getElementsByName($(this).attr("igualCon"))[0].value;        
        if (this.value != valor) {
            $("[relIgual=" + this.name + "]").addClass("txtError");
            ret = false;
        } else
            $("[rel=" + this.name + "]").removeClass("txtError");
    });

    $("#" + formId + " [expresion]").each(function() {        
        var re = new RegExp($(this).attr("expresion"));                
        if (this.value.match(re)) {
            $("[rel=" + this.name + "]").removeClass("txtError");
        } else {
            $("[rel=" + this.name + "]").addClass("txtError");
            ret = false;
        }
    });
    
    if (!ret)
        $("[class^=txtOblig]").addClass("txtError");
        
    return ret;
}

function blockui() {
    $.blockUI({ message: $('#divLoader'), overlayCSS: { backgroundColor: '#fff'} });
}
function unblockui() {
    $.unblockUI();    
    $(".blockUI").hide();
}

//LISTADO DE RECETAS
function initListadoOrdenes()
{
    $("#btnOrderRecetas_nuevas").css("visibility", "visible");
    $("#btnOrderRecetas_votadas").css("visibility", "visible");

    $("#btnOrderRecetas_nuevas").click(function() {
        blockui();
        $.ajax({
            type: "POST",
            url: ServidorURl + "recetas/RecetasHome",
            data: "orderBy=nuevas",
            success: function(msg) {
                $("#ContenedorRecetas").html(msg);
                $("#btnOrderRecetas_nuevas").removeClass("receipt-link-off");
                $("#btnOrderRecetas_nuevas").addClass("receipt-link-on");
                $("#btnOrderRecetas_votadas").removeClass("receipt-link-on");                
                $("#btnOrderRecetas_votadas").addClass("receipt-link-off");
                unblockui();
            }
        });
    });

    $("#btnOrderRecetas_votadas").click(function() {
        blockui();
        $.ajax({
            type: "POST",
            url: ServidorURl + "recetas/RecetasHome",
            data: "orderBy=votadas",
            success: function(msg) {
                $("#ContenedorRecetas").html(msg);
                $("#btnOrderRecetas_votadas").removeClass("receipt-link-off");
                $("#btnOrderRecetas_votadas").addClass("receipt-link-on");
                $("#btnOrderRecetas_nuevas").removeClass("receipt-link-on");
                $("#btnOrderRecetas_nuevas").addClass("receipt-link-off");
                unblockui();
            }
        });
    });

}


function Ajax_popup(controller, action, query, Metodo) {
    //blockui();
    if (!query)
        query = "";
    $.ajax({
        type: (Metodo) ? Metodo : "POST",
        data:{},
        url: ServidorURl + controller + "/" + action + query,
        success: function(msg) {
            $.blockUI({
                message: $(msg),
                css: { top: '10%', left: '0%', cursor: 'default', textAlign: 'left' },
                overlayCSS: { backgroundColor: '#fff' }
            });            
        }
    });
    return false;
}

function votarReceta(id) {
    blockui();
    $.ajax({
        type: "POST",
        data: {},
        url: ServidorURl + "Recetas/ajaxVotar/" + id + "?returnUrl=" + document.location,
        success: function(msg) {
            unblockui();
            if (msg == "LOGIN") {
                var href = ServidorURl + "Recetas/Votar/" + id;
                Ajax_popup("Account", "userLoginRegistro", "?returnurl=" + href);
            } else if (msg == "VOTO_REPETIDO") {
                $(".votar").css("display", "none");
                $(".votado").css("display", "");                                
            }
            else {
                $("[element_votos=" + id + "]").html("(" + msg + ")");
                $(".votar").css("display", "none");
                $(".votado").css("display", "");                
                unblockui();
            }
        }
    });
}
function cerrarLogin() {
    var loc= document.location + "";
    if (loc.toLowerCase().indexOf("account/logon") < 0)
        unblockui();
    else
        document.location = ServidorURl;
        
}

function printReceta() {
    var html = $(".receipt-content-left-receta").html();
    
    docPrint = window.open("", "Print");
    docPrint.document.open();
    docPrint.document.write('<html><head>');
    docPrint.document.write('<link rel="stylesheet" type="text/css" href="'+ServidorURl+'Content/css/Site.css" />');
    docPrint.document.write('<link href="' + ServidorURl + 'Content/css/SiteExtended.css" rel="stylesheet" type="text/css" />');

    docPrint.document.write('</head><body><left>');

    docPrint.document.write('<div class="receipt-content-receta print">');
    
    docPrint.document.write(html);    
    docPrint.document.write($(".receta-autor-center").html());
    
    docPrint.document.write('</div>');
    docPrint.document.write('</body></html>');
    docPrint.document.close();
    docPrint.print();
    docPrint.close();
}

function showhideMenu(e) {
    var item =document.getElementById(e);
    if (item) {
        var els = item.style;
        if (els.display == 'none') {
            els.display = 'block';
        } else {
            els.display = 'none';
        }
    }
}

function changeBullet(e) {
    var item =document.getElementById(e);
    if (item) {
        var els = item.style;
        if (els.backgroundImage == 'url(' + ServidorURl + 'Content/images/bullet.gif)') {
            els.backgroundImage = 'url(' + ServidorURl + 'Content/images/bullet-active.gif)';
        } else {
            els.backgroundImage = 'url(' + ServidorURl + 'Content/images/bullet.gif)';
        }
    }
}

function openFileUpload() {
    $.blockUI({
        message: $("#controlImageUpload").html(),
        css: { top: '10%', left: '0%', cursor: 'default', textAlign: 'left' },
        overlayCSS: { backgroundColor: '#fff' }
    });

}

function updateImagen() {
    var img = document.getElementById("imgFoto");
    var file = document.getElementById("fileImagen");
    img.src = file.value;
}

function changeInputType(
  oldElm, // a reference to the input element
  iType, // value of the type property: 'text' or 'password'
  iValue, // the default value, set to 'password' in the demo
  blankValue, // true if the value should be empty, false otherwise
  noFocus) {  // set to true if the element should not be given focus
    if (!oldElm || !oldElm.parentNode || (iType.length < 4) ||
    !document.getElementById || !document.createElement) return;
    var isMSIE = /*@cc_on!@*/false; //http://dean.edwards.name/weblog/2007/03/sniff/
    if (!isMSIE) {
        var newElm = document.createElement('input');
        newElm.type = iType;
    } else {
        var newElm = document.createElement('span');
        newElm.innerHTML = '<input type="' + iType + '" name="' + oldElm.name + '">';
        newElm = newElm.firstChild;
    }
    var props = ['name', 'id', 'className', 'size', 'tabIndex', 'accessKey'];
    for (var i = 0, l = props.length; i < l; i++) {
        if (oldElm[props[i]]) newElm[props[i]] = oldElm[props[i]];
    }
    newElm.onfocus = function() {
        return function() {
            if (this.hasFocus) return;
            var newElm = changeInputType(this, 'password', iValue,
      (this.value.toLowerCase() == iValue.toLowerCase()) ? true : false);
            if (newElm) newElm.hasFocus = true;
        }
    } ();
    newElm.onblur = function() {
        return function() {
            if (this.hasFocus)
                if (this.value == '' || (this.value.toLowerCase() == iValue.toLowerCase())) {
                changeInputType(this, 'text', iValue, false, true);
            }
        }
    } ();
    // hasFocus is to prevent a loop where onfocus is triggered over and over again
    newElm.hasFocus = false;
    // some browsers need the value set before the element is added to the page
    // while others need it set after
    if (!blankValue) newElm.value = iValue;
    oldElm.parentNode.replaceChild(newElm, oldElm);
    if (!isMSIE && !blankValue) newElm.value = iValue;
    if (!noFocus || typeof (noFocus) == 'undefined') {
        window.tempElm = newElm;
        setTimeout("tempElm.hasFocus=true;tempElm.focus();", 1);
    }
    return newElm;
}
