//if(window.addEventListener)
//    window.addEventListener('error', function(e) { e.preventDefault(); console.error(e); });
//else if (window.attachEvent)
//    window.attachEvent('error', function(e) { e.preventDefault(); console.error(e); });

// Plugins de jQuery
(function ($) {
    // Plugin para cambiar la etiqueta de un div, manteniendo todos sus
    // atributos e hijos
    $.fn.tag = function (tag) {
        // create the new, empty shim
        var replacement = $('<' + tag + '>');
        // empty container to hold attributes
        var attributes = {};
        // copy all the attributes to the shell
        $.each(this.get(0).attributes, function (index, attribute) {
            attributes[attribute.name] = attribute.value;
        });
        // assign attributes to replacement
        replacement.attr(attributes);
        // copy the data
        replacement.data(this.data());
        // get all the kids, with data and events
        var contents = this.children().clone(true);
        // inseminate
        replacement.append(contents);
        // swap it out
        this.replaceWith(replacement);

        return this;
    }

    $.humanize = function (string) {
        return string.substring(0, string.lastIndexOf('.')).replace('_', ' ').replace('-', ' ').replace('.', ' ').ucwords();
    }

    $.normalize = function (string) {
        var from = "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç",
            to = "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc",
            mapping = {};

        for (var i = 0, j = from.length; i < j; i++) {
            mapping[from.charAt(i)] = to.charAt(i);
        }

        var ret = [];
        for (var i = 0, j = string.length; i < j; i++) {
            var c = string.charAt(i);
            if (mapping.hasOwnProperty(string.charAt(i)))
                ret.push(mapping[c]);
            else
                ret.push(c);
        }
        return ret.join('');
    }

    $.denormalize = function (string, options) {

        var defaults = {
            to: "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç",
            from: "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc"
        }

        var options = $.extend(defaults, options);

        var from = options.from;
        var to = options.to;

        mapping = {};

        for (var i = 0, j = from.length; i < j; i++) {
            mapping[from.charAt(i)] = to.charAt(i);
        }

        var ret = [];
        for (var i = 0, j = string.length; i < j; i++) {
            var c = string.charAt(i);
            if (mapping.hasOwnProperty(string.charAt(i)))
                ret.push(mapping[c]);
            else
                ret.push(c);
        }
        return ret.join('');
    }

    $.fn.expand_all = function (child) {

        if (typeof(child) == 'object') {

            $(child).each(function (index, element) {

                $(this).removeAttr('style')
                if (!$(this).hasClass('in')) {
                    $(this).collapse('show');
                }
            });

        } else {
            $('.accordion-body', $(this)).each(function (index) {
                $(this).removeAttr('style')
                if (!$(this).hasClass('in')) {
                    $(this).collapse('show');
                }
            });
        }


        return this;
    }

    $.fn.collapse_all = function (child) {

        if (typeof(child) == 'object') {

            $(child).each(function (index, element) {

                $(this).removeAttr('style')
                if ($(this).hasClass('in')) {
                    $(this).collapse('hide');
                }

            });
        } else {
            $('.accordion-body', $(this)).each(function (index, element) {
                $(element).removeAttr('style')
                if ($(element).hasClass('in')) {
                    $(element).collapse('hide');
                }
            });
        }


        return this;
    }

    $.fn.placeAtBottom = function () {
        var windowHeight = 0;
        var bodyHeight = 0;
        var heightDifference = 0;

        windowHeight = $(window).height();
        bodyHeight = $('body').height();

        heightDifference = windowHeight - bodyHeight;

        if ((heightDifference > 0)) {
            $(this).css('margin-top', heightDifference + 'px');
            $('body').addClass("body_color");
        }

        return $(this);
    }


    $.fn.resizeTillBotom = function () {
        var windowHeight = 0;
        var bodyHeight = 0;
        var heightDifference = 0;

        windowHeight = $(window).height();
        bodyHeight = $('body').height();

        heightDifference = windowHeight - bodyHeight;

        if ((heightDifference > 0)) {
            $(this).css('min-height', $(this).get(0).clientHeight + heightDifference + 'px');
            // $('body').addClass("body_color");
        }

        return $(this);
    }

    $.fn.getTagName = function () {
        return this.get(0) ? this.get(0).tagName : null;
    }

    $.fn.toString = function () {
        switch ($(this).getTagName()) {
            case 'INPUT':
                return $(this).val();
            case 'SELECT':
                return $(this).find('option:selected').toString();
            case 'STRONG':
            case 'P':
            case 'SPAN':
            case 'DIV':
                return $(this).text();
            default:
                return '';
        }
    }

    /**
     * Enable a container as a dropdown menu
     * @param  {[type]} options [description]
     * @return {[type]}         [description]
     */
    $.fn.dropdown_menu = function (options) {
        var defaults = {
            delay_time: 500,
            onShow: function () {
            },
            onHide: function () {
            }
        }


        var options = $.extend(defaults, options);

        $(this).each(function () {
            var jObject = $(this);

            // var jObjectHover = $("ul.dropdown-menu, a", jObjectParent);

            jObject.data('timeout_close', null);
            jObject.hover(function () {
                jObject.data('hover', true);
                if (jObject.data('timeout_close') != null) {
                    clearTimeout(jObject.data('timeout_close'));
                    jObject.data('timeout_close', null);
                }
                var slideDown = function (options) {
                    if (!$("ul.dropdown-menu", jObject).is(':animated') && jObject.data('hover') == true) {
                        $("ul.dropdown-menu", jObject).slideDown();
                        options.onShow();
                    } else {
                        if (jObject.data('hover') == true) {
                            $("ul.dropdown-menu", jObject).stop(true, true);
                            $("ul.dropdown-menu", jObject).slideDown();
                            options.onShow();
                            slideObjectDown();
                        }
                    }
                }
                var slideObjectDown = function () {
                    jObject.data('timeout_close', setTimeout(function () {
                        slideDown(options);
                    }, options.delay_time));
                }
                slideObjectDown();
            }, function () {
                jObject.data('hover', false);
                if (jObject.data('timeout_close') != null) {
                    clearTimeout(jObject.data('timeout_close'));
                    jObject.data('timeout_close', null);
                }
                var slideUp = function (options) {
                    if (!$("ul.dropdown-menu", jObject).is(':animated') && jObject.data('hover') == false) {
                        $("ul.dropdown-menu", jObject).slideUp();
                        options.onHide();
                    } else {
                        if (jObject.data('hover') == false) {
                            slideObjectUp();
                        }
                    }
                }

                var slideObjectUp = function () {
                    jObject.data('timeout_close', setTimeout(function () {
                        slideUp(options);
                    }, options.delay_time));
                }
                slideObjectUp();
            });
        });

        return $(this);
    }

    $.getUserAgent = function (agent) {

        if (typeof(agent) != 'undefined') {
            var regexp = new RegExp(agent, "g");
            return (navigator.userAgent.match(regexp) != null);
        } else {
            return navigator.userAgent;
        }


    }


})(jQuery);

