OMINOR = {
  show_and_center : function(form, height){
    var my_width  = 0;
    var my_height = 0;
    
    if ( typeof( window.innerWidth ) == 'number' ){
      my_width  = window.innerWidth;
      my_height = window.innerHeight;
    }else if ( document.documentElement && 
      ( document.documentElement.clientWidth ||
      document.documentElement.clientHeight ) ){
      my_width  = document.documentElement.clientWidth;
      my_height = document.documentElement.clientHeight;
    }
    else if ( document.body && 
      ( document.body.clientWidth || document.body.clientHeight ) ){
      my_width  = document.body.clientWidth;
      my_height = document.body.clientHeight;
    }
    
    form.style.position = 'absolute';
    form.style.zIndex   = 99;
    
    var scrollY = 0;
    
    if ( document.documentElement && document.documentElement.scrollTop ){
      scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
      scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
      scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
      scrollY = window.scrollY;
    }
    
    var elementDimensions = Element.getDimensions(form);
    
    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;
    
    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;
    
    form.style.left = setX + "px";
    form.style.top  = setY + "px";
    form.style.width = '600px';
    form.style.height = height;
    form.style.background = '#fff';
    form.show();  
  }
}

OMINOR.InfoPopup = {
  setUpInfoPopup: function(popupParent) {
    $$('.icon_info').each(function(item) {
      var popup = item.next('.info_popup');
      if (popupParent)
        item = item.parentNode;
      Event.observe(item, 'mousemove', function() {
          popup.style.display = "block";
        });
      Event.observe(item, 'mouseout', function() {
          popup.style.display = "none";
        });
    });
  },
  showInfoPopup: function() {
    this.next('.info_popup').style.display = "block";
  },
  hideInfoPopup: function() {
    this.next('.info_popup').style.display = "none";
  }
}

OMINOR.FinancePopup = {
  setUpFinancePopup: function() {
    if ($('icon_finance') ) {
      Event.observe('icon_finance', 'mousemove', OMINOR.FinancePopup.showFinancePopup);
      Event.observe('icon_finance', 'mouseout', OMINOR.FinancePopup.hideFinancePopup);
    }
  },
  showFinancePopup: function() {
    $("finance_popup").style.display = "block";
  },
  hideFinancePopup: function() {
    $("finance_popup").style.display = "none";
  }
}

OMINOR.MiniBasket = {
  
  event_queue: { scope: 'mini_basket', position: 'end' },
  shown_item_ids: [],
  
  showDetails: function(){
    $('basket_details').visualEffect('blind_down',{duration:0.5, queue: OMINOR.MiniBasket.event_queue});
  },
  
  hideDetails: function(){
    $('basket_details').visualEffect('blind_up',{duration:0.5, queue: OMINOR.MiniBasket.event_queue});
  },
  
  showProductImage: function(item_id){
    var el = $('basket_image_'+item_id);
    // hide all the other images
    OMINOR.MiniBasket.shown_item_ids.without(item_id).each(function(item_id) {
      OMINOR.MiniBasket.hideProductImage(item_id);
    });
    el.visualEffect('appear',{duration:0,queue: OMINOR.MiniBasket.event_queue});
    if (OMINOR.MiniBasket.shown_item_ids.indexOf(item_id) == -1)
      OMINOR.MiniBasket.shown_item_ids[OMINOR.MiniBasket.shown_item_ids.length] = item_id;
  },
  
  hideProductImage: function(item_id){
    var el = $('basket_image_'+item_id);
    el.visualEffect('fade',{duration:0,queue: OMINOR.MiniBasket.event_queue});
  },
  
  changeDeliveryCountryLink: function() {
    var el = $('change_delivery_country');
    if (el && !el.readAttribute('href').match('delivery_address')) {
      Event.observe('change_delivery_country', 'click', OMINOR.DeliveryCountry.declarePopupEvent('delivery_country_dropdown'));
    }
  },
  
  setup: function() {
    OMINOR.MiniBasket.changeDeliveryCountryLink();
  }
}

