var GCR_JS = {};

function show_flash() {
  $('flash').down('div.container').show();
}

function hide_flash() {
  $('flash').down('div').slideUp({duration: 0.5});
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function update_shipping_price(select, total_without_shipping, reward) {
  var text = select.options[select.selectedIndex].text
  var a = /- \$([0-9.]*)$/.exec(text);
  var price = parseFloat(a[1]);
  $('shipping_price').innerHTML = '$' + price.toFixed(2);
  $('total').innerHTML = '$' + (price + total_without_shipping).toFixed(2);
}

function change_shipping_address() {
  $('show_address').hide();
  $('edit_address').show();
}

function show_password() {
  $('password_link').hide();
  $('password_div').show();
  $('password_confirm_tr').show();
}

function start_subscription(message) {
  $('subscribe_message').innerHTML = "Subscribe..."
  $('subscribe_message').show();
}
function bad_subscription(message) {
  $('subscribe_message').innerHTML = message;
  $('subscribe').down('form').enable();
}
function good_subscription() {  
  $('subscribe_message').innerHTML = "Thank you."
}

function same_shipping(element) {
  if (element.checked) {
    $('same_shipping').show();
    $('different_shipping').hide();
  }
  else {
    $('same_shipping').hide();
    $('different_shipping').show();
  }
}

function inPlaceEdit(link) {
  cancelInPlaceEdits();
  Element.extend(link);
  var container = link.up('.in-place-edit').down('div');
  container.show();
}
function cancelInPlaceEdits(event) {
  if (event == null || !event.element().up('div.in-place-edit')) {
    $$('div.in-place-edit').each(function(d) {
      d.down('div').hide();
    });
  }
}

function chooseMerchant() {
  if ($F('merchant')) {
    window.location = "/buy/" + $F('merchant');
  } 
  else {
    window.location = "/buy/choose";
  }
  
}
function wishMerchant() {
  if ($F('wish')) {
    window.location = "/subscriptions/" + $F('wish');
  }   
}

GCR_JS.initCardHighlight = function() {
  $$('.over-link').each(function(n) {
    n.observe('mouseover', GCR_JS.highlightCard);
    n.observe('mouseout', GCR_JS.unhighlightCard);
  });
}

GCR_JS.highlightCard = function(event) {
  var link = event.element();
  link.up('li').addClassName('hover');
}
GCR_JS.unhighlightCard = function(event) {
  var link = event.element();
  link.up('li').removeClassName('hover');
}

GCR_JS.quote = function(options) {
  var merchantField = $(options.merchantId);
  var valueField = $(options.valueId);
  var result = $(options.result);
  var minSell = options.minSell;
  var maxSell = options.maxSell;
  var amazonDiscount = options.amazonDiscount;
  var rates = options.rates;
  var context = options.context || 'home';
  
  var merchantId = null;
  var rate = null;
  var currentValue = null;
  var quoteValue = null;

  $(options.merchantId).observe('change', function(event) {quote.merchant()});
  new Form.Element.Observer(options.valueId, 0.5, function(event) {quote.currentValue()});
    
  return {  
    
    init: function() {
      this.merchant(merchantField.value);
      this.currentValue(valueField.value);
    },

    merchant: function() {
      merchantId = $F(options.merchantId);
      rate = rates[merchantId];
      this.check();
      valueField.focus();
    },

    currentValue: function() {
      currentValue = $F(options.valueId);
      this.check();
    },

    check: function() {
      quoteValue = currentValue * rate;
      if (context == 'sell') {
        if (rate && rate > 0 && currentValue && currentValue > 0) {
          if (currentValue < minSell) {
            result.innerHTML = 'We only accept cards between ' + GCR_JS.formatCurrency(minSell) + ' and ' + GCR_JS.formatCurrency(maxSell);
          } else if (currentValue > maxSell) {
            result.innerHTML = 'We only accept cards under ' + GCR_JS.formatCurrency(maxSell) + '. Please email us at <a href="mailto:bulksales@giftcardrescue.com">bulksales@giftcardrescue.com</a>.';
          } else {
            result.innerHTML = 'We pay <span class="highlight">' + GCR_JS.formatCurrency(quoteValue / 100.0) + '</span> cash or <span class="highlight">' + GCR_JS.formatCurrency(quoteValue * (1 + amazonDiscount) / 100.0) + '</span> Amazon.com<super>&reg;</super> Gift Card&nbsp;*';
          }
        }
      } else {
        if (!rate || rate == 0) {
          result.innerHTML = 'Pick a merchant';
          $('intro').show();
        } else if (!currentValue || currentValue == 0 || currentValue < minSell) {
          result.innerHTML = 'Enter the current value of the card. (It must be over ' + GCR_JS.formatCurrency(minSell) + ')';
          $('intro').show();
        } else if (currentValue > maxSell) {
          result.innerHTML = 'We only accept cards under ' + GCR_JS.formatCurrency(maxSell) + '. Please email us at <a href="mailto:bulksales@giftcardrescue.com">bulksales@giftcardrescue.com</a>.';
          $('intro').show();
        } else {
          var href = '/sell/new?merchant[id]=' + merchantId + '&merchant[current_value]=' + currentValue;
          var link = new Element('div').insert(new Element('a', {href: href}).insert('Sell Your Card Now'));
          link.addClassName('sell-now');
          result.innerHTML = 'We pay <span class="highlight">' + GCR_JS.formatCurrency(quoteValue / 100.0) + ' cash</span><div class="amazon">Or exchange for a <span class="highlight">' + GCR_JS.formatCurrency(quoteValue * (1 + amazonDiscount) / 100.0) + '</span> Amazon.com<super>&reg;</super> Gift Card&nbsp;*</div>';
          result.insert(link);
          $('intro').hide();
        }
      }
    },
    
  };
  
}

GCR_JS.slider = function(options) {
  var slide = $(options.slide);
  var steps = options.steps;
  var width = options.width;
  var offset = options.offset || 0;
  var position = 0;
  var duration = options.duration || 0.5;
  slide.morph({left: offset + 'px'}, {duration: 0});
  
  return {
    
    slide: function() {
      position++;
      var left = offset - (position * width);
      slide.morph({left: left + 'px'}, {duration: duration});
      if (position == steps - 1) {
        position = 0;
        slide.morph({left: offset + 'px'}, {duration: 0, queue: 'end'});
      }
    }
    
  };
  
}

GCR_JS.cart = function(options) {
  var subtotal = options.subtotal;
  var availableReward = options.availableReward;
  var shippingPrices = options.shippingPrices;
  new Form.Element.Observer(options.shippingSelectId, 0.5, function(element, value) {cart.changeShipping(value)});
  
  return {
    
    changeShipping: function(value) {
      var shippingPrice = shippingPrices[value];
      var usedReward = availableReward;
      if (availableReward > shippingPrice + subtotal) {
        usedReward = shippingPrice + subtotal;
      }
      $('shipping_price').innerHTML = GCR_JS.formatCurrency(shippingPrice / 100.0);
      if ($('used_reward')) {
        $('used_reward').innerHTML = GCR_JS.formatCurrency(usedReward / 100.0);
      }
      $('total').innerHTML = GCR_JS.formatCurrency((shippingPrice + subtotal - usedReward) / 100.0);
    }
    
  };
}

GCR_JS.formatCurrency = function(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  num = Math.abs(num);
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+ ',' + num.substring(num.length-(4*i+3));
  return ('$' + num + '.' + cents);
}

GCR_JS.addHint = function(id, hint) {
  $(id).writeAttribute('hint', hint);
  if ($F(id) == '') {
    $(id).value = hint;
    $(id).addClassName('hint');
  }
  $(id).observe('focus', function(event){
    if ($F(id) == hint) {
      $(id).value = '';
    }
    $(id).removeClassName('hint');
  });
  $(id).observe('blur', function(event){
    if ($F(id) == '') {
      $(id).value = hint;
      $(id).addClassName('hint');
    }
  });
}
GCR_JS.cleanHint = function() {
  $$('input.hint').each(function(id){
    var hint = $(id).readAttribute('hint');
    if ($F(id) == hint) {
      $(id).value = '';
    }
  })
}

GCR_JS.ready = function() {
  var orders = []
  var recalculate = function() {
    var total = 0;
    for (var i = 0; i < orders.length; i++) {
      if (orders[i]['checkbox'].checked) {
        total = total + orders[i]['value'] * 1;
      }
    }
    $('ready_total').innerHTML = GCR_JS.formatCurrency(total);
  };
  $$('input.behaviour-follow').each(function(n) {
    var value = n.up('tr').down('td.behaviour-value').innerHTML.replace(',', '');
    orders.push({checkbox: n, value: value});
    n.observe('click', function(event) {
      recalculate();
    });
  });
  $('select_all').observe('click', function(event) {
    var value = (event.element().checked ? 1 : 0); 
    for (var i = 0; i < orders.length; i++) {
      orders[i]['checkbox'].checked = value;
    }
    recalculate();
  });
}

GCR_JS.formatCurrency = function(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  num = Math.abs(num);
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+ ',' + num.substring(num.length-(4*i+3));
  return ('$' + num + '.' + cents);
}

GCR_JS.merchantHabtm = function(ul) {
  
  var update = function(select) {
  };
  
  $(ul).select('select').each(function(s) {
    s.observe('change', function(event) {update(s);});
  });
}

GCR_JS.couponTarget = function() {
  $('coupon_target_all').observe('click', function(event) {
    $('merchants').addClassName('faded');
    $('merchants').select('input').each(function(n) {
      n.disabled = true;
    })
  });
  $('coupon_target_some').observe('click', function(event) {
    $('merchants').removeClassName('faded');
    $('merchants').select('input').each(function(n) {
      n.disabled = false;
    })
  });
}
GCR_JS.card_buying = function(card_id) {
  $('card_' + card_id).addClassName('buying');
}
GCR_JS.card_bought = function(card_id) {
  $('card_' + card_id).removeClassName('buying');
  $('card_' + card_id).addClassName('in-cart');
  $('card_' + card_id).down('.caption').innerHTML = "&nbsp;";
  $('cart-box').highlight();
}

GCR_JS.findSimilar = function(container) {
  $(container).observe('mouseover', function(event) {
    var td = event.findElement('td.find-similar');
    if (td) {
      $(container).select('.' + $w(td.className)[0]).each(function(n) {
        n.addClassName('highlight');
      });
    }
  });
  $(container).observe('mouseout', function(event) {
    var td = event.findElement('td.find-similar');
    if (td) {
      $(container).select('.' + $w(td.className)[0]).each(function(n) {
        n.removeClassName('highlight');
      });
    }
  });
}
GCR_JS.editablePages = function() {
  $$('.show-page').each(function(n) {
    var permalink = n.identify();
    var editLink = new Element('a', {className: 'edit', href: "/pages/" + permalink + "/edit?back=" + window.location.pathname}).insert('edit');
    n.insert({top: editLink});
    var timer = null;
    n.observe('mouseover', function(event) {
      n.addClassName('expose');
      clearTimeout(timer);
    });
    n.observe('mouseout', function(event) {
      clearTimeout(timer);
      timer = setTimeout(function() {n.removeClassName('expose');}, 200);
    });
  });
}

GCR_JS.auditNote = function(container, options) {
  var modelType = options.modelType;
  var modelId = options.modelId;
  var container = $(container);
  var modelLink = options.modelLink;
  var currentUserName = options.currentUserName;
  var textArea = container.down('textarea');
  container.down('form').hide();
  
  var closeUp = function() {
    container.down('a').show();
    container.down('form').hide();
    textArea.value = '';
  };
  
  return {
    add: function() {
      container.down('a').hide();
      container.down('form').show();
      setTimeout(function() {textArea.focus()}, 50);
    },
    
    create: function(a) {
      var audit = a.audit;
      closeUp();
      var tr = new Element('tr', {className: 'level-2 '});
      tr.insert(new Element('td', {className: 'id'}).insert(audit.id));
      tr.insert(new Element('td', {className: 'datetime'}).insert('<span class="date">' + GCR_JS.formatDate(audit.created_at) + '</span> <span class="time">' + GCR_JS.formatTime(audit.created_at) + '</span>'));
      tr.insert(new Element('td', {className: 'object'}).insert(modelLink));
      tr.insert(new Element('td', {className: 'action'}).insert('Note'));
      tr.insert(new Element('td', {className: 'comment'}).insert(audit.comment + ' - ' + currentUserName));
      container.up('tr').insert({after: tr});
    },
    
    cancel: function() {
      closeUp();
    },
    
    invalid: function(msg) {
      closeUp();
      alert(msg);
    }
  }
}

GCR_JS.formatDate = function(value) {
  return value.substring(8, 10) + '/' + value.substring(5, 7) + '/' + value.substring(2, 4);
}

GCR_JS.formatTime = function(value) {
  return value.substring(11, 16);  
}

GCR_JS.quickFilter = function(input, lists) {
  var lists = lists;
  var input = $(input)
  
  var filterList = function(container, text) {
    var stockOnly = container.down('input.stock-control').checked;
    container.select('.filterable').each(function(n) {
      var f = n.readAttribute('data-filter');
      if ((!stockOnly || !n.hasClassName('empty')) && new RegExp(text, 'i').exec(f)) {
        n.show();
      } else {
        n.hide();
      }
    });
  }
  
  var doBoth = function() {
    for (var i = 0; i < lists.length; i++) {
      var text = $F(input);
      var hint = input.readAttribute('hint');
      if (text == hint) {
        text = '';
      }
      filterList($(lists[i]), text);
    }
  }
  
  new Form.Element.Observer(input, 0.25, function(event) { doBoth() });
  
  return {
    trigger: function() {
      doBoth();
    }
  }
  
}

GCR_JS.watchCashSellButton = function() {
  
  var showTimeout = null;
  var hideTimeout = null;
  
  var showBalloon = function() {
    $('extra_with_amazon').show();
    $('sell_video_link').fade({to: 0.2, duration: 0});
  }
  
  var hideBalloon = function() {
    $('extra_with_amazon').hide();
    $('sell_video_link').appear({to: 1, duration: 0});
  }
  
  var mouse = function(target) {
    target.observe('mouseover', function() {
      clearTimeout(hideTimeout);
      showTimeout = setTimeout(function() { showBalloon() }, 100);
    });
    target.observe('mouseout', function() {
      clearTimeout(showTimeout);
      hideTimeout = setTimeout(function() { hideBalloon() }, 500);
    });
  }
  if ($('extra_with_amazon')) {
    mouse($('cash_sell_button'));
    $('cash_sell_button').select('span', function(n) {
      mouse(n);
    });
  }
}