Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;

function when(obj, fn) {
  if (Object.isString(obj)) obj = /^[\w-]+$/.test(obj) ? $(obj) : $(document.body).down(obj)
  if (Object.isArray(obj) && !obj.length) return
  if (obj) fn(obj)
}

function getNamedArguments(object){
  return $H(object).collect(function(item){
    return item.key+':'+item.value;
  }).join('/');
}

function parseNamedArguments(url){
  return $A(url.split('/')).findAll(function(piece){
    return piece.match(/\S+:\S+/);
  }).inject($H(), function(hash, piece){
    var pair = piece.split(':');
    hash.set(pair[0], pair[1]);
    return hash;
  });
}

(function(){
  function wheel(e){
    if(e.wheelDelta){
      delta = e.wheelDelta/120;
    }else if(e.detail){
      delta =- e.detail/3;
    }
    if(!delta){
      return;
    }
    var custom_event = Event.element(e).fire('mouse:wheel',{
      delta: delta
    });
    if(custom_event.stopped){
      Event.stop(e);
      return false;
    }
  }

  document.observe('mousewheel',wheel);
  document.observe('DOMMouseScroll',wheel);
})();

window.fbf = window.fbf||{};

fbf.Scrollbox = Class.create({
  initialize : function(wrapper, element){
    this.wrapper = $(wrapper).setStyle({'overflow':'hidden'});
    this.element = $(element).setStyle({'overflow':'hidden'});

    this.scrollbar = new Element('div', {className: 'scrollbar'});
    this.handle = new Element('div', {className: 'scrollbar-handle'}).update('<span class="t"></span><span class="b"></span>');
    this.scrollbarWrapper = new Element('div', {className : 'scrollbar-wrapper'});

    this.wrapper.insert(this.scrollbarWrapper.insert(this.scrollbar.insert(this.handle)));

    this.slider = new Control.Slider(this.handle, this.scrollbar, {
      axis : 'vertical',
      onChange : this.onChange.bind(this),
      onSlide : this.onChange.bind(this)
    });

    this.render();

    this.onMouseWheelListener = this.onMouseWheel.bindAsEventListener(this);
    this.wrapper.observe('mouse:wheel', this.onMouseWheelListener);

    this.up = new Element('a', {href: '#', className: 'up'}).update('Up');
    this.down = new Element('a', {href: '#', className: 'down'}).update('Down');

    this.scrollbarWrapper.insert(this.up);
    this.scrollbarWrapper.insert(this.down);

    this.up.observe('click', this.scrollUp.bindAsEventListener(this));
    this.down.observe('click', this.scrollDown.bindAsEventListener(this));

    var height = this.element.getHeight();
    var scrollHeight = this.element.scrollHeight;
    this.scrollAmount = height/scrollHeight;

    if(scrollHeight<=height){
      this.scrollbarWrapper.hide();
    }

    this.handle.observe('mouseenter', this.onMouseEnter.bindAsEventListener(this));
    this.handle.observe('mouseleave', this.onMouseLeave.bindAsEventListener(this));

  },
  onMouseEnter : function(){
    this.handle.addClassName('scrollbar-handle-hover');
  },
  onMouseLeave : function(){
    this.handle.removeClassName('scrollbar-handle-hover');
  },
  onMouseWheel : function(e){
    this.slider.setValueBy(-(e.memo.delta / 20));
    e.stop();
    return false;
  },
  onChange : function(value){
    this.element.scrollTop = Math.round(value/this.slider.maximum * (this.element.scrollHeight - this.element.offsetHeight));
  },
  render : function(){
    this.slider.trackLength = this.slider.maximumOffset() - this.slider.minimumOffset();
    var h = Math.max((this.scrollbar.offsetHeight * (this.element.offsetHeight / this.element.scrollHeight)), 30);
    if(!isNaN(h)){
      if(h >= this.element.offsetHeight){
        this.handle.hide();
      }else{
        this.handle.show();
        this.handle.style.height = h+'px';
        this.slider.handleLength = this.handle.style.height.replace(/px/,'');
      }
    }
  },
  scrollDown : function(e){
    this.slider.setValueBy(this.scrollAmount);
    e.stop();

  },
  scrollUp : function(e){
    this.slider.setValueBy(-this.scrollAmount);
    e.stop();
  }
});