function empty() {
};

/* Capitalize all word starting letter */
String.prototype.ucwords = function () {
    return (this + '').replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) {
        return $1.toUpperCase();
    });
}

String.prototype.urlparse = function () {
    return (this).replace(/(^[\/\\])|([\/\\]$)/g, '');
}

String.prototype.addTrailSlash = function () {
    return (empty(this) ? '' : this + '/' );
};

String.prototype.addStartSlash = function () {
    return (empty(this) ? '' : '/' + this);
};


$(document).on('click', 'a[data-toggle="block"][href]', function (e) {
    e.preventDefault();
    var options = {};
    var defaults = {
        duration: 400,
        easing: 'easeInOutBounce',
        queue: true
    };
    for (index in defaults) {
        var value = $(this).data(index);
        options[index] = value ? value : defaults[index];
    }
    $($(this).attr('href')).toggle($(this).data('effect'), options);
});

$(document).on('click', 'button[data-action="link"][data-href]', function (e) {
    e.preventDefault();
    window.open($(this).data('href'), $(this).data('target') ? $(this).data('target') : '_blank');
});

$(function(){




    // $('input[data-mirror], textarea[data-mirror]').each(function (i, e) {
    //
    //     var input = $(e);
    //     var options = {};
    //     var mirrorValue = $(this).data('mirror');
    //     var mirror = $(mirrorValue);
    //
    //     if (mirror.length == 0) {
    //         mirror = $('[id$="'+mirrorValue+'"]');
    //     }
    //
    //
    //
    //     var patt = new RegExp("metaTitle$");
    //
    //     if (patt.test(mirrorValue)) {
    //         input.data('initValue', $(this).val());
    //         input.data('titleTarget', true);
    //     }
    //
    //     var defaults = {
    //         behavior: 'overwrite',
    //         event: 'change',
    //         cut: 0
    //     };
    //
    //     for (var key in defaults) {
    //         if (null !== input.data(key)) {
    //             options[key] = input.data(key);
    //         }
    //     }
    //
    //     options = $.extend(defaults, options);
    //
    //     input.on("keyup", function(){
    //         if ($(this).is('input') && $(this).data("titleTarget") === true && !$(this).data("slug-message-shown")) {
    //             ComitiumUtils.displaySlugMessage($(this));
    //             $(this).data("slug-message-shown", true);
    //         };
    //     });
    //
    //     input.on(options.event, function () {
    //
    //         var value = $(this).val();
    //
    //         _updateMirrorData(mirror,value,options);
    //
    //         $(this).data('last-value', value);
    //
    //     });
    // });


    // for (var i in CKEDITOR.instances) {
    //     CKEDITOR.instances[i].on('blur', function(e) {
    //
    //         var input = $(e.editor.element.$);
    //         var options = {};
    //         var mirrorValue = input.data('mirror');
    //         var mirror = $(mirrorValue);
    //
    //         if (mirror.length == 0) {
    //             mirror = $('[id$="'+mirrorValue+'"]');
    //         }
    //
    //         if (mirror) {
    //             input.data('initValue', input.val());
    //
    //             var patt = new RegExp("/(.+)metaTitle$/g");
    //
    //             if (patt.test(mirrorValue)) {
    //                 input.data('titleTarget', true);
    //             }
    //
    //             var defaults = {
    //                 behavior: 'overwrite',
    //                 event: 'change',
    //                 cut: 0
    //             };
    //
    //             for (var key in defaults) {
    //                 if (null !== input.data(key)) {
    //                     options[key] = input.data(key);
    //                 }
    //             }
    //
    //             options = $.extend(defaults, options);
    //
    //             if (input.is('input') && input.data("titleTarget") === true) {
    //                 ComitiumUtils.displaySlugMessage($(this));
    //             }
    //
    //             var value = input.val();
    //
    //             _updateMirrorData(mirror,value,options, true);
    //
    //             input.data('last-value', value);
    //         }
    //     });
    // }
});