OMINOR.ShowMore = {
  // constructor to attach "show more" link to button, allowing collapseable to be shown and hidden
  Attach: function(button, collapseable) {
            this.button = $(button);
            this.collapseable = $(collapseable);
            this.button.innerHTML = 'Show more...';
            this.expand = function(event) {
              this.o.collapseable.visualEffect('blind_down',{duration:0.25, queue:'end'});
              this.o.button.innerHTML = 'Show less...';
              Event.stopObserving(this.o.button);
              Event.observe(this.o.button, 'click', this.o.collapse);
            };
            this.collapse = function(event) {
              this.o.collapseable.visualEffect('blind_up', {duration:0.25, queue:'end'});
              this.o.button.innerHTML = 'Show more...';
              Event.stopObserving(this.o.button);
              Event.observe(this.o.button, 'click', this.o.expand);
            };
            this.button.o = this;
            Event.observe(this.button, 'click', this.expand);
            return this;
          }
};

OMINOR.Products = {
  onShow: function() { 
    OMINOR.DocumentTabs.hideTabs();
    OMINOR.DocumentTabs.showActiveTab(); 
  }
}

OMINOR.Brands = {
  onShowProduct: function() {
    OMINOR.Products.setUpSkuAttributes();
    //Product page can render under both products and brands controller.
  }
}

OMINOR.AvailabilityContactUs = {
  
  hideContactForm: function() {
    $('contact_form').hide();
    
    var thanx_para = document.createElement('p');
    var thanx_txt = document.createTextNode('Thank you for your enquiry, we will contact you shortly.');
    thanx_para.appendChild(thanx_txt);
    $('contact_form_container').appendChild(thanx_para);
    
    var close_link = document.createElement('a');
    close_link.setAttribute('href', '#');
    close_link.setAttribute('id', 'close_contact_us');
    close_link.onclick = OMINOR.AvailabilityContactUs.closeButton;
    var close_txt = document.createTextNode('Close this window');
    close_link.appendChild(close_txt);
    $('contact_form_container').appendChild(close_link);
  },
  
  closeButton: function() {
    $('availability_contact_form_container').hide();
  },
  
  show_and_center : function(){
    func = OMINOR.show_and_center;
    func($('availability_contact_form_container'), 'auto');
  }
}

OMINOR.EmailMeWhenInStock = {
  
  hideContactForm: function() {
    $('email_me_form').hide();
    
    var thanx_para = document.createElement('p');
    var thanx_txt = document.createTextNode('Thanks, we will email you when this product comes in to stock.');
    thanx_para.appendChild(thanx_txt);
    $('email_me_form_container').appendChild(thanx_para);
    
    var close_link = document.createElement('a');
    close_link.setAttribute('href', '#');
    close_link.setAttribute('id', 'close_email_me');
    close_link.onclick = OMINOR.EmailMeWhenInStock.closeButton;
    var close_txt = document.createTextNode('Close this window');
    close_link.appendChild(close_txt);
    $('email_me_form_container').appendChild(close_link);
  },
  
  closeButton: function() {
    $('email_me_when_in_stock_form_container').hide();
  },
  
  show_and_center :function() {
    func = OMINOR.show_and_center;
    func($('email_me_when_in_stock_form_container'), '235px');
  }
  
}

OMINOR.Tabs = {}

