// JS for AG cms

/*jslint nomen: false, regexp: false */
/*global $, ag */

$.extend(ag, {
    plain: function (str) {
        str = String(str);
        var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
        for (var character in replace) {
            var regex = new RegExp(character, 'g');
            str = str.replace(regex, replace[character]);
        }
        return str;
    },
    trim: function (string) {
        return string.replace(/(^\s+)|(\s+$)/g, "");
    },
    t: function(str, args) {
        str = ag.trim(str)
        if (ag.locale_usable && ag.locale.strings[str]) {
            str = ag.locale.strings[str];
        }
        if (args) {
            for (var key in args) {
                switch (key.charAt(0)) {
                    case '!':
                        break;
                    case '%':
                    default:
                        args[key] = ag.plain(args[key]);
                    break;
                }
                str = str.replace(key, args[key]);
            }
        }
        return str;
    },
    plural: function (count, singular, plural, args) {
        var args = args || {};
        args['@count'] = count;
        var index = ( ag.locale_usable ? ag.locale.formula(args['@count']) : ((args['@count'] == 1) ? 0 : 1) );

        if (index == 0) {
            return ag.t(singular, args);
        } else if (index == 1) {
            return ag.t(plural, args);
        } else {
            args['@count['+ index +']'] = args['@count'];
            delete args['@count'];
            return ag.t(plural.replace('@count', '@count['+ index +']'), args);
        }
    },
    json : function (url, req, callback){
        $.ajax({
            url : url,
            data : req,
            type : "POST",
            dataType : 'json',
            error : function (){
                $.jGrowl('Не удалось соединиться с свервером.', {
                    theme: 	'error',
                    header: 'Ошибка',
                    sticky: true
                });
            },
            success : function (data) {
                if (data.error) {
                    $.jGrowl(data.error ,{
                        theme: 	'error',
                        header: 'Error',
                        sticky: true
                    });
                } else {
                    callback(data);
                }
            },
            timeout: 7000
        });
    }
});

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};