fbf.FixDualViewModules = function(){
  $('content').select('div.dual-view').each(function(module){
    var headers = $A(module.getElementsByTagName('h2'));
    if(headers.length == 2) {
      // var heights = headers.invoke('getStyle', 'height');
      // var max = parseInt(heights.max(), 10);
      // for(var i=0; i<2; i++){
      //   headers[i].style.paddingTop = 15+max-parseInt(heights[i], 10)+'px'
      // }
    }
  });
}

fbf.Preload = function(url){
  var image = new Image();
  image.src = url;
};

fbf.SetupWideFaqModules = function() {
  var modules = $('content').select('.cols-2-wide .col1 .faq, .cols-2-left .col2 .faq, .cols-3 .col2 .faq');
  modules.each(function(module){
    var questions = $A(module.getElementsByTagName('dt'));
    questions.each(function(question){
      var answer = $(question).next();
      answer.hide();
      question.removeClassName('open');
      Event.observe(question, 'click', function() {
        questions.each(function(question){
          if (question.hasClassName('open')) {
            var answer = $(question).next();
            answer.hide();
            question.removeClassName('open');
          }
        });
        question.addClassName('open');
        answer.show();
      });
    })
  });
}

/**
 * fbf.Button
 **/

fbf.Button = function(){
  return {
    mouseenter : function(e){
      this.addClassName('hover');
    },
    mouseleave : function(e){
      this.removeClassName('hover');
    }
  }
}();

/**
 * fbf.VideoPlayer
 *
 * Controls Flash Video Player
 */

fbf.VideoPlayer = function(){
  return {
    update : function(name, url, movieName){
      var movie = this.getMovie(name);
      movie.playFile(url, movieName);
    },
    getMovie : function(name){
        if(navigator.appName.indexOf("Microsoft") != -1) {
            return window[name];
            return document.getElementById(name);
        }else {
            return document[name];
        }
    }
  }
}();

/**
 * fbf.QuoteSlider
 *
 * Get a quote slider
 */