OMINOR.Tabs.Delivery = {
  
  setupDelivery: function() {
    $('tab_delivery_info').className = "active";    
    $('ship_2_store').hide();
  },

  setupShipToStore: function() {
    $('tab_ship_2_store').className = "active";    
    $('delivery_info').hide();
  },

  setup: function() {
    $('uk').hide();
    $('international').hide();
    $('channel_islands_and_isle_of_man').hide();
    Event.observe('tab_delivery_info', 'click', OMINOR.Tabs.Delivery.tab_clicked);
    Event.observe('tab_uk', 'click', OMINOR.Tabs.Delivery.tab_clicked);
    Event.observe('tab_international', 'click', OMINOR.Tabs.Delivery.tab_clicked);
    Event.observe('tab_ship_2_store', 'click', OMINOR.Tabs.Delivery.tab_clicked);
    Event.observe('tab_channel_islands_and_isle_of_man', 'click', OMINOR.Tabs.Delivery.tab_clicked);
    $('uk_link_extra').hide();
    $('international_link_extra').hide();
    $('ship_2_store_link_extra').hide();
    $('channel_islands_and_isle_of_man_link_extra').hide();
    $('uk_link_hide').hide();
    $('international_link_hide').hide();
    $('ship_2_store_link_hide').hide();
    $('channel_islands_and_isle_of_man_link_hide').hide();
    Event.observe('uk_link_show', 'click', OMINOR.Tabs.Delivery.extra_show);
    Event.observe('uk_link_hide', 'click', OMINOR.Tabs.Delivery.extra_hide);
    Event.observe('international_link_show', 'click', OMINOR.Tabs.Delivery.extra_show);
    Event.observe('international_link_hide', 'click', OMINOR.Tabs.Delivery.extra_hide);
    Event.observe('ship_2_store_link_show', 'click', OMINOR.Tabs.Delivery.extra_show);
    Event.observe('ship_2_store_link_hide', 'click', OMINOR.Tabs.Delivery.extra_hide);
    Event.observe('channel_islands_and_isle_of_man_link_show', 'click', OMINOR.Tabs.Delivery.extra_show);
    Event.observe('channel_islands_and_isle_of_man_link_hide', 'click', OMINOR.Tabs.Delivery.extra_hide);
  },
  
  tab_clicked: function()  {
    $$("#delivery_info_tabs li").each (
      function(e) {
        e.removeClassName("active");
      }
    );
    $(this.id).className = "active";

    element_id = this.id.gsub("tab_", "");
    
    $$(".delivery_info_box").each (
      function(value, index) {
        value.hide();
      }
    );
    $(element_id).show();
  },

  extra_show: function()  {
    element_id = this.id.gsub("_show", "");
    $(element_id + "_extra").visualEffect('blind_down',{duration:0.5});
    $(element_id + "_show").hide();
    $(element_id + "_hide").show();
  },

  extra_hide: function()  {
    element_id = this.id.gsub("_hide", "");
    $(element_id + "_extra").visualEffect('blind_up',{duration:0.5});
    $(element_id + "_hide").hide();
    $(element_id + "_show").show();
  }

}

OMINOR.PaymentAddresses = {  
  onIndex: function() { 
    OMINOR.Tabs.Delivery.setup();
    OMINOR.Tabs.Delivery.setupDelivery();
  }
}

OMINOR.BasketShipToStore = {
  onShow: function() {
    OMINOR.Tabs.Delivery.setup();
    OMINOR.Tabs.Delivery.setupShipToStore();
  }
}

OMINOR.Payments = {
  formSubmitted: false,
    
  disablePaymentForm: function() {
    if(OMINOR.Payments.formSubmitted == false){
      $('payment_form').submit();
      OMINOR.Payments.formSubmitted = true;
    }
  },
  
  payByCard: function(radio_button) {
    if (radio_button.checked == true) {
      OMINOR.Payments.cardFields().each(function(el) {
        el.disabled = false;
      });
    }
  },
  
  payByPayPal: function(radio_button) {
    if (radio_button.checked == true) {
      OMINOR.Payments.cardFields().each(function(el) {
        el.disabled = true;
      });
    }
  },
  
  cardFields: function() {
    return $('payment_form').select('input[type="text"], select');
  }
  
}

OMINOR.Baskets = {
  update_delay: 800,
  basket_update_callback: null,
  current_qty_box: null,
  update_auth_token: null,
  
  onShow: function() {
    //attach listeners to quantity plus buttons.
    $$(".inc_qty_btn").each(
      function(increase_quantity_image) {
        increase_quantity_image.observe('click', OMINOR.Baskets.increase_quantity);
        increase_quantity_image.style.visibility = 'visible';
      }
    );
    
    //attach listeners to quantity minus buttons.
    $$(".dec_qty_btn").each(
      function(decrease_quantity_image) {
        decrease_quantity_image.observe('click', OMINOR.Baskets.decrease_quantity);
        decrease_quantity_image.style.visibility = 'visible';
      }
    );
    
    //attach listeners to qty input field when focus is lost
    $$(".qty_box").each(
      function(adjust_quantity_box) {
        adjust_quantity_box.observe('change', OMINOR.Baskets.update_qty_text_box);
      }
    );
    
    OMINOR.MiniBasket.changeDeliveryCountryLink();
    OMINOR.Tabs.Delivery.setup();
    OMINOR.Tabs.Delivery.setupDelivery();
    OMINOR.InfoPopup.setUpInfoPopup();
  },
  
  //increase value in text box and submit ajax update request
  increase_quantity: function() {
    OMINOR.Baskets.current_qty_box = this.previousSibling;
    OMINOR.Baskets.current_qty_box.value++;
    OMINOR.Baskets.update_basket();
  },
  
  //decrease value in text box and submit ajax update request
  decrease_quantity: function() {
    OMINOR.Baskets.current_qty_box = this.nextSibling;
    OMINOR.Baskets.current_qty_box.value--;
    OMINOR.Baskets.update_basket();
  },
  
  //cancel callback and show the update_basket button.
  update_qty_text_box: function() {
    OMINOR.Baskets.current_qty_box = this;
    OMINOR.Baskets.update_basket();
  },
  
  //setup a callback to submit the form, (clear the existing one if present) (which means we wait between clicks)
  update_basket: function() {
    OMINOR.Baskets.clear_update_callback_method_if_it_exists();
    OMINOR.Baskets.basket_update_callback = setTimeout(OMINOR.Baskets.send_form, OMINOR.Baskets.update_delay);
  },
  
  clear_update_callback_method_if_it_exists: function() {
    if (OMINOR.Baskets.basket_update_callback) {
      clearTimeout(OMINOR.Baskets.basket_update_callback);
    }
  },
  
  send_form: function() {
    qty_box = OMINOR.Baskets.current_qty_box
    
    if (qty_box.value == null || qty_box.value <= 0 || qty_box.value == '') {
      if (confirm('Remove this item?') ) {
        qty_box.value = 0;
      } else {
        qty_box.value = 1;
      }
    }
    new Ajax.Request('/basket', {asynchronous:true, evalScripts:true, parameters:Form.serialize($("basket_form")) + '&amp;authenticity_token=' + encodeURIComponent(OMINOR.Baskets.update_auth_token)});
  }
};