function _updateMirrorData(mirror, value, options, escape) {
    var t = parseText(value);
    var currentUrl = window.location.href;
    var patt = new RegExp(/.+\/edit\/.+?/g);
    var isEdit = patt.test(currentUrl);

    if (((isEdit === false || $.trim(mirror.val()) === "") && options.behavior === "overwrite") || options.force === true ) {

        if (parseInt(options.cut) > 0 || parseInt(options.maxLength) > 0) {
            var cut = parseInt(options.maxLength) > 0 ? parseInt(options.maxLength) : parseInt(options.cut)
            t = ComitiumUtils.cutText(t, cut, "...", true);
        }

        if (escape === true) {
            t = $('<div />').html(t).text();
        }


        mirror.val(t);

        $(mirror).trigger('change');
    }
}

function parseText(text, limit)
{
    var t = ComitiumUtils.stripTags(text);

    if (limit) {
        t.substring(0, limit);
    }
    return t;
}

$('input[data-slugable]').each(function () {
    var input = $(this);
    var options = {};
    var slugInput = $($(this).data('slugable'));
    var url = $(this).data('url');

    var defaults = {
        behavior: 'ignore',
        event: 'change'
    };

    for (var key in defaults) {
        if (null !== input.data(key)) {
            options[key] = input.data(key);
        }
    }

    options = $.extend(defaults, options);

    input.on(options.event, function () {

        if ($(this).val() == '') {
            return;
        }

        var data = {text: $(this).val()};

        _makeSlug(url, data, function(slugResult){

            if ('overwrite' == options.behavior) {
                slugInput.val(slugResult);
            } else if ('ignore' == options.behavior && !slugInput.val() || slugInput.val() == $(this).data('last-value')) {
                slugInput.val(slugResult);
            }

            $(this).data('last-value', slugResult);
        });
    });
});

function _makeSlug(url, data, callBack) {
    $.get(url, data)
        .success(function (slugResult) {
            callBack.call(this,slugResult);
        })
        .fail(function (jqXHR) {
            throw new Error(jqXHR.responseText);
        });
};

