﻿var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var hoy = day + "/" + month + "/" + year;


$(document).ready(function () {


    // Prevent memory leaks in IE 
    // Window isn't included so as not to unbind existing unload events 
    // More info: 
    //  - http://isaacschlueter.com/2006/10/msie-memory-leaks/ 
    if (window.attachEvent && !window.addEventListener) {
        window.attachEvent("onunload", function () {
            for (var id in jQuery.cache) {
                if (jQuery.cache[id].handle) {
                    // Try/Catch is to handle iframes being unloaded, see #4280 
                    try {
                        jQuery.event.remove(jQuery.cache[id].handle.elem);
                    } catch (e) { }
                }
            }
        });
    }



    jQuery.datepicker.setDefaults($.datepicker.regional['es']);




    $('.calendario').datepicker();

    //paginador
    (function ($) {
        $.dialog_contenido_pager = function (_url, _pagina) {
            location.href = _url.replace('-99999', _pagina);
        }
    })(jQuery);

    


    // rotacion imagenes noticia portada
    $('.hoverIn').live('mouseover', function () {
  
        var _imgOut = $('#' + $(this).attr('rel')).attr('src');
        var _img = $(this).attr('src');

        $('#' + $(this).attr('rel')).attr('oldsrc', _imgOut)
        $('#' + $(this).attr('rel')).attr('src', _img)

    }).live('mouseout', function () {
        $('#' + $(this).attr('rel')).attr('src', $('#' + $(this).attr('rel')).attr('oldsrc'))
        $('#' + $(this).attr('rel')).removeAttr('oldsrc')

    });


});






///***************************************************************/
///* ventana de login/logout                                    */
///***************************************************************/
(function ($) {
    $.dialog_login = function (_accion) {

        $('#login').load('/modulos/admin/login.htm', function () {

            $('#login').dialog({
                resizable: false,
                modal: true,
                closeOnEscape: true,
                stack: true,
                title: 'Acceso al sistema',
                width: 300,
                height: 300,
                dialogClass: 'dialogLogin',
                beforeClose: function () {
                    $('body').css('overflow', 'auto');
                },
                open : function() {
                    if(_accion =='LOGIN') {
                        $('#_login').show();
                        $('#_logOut').hide();
                        $("div.dialogLogin div button:nth-child(2)").hide();
                        $('#usuario').focus();
                    } else {
                        $('#_login').hide();
                        $('#_logOut').show();
                        $("div.dialogLogin div button:nth-child(1)").hide();
                    }
                },
                buttons: {
                    Validar : function () {
                        $.ajax({
                            type: "POST",
                            cache: false,
                            url: "/modulos/admin/serviciosWeb/usuariosWS.asmx/iniciarSesion",
                            data: "{'_usuario': '" + $('#usuario').val() + "', '_clave': '" + $('#clave').val() + "'}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                if (response.d[0].MSG == 'OK') {
                                    location.reload();
                                } else {
                                    $.crearDialogoError('Error en la validación del usuario', response.d[0].VALOR);
                                }
                            },
                            error: function (response) {
                                $.crearDialogoError('Error en la validación del usuario', response.responseText);
                            }
                        });
                    },
                    Desconectar  : function (){
                       $.ajax({
                            type: "POST",
                            cache: false,
                            url: "/modulos/admin/serviciosWeb/usuariosWS.asmx/cerrarSesion",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                if (response.d[0].MSG == 'OK') {
                                    location.reload();
                                } else {
                                    $.crearDialogoError('Error en el cierre de la sesión del usuario', response.d[0].VALOR);
                                }
                            },
                            error: function (response) {
                                $.crearDialogoError('Error en el cierre de la sesión del usuario', response.responseText);
                            }
                        });
                    }
                }
            });
        });



        $('body').css('overflow', 'hidden');



        return true;

    };
})(jQuery);

/***************************************************************/
/* obtiene un boton de una ventana por su nombre               */
/***************************************************************/
(function ($) {
    $.getDialogButton = function (dialog_selector, button_name) {
        var buttons = $(dialog_selector + ' .ui-dialog-buttonpane button');
            for (var i = 0; i < buttons.length; ++i) {
                var jButton = $(buttons[i]);
                    if (jButton.text() == button_name) {
                        return jButton;
                    }
            } 
       return null; 
    };

})(jQuery);




///***************************************************************/
///* Cierra un dialogo. Común para todos los dialogos            */
///***************************************************************/
(function ($) {
    $.dialog_com_close = function (_ventana) {
        $('div' + _ventana).dialog('close').dialog('destroy').empty();
        $('body').css('overflow', 'auto');
    };
})(jQuery);