OMINOR.Shops = {

};

OMINOR.StoreLocator = {
  
  directions: null,
  store_map: null,
  three_nearest_bounds: null,
  all_shops_bounds: null,
  store_icon: null,
  origin: null,
  
  handleDirectionsErrors: function(){
    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
      alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
      alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_KEY)
      alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
      alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
    else alert("An unknown error occurred.");
  },
  
  onDirectionsLoad: function(){
    //unused callback function
  },
  
  centreMapOn: function(bounds){
    if (OMINOR.StoreLocator.directions) {
      OMINOR.StoreLocator.directions.clear();
    }
    OMINOR.StoreLocator.store_map.setCenter(
      bounds.getCenter(),
      OMINOR.StoreLocator.store_map.getBoundsZoomLevel(bounds)
    );
  },
  
  centreOnThreeNearest: function(){
    OMINOR.StoreLocator.centreMapOn(OMINOR.StoreLocator.three_nearest_bounds);
  },
        
  centreOnAllStores: function(){
    OMINOR.StoreLocator.centreMapOn(OMINOR.StoreLocator.all_shops_bounds);
  },
  
  setupStoreIcon: function(){
    OMINOR.StoreLocator.store_icon = new GIcon();
    OMINOR.StoreLocator.store_icon.iconAnchor = new GPoint(20, 20);
    OMINOR.StoreLocator.store_icon.infoWindowAnchor = new GPoint(20, 0);
    OMINOR.StoreLocator.store_icon.iconSize = new GSize(20, 20);
    OMINOR.StoreLocator.store_icon.image = '/images/layout/icon_store.gif'
  },
  
  setupMap: function(){
    OMINOR.StoreLocator.store_map = new GMap2(document.getElementById("map_canvas"));
    OMINOR.StoreLocator.store_map.addControl(new GSmallMapControl());
    OMINOR.StoreLocator.setupStoreIcon();
  },
  
  setupDirections: function(){
    OMINOR.StoreLocator.directions = new GDirections(OMINOR.StoreLocator.store_map,$('directions_pannel'));
    GEvent.addListener(OMINOR.StoreLocator.directions, 'load', OMINOR.StoreLocator.onDirectionsLoad);
    GEvent.addListener(OMINOR.StoreLocator.directions, "error", OMINOR.StoreLocator.handleDirectionsErrors);
  },
  
  setOrigin: function(lat,lng){
    OMINOR.StoreLocator.origin = new GLatLng(lat,lng);
  },
  
  directionsToPoint: function(destination_point){
    OMINOR.StoreLocator.directions.clear();
    OMINOR.StoreLocator.directions.loadFromWaypoints([OMINOR.StoreLocator.origin, destination_point], { locale: 'en_GB'});
  }
}