$('[maxlength]').maxlength({
    alwaysShow: true
});

(function ($, window) {
    //@TODO modificar modal per poder-li pasar més opcions
    window.bootstrap = {
        createModal: function() {
            return {
                struct: '<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span>&times;</span><span class="sr-only">Close</span></button><h4 class="modal-title"></h4></div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn defaultBtn" data-dismiss="modal" data-btn-type="cancel"></button><button type="button" class="btn mainBtn" data-btn-type="save"></button></div></div></div></div>',
                show: function (header, body, button, hiddenAccept, modalOptions, addDelete) {
                    var modal = $(bootstrap.modal.struct);
                    modal.find('h4').html(header);
                    modal.find('.modal-body').html(body);
                    modal.find('.mainBtn').html(button);
                    modal.find('.defaultBtn').html(Translator.trans("cs_core.action.cancel.default"));

                    if (typeof modalOptions === "object") {
                        modal.filter('.modal').modal(modalOptions);
                    } else {
                        modal.filter('.modal').modal('show');
                    }

                    if (addDelete) {
                        modal.find(".defaultBtn").after('<button type="button" class="btn deleteBtn" data-btn-type="delete" data-action="delete">'+Translator.trans("cs_core.action.delete.default")+'</button>');
                    }

                    if (hiddenAccept) {
                        modal.find('.mainBtn').remove();
                    }

                    return modal;
                },
                hide: function () {
                    var modal = $(bootstrap.modal.struct);
                    $('body').filter('.modal').modal('hide');
                }
            };
        },
        modal: null,
    };

    bootstrap.modal = bootstrap.createModal();
})(jQuery, window);

var documentBody = $('body');

function secondsToString(totalSeconds){

    var stringTime = "";

    var hour = Math.floor(totalSeconds / 3600);
    var minutes = Math.floor(totalSeconds % 3600 / 60);
    var seconds = Math.floor(totalSeconds % 3600 % 60);


    stringTime += (hour) ? ((hour < 10) ? "0"+hour : hour) : '00';
    stringTime += ":";
    stringTime += (minutes) ? ((minutes < 10) ? "0"+minutes : minutes) : '00';
    stringTime += ":";
    stringTime += (seconds) ? ((seconds < 10) ? "0"+seconds : seconds) : '00';

    return stringTime;

    function secondsToHms(d) {
        d = Number(d);
        var h = Math.floor(d / 3600);
        var m = Math.floor(d % 3600 / 60);
        var s = Math.floor(d % 3600 % 60);
        return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s); }
}

function checkDeletion(params) {
    var d = Q.defer();

    $.get(params.url)
        .success(function (data) {
            if(params.html) {
                params.html = data;
            }
            d.resolve(params);
        })
        .fail(function (jqXHR) {
            d.reject(new Error(jqXHR.responseText));
        });

    return d.promise;
}

function confirmDeletion(params) {
    var d = Q.defer();

    var title = params.title ? params.title : Translator.trans("cs_core.delete_entity");
    var message = params.message ? params.message : Translator.trans("cs_core.messages.confirm_delete");
    var modal;

    if(params.html) {
        modal = $(params.html);
        documentBody.append(modal);
        modal.modal('show');
    } else {
        modal = window.bootstrap.modal.show(title, message, Translator.trans("cs_core.action.accept"));
    }


    modal.find(".mainBtn").on("click", function () {
        d.resolve(params);
    });

    return d.promise;
}

function deleteEntity(params) {
    var d = Q.defer();

    $.post(params.url)
        .success(function () {
            d.resolve(true);
        })
        .fail(function (jqXHR) {
            d.reject(new Error(jqXHR.responseText));
        });

    return d.promise;
}

