// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var App = {
  disable: function(element) {
    element = element || {};
    element.disabled = true;
  },
  enable: function(element) {
    element = element || {};
    element.disabled = false;
  },
  urlize: function(str) {
    return str.urlize();
  },
  changeLocale: function(locale) {
    if(window.location.pathname.search(/^\/(en|zh|fr|jp|kr|es)\//) >= 0) {
      window.location = window.location.pathname.replace(/^\/(en|zh|fr|jp|kr|es)\//,"/" + locale + "/");
    } else {
      window.location = "/" + locale + window.location.pathname;
    }
  },
  toggleCollapse: function(id) {
    var el = $(id).select('.collapsible-body')[0];
    if(el) {
      if(el.style.display == "") { //Hide
        Effect.SlideUp(el, { duration: 0.5, queue: 'end' });
      } else { //Show
        Effect.SlideDown(el, { duration: 0.5, queue: 'end' });
      }
    }
  },
  back_or_default: function(path) {
    if(history.length == 1) window.location = path;
    else history.back();
  },
  printDialog: function(imgPath) {
    var win;
    win = window.open('/print.coupon.html?coupon=' + imgPath);	
  },
  printDialog2: function(url) {
    var win;
    win = window.open(url);
  },
  runningRotations: {},
  startRotation: function(id, frequency, htmls) {
    if(this.runningRotations[id]) {
      //Stop the running Rotation
      this.runningRotations[id].stop();
    }

    var periodicalexecuter = new PeriodicalExecuter(function() {
      this.rotator.index++;
      if(this.rotator.index >= this.rotator.content.length) {
        this.rotator.index = 0;
      }
      $(id).innerHTML = this.rotator.content[this.rotator.index];
    }, frequency);

    periodicalexecuter.rotator = {
      id: id,
      index: 0,
      content: htmls
    };

    this.runningRotations[id] = periodicalexecuter;
  }
};

App.Currency = {
  ratio: {
    usd: 1,
    cny: 0.15
  },
  CnyToUsd: function(value) {
    return Math.round(value * App.Currency.ratio.cny);
  },
  UsdToCny: function(value) {
    return Math.round(value / App.Currency.ratio.cny);
  }
};

String.prototype.urlize = function(options) {
  options = options || {};
  options.allowSlash = options.allowSlash || false;
  var regex = new RegExp("[^a-z0-9" + (options.allowSlash ? "\\/" : "") + "]");
  return this.toLowerCase().strip().gsub(/('|")/,'').gsub(regex, '-').gsub(/--/,'-').gsub(/--/,'-').gsub(/-$/,'');
};
