﻿
var hosturl = "https://aguaoptima.com/";
var urlparametros = "";
var registrocompleto = true;
var checkout_invitado = false;
function dpUsuario() {
    $("#dp-usuario").dropdown("toggle");
}
var main_uid = "";
$(document).on("click", "#rentabtn", function (event) {
    event.preventDefault();
    var ct = $("#renta02 option:selected").val();
    var cp = $("#renta01").val();
    var errores = 0;
    $("#renta01c .form-error").remove();
    if (cp.length < 3) {
        $("#renta01c").append("<p class='form-error'>Ingresa un código postal válido</p>");
        errores += 1;
    }

    if (errores == 0) {
        location.href = "/ProductoIdeal?cp=" + cp + "&ct=" + ct;
    }
});

$(document).on("keydown", "#renta01", function (event) {
    if (event.keyCode == 13) {
        var ct = $("#renta02 option:selected").val();
        var cp = $("#renta01").val();
        var errores = 0;
        $("#renta01c .form-error").remove();
        if (cp.length < 3) {
            $("#renta01c").append("<p class='form-error'>Ingresa un código postal válido</p>");
            errores += 1;
        }

        if (errores == 0) {
            location.href = "/ProductoIdeal?cp=" + cp + "&ct=" + ct;
        }
    }
});

$(document).ready(function (event) {
	
	$(".politicaslink").each(function(index) {
		var href = $(this).attr("href");
		href = href.replace("docx","pdf");
		$(this).attr("href",href);
	});
	
	$("a.ctm-btn-wa").attr("href","https://api.whatsapp.com/send?phone=5218115852222&text=Hola,%20me%20comunico%20desde%20el%20portal%20de%20Pure%20Water")
	
	$("#ctm-header-actions .dropdown-item[seccion='Descargables']").attr("href", "/MaterialesDescargables");
	
	$("#myBtn").html("<i class='fa fa-arrow-up'></i>");
    //document.cookie = "carrito="
    var main_cookie = new Array();
    var cookie_str = document.cookie;
    if (cookie_str != "") {
        var cookie_arr = cookie_str.split(" ");
        if (cookie_arr.length > 0) {
            for (var i = 0; i < cookie_arr.length; i++) {
                var attrs = cookie_arr[i].split("=");
                if (attrs.length > 1) {
                    main_cookie.push({ attr: attrs[0], value: attrs[1].replace(";","") });
                } else {
                    main_cookie.push({ attr: attrs[0], value: 1 });
                }
                if (attrs[0] == "uid") {
                    main_uid = attrs[1].replace(";", "");
                }
            }
        }
    }
    if (main_uid == "") {
        main_uid = generateUID();
    }
    document.cookie = "uid=" + main_uid;

    if (isLogged != true) {
        var sended_url = services_url + "GetCarritoUnLogged";
        $.ajax({
            type: "POST",
            url: sended_url,
            data: JSON.stringify({ id: main_uid }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var jsonResponse = response;
                if (jsonResponse.flag != false) {
                    $("#carrito").text(jsonResponse.data_int);
                } else {
                    $("#carrito").text(0);
                }
            },
            failure: function (response) {
                //console.log("failure");
                //console.log(response);
            },
            error: function (response) {
                //console.log("error");
                //console.log(response);
            }
        });
    }
});
function generateUID() {
    var length = 16,
        charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    retVal += ".";
    return retVal;

}
$(document).on("keypress", 'input[type="number"]', function (event) {
    //console.log("event.keyCode: ", event.keyCode);
    if (event.keyCode == 69 || event.keyCode == 101) {
        event.preventDefault();
    }
});

function getFromArrayByValue(value, nameKey, myArray) {
    var arr = new Array();
    for (var i = 0; i < myArray.length; i++) {
        if (myArray[i][nameKey] === value) {
            var tmpobj = myArray[i];
            tmpobj.idx = i;
            arr.push(tmpobj);
        }
    }
    return arr;
}

