/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------- MODALS INIT --------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$(document).ready(function () {
    insertLoginModals();
    initGraphEffects();
});

function initModals() {
    //select all the a tag with name equal to modal
    $('a[name=modal]').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        ShowModal(this);
    });

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });
}
function ShowModal(ctrl) {    
    //Get the A tag
    var id = $(ctrl).attr('href');

    //Fix para IE7
    if (id.indexOf("#") > 0) //si no arranca con #
    {
        id = id.substring(id.indexOf("#"));
    }

    //si hay otro modal abierto lo cierro
    $('.window').hide();

    //Get the screen height and width
//    var maskHeight = $(document).height();
//    var maskWidth = $(window).width();

    //Set heigth and width to mask to fill up the whole screen
//    $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

    //transition effect		
    $('#mask').fadeIn(500);
    $('#mask').fadeTo("fast", 0.6);

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    //Set the popup window to center
    $(id).hide(); //cust 
    $(id).css('top', winH / 2 - $(id).height() / 2);
    $(id).css('left', winW / 2 - $(id).width() / 2);
    //Custom MD.com - lo mantengo siempre en el mismo lugar
    $(id).css('position', 'fixed');

    //transition effect
    $(id).fadeIn(500);

    //if close button is clicked
    $(id +' .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        $('#mask').hide();
        $('.window').hide();
    });
}
//--------------------------------------------------- ALERT MODAL --------------------------------------------------
var errContent = 'No es posible realizar esta acción ahora.<br/>Por favor intenten más tarde.';
var errTit = 'Error';
function InitAlert() {
    $('#btnAlert').click(function () {
        $('#mask').hide();
        $('.window').hide();
    });
}
function launchAlert(title, content, useMask) {
    var id = '#alert';
    if (useMask) {
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({ 'width': maskWidth, 'height': maskHeight });
        //transition effect		
        $('#mask').fadeIn(500);
        $('#mask').fadeTo("slow", 0.5);
    }
    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    //Inicializo el contenido
    $('#alert .tit_boxes').empty();
    $('#alert .tit_boxes').append(title);
    $('#alert .modal_content').empty();
    $('#alert .modal_content').append(content);

    //Set the popup window to center
    $(id).hide(); //cust 
    $(id).css('top', winH / 2 - $(id).height() / 2);
    $(id).css('left', winW / 2 - $(id).width() / 2);
    //Custom MD.com - lo mantengo siempre en el mismo lugar
    $(id).css('position', 'fixed');                     
    //transition effect
    $(id).fadeIn(500);
}
//------------------------------------------------ LOGIN - SIGNIN --------------------------------------------------
function insertLoginModals() {
    var wslink;
    if (window.location.hostname == "localhost") {
        wslink = "/web/services.aspx/getLoginModals";
    } else {
        wslink = "/services.aspx/getLoginModals";
    }
    $.ajax({
        type: "POST",
        url: wslink,
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('#boxes').append(msg.d);
            initLogin();
            launchForcedSignIn();
            initModals();
        },
        error: function (result) {
            initModals();
            //TODO: poner en onclick los links directos a las paginas de login y registración
        }
    });
}
function btnLogInClick(user) {
    //Track Event 10710
    _gaq.push(['_trackEvent', 'User', 'Log In Attempt', user]);
}
function btnLogOutClick(user) {
    //Track Event 10800
    _gaq.push(['_trackEvent', 'User', 'Log Off', user]);
}
function initLogin() {
    $('#btnLogin').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        var user = $('#txtUser').attr('value');
        var pass = $('#txtPass').attr('value');
        var remember = $('input[name=nocerrar]').attr('checked');
        e.preventDefault();

        var pdata = "{'user':'" + user + "'," + "'pass':'" + pass + "'," + "'remember':'" + remember + "'" + "}";
        var wslink;
        if (window.location.hostname == "localhost") {
            wslink = "/web/services.aspx/login";
        } else {
            wslink = "/services.aspx/login";
        }
        //Track Event 10710
        _gaq.push(['_trackEvent', 'User', 'Log In Attempt', user]);
        //
        $.ajax({
            type: "POST",
            url: wslink,
            data: pdata,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.d === 0) {
                    if (window.location.hostname == "localhost") {
                        window.location.href = "/web/members/search.aspx";
                    }
                    else {
                        window.location.href = "/members/search.aspx";
                    }
                    $('#loginMsg').hide();
                    //Track Event 10700
                    _gaq.push(['_trackEvent', 'User', 'Log In', user]);
                    //
                } else {
                    //Track Event 20200
                    _gaq.push(['_trackEvent', 'Error', 'Log In', user]);
                    //
                    if (window.location.hostname == "localhost") {
                        window.location.href = "/web/public/login.aspx?err=" + msg.d;
                    }
                    else {
                        window.location.href = "/public/login.aspx?err=" + msg.d;
                    }
                }
            },
            error: function (result) {
                $('#loginMsg').html("Error de login. Intente más tarde.");
                $('#loginMsg').show();
                //Track Event 20200
                _gaq.push(['_trackEvent', 'Error', 'Log In', user]);
                //
            }
        });
    });

    $("#txtUser").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#btnLogin").click();
        }
    });

    $("#txtPass").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#btnLogin").click();
        }
    });
    $('#btnSignIn').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        var mail = $('#txtSigninMail').val();
        mail = mail.replace(/^\s+|\s+$/g, '');
        var pdata = "{'mail':'" + mail + "'" + "}";
        var aux = "";
        var wslink;
        if (window.location.hostname == "localhost") {
            wslink = "/web/services.aspx/signin";
            aux = "/web";
        } else {
            wslink = "/services.aspx/signin";
        }
        $.ajax({
            type: "POST",
            url: wslink,
            data: pdata,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                            
                if (msg.d === true) {
                    $('#regmsg').hide();
                    $('#regform').hide();
                    $('#regtit').html("Bienvenido!");
                    $('#regend').html("Bienvenido a MisDescuentos.com!!! Desde ahora tendrás tu propio perfil para almacenar tus búsquedas, favoritos, alertas y mucho más. Miles de descuentos esperan por vos! <br/>" +
                    "<img src='" + aux + "/App_Web/img/es-AR/howitworks1.png'></img><br/>" +
                    "<span>IMPORTANTE: Para conservar tu cuenta recordá <strong>activar tu usuario</strong> desde el mail que te hemos enviado.</span>");
                    $('#regend').show();
                    //Track Event 11100
                    _gaq.push(['_trackEvent', 'User', 'Sing In', mail]);

                } else {
                    $('#regmsg').html("Usuario ya existe o mail incorrecto");
                    $('#regmsg').show();
                    //Track Event 20100
                    _gaq.push(['_trackEvent', 'Error', 'Sing In', mail]);
                }
            },
            error: function (result) {
                $('#regmsg').html("Error de login. Intente más tarde.");
                $('#regmsg').show();
                //Track Event 20100
                _gaq.push(['_trackEvent', 'Error', 'Sing In', mail]);
            }
        });
    });

    $("#txtSigninMail").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#btnSignIn").click();
        }
    });

    $('#txtUser').focus(function () {
        if ($('#txtUser').val() == "Ingresá tu usuario...") {
            $('#txtUser').attr("value", "");
        }
    });
    $('#txtUser').focusout(function () {
        if ($('#txtUser').val().replace(/^\s+|\s+$/g, '').length === 0) {
            $('#txtUser').attr("value", "Ingresá tu usuario...");
        }
    });
    $('#txtPass').focus(function () {
        if ($('#txtPass').val() == "Ingresá tu clave...") {
            $('#txtPass').attr("value", "");
        }
    });
    $('#txtPass').focusout(function () {
        if ($('#txtPass').val().replace(/^\s+|\s+$/g, '').length === 0) {
            $('#txtPass').attr("value", "Ingresá tu clave...");
        }
    });
    $('#txtSigninMail').focus(function () {
        if ($('#txtSigninMail').val() == "Ingresá tu email...") {
            $('#txtSigninMail').attr("value", "");
        }
    });
    $('#txtSigninMail').focusout(function () {
        var mail = $('#txtSigninMail').val();
        mail = mail.replace(/^\s+|\s+$/g, ''); 
        if (mail.length === 0) {
            $('#txtSigninMail').attr("value", "Ingresá tu email...");
        }
    });
}
//Valido si vino flagueado mostrar o no el modal de registración
var signInTmr;
function launchForcedSignIn() {
    if ($('#signInFlag').length > 0) {
        if (signInTmr) {                                                           //si ya existe un timer activo
            window.clearTimeout(signInTmr);                                      //lo reseteo
        }
        signInTmr = window.setTimeout(function () { ShowModal('#signInFlag'); }, 1000); //lo activo con 1 seg de delay
    }       
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------- GRAPHIC EFFECTS --------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$(function () {
    $('.defaultP input').ezMark();
});
function showSlidingDiv() {
    $("#slidingDiv").animate({ "height": "toggle" }, { duration: 300 });
}
function initGraphEffects() {
    //dropdown del menu de usuario
    $("#user_logbot").click(function () {
        $('#user_logmenu').slideToggle();
    });
    //freetext internal
    if ($('#search').length > 0 && $('#search').attr("value").length === 0) {
        $('#search').attr("value", "Buscar...");
    }
    fixInternalFooter();
    initSocial();
}
function fixInternalFooter() {
    //valido si es una página interna
    if ($('#headint').length > 0) {
        var hhead = $('#headint').height();
        var hcont = $('.frameint').height();
        var hfoot = $('#footer').height();
        var hwin = $(window).height();
        //si la pantalle es mayor que la altura de todo lo que hay para dibujar
        if (hwin > hhead + hcont + hfoot) {
            //estiro el content para que al menos lo llene todo
            $('#contentint').css({ 'min-height': hwin - hhead - hfoot - 36 }); //-30 es un ajuste empirico
            $('.frameint').css({ 'min-height': hwin - hhead - hfoot - 30 }); //-30 es un ajuste empirico
        } 
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------- COUNT DOWN --------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function () {
    initCountDown();
});
function initCountDown() {
    $('input[class^="hdExp"]').each(function () {
        var val = $(this).val().split('|');
        var cd = new cdtime('grExp' + val[0], val[1]);
        cd.displaycountdown("days", formatsearch);
    });
}
function cdtime(container, targetdate) {
    if (!document.getElementById || !document.getElementById(container)) { return; }
    this.container = document.getElementById(container);
    this.currentTime = new Date();
    this.targetdate = new Date(targetdate);
    this.timesup = false;
    this.updateTime();
}
cdtime.prototype.updateTime = function () {
    var thisobj = this;
    this.currentTime.setSeconds(this.currentTime.getSeconds() + 1);
    setTimeout(function () { thisobj.updateTime(); }, 1000); //update time every second
};

cdtime.prototype.displaycountdown = function (baseunit, functionref) {
    this.baseunit = baseunit;
    this.formatresults = functionref;
    this.showresults();
};


cdtime.prototype.showresults = function () {
    var thisobj = this;
    var timediff = (this.targetdate - this.currentTime) / 1000; //difference btw target date and current date, in seconds
    if (timediff < 0) { //if time is up
        this.timesup = true;
        this.container.innerHTML = this.formatresults();
        return;
    }
    var oneMinute = 60; //minute unit in seconds
    var oneHour = 60 * 60;  //hour unit in seconds
    var oneDay = 60 * 60 * 24;  //day unit in seconds
    var dayfield = Math.floor(timediff / oneDay);
    var hourfield = Math.floor((timediff - dayfield * oneDay) / oneHour);
    var minutefield = Math.floor((timediff - dayfield * oneDay - hourfield * oneHour) / oneMinute);
    var secondfield = Math.floor((timediff - dayfield * oneDay - hourfield * oneHour - minutefield * oneMinute));
    if (this.baseunit == "hours") { //if base unit is hours, set "hourfield" to be topmost level
        hourfield = dayfield * 24 + hourfield;
        dayfield = "n/a";
    }
    else if (this.baseunit == "minutes") { //if base unit is minutes, set "minutefield" to be topmost level
        minutefield = dayfield * 24 * 60 + hourfield * 60 + minutefield;
        dayfield = hourfield = "n/a";
    }
    else if (this.baseunit == "seconds") { //if base unit is seconds, set "secondfield" to be topmost level
        secondfield = timediff;
        dayfield = hourfield = minutefield = "n/a";
    }
    this.container.innerHTML = this.formatresults(dayfield, hourfield, minutefield, secondfield);
    setTimeout(function () { thisobj.showresults(); }, 1000);  //update results every second
};

function formatsearch() {
    if (this.timesup === false) { //if target date/time not yet met
        var displaystring = arguments[0] + "d " + arguments[1] + "h " + arguments[2] + "m " + arguments[3] + "s"; 
        return displaystring;
    }
    else {
        return "0d 0h 0m 0s"; 
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------- SOCIAL   ------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//----------------------------------------- FACEBOOK/TWITTER LIKEBUTTON -----------------------------------------------

function fbs_click(link) {
    var url = $(link).attr('href');
    window.open(url, 'sharer', 'toolbar=0,status=0,width=626,height=436');
    //Track Event 14600
    _gaq.push(['_trackEvent', 'Social', 'Facebook Share Button Pressed', url]);
    //
    return false;
}
function tws_click(link) {
    var url = $(link).attr('href');
    window.open(url, 'sharer', 'toolbar=0,status=0,width=626,height=436');
    //Track Event 14601
    _gaq.push(['_trackEvent', 'Social', 'Twitter Share Button Pressed', url]);
    //
    return false;
}
function InitShareButtons() {
    //facebook like button
    $('a[class="fb"]').click(function (e) {
        e.preventDefault();
        return fbs_click(this);
    });
    //twitter like button
    $('a[class="tw"]').click(function (e) {
        e.preventDefault();
        return tws_click(this);
    });
}
function initSocial() {

    if (screen.width <= 1024) {
        $('#likebarbtns').hide();
        $('#likeToggle').hide();
        $('#likeToggle2').show();
    } else {
        $('#likebarbtns').show();
        $('#likeToggle').show();
        $('#likeToggle2').hide();
    }
    $('.likebar').show();

    //validar resolución del monitor y ocultar
    $('#likeToggle').click(function (e) {
        e.preventDefault();
        $('#likebarbtns').hide();
        $('#likeToggle').hide();
        $('#likeToggle2').show();
    });
    $('#likeToggle2').click(function (e) {
        e.preventDefault();
        $('#likebarbtns').show();
        $('#likeToggle2').hide();
        $('#likeToggle').show();
    });

    //script de FB diferido
    $('.fb-like-box').show();
    var js, fjs = document.getElementsByTagName('head')[0];
    js = document.createElement('script');
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=191363247561832";
    fjs.parentNode.appendChild(js);

    //script de TT diferido
    js = document.createElement('script');
    js.src = "//platform.twitter.com/widgets.js";
    fjs.parentNode.appendChild(js);

    //script de G+1 diferido
    js = document.createElement('script');
    js.src = "https://apis.google.com/js/plusone.js";
    fjs.parentNode.appendChild(js);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------- CUSTOM UTILS --------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function friendly(text, len) {
    if (text.length > len) {
        return text.substr(0, len - 3).replace(/^\s+|\s+$/g, '') +"...";
    } else {
        return text;
    }
}
String.prototype.format = function () { var s = this, i = arguments.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); } return s; };

function fix_height() {
    var frameObj = document.getElementById("frame");
    var screenHeight = getScreenHeight();
    var topBarHeight = document.getElementById("headint").clientHeight;
    var bottomBarHeight = 0;
    frameObj.height = screenHeight - topBarHeight - bottomBarHeight - 10 + "px";
    return false;
}
function getScreenHeight() {
    var sHeight = 0;
    if (typeof (window.innerWidth) == 'number') {//Non-IE
        sHeight = window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { //IE 6+ in 'standards compliant mode'
        sHeight = document.documentElement.clientHeight;
    }
    else {
        sHeight = $(window).height;
    }
    return sHeight;
}

function openFullscreen(url) {
    var win = window.open("", "_blank");
    win.location.href = url;
    win.focus();
} 


//Reload
//$(document).ready(function () {
//    reloadTimerTick();
//});
//Función temporizadora el reload forzado cada 5min
//var reloadTimer;
//function reloadTimerTick() {
//    if (reloadTimer !== null) {                                         //si ya existe un timer activo
//        window.clearTimeout(reloadTimer);                               //lo reseteo
//    }
//    reloadTimer = window.setTimeout(function () {
//        window.location.href = window.location.href;
//    }, 290000 + 20000* Math.random());     //4:50 - 5:10 min aprox
//}