fbf.QuoteTable = function(){
  var addHomeCollect,
  content,
  container,
  containerDims,
  currentAmount,
  d,
  dropdown,
  element,
  filters,
  minAmount,      // Minimum available loan amount (Integer)
  minAmountLabel, // Mininum available loan amount label (DOM Element)
  maxAmount,      // Maximum available loan amount (Integer)
  maxAmountLabel, // Maximum available loan amount label (DOM Element)
  params = $H(),
  slider,         // Slider (Instance of Control.Slider class)
  sliderThumb,    // Slider thumb (DOM Element)
  sliderTrack,    // Slider track (DOM Element)
  source,         // HTML select element with values for loan calculator (DOM Element)
  sourceSelect,
  resultsTable,
  tableOverlay,
  url = '/loan_applications/quote_results_09/',
  values; // Discrete values available for slider (Array of Integers)
  /**
   * fbf.QuoteSlider.build
   *
   * Builds quote slider.
   */
  function build(){

    var currencyFront = '';
    var currencyBack = CURRENCY;
    if (LOCALE == 'en-GB' || LOCALE == 'es-MX') {
      currencyFront = currencyBack;
      currencyBack = '';
    } else if (LOCALE == 'cs-CZ') {
      currencyBack = ' '+currencyBack;
    }

    var tooltipInner = '<div class="tooltip arrow-bottom"><div class="hd"><div class="tr"></div><div class="tl"></div><div class="t"><div></div></div></div><div class="bd"><div class="r"><div></div></div><div class="l"><div></div></div><div class="c"><div class="content"></div></div></div><div class="ft"><div class="br"></div><div class="bl"></div><div class="b"><div></div></div></div></div>';

    resultsTable = $('quotetable');
    sliderThumb = new Element('div', { 'class' : 'slider-thumb' }).update(tooltipInner);
    sliderTrack = new Element('div', { 'class' : 'slider-track' }).update(sliderThumb);
    content = sliderThumb.down('.content');

    minAmountLabel = new Element('span', { 'class' : 'min' }).update(currencyFront+getAmount(minAmount)+currencyBack);
    maxAmountLabel = new Element('span', { 'class' : 'max' }).update(currencyFront+getAmount(maxAmount)+currencyBack);

    element.insert(sliderTrack).insert(minAmountLabel).insert(maxAmountLabel);

    slider = new Control.Slider(sliderThumb, sliderTrack,{
      range : $R(minAmount, maxAmount),
      values : values,
      onSlide : function(value, slider){
        // Update tooltip for slider
        currentAmount = value;

        updateTooltip(currencyFront+getAmount(value)+currencyBack);
      },
      onChange : function(value, slider){
        // Submit AJAX request updating results
        params.set('LoanAmount', value);

        updateTooltip(currencyFront+getAmount(value)+currencyBack);
        container.fire('quote:change');
      },
      sliderValue : currentAmount
    });

    content.update(currencyFront+getAmount(currentAmount)+currencyBack);

    myTooltip1 = new Tooltip('filters-and-results', { 'className' : 'arrow-left' });  // tooltip with left side arrow for help text

    addListeners();
    addOverlay();

    params.set('LoanAmount', currentAmount);
    //processFilters();
    
    addHomeCollectToggle();
  }

  function addListeners(){
    filters = container.select('#filters input[type=radio]');
    filters.invoke('observe', 'click', onFilterClick);

    sortControls = container.select('div.sort-control a');
    sortControls.invoke('observe', 'click', onSortClick);

    container.observe('quote:change', updateLoanAmounts);
  }

  function addOverlay() {
    containerDims = container.getDimensions();

    loading = new Element('div', { 'class' : 'loading' });

    tableOverlay = new Element('div', { 'id' : 'table-overlay' }).setStyle({
      'height' : containerDims.height+'px',
      'opacity' : .75,
      'width' : containerDims.width+'px'
    }).update(loading).hide();

    container.insert(tableOverlay);
  }
  
  function addHomeCollectToggle(){
    // add special home collect functionality for Romania only
    if($$('body.ro-RO').length > 0){
      addHomeCollect = $('addHomeCollection').down('input');
      addHomeCollect.observe('click', toggleHomeCollect);
  }
  }
   
  function formatCzAmount(amount){
    var str = String(amount);
    var len = str.length;
    var _amount = "";

    for(i = len-1; i >= 0; i--){
      if((len - (i+1))%3 < 1){
        _amount = ' '+_amount;
      }
      _amount = str.charAt(i)+_amount;
    }

    return _amount;
  }

  function getAmount(amount){
    if(LOCALE == 'cs-CZ') {
      return formatCzAmount(amount);
    } else {
      return amount;
    }
  }

  function onFilterClick(e){
    element = e.findElement('input');
    processFilters(element);
    container.fire('quote:change');
  }

  function onSortClick(e){
    var el = e.findElement('a');
    e.stop();

    params.update(parseNamedArguments(el.href));

    container.fire('quote:change');
  }

  function processFilters(element){
    // filters.each(function(flt) {
       params.set("filters", element.value);
    // });


    //console.log(params);

    /*
    if(filters[0].checked) {
      params.set('filter', filters[0].value);
    } else if(filters[1].checked) {
      params.set('filter', filters[1].value);
    }

    if((filters[0].checked && filters[1].checked) || (!filters[0].checked && !filters[1].checked)) {
      params.unset('filter');
    }
    */
  }

  function renderLoanAmounts(t){
    var id = container.identify();
    container.stopObserving();
    container.descendants().invoke('stopObserving');
    container.select('div.help').invoke('stopObserving');
    container.select('div.sort-control a').invoke('stopObserving');
    container.up().update(t.responseText); // refresh table HTML
    container = $(id);

    resultsTable = $('quotetable');

    myTooltip1 = new Tooltip('filters-and-results', { 'className' : 'arrow-left' });  // tooltip with left side arrow for help text
    //myTooltip2 = new Tooltip('filters-and-results', { 'className' : 'arrow-bottom', 'selector' : '.loan-type .inner .inner-inner div' });  // tooltip with bottom arrow

    addListeners();
    addHomeCollectToggle();
    addOverlay();
  }

  function toggleHomeCollect(){
    if(addHomeCollect.checked){
      params.set("homeCollect", "true");
    }else{
      params.set("homeCollect", "false");
    }
    
    updateLoanAmounts();
  }
  
  function updateLoanAmounts(e){
    var targetUrl = url+getNamedArguments(params);

    new Ajax.Request(targetUrl, {
      'method' : 'get',
      onCreate : function() {
        tableOverlay.show();
      },
      onComplete : function() {
        tableOverlay.hide();
      },
      onSuccess : renderLoanAmounts
    });
  }

  function updateTooltip(value){
    // Tooltip loan amount is updated here.
    content.update(value);
  }

  /**
   * fbf.QuoteSlider.getValues
   *
   * Gets values from HTML select element, and calculates the min and max values of this range.
   */
  function getValues(){
    sourceSelect = dropdown.down('select');
    values = $A(sourceSelect.options).map(function(option, i){ return option.value ? parseInt(option.value, 10) : null; }).compact();

    currentAmount = sourceSelect.options[sourceSelect.selectedIndex].value;
    minAmount = values.min();
    maxAmount = values.max();
    dropdown.hide();
  }

  return {
    initialize : function(el, src, d){
      element = $(el);
      dropdown = $(src);
      container = $(d);
      getValues();
      build();
    }
  }
}();