/* Some key codes global variables */
var KEY_BACKSPACE = 8;
var KEY_TAB = 9;
var KEY_ENTER = 13;
var KEY_SHIFT = 16;
var KEY_CTRL = 17;
var KEY_ALT = 18;
var KEY_PAUSE_BREAK = 19;
var KEY_CAPS_LOCK = 20;
var KEY_ESCAPE = 27;
var KEY_PAGE_UP = 33;
var KEY_PAGE_DOWN = 34;
var KEY_END = 35;
var KEY_HOME = 36;
var KEY_LEFT_ARROW = 37;
var KEY_UP_ARROW = 38;
var KEY_RIGHT_ARROW = 39;
var KEY_DOWN_ARROW = 40;
var KEY_INSERT = 45;
var KEY_DELETE = 46;
var KEY_0 = 48;
var KEY_1 = 49;
var KEY_2 = 50;
var KEY_3 = 51;
var KEY_4 = 52;
var KEY_5 = 53;
var KEY_6 = 54;
var KEY_7 = 55;
var KEY_8 = 56;
var KEY_9 = 57;
var KEY_A = 65;
var KEY_B = 66;
var KEY_C = 67;
var KEY_D = 68;
var KEY_E = 69;
var KEY_F = 70;
var KEY_G = 71;
var KEY_H = 72;
var KEY_I = 73;
var KEY_J = 74;
var KEY_K = 75;
var KEY_L = 76;
var KEY_M = 77;
var KEY_N = 78;
var KEY_O = 79;
var KEY_P = 80;
var KEY_Q = 81;
var KEY_R = 82;
var KEY_S = 83;
var KEY_T = 84;
var KEY_U = 85;
var KEY_V = 86;
var KEY_W = 87;
var KEY_X = 88;
var KEY_Y = 89;
var KEY_Z = 90;
var KEY_LEFT_WINDOW_KEY = 91;
var KEY_RIGHT_WINDOW_KEY = 92;
var KEY_SELECT_KEY = 93;
var KEY_NUMPAD_0 = 96;
var KEY_NUMPAD_1 = 97;
var KEY_NUMPAD_2 = 98;
var KEY_NUMPAD_3 = 99;
var KEY_NUMPAD_4 = 100;
var KEY_NUMPAD_5 = 101;
var KEY_NUMPAD_6 = 102;
var KEY_NUMPAD_7 = 103;
var KEY_NUMPAD_8 = 104;
var KEY_NUMPAD_9 = 105;
var KEY_MULTIPLY = 106;
var KEY_ADD = 107;
var KEY_SUBTRACT = 109;
var KEY_DECIMAL_POINT = 110;
var KEY_DIVIDE = 111;
var KEY_F1 = 112;
var KEY_F2 = 113;
var KEY_F3 = 114;
var KEY_F4 = 115;
var KEY_F5 = 116;
var KEY_F6 = 117;
var KEY_F7 = 118;
var KEY_F8 = 119;
var KEY_F9 = 120;
var KEY_F10 = 121;
var KEY_F11 = 122;
var KEY_F12 = 123;
var KEY_NUM_LOCK = 144;
var KEY_SCROLL_LOCK = 145;
var KEY_SEMI_COLON = 186;
var KEY_EQUAL_SIGN = 187;
var KEY_COMMA = 188;
var KEY_DASH = 189;
var KEY_PERIOD = 190;
var KEY_FORWARD_SLASH = 191;
var KEY_GRAVE_ACCENT = 192;
var KEY_OPEN_BRACKET = 219;
var KEY_BACK_SLASH = 220;
var KEY_CLOSE_BRAKET = 221;
var KEY_SINGLE_QUOTE = 222;

var DateUtils = {
    expRegDate: /^\d{2}\/\d{2}\/\d{4}$/,
    expRegDateTime: /^\d{2}\/\d{2}\/\d{4} - \d{2}:\d{2}$/,
    dateSeparator: '/',
    timeSeparator: ':',
    dateAndTimeSeparator: ' - ',
    getDate: function(date)
    {
        if(date.match(this.expRegDate))
        {
            date = date.split(this.dateSeparator);
            return this.dateFactory(parseInt(date[0]), parseInt(date[1]), parseInt(date[2]));
        }
        else if(date.match(this.expRegDateTime))
        {
            var aux = date.split(this.dateAndTimeSeparator);
            date = aux[0].split(this.dateSeparator);
            var time = aux[1].split(this.timeSeparator);

            return this.dateFactory(parseInt(date[0]), parseInt(date[1]), parseInt(date[2]), parseInt(time[0]), parseInt(time[1]), 0);

        }

        return false;
    },
    dateFactory: function( day, month, year, hours, minutes, seconds)
    {
        month = month-1;

        if( arguments.length === 3 )
        {
            return new Date(year, month, day );
        }
        else if ( arguments.length === 6 )
        {
            return new Date(year, month, day, hours, minutes, seconds);
        }

        return false;
    }
};
