/**
 * 2011(c) goplek.com
 * Moka standard business
 */
 
/**
 * Strings object. 
 * This object is loaded using Moka.getStrings()
 */
var strings = null;
 
var Moka = {
  
  /**
   * System Constants
   */
  CATEGORY_LOCK: 4,     // Content can't be added or removed from category
  CATEGORY_SYSTEM: 2,   // Category can't be removed
  CONTENT_COMMENTS: 2,  // Content allows comments
  CONTENT_RATING: 4,    // Content allows rating
  CONTENT_SEXYBAR: 8,   // Content presents sexybar
  CONTENT_ISINDEX: 16,  // Content is index of its category
  
  eStringsLoaded: 'strings_loaded',   // Event triggered when strings are loaded 

  /**
   * Holds the data for sync command calls
   */
  _syncData: null,
  
  session: {},
  
  
  _construct: function(){
     //Global ajax error handler
     $('body').ajaxError(Moka.ajax_Error);
          
     
     Moka.loadStrings(true);

  },

  
  
  /**
    * Handles ajax related errors
    */
   ajax_Error: function (a, b, c, d){
     Moka.loading();
     var message = "";
     if(typeof(d) == 'undefined' && typeof(MokaManager) != 'undefined'){
       message = "Some descriptionless AJAX error occured";
     }else if(d.indexOf("++NO SESSION++") > 0  && typeof(MokaManager) != 'undefined' ){
       MokaManager._construct();
     }else{
      message = "AJAX Err: " + d;
     }
     if(message && typeof(Editor) != 'undefined'){
         alert(message);
     }
     console.log(message);
   },
  
  /**
   * Checks the navigator.userAgent string for the specified key
   */
   browserIs: function(key){
     return navigator.userAgent.toLowerCase().indexOf(key.toLowerCase()) >= 0;
   },
  
  /**
   * Executes a command
   * @param cmd       {string}    Command name
   * @param data      {Object}    Command data
   * @param callback  {function}  Callback for operation
   * @param context   {object}    Context for callback
   */
  command: function (cmd, data, callback, context){
    
    if (typeof(MOKA_CALL) == 'undefined'){
      throw "MOKA_CALL variable is not configured (cms-data/cms-config.js)?.";
    }
    
    $.ajax({
      data: $.extend(data, {command: cmd}),
      dataType: "json",
      type: "post",
      success: callback,
      url: MOKA_CALL, 
      context: context
    });
  },
  
  /**
   * Executes a command synchronously and returns the JSON object 
   * @param cmd {string} Command name
   * @param data {Object} Command data
   */
  commandSync: function (cmd, data){
    
    if (typeof(MOKA_CALL) == 'undefined'){
      throw "SERVER_CALL variable is not configured (cms-data/cms-config.js present?)";
    }
    
    $.ajax({
      async: false,
      data: $.extend(data, {command: cmd}),
      dataType: "json",
      type: "get",
      cache: "false",
      timeout: 5000, //Five seconds, this commands should be super-fast
      success: function (data){
        Moka._syncData = data;
      },
      url: MOKA_CALL
    });
    
    return Moka._syncData;
  },
  
  /**
   * Creates an icon, using the specified coordinates
   */
   createIcon: function(size, x, y){
     var icon = $('<div>').addClass('icon-' + size);
     var img = $('<div>').addClass('icons');
     
     icon.append(img);
     
     img.css({
       left: -x,
       top: -y
     });
     
     return icon;
   },
   
   /**
    * Creates the element representing the specified message
    */
   createInstantMessageElement: function(msg){
       var divMsg = $('<div>')
            .append($('<div>').text(msg.sent).css({fontSize: '0.8em', color: '#ccc'}))
            .append($('<div>').text(msg.message))
            .css({
                margin: 10,
                paddingBottom: 10,
                borderBottom: 'solid 1px #f0f0f0'
            });

         // Add to messages view
         if(msg.isoperator == 1){
             divMsg.css('color', 'blue');
         }else{
             divMsg.css('color', 'black');
         }
         
         return divMsg;

   },
  
  dialog: function (data){
      return MokaManager.dialog(data);
  },
  
  /**
   * Gets the extension of specified file name
   */
  extension: function(name){
    if(!name || name.indexOf('.') < 0) return name;
    
    var parts = name.split(".");
    var ext = parts[parts.length - 1].toLowerCase();
    
    return ext;
  },
  
  
  /**
   * Gets the link for the specified content
   */
  getContentLink: function(idcontent, title){
    return MOKA_CONTENT_LINK
              .replace('[ID]', idcontent)
              .replace('[TITLE]', Moka.getSeo(title));
  },
  
  /**
   * Gets the link for the specified category
   */
  getCategoryLink: function(idcategory, name){
    return MOKA_CATEGORY_LINK
              .replace('[ID]', idcategory)
              .replace('[NAME]', Moka.getSeo(name));
  },
  
  /**
   * Returns a SEO friendly version of the string
   */
  getSeo: function(string){
    return  string
            .replace(/Ñ/g, "N")
            .replace(/ñ/g, "n")
            .replace(/á/g, "a")
            .replace(/é/g, "e")
            .replace(/í/g, "i")
            .replace(/ó/g, "o")
            .replace(/ú/g, "u")
            .replace(/Á/g, "A")
            .replace(/É/g, "E")
            .replace(/Í/g, "I")
            .replace(/Ó/g, "O")
            .replace(/Ú/g, "U")
            .replace(/\s/g, "-")
            .replace(/\?/g, "-")
            .replace(/\//g, "-")
            .replace(/:/g, "-") 
            .replace(/&/g, "")
  },
  
  /**
   * Gets the session data
   */
  loadSession: function(){
    Moka.session = Moka.commandSync('get-session');
  },
  
  /**
   * Shows or hides the loading sign
   */
  loading: function(message){
    
    var ldr = $('.loader');
    
    if(ldr.length == 0){
      ldr = $('<div>').addClass('loader').appendTo('body');
    }
    
    if(!message){
      ldr.remove();
    }else{ 
    
      ldr
        .html('')
        .append( $('<img>').attr({
          'src': 'imgs/ajax-loader.gif',
          'align' : 'absmiddle',
          'hspace' : 10
        }) )
        .append(message)
        .css({
          top: 100,
          left: ( $(document).width() - ldr.width()) / 2,
          'z-index': 99999
        })
        .show()
   }
      
    
  },
  
  /**
   * Loads the strings into the global "strings" object.
   */
  loadStrings: function (async){
    
    if(!async){ 
      strings = Moka.commandSync('get-strings');
      Moka.loadStrings_Clean();
      $(document).trigger(Moka.eStringsLoaded);
    }else{
      Moka.command('get-strings', {}, Moka.loadStrings_CallBack);      
    }
  },
  
  
   /**
   * CallBack for loadStrings
   */
  loadStrings_CallBack: function (data){
    
    strings = data;
    
    Moka.loadStrings_Clean();
    
    $(document).trigger(Moka.eStringsLoaded);
    
  },
  
  /**
   * Cleans the loaded strings
   */
  loadStrings_Clean: function(){
    for(var i in strings){
          strings[i] = strings[i].replace("\\n", "\n");
      }
  },
  
  
  /**
   * Terminates the session
   */
  logout: function(){
    Moka.loading(strings.closingSession);
    Moka.switchApp('none');
    Moka.command('log-out', {}, Moka.logout_callback);
  },
  
  /**
   * Terminates the session
   */
  logout_callback: function(){
    Moka.loading();
  },
  
   
   /**
    * Switches to the specified app
    * 
    * @param app  {string} explorer | editor | login
    * @param data {object} Optional data to pass to _show function
    */
   switchApp: function(app, data){
     
     MokaManager.switchApp(app, data);
   }
  
};

//Launch explorer
  $(function (){
    Moka._construct();
  });