fbf.HomeCharge = function(){
  var body, charge, overlay, popup, no, yes;

  function build(){
    overlay = new Element('div', {id: 'overlay', className: 'dark'}).hide();
    popup = $('home-charge-popup');
    charge = $('home-charge-charge');
    
    if(window.LOCALE=='ro-RO'){
      weeks = $('home-charge-weeks');
      weeklyPayment = $('home-charge-weekly-payment');
      total = $('home-charge-total');
    }
    
    yes = $('home-charge-yes');
    no = $('home-charge-no');

    body.insert(overlay);
    body.insert(popup);
  }

  function registerEvents(){
    body.observe('click', onClick);
  }

  function onClick(e){
    if(window.LOCALE=='ro-RO'){
      showRo(e);
    }else{
      show(e);
    }
  }
  
  function showRo(e) {
    var element;
    if(element = e.findElement('tr.homeCollectOption a.select-loan')){
      e.stop();
      var tableRow = element.up('tr');

      var url = element.href.split('/');
      var params = url[url.length-3]+'/'+url[url.length-2]+'/';


      weeklyPayment.update(tableRow.down('td.weekly-repayment .weekly-plus-hc').innerHTML);
      total.update(tableRow.down('td.total-amount .total-plus-hc').innerHTML);
      charge.update(tableRow.down('td.home-service .realValue').innerHTML);

      yes.href = '/loan_applications/select/'+params+'1';
      no.href = '/loan_applications/select/'+params+'0';

      popup.show();
      var height = Client.height();
      var dimensions = popup.getDimensions();

      var t = (height/2)-(dimensions.height/2)+Client.scrollTop()+'px';
      popup.style.top = t;


      var h = Math.max(body.getHeight(), document.viewport.getHeight());
      overlay.setStyle({
        height: h+'px'
      }).show();
    }
  }

  function show(e){

    var element;
    if(element = e.findElement('tr.homeCollectOption a.select-loan')){
      e.stop();
      
      var url = element.href.split('/');
      var params = url[url.length-3]+'/'+url[url.length-2]+'/';

      if(charge){
      charge.innerHTML = element.next('span.home-charge').innerHTML;
      }
      
      yes.href = '/loan_applications/select/'+params+'1';
      no.href = '/loan_applications/select/'+params+'2';

      popup.show();
      var height = Client.height();
      var dimensions = popup.getDimensions();

      var t = (height/2)-(dimensions.height/2)+Client.scrollTop()+'px';
      popup.style.top = t;


      var h = Math.max(body.getHeight(), document.viewport.getHeight());
      overlay.setStyle({
        height: h+'px'
      }).show();
    }
  }

  return {
    initialize : function(){
      body = $$('body').first();
      build();
      registerEvents();
    }
  }
}();

