
(function($) {
  var app = window.app = {
    
    config: {
      AMOUNT_ALIGNMENT_SIZE: 1000,
      MEDIA_RATE_URL: null,
      MEDIA_INFO_URL: null
    },
    
    shortAmount: function(n) {
      var s = app.config.AMOUNT_ALIGNMENT_SIZE;
      return (s < n) ? parseInt(n / s) : n;
    },
    
    realAmount: function(n) {
      var s = app.config.AMOUNT_ALIGNMENT_SIZE;
      return n * s;
    },
    
    addComma: function(s) {
      var v = new String(app.removeComma(s));
      while (v != (v = v.replace(/^([+-]?\d+)(\d{3})/, "$1,$2")));

      return v;
    },

    removeComma: function(s) {
      return new String(s).replace(/,/g, "");
    },

    // z2h: function(s) {
    //   return new String(s).replace(/([！-～])/g, function ($0) {
    //     return String.fromCharCode($0.charCodeAt(0) - 65248);
    //   });
    // },
    // 
    // h2z: function(s) {
    //   return new String(s).replace(/(\w)/g, function ($0) {
    //     return String.fromCharCode($0.charCodeAt(0) + 65248);
    //   });
    // },

    scrollTo: function(target) {
      $($.browser.safari ? 'body' : 'html')
      .animate({scrollTop: $(target).offset().top}, 'fast', 'swing');
      return false;
    },

    decimalAlignment: function(n, d) {
      if (!d) d = 2;
      n = new Number(n);
      return isFinite(n) ? n.toFixed(d) : n;
    },

    numfmt: function(n) {
      return app.addComma(n);
    },

    pctfmt: function(n) {
      return app.addComma(app.decimalAlignment(n)+'%');
    },

    ymfmt: function(y, m) {
      if (/^\d{4}/.test(y)) {y = y.substr(2)}
      return y+'年'+parseInt(m)+'月';
    },

    sanitizeNum: function(num, defval) {
      defval = (typeof defval === 'number') ? defval : 0;
      num    = parseFloat(app.z2h(new String(num)).replace(/[^\d\.]/g, '').replace(/^0+/, ''));
      return isFinite(num) ? num : defval;
    },

    parseTemplate: function(tmpl, ns, scope) {
      // http://amix.dk/blog/viewEntry/?id=163
      // RND
      scope = scope || window;
      var fn = function(w, g) {
        g = g.split("|");
        var cnt = ns[g[0]];

        for (var i = 1; i < g.length; i++) {
          cnt = scope[g[i]](cnt);
        }

        if (cnt == 0 || cnt == -1) cnt += '';

        return cnt || w;
      };
      return tmpl.replace(/%\(([A-Za-z0-9_\|\.]+)\)/g, fn);
    },

    myAjaxSubmit: function(form, opts) {
      if ($.isFunction(opts)) opts = {success: opts};

      var oldSuccess = $.isFunction(opts.success) ? opts.success : function() {};

      // opts.beforeSend = function(xhr) {
      //   xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      // };

      opts.success = function(data, resstatus, $form) {
        // check status code
        var status  = data.status || {};
        var code    = status.code || 0;
        var message = status.message || '';

        // timeout or forbidden
        if (code == 403) {
          var mes = (message == 'timeout')
                  ? '一定時間の操作がなかったため、自動的にログアウトとなりました。再度ログインしてください。'
                  : 'このページを閲覧するためには、ログインが必要です。';

          // show login page
          alert(mes);
          window.location.reload();
          return;
        } else {
          oldSuccess.apply(opts, [data, resstatus, $form]);
        }
      };

      $(form).ajaxSubmit(opts);

      return false;
    }
  };
  
  app.z2h = (function() {
    var pat = /[\uFF01-\uFF5E]/g, rep = function(m) {
      return String.fromCharCode(m.charCodeAt() - 0xFEE0);
    };
    return function(s) { return s.replace(pat, rep); };
  })();
  
  app.h2z = (function() {
    var pat = /[\u0021-\u007E]/g, rep = function(m) {
      return String.fromCharCode(m.charCodeAt() + 0xFEE0);
    };
    return function(s) { return s.replace(pat, rep); };
  })();
  
  app.MediaRate = function() {
    this.rates = {};
  };
  
  app.MediaRate.prototype = {
    load: function() {
      this._call(null, true);
    },
    
    get: function(id) {
      var v = this.rates[id];
      if (v == null) {
        v = 0;
        this.set(id, 0);
      }
      return v;
    },

    set: function(id, val) {
      if (!/^\d+$/.test(new String(id))) return;
    
      if (typeof val === 'number') {
        val = parseInt(val);
      } else if (typeof val === 'string') {
        if (!/^\d+$/.test(val)) {
          val = app.z2h(val).replace(/\D/, '');
        }
        val = parseInt(val.replace(/^[0]+/, ''));
      }
    
      if (!isFinite(val) || isNaN(val)) {
        val = 0;
      }
    
      // alignment
      val = app.shortAmount(val);
    
      var org = this.rates[id];
      if (org !== val) {
        var r = {};
        r[id] = val;
        this._store(r);
      }
    
      this.rates[id] = val;
    },
  
    _store: function(rate) {
      var qs = [];
      $.each(rate, function(id, val) {
        qs.push('rate['+id+']='+val);
      });
      this._call({data: qs.join('')});
    },
    
    _call: function(opts, update) {
      var url = app.config.MEDIA_RATE_URL;
      var self = this;

      if (url == null) return;

      update = update ? true :false;
      opts   = $.extend({
        'url':     url,
        type:    'GET',
        dataType: 'json',
        cache: false,
        success: function(data, textStatus) {
          var status = data.status, result = data.result || {}, rates = {};
          if (update) {
            $.each(result, function(id, val) {
              rates[id] = val;
            });
            self.rates = rates;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          // typically only one of textStatus or errorThrown 
          // will have info
          this; // the options for this ajax request
        }
      }, opts || {});
      
      $.ajax(opts);
    }
  };
  
  app.mediaInfoWindow = function() {
    var url = app.config.MEDIA_INFO_URL;
    w = window.open('', 'media_info', 'width=680,height=600,status=yes,scrollbars=yes,directories=no,menubar=yes,resizable=yes,toolbar=yes');
    if (w != null) { w.focus(); }
    w.location.href = url;
  };
})(jQuery)


// window.onload
$(document).ready(function(){
  $.smoothAnchors('fast', 'swing');
});