function searchArrayByKeyProp(value, nameKey, myArray) {
    var tmp = new Array();
    for (var i = 0; i < myArray.length; i++) {
        if (myArray[i][nameKey] === value) {
            tmp = myArray[i];
            tmp.idx = i;
            return tmp;
        }
    }
}

function isInArray(value, array) {
    return array.indexOf(value) > -1;
}

function removeFromArray(index, arr) {
    arr.splice(index, 1);
}



function openNav() {
    document.getElementById("mobileNav").style.display = "block";
    $("#burgerFlop").attr("onclick", "closeNav()");
}

function closeNav() {
    document.getElementById("mobileNav").style.display = "none";
    $("#burgerFlop").attr("onclick", "openNav()");
}

function openNav2() {
    $("#respmenu").modal("show");
}

function buscar2() {
    $("#buscmenu").modal("show");
}

$(document).on("keypress", "#main01", function (event) {
    var value = $(this).val();
    if (event.keyCode == 13 && value.length > 0) {
        location.href = "/Productos?search=" + value;
    }
});

function busquedaPrincipal() {
    var value = $("#main01").val();

    if (value.length > 0) {
        location.href = "/Productos?search=" + value;
    }
}

function ModalLogin(params) {
    urlparametros = params;
    if (registrocompleto != true) {
        $("#lg15c").hide();
        $("#lg11c").hide();
        $("#lg12c").hide();
        //$("#lg16c").hide();
        //$("#lg17c").hide();
    } else {
        $("#lg15c").show();
        $("#lg11c").show();
        $("#lg12c").show();
        //$("#lg16c").show();
        //$("#lg17c").show();
    }
    if (urlparametros == '?step=address') {
        $("#title-registrate").text("Continuar como invitado");
        $("#lg15c").hide();
        $("#lg11c").hide();
        $("#lg12c").hide();
        //$("#lg16c").hide();
        //$("#lg17c").hide();
    } else {
        $("#title-registrate").text("Registrate");
        $("#lg15c").show();
        $("#lg11c").show();
        $("#lg12c").show();
        //$("#lg16c").show();
        //$("#lg17c").show();
    }
    $("#respmenu").modal("hide");
    setTimeout(function () {
        $("#login input").val("");
        $("#login .form-error").remove();
        $("#login").modal("show");
    }, 500);
}

function ModalRP() {
    $("#login").modal("hide");
    setTimeout(function () {
        $("#resetPassword input").val("");
        $("#resetPassword .form-error").remove();
        $("#rpConfirmar").show();
        $("#rpCerrar").hide();
        $("#resetPassword").modal("show");
    }, 500);
}

function ModalRegistro() {
    $("#respmenu").modal("hide");
    setTimeout(function () {
        $("#registro input").val("");
        $("#registro .form-error").remove();
        $("#registro").modal("show");
    }, 500);
}

$(document).on("keypress", "#lg01", function (event) {
    if (event.keyCode == 13) {
        ConfirmaLogin();
    }
});