/***************************************************************/
/* Calcula las proporciones de una imagen                      */
/***************************************************************/
(function ($) {
    $.tamanoImagen = function (max, w, h, imagen) {

        $(imagen).each(function () {
            var maxWidth = max; // Max width for the image
            var maxHeight = max;    // Max height for the image
            var ratio = 0;  // Used for aspect ratio
            var width = w;    // Current image width
            var height = h;  // Current image height

            // Check if the current width is larger than the max
            if (width > maxWidth) {
                ratio = maxWidth / width;   // get ratio for scaling image
                $(this).css("width", maxWidth); // Set new width
                $(this).css("height", height * ratio);  // Scale height based on ratio
                height = height * ratio;    // Reset height to match scaled image
                width = width * ratio;    // Reset width to match scaled image
            }

            // Check if current height is larger than max
            if (height > maxHeight) {
                ratio = maxHeight / height; // get ratio for scaling image
                $(this).css("height", maxHeight);   // Set new height
                $(this).css("width", width * ratio);    // Scale width based on ratio
                width = width * ratio;    // Reset width to match scaled image
            }
        });


    };
})(jQuery);






/***************************************************************/
/* Crea un dialogo de error                 */
/***************************************************************/
(function ($) {
    $.crearDialogoError = function (_accion, _error) {

        var _dialogError = document.createElement('div');
        _dialogError.setAttribute('title', 'Error en la operación');

        var textoAviso;

        textoAviso = 'Ha ocurrido el siguiente error en la operación';

        _dialogError.appendChild($.createDiv('nm-dialog-warning'));
        _dialogError.appendChild($.createP('nm-info-text-b', _accion));
        _dialogError.appendChild($.createP('nm-info-text', _error));



        $(_dialogError).dialog({
            bgiframe: true,
            modal: true,
            width: 500,
            height: 300,
            buttons: {
                Aceptar: function () {
                    $(_dialogError).dialog('close');
                    $(_dialogError).remove()
                    $(_dialogError).empty
                    $('body').css('overflow', 'auto');
                }
            }
        })
        return _dialogError;
    };
})(jQuery);



/***************************************************************/
/* Crea un dialogo de info                 */
/***************************************************************/
(function ($) {
    $.crearDialogoInfo = function (_accion, _error) {
        $('body').css('overflow', 'hidden');
        var _dialogInfo = document.createElement('div');
        _dialogInfo.setAttribute('title', 'Error en la operación');

        _dialogInfo.appendChild($.createDiv('nm-dialog-info'));
        _dialogInfo.appendChild($.createP('nm-info-text-b', _accion));
        _dialogInfo.appendChild($.createP('nm-info-text', _error));
        
        $(_dialogInfo).dialog({
            bgiframe: true,
            modal: true,
            width: 420,
            height: 300,
            buttons: {
                Aceptar: function () {
                    $(_dialogInfo).dialog('close');
                    $(_dialogInfo).remove()
                    $(_dialogInfo).empty
                    $('body').css('overflow', 'auto');
                }
            }
        })
        return _dialogInfo;
    };
})(jQuery);



/***************************************************************/
/* crea un checkbox                    */
/***************************************************************/
(function ($) {
    $.createCheckBox = function (_id, _texto) {

        var _div = document.createElement('div');

        var _input = document.createElement('input');
        _input.setAttribute('type', 'checkbox');
        _input.setAttribute('id', _id);
        _input.setAttribute('class', 'nm-info-text');

        var _label = document.createElement('label');
        _label.appendChild(document.createTextNode(_texto));

        _div.appendChild(_label);
        _div.appendChild(_input);

        return _div
    };
})(jQuery);


/***************************************************************/
/* Crea una caja de texto                                      */
/***************************************************************/
(function ($) {
    $.createTextBox = function (_id, _estilo, _texto, _width) {
        var d = document.createElement('div');

        var i = document.createElement('input');
        i.setAttribute('type', 'text');
        i.setAttribute('id', _id);
        i.setAttribute('style', 'width:' + _width + '');

        var l = document.createElement('label');
        l.appendChild(document.createTextNode(_texto));
        l.setAttribute('class', _estilo);

        d.appendChild(l);
        d.appendChild(i);
        return d
    };
})(jQuery);


/***************************************************************/
/* Crea un span  <span></span>                                 */
/***************************************************************/
(function ($) {
    $.createSpan = function (clase, _texto) {
        var _span = document.createElement('span');
        _span.setAttribute('class', clase);
        _span.appendChild(document.createTextNode(_texto));
        return _span
    };
})(jQuery);


/***************************************************************/
/* Crea un parrafo <p></p>                                     */
/***************************************************************/
(function ($) {
    $.createP = function (clase, _texto) {
        var _span = document.createElement('p');
        _span.setAttribute('class', clase);
        _span.appendChild(document.createTextNode(_texto));
        return _span
    };
})(jQuery);


/***************************************************************/
/* Crea un div <div></div>                                     */
/***************************************************************/
(function ($) {
    $.createDiv = function (clase) {
        var _div = document.createElement('div');
        _div.setAttribute('class', clase);
        return _div
    };
})(jQuery);

/***************************************************************/
/* Crea un div <div></div> con id                              */
/***************************************************************/
(function ($) {
    $.createDivWithId = function (id) {
        var _div = document.createElement('div');
        _div.setAttribute('id', id);
        return _div
    };
})(jQuery);