OMINOR.Ride2WorkCalculator = {
  form_changed: true,
  with_vat: true,
  changing_vat: false,
  
  clear: function(element) {
    $(element).clear();
    OMINOR.Ride2WorkCalculator.calculate();
  },
  calculate: function(){  
      
    if(OMINOR.Ride2WorkCalculator.formIsValid()){
      OMINOR.Ride2WorkCalculator.form_changed = true;
      $('cost_including_vat').value = OMINOR.Ride2WorkCalculator.itemsRetailCost();
      if (OMINOR.Ride2WorkCalculator.with_vat) {
        $('cost_excluding_vat').value = OMINOR.Ride2WorkCalculator.itemsRetailCostExcludingVat();
      }
      $('monthly_salary_sacrifice').value = OMINOR.Ride2WorkCalculator.monthlySalarySacrifice();
      $('income_tax_saving').value = OMINOR.Ride2WorkCalculator.incomeTaxSaving();
      $('national_insurance_saving').value = OMINOR.Ride2WorkCalculator.nationalInsuranceSaving();
      $('vat_saving').value = OMINOR.Ride2WorkCalculator.vatSaving();
      $('total_saving').value = OMINOR.Ride2WorkCalculator.totalSaving();
      $('total_cost').value = OMINOR.Ride2WorkCalculator.totalCost();
      $('effective_monthly_cost').value = OMINOR.Ride2WorkCalculator.effectiveMonthlyCost();
      $('percentage_saving_via_ride_to_work').value = OMINOR.Ride2WorkCalculator.percentageSavingViaRideToWork();
    }else{
      $('cost_including_vat').value = '';
      $('cost_excluding_vat').value = '';
      $('monthly_salary_sacrifice').value = '';
      $('income_tax_saving').value = '';
      $('national_insurance_saving').value = '';
      $('vat_saving').value = '';
      $('total_saving').value = '';
      $('total_cost').value = '';
      $('effective_monthly_cost').value = '';
      $('percentage_saving_via_ride_to_work').value = '';
      if(OMINOR.Ride2WorkCalculator.form_changed){
        OMINOR.Ride2WorkCalculator.form_changed = false;
      }
    }
  },
  
  formIsValid: function(){
    var cost_of_bike_overflow_el = $('cost_of_bike_overflow');
    var cost_of_bike_el = $('cost_of_bike');
    cost_of_bike_overflow_el.innerHTML = '';
    cost_of_bike_overflow_el.style.display = 'none';
    cost_of_bike_el.className = '';
    if (OMINOR.Ride2WorkCalculator.changing_vat) {
      return true;
    }
    ['annual_salary','cost_of_bike'].each(function(field_name){
      if((($(field_name).value != parseFloat($(field_name).value)) || ($(field_name).value < 0)) && $(field_name).value != ''){
        return false;
      }
    });
    var cost_of_bike = parseFloat(cost_of_bike_el.value);
    if (cost_of_bike > 1000) {
      cost_of_bike_el.className = 'warning';
      cost_of_bike_overflow_el.innerHTML = "<small>Cost of bike and accessories cannot exceed the value of £1,000</small>"
      cost_of_bike_overflow_el.style.display = 'block';
      return false;
    }
    return true;
  },
  
  vatChange: function() {
    changing_vat = true;
    if ($('without_vat').checked) { 
      OMINOR.Ride2WorkCalculator.with_vat = false;
    } else {
      OMINOR.Ride2WorkCalculator.with_vat = true;
    }
    if (OMINOR.Ride2WorkCalculator.with_vat) {
      $('total_vat_saving_row').show();
    } else {
      $('total_vat_saving_row').hide();
    }
    OMINOR.Ride2WorkCalculator.calculate();
    changing_vat = false;
  },
  
  effectiveMonthlyCost: function(){
    effective_monthly_cost = OMINOR.Ride2WorkCalculator.totalCost()/12;
    return Math.round(effective_monthly_cost*100)/100;
  },
  
  totalCost: function(){
    total_cost =  OMINOR.Ride2WorkCalculator.itemsRetailCost() - OMINOR.Ride2WorkCalculator.totalSaving(); 
    return Math.round(total_cost*100)/100;
  },
  
  totalSaving: function(){
    total_saving = OMINOR.Ride2WorkCalculator.incomeTaxSaving() + OMINOR.Ride2WorkCalculator.nationalInsuranceSaving();
    if (OMINOR.Ride2WorkCalculator.with_vat) {
      total_saving += OMINOR.Ride2WorkCalculator.vatSaving();
    }
    return Math.round(total_saving*100)/100;
  },
  
  itemsRetailCost: function(){
    var total = 0.0;
    fields = ['cost_of_bike'];
    fields.each(function(i){
        var value = parseFloat($(i).value);
        if(!isNaN(value)){
          total += value;
        }
    })
    return Math.round(total*100)/100;
  },
  
  itemsRetailCostExcludingVat: function(){
    var cost_excluding_vat = OMINOR.Ride2WorkCalculator.itemsRetailCost() - OMINOR.Ride2WorkCalculator.vatSaving();
    return OMINOR.Ride2WorkCalculator.roundToTwoDecimalPlaces(cost_excluding_vat);
  },
  
  vatSaving: function(){
    var cost_of_bike        = parseFloat($('cost_of_bike').value) || 0.0;
    var total_cost          = cost_of_bike;
    var vat_exclusive_cost  = (total_cost)/1.175;
    var vat_saving          = total_cost - vat_exclusive_cost
    return OMINOR.Ride2WorkCalculator.roundToTwoDecimalPlaces(vat_saving);
  },
  
  monthlySalarySacrifice: function(){
    if (OMINOR.Ride2WorkCalculator.with_vat) {
      var monthly_salary_sacrific = OMINOR.Ride2WorkCalculator.itemsRetailCostExcludingVat() / 12;
    } else {
      var monthly_salary_sacrific = OMINOR.Ride2WorkCalculator.itemsRetailCost() / 12;
    }
    return Math.round(monthly_salary_sacrific*100)/100;
  },
  
  incomeTaxSaving: function(){
    var base_rate = 37400;
    if (OMINOR.Ride2WorkCalculator.with_vat) {
      var cost_excluding_vat = OMINOR.Ride2WorkCalculator.itemsRetailCostExcludingVat();
    } else {
      var cost_excluding_vat = OMINOR.Ride2WorkCalculator.itemsRetailCost();
    } 
    var annual_salary = $('annual_salary').value;
    var tax_free_allowance = 6475;
    var saving = 0;
    
    if(annual_salary <= tax_free_allowance){
      return 0;
    }
    
    if(annual_salary >= base_rate){
      if((annual_salary - base_rate) >= cost_excluding_vat){
        saving = cost_excluding_vat * 0.4;
        return Math.round(saving*100)/100;
      }else{
        saving = ((annual_salary - base_rate)*0.4) + ((cost_excluding_vat - (annual_salary - base_rate))*0.2);
        return Math.round(saving*100)/100;
      }
    }else{
      if((annual_salary - tax_free_allowance) >= cost_excluding_vat){
        saving = cost_excluding_vat * 0.2
        return Math.round(saving*100)/100;
      }else{
        saving = ((annual_salary - tax_free_allowance)*0.2)+((cost_excluding_vat-(annual_salary - tax_free_allowance))*0)
        return Math.round(saving*100)/100;
      }
    }
  },
  
  nationalInsuranceSaving: function(){
    var annual_salary = $('annual_salary').value;
    var primary_threshold = 4940;
    var upper_earning_limit = 43888;
    if (OMINOR.Ride2WorkCalculator.with_vat) {
      var cost_excluding_vat = OMINOR.Ride2WorkCalculator.itemsRetailCostExcludingVat();
    } else {
      var cost_excluding_vat = OMINOR.Ride2WorkCalculator.itemsRetailCost();
    }
    var saving = 0;
    
    if(annual_salary <= primary_threshold){
      return 0;
    }
    
    
    if(annual_salary >= upper_earning_limit){
      if((annual_salary - upper_earning_limit) >= cost_excluding_vat){
        saving = cost_excluding_vat*0.01
        return Math.round(saving*100)/100;
      }else{
        saving = ((annual_salary - upper_earning_limit)*0.01) + ((cost_excluding_vat - (annual_salary - upper_earning_limit))*0.11)
        return Math.round(saving*100)/100;
      }
    }else{
      if((annual_salary - primary_threshold) >= cost_excluding_vat){
        saving = cost_excluding_vat*0.11;
        return Math.round(saving*100)/100;
      }else{
        saving = ((annual_salary - primary_threshold)*0.11)+((cost_excluding_vat-(annual_salary - primary_threshold))*0)
        return Math.round(saving*100)/100;
      }
    }
  },
  
  percentageSavingViaRideToWork: function(){ with(this){
    percentage = (OMINOR.Ride2WorkCalculator.totalSaving() / OMINOR.Ride2WorkCalculator.itemsRetailCost()) * 100;
    return Math.round(percentage) || "-";
  }},
  
  roundToTwoDecimalPlaces: function(value){
    if(isNaN(value)){
      return 0;
    }
    return Math.round(value*100)/100;
  }
}