function ConfirmaLogin() {
    $("#login .form-error").remove();
    var u = $("#lg00").val();
    var p = $("#lg01").val();
    var sended_url = services_url + "Login";
    if (u.length > 1 && p.length > 1) {
        $("#login .form-control").attr("disabled", "disabled");
        $.ajax({
            type: "POST",
            url: sended_url,
            data: JSON.stringify({ username: u, password: p, notas: main_uid }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                $("#login .form-control").removeAttr("disabled");
                var jsonResponse = response;
                if (jsonResponse.flag != false) {
                    $("#login .form-control").val("");
                    setTimeout(function () {
                        location.href = location.href + urlparametros;
                    }, 1000);
                } else {
                    for (var i = 0; i < jsonResponse.errors.length; i++) {
                        $("#login .uu_errores").append("<p class='form-error'>" + jsonResponse.errors[i] + "</p>");
                    }
                    if (jsonResponse.description == "Usuario inactivado") {
                        $("#login .uu_errores").append("<p class='form-error'>Tu cuenta no esta activa, favor de activarla dando click al enlace que te enviamos a tu correo electrónico al momento de registrarte.</p>");
                        $("#login .uu_errores").append("<a href='javascript:void(0);' onclick='enlaceActivacion()'>Solicitar enlace de activación</a>");
                    }
                    //console.log("success");
                    //console.log(jsonResponse.description);
                }
            },
            failure: function (response) {
                $("#login .form-control").removeAttr("disabled");
                //console.log("failure");
                //console.log(response);
            },
            error: function (response) {
                $("#login .form-control").removeAttr("disabled");
                //console.log("error");
                //console.log(response);
            }
        });
    } else {
        $("#login .uu_errores").append("<p class='form-error'>Hay campos incompletos</p>");
    }
}

function ValidateEmail(mail) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) {
        return (true)
    }
    //alert("You have entered an invalid email address!")
    return (false)
}

function ConfirmaRegistro() {
    $("#login .form-error").remove();
    var nom = $("#lg14").val();
    var ape = $("#lg15").val();
    var u = $("#lg10").val();
    var p = $("#lg11").val();
    var p2 = $("#lg12").val();
    var t = $("#lg13").val();
    var pedidos = $("#lg16").val();
    var giro = $("#lg17").val();
    var errores = 0;
    if (nom.length <= 0) {
        $("#login .uu_errores2").append("<p class='form-error'>El nombre esta vacío</p>");
        errores += 1;
    }
    if (u.length <= 0) {
        $("#login .uu_errores2").append("<p class='form-error'>El correo electrónico esta vacío</p>");
        errores += 1;
    }

    if (ValidateEmail(u) != true) {
        $("#login .uu_errores2").append("<p class='form-error'>El correo electrónico no tiene el formato correcto</p>");
        errores += 1;
    }
	
    if (t.length != 10) {
        $("#login .uu_errores2").append("<p class='form-error'>El télefono debe tener 10 caracteres</p>");
        errores += 1;
    }
	
    if (registrocompleto != false) {
        if (ape.length <= 0) {
            $("#login .uu_errores2").append("<p class='form-error'>Los apellidos estan vacíos</p>");
            errores += 1;
        }
        if (p != p2) {
            $("#login .uu_errores2").append("<p class='form-error'>Las contraseñas no coinciden</p>");
            errores += 1;
        }
    }
    if (errores == 0) {
        var sended_url = services_url + "AddUsuario";
        if (urlparametros == '?step=address') {
            sended_url = services_url + "VerificaUsuario";
            $("#login .form-control").attr("disabled", "disabled");
            $.ajax({
                type: "POST",
                url: sended_url,
                data: JSON.stringify({ username: u, password: p, phone: t, email: u, name: (nom + "|" + ape), pedidos: pedidos, formatomail: giro, puesto: "Retail" }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $("#login .form-control").removeAttr("disabled");
                    var jsonResponse = response;
                    if (jsonResponse.flag != false) {
                        $("#login .form-control").val("");
                        $("#login #lg16").val(0);
                        try {
                            eu_lu.name = (nom + "|" + ape);
                            eu_lu.email = u;
                            eu_lu.phone = t;
                            eu_lu.username = u;
                            eu_lu.puesto = "Retail";
                            eu_lu.activo = false;
                            //console.log(eu_lu);
                            $("#login").modal("hide");
                            checkout_invitado = true;
                            Siguiente();
                        } catch (exception) {
                            //console.log(exception);
                        }
                    } else {
                        for (var i = 0; i < jsonResponse.errors.length; i++) {
                            $("#login .uu_errores2").append("<p class='form-error'>" + jsonResponse.errors[i] + "</p>");
                        }
                        //console.log("success");
                        //console.log(jsonResponse.description);
                    }
                },
                failure: function (response) {
                    $("#login .form-control").removeAttr("disabled");
                    //console.log("failure");
                    //console.log(response);
                },
                error: function (response) {
                    $("#login .form-control").removeAttr("disabled");
                    //console.log("error");
                    //console.log(response);
                }
            });
        } else {
            $("#login .form-control").attr("disabled", "disabled");
            $.ajax({
                type: "POST",
                url: sended_url,
                data: JSON.stringify({ username: u, password: p, phone: t, email: u, name: (nom + "|" + ape), pedidos: pedidos, formatomail: giro, puesto: "Retail" }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $("#login .form-control").removeAttr("disabled");
                    var jsonResponse = response;
                    if (jsonResponse.flag != false) {
                        $("#login .form-control").val("");
                        $("#login #lg16").val(0);
                        if (urlparametros == '?step=address') {
                            setTimeout(function () {
                                location.href = location.href + urlparametros;
                            }, 1000);
                        } else {
                            setTimeout(function () {
                                $("#login .form-control").val("");
                                $("#login #lg16").val(0);
                                $("#login .form-error").remove();
                                $("#login .uu_errores2").append("<p class='text-success'>Revisa la bandeja de entrada de tu correo electrónico y sigue las instrucciones</p>");
                            }, 500);
                        }
                    } else {
                        for (var i = 0; i < jsonResponse.errors.length; i++) {
                            $("#login .uu_errores2").append("<p class='form-error'>" + jsonResponse.errors[i] + "</p>");
                        }
                        //console.log("success");
                        //console.log(jsonResponse.description);
                    }
                },
                failure: function (response) {
                    $("#login .form-control").removeAttr("disabled");
                    //console.log("failure");
                    //console.log(response);
                },
                error: function (response) {
                    $("#login .form-control").removeAttr("disabled");
                    //console.log("error");
                    //console.log(response);
                }
            });
        }
    } else {
        $("#login .uu_errores2").append("<p class='form-error'>Hay campos incompletos</p>");
    }
}