fbf.customerPinToggle = function(){
  function onClick(e) {
    selected = e.findElement('input');
    togglePinField(selected);
  }

  function togglePinField(selected) {
    if(!radios.indexOf(selected) || radios.indexOf(selected) == -1) { // the first option, ie. index 0 is selected
      loanAppPinContainer.hide();
    } else {
      loanAppPinContainer.show();
    }
  }

  var loanAppPin = $('LoanApplicationPin');
  var loanAppPinContainer = loanAppPin.up('div.input');
  radios = $('customer-status').select('input[type=radio]');

  togglePinField($('customer-status').down('input:checked'));
  radios.invoke('observe', 'click', onClick);
}

fbf.Faqs = function(){
  function toggleFaq(e){
    if(clicked = e.findElement('a.question')) {
      if(clicked.up('li').hasClassName('open')) {
        clicked.up('li').removeClassName('open');
        Effect.BlindUp(clicked.next('div.answer'), { duration: 0.4 });
      } else {
        clicked.up('li').addClassName('open');
        Effect.BlindDown(clicked.next('div.answer'), { duration: 0.4 });
      }
    }
  }

  return {
    initialize : function(){
      var faqList = $('faqs');
      faqList.select('div.answer').invoke('hide');
      faqList.observe('click', toggleFaq);
    }
  }
}();


/**
 * fbf.initialize
 *
 * Automatically invoked as soon as the DOM is ready.
 */

fbf.initialize = function(e){

  fbf.FixDualViewModules();
  fbf.SetupWideFaqModules();

  $$('.scrollbox').each(function(element){
    new fbf.Scrollbox(element, element.down('.scrollbox-content'));
  });

  if(Prototype.Browser.IE6){
    $$('button').each(function(button){
      var span = button.down();
      span.observe('mouseenter', fbf.Button.mouseenter);
      span.observe('mouseleave', fbf.Button.mouseleave);
    });
  }

  fbf.Preload('/img/site/layout/buttons/button-white-on.png');
  fbf.Preload('/img/site/layout/buttons/button-grey-on.png');
  fbf.Preload('/img/site/layout/buttons/button-red-on.png');

  /* Quote amount slider for loan results page */
  when('slider', fbf.QuoteTable.initialize.curry('slider', 'amount-select', 'filters-and-results'));

  /* tooltips for loan results page  */
  when('filters-and-results', function(){
    myTooltip1 = new Tooltip('filters-and-results', { 'className' : 'arrow-left' });  // tooltip with left side arrow for help text
    //myTooltip2 = new Tooltip('filters-and-results', { 'className' : 'arrow-bottom', 'selector' : '.loan-type .inner .inner-inner div' });  // tooltip with bottom arrow
  });


  when('quotetable', function(){
    fbf.HomeCharge.initialize();
  });

  when('faqs', function(){
    fbf.Faqs.initialize();
  });

  function print(el) {
    Event.observe($(el), 'click', function(e){
      Event.stop(e);
      Element.addClassName(document.body, 'print');
      window.print();
    });
  }

  when('print', function(){
   print('print');
  });

  when('print2', function(){
   print('print2');
  });

  when('footer_print_button', function(){
   print('footer_print_button');
  });

  // Toggles the LoanApplicationPin form field on or off depending on setting of customer_status field.
  // Slovakia only.
  when('.skSK #customer-status', fbf.customerPinToggle);
}

document.observe('dom:loaded', fbf.initialize);