OMINOR.StockPopup = {
    enable: function(id) {
      var link = $(id).select('p.stock_info').first();
      Event.observe(link, 'mousemove', function(event) {
          OMINOR.StockPopup.current_window = id;
          OMINOR.StockPopup.show(event, id + '_popup');
        });
      Event.observe(link, 'mouseout', function(event) {
      OMINOR.StockPopup.hide(id + '_popup');
      });
      
    },
    // event handler to show the popup
    show: function(event, id) {
      $(id).className = 'stock_info_popup show';
      $(id).style.position = 'absolute';
      $(id).style.top = Event.pointerY(event)+10 + 'px';
    $(id).style.left = Event.pointerX(event)+10 + 'px';
    },
    hide: function(id) {
      $(id).className = 'stock_info_popup hide';
    }
}

OMINOR.SearchResults = {
  
  event_queue: { scope: 'search_result', position: 'end' },
  
  reveal: function(link, element, show_element) {
    link.style.display = 'none';
    $(element).visualEffect('blind_down',{duration:0.5, queue: OMINOR.SearchResults.event_queue});
    if (show_element != null) { Element.show(show_element) }
    return false;
  },
  collapse: function(link, element, show_element) {
    link.style.display = 'none';
    $(element).visualEffect('blind_up',{duration:0.5, queue: OMINOR.SearchResults.event_queue});
    if (show_element != null) { Element.show(show_element) }
    return false;
  },
  replace: function(link, new_link_element, show_content_element, hide_content_element) {
    $(link).style.display = 'none';
    var el;
    if (el = $(new_link_element)) el.show();
    if (el = $(show_content_element)) el.visualEffect('blind_up', { duration: 0.5, queue: OMINOR.SearchResults.event_queue });
    if (el = $(hide_content_element)) el.visualEffect('blind_down', { duraction: 0.5, queue: OMINOR.SearchResults.event_queue });
    return false;
  }
};