function ConfirmaRP() {
    var usuario = {
        email: ""
    };
    $("#rp00").text("");
    $("#resetPassword .uu-errores").empty();
    var p1 = $("#rp00").val();
    var errors = 0;
    if (p1.length < 1) {
        $("#resetPassword .uu-errores").append("<p class='text-danger'>Datos inválidos</p>");
        errors += 1;
    }

    if (ValidateEmail(p1) != true) {
        $("#resetPassword .uu-errores").append("<p class='text-danger'>No se ingresó un correo electrónico válido</p>");
        errors += 1;
    }

    if (errors == 0) {
        usuario.email = p1;
        var sended_url = services_url + "ResetPassword";
        $.ajax({
            type: "POST",
            url: sended_url,
            data: JSON.stringify(usuario),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var jsonResponse = response;
                if (jsonResponse.flag != false) {
                    //console.log(jsonResponse);
                    $("#rp00").val("");
                    $("#resetPassword .uu-errores").append("<p class='text-success'>Se ha enviado un correo con el enlace para restaurar la contraseña</p>");

                    $("#rpConfirmar").hide();
                    $("#rpCerrar").show();
                } else {
                    //
                    $("#resetPassword .uu-errores").append("<p class='text-success'>" + jsonResponse.description + "</p>");
                    //console.log("success");
                    //console.log(jsonResponse.description);
                }
            },
            failure: function (response) {
                //console.log("failure");
                //console.log(response);
            },
            error: function (response) {
                //console.log("error");
                //console.log(response);
            }
        });
    }
}
//
jQuery.ui.autocomplete.prototype._resizeMenu = function () {
    var ul = this.menu.element;
    ul.outerWidth(this.element.outerWidth());
}

function menuModal() {
    $("#respmenu").modal("show");
}

function topFunction(){	
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