var notice_counter = 0;
OMINOR.Notification = {
  notice: function (notice_title, notice_message, target_element_id, link_to_checkout) {
    notice_counter++;
    var box = document.createElement('div');
    var box_id = 'notice' + notice_counter;
    box.setAttribute('id', box_id);
    box.className = 'notice_notification_box';

    OMINOR.Notification.add_close_button(box, target_element_id);

    var box_title = document.createElement('h3');
    box_title.appendChild(document.createTextNode(notice_title));
    box.appendChild(box_title);

    var box_message = document.createElement('p');
    box_message.appendChild(document.createTextNode(notice_message));
    box.appendChild(box_message);
    
    if (link_to_checkout != undefined) {
      OMINOR.Notification.add_view_basket_link(box);
    }
    
    document.getElementById(target_element_id).appendChild(box);
    setTimeout('OMINOR.Notification.destroy(\'' + box_id + '\', \'' + target_element_id + '\')', 8000);
  },
  
  destroy: function(box_id, target_element_id) {
    var box = document.getElementById(box_id);
    if(box) {
      document.getElementById(target_element_id).removeChild(box);
    }
  },
  
  add_close_button: function(box, target_element_id) {
    var div = document.createElement('div');
    div.className = 'close_notification_box_link';
    
    var a = document.createElement('a');
    a.setAttribute('href', 'javascript:void(0);');
    a.onclick = function() { 
      OMINOR.Notification.destroy(this.parentNode.parentNode.getAttribute('id'), target_element_id); 
    }
    a.appendChild(document.createTextNode('[x]'));
    div.appendChild(a);
    
    box.appendChild(div);
  },
  
  add_view_basket_link: function(box) {
    img = document.createElement('img');
    img.src = "/images/buttons/mini_basket_view_basket_red.jpg";
    img.setAttribute('alt', 'View Basket');
    var a = document.createElement('a');
    a.setAttribute('href', '/basket');
    a.setAttribute('id', 'popup_view_basket');
    a.appendChild(img)
    box.appendChild(a);
  }
};

OMINOR.RedeyeTracking = {
  callTrackingTag: function(url) {
    new Ajax.Request(url, { 
      method:'get',
      onComplete: function(response) {
        if (200 == response.status) {
          $(document.body).insert(response.responseText);
        }
      } 
    });
  }
};

OMINOR.DocumentTabs = {
  document_tabs: ['features_tab', 'reviews_tab', 'awards_tab', 'guides_tab', 'sizing_tab', 'downloads_tab', 'answers_tab'],
  
  triggerTab: function(anchor_override) {
    OMINOR.DocumentTabs.hideTabs(anchor_override);
    OMINOR.DocumentTabs.showActiveTab(anchor_override);
  },
  
  hideTabs: function(anchor_override) {
    var anchor = OMINOR.DocumentTabs.getAnchor();
    (anchor == null && anchor_override == null) ? exclusion = ':not(#features_tab)' : exclusion = '';
    $$('#tab_product_details .tab_content' + exclusion).each(function(el) {
      el.hide();
    });
  },
  
  showActiveTab: function(anchor_override) {
    if (anchor_override == null) {
      var anchor = OMINOR.DocumentTabs.getAnchor();
    } else {
      var anchor = anchor_override;
    }
    var selector  = anchor + '_tab';
    el = $(selector);
    if (el != null) {
      el.show();
      OMINOR.DocumentTabs.updateImages(anchor);
    }
    OMINOR.DocumentTabs.updateURL(anchor);
  },
  
  updateImages: function(anchor) {
    $$('img.document_link').each(function(el) {
      var id = el.identify().split('_')[0];
      if (anchor && anchor == id) {
        el.src = '/images/tabs/' + id + '_active.gif';
      } else {
        el.src = '/images/tabs/' + id + '.gif';
      }
    });
  },
  
  getURLString: function() {
   return window.location.toString(); 
  },
  
  getAnchor: function() {
    var page_url = OMINOR.DocumentTabs.getURLString();
    anchor = page_url.split('#')[1];
    if (anchor && !anchor.match('show')) { // cater for EvansZoomer appending #show to URL
      return anchor;
    } else {
      return null;
    }
  },
  
  getURL: function() {
    var page_url = OMINOR.DocumentTabs.getURLString();
    return page_url.split('#')[0];
  },
  
  updateURL: function(new_anchor) {
    var current_anchor = OMINOR.DocumentTabs.getAnchor();
    if (current_anchor != new_anchor) {
      window.location = OMINOR.DocumentTabs.getURL() + '#' + new_anchor;
    }
  },
  
  setupReadReviewsListener: function() {
    if ($('product_detail_banner')) { // only run when on product detail page
      // wait until BV 'Read reviews' link loads
      // then attach click listener for activating reviews tab
      review_timer = setTimeout(function() {
        if ($('BVRRRatingSummaryLinkReadID')) {
          Event.observe('BVRRRatingSummaryLinkReadID', 'click', function() {
            if($('features_tab')) {
              $('features_tab').hide();
            }
            
            OMINOR.DocumentTabs.showActiveTab('reviews');
          });
          clearTimeout(review_timer);
        }
      }, 500);
    }
  }
  
};

OMINOR.ProductComparison = {
  element_present: function(product_id)
  {
    var link_id = 'compare_link_container_'+product_id
    var link_container = document.getElementById(link_id)
    if(link_container) {
      return true;
    } else {
      return false;
    }
  },
  
  scrollToBox: function() {
    // set offset to 20 pixels above element so popup bubble is visible
    var offset = (document.getElementById('mini_comparison_table').offsetTop - 20);
    scroll(0,offset);
  }
};

OMINOR.AdminUsers = {
  check_all: function(label, id) {
    $$('input.' + label + '_' + id).each(function(s) { s.checked = true;})
  },
  un_check_all: function(label, id) {
    $$('input.' + label + '_' + id).each(function(s) { s.checked = false;})
  } 
}

OMINOR.ToggleContent = function(link_id, content_id, off_text, on_text) {
  var link = document.getElementById(link_id);
  if (link.innerHTML == off_text) {
    link.innerHTML = on_text;
  } else {
    link.innerHTML = off_text;
    $(content_id).remove();
  }
}

Event.observe(window, 'load', function() { 
  OMINOR.DocumentTabs.hideTabs();
  OMINOR.DocumentTabs.showActiveTab();
  OMINOR.DocumentTabs.setupReadReviewsListener();
});

