var premium_map_cover = null;

function over50scover()
{
  $$('#over_50s_options input[type!=radio], #over_50s_options select, #premium-cover-display select').each(function (element) {
    element.observe('change', function (event) {
      if (event.element().id != 'quote_premium' && event.element().id != 'quote_cover')
      {
        calculateOver50s();
      }
      else if (event.element().id == 'quote_premium')
      {
        $('premium-display').innerHTML = Math.formatNumber(premium_map_cover.get(event.element().value),{decimals:0, currency:true, currencySymbol:'&pound;'});
      }
    })
  });
  $$('#over_50s_options input[type=radio]').each(function (element) {
    element.observe('click', function (event) {
      if (event.element().id != 'quote_premium' && event.element().id != 'quote_cover')
      {
        calculateOver50s();
      }
      else if (event.element().id == 'quote_premium')
      {
        $('premium-display').innerHTML = Math.formatNumber(premium_map_cover.get(event.element().value),{decimals:0, currency:true, currencySymbol:'&pound;'});
      }
    })
  });
  calculateOver50s();
}

function calculateOver50s()
{
  new Ajax.Request('/ajax/over-50s-insurance-quote',
  {
    method:'post',
    onSuccess: function (transport)
    {
      var json = transport.responseJSON;
      premium_map_cover = $H(json.premium_map_cover);
      //$('quote_cover').populate(json.cover_options, true);
      //$('quote_premium').populate(json.premium_options, true);
      if ($F('quote_premium') != '')
      {
        $('premium-display').innerHTML = Math.formatNumber(premium_map_cover.get($F('quote_premium')),{decimals:0, currency:true, currencySymbol:'&pound;'});
      }
    },
    parameters:Form.serialize('over_50s_form')
  });
}


var opened = null;

function clickInfo(id,box_id)
{
  if(opened != null)
  {
    closeInfo(opened);
  }
  opened = box_id;
  
  var box_element = $(box_id);
  var position = $(id).cumulativeOffset();
  position = position[1];
  
  var parent = $('content-wrap3');
  var right_div = $('right_editable');
  
  var top_minimum = right_div.cumulativeOffset();
  var top_minimum = top_minimum[1] + right_div.getHeight();
  
  var bottom_max = parent.cumulativeOffset();
  var bottom_max = parent.getHeight() + bottom_max[1];

  if(position + box_element.getHeight() > bottom_max)
  {
    position = bottom_max - box_element.getHeight();
  }
  else if(position < top_minimum)
  {
    position = top_minimum;
  }
  
  box_element.style.display = 'block';
  box_element.style.top = position + 'px';
  
  return false;
}

function closeInfo(box_id)
{
  $(box_id).style.display = 'none';
}

function chooseOther(el,id)
{
  if(el.value=='other')
  {
    el.selectedIndex = 1;
    $(id).enable();
    $(id).removeClassName('disabled');
    $(id).focus();
  }
  else
  {
    $(id).value = '';
    $(id).disable();
    $(id).addClassName('disabled');
  }
}

function showDIV(id)
{
  $(id).style.display = 'block';
}

function hideDIV(id)
{
  $(id).style.display = 'none';
}

function callMeNow(button)
{
  if($('call-me-now')&&button)
  {
    //Set up alt right column
    var height = $('right-col').getHeight();
    $('right-col-alternative').style.height = height + 'px';
    $('right-col').style.display = 'none';
    $('right-col-alternative').style.display = 'block';
    
    //Look for button on the left column
    var button_on_left = false;
    $$('div#left-col .' + button.className).each(
      function (element) {
      button_on_left = true;
      }
    );
    
    //Only perform positioning if button on left column
    if(button_on_left)
    {
      //Position call-me-now button
      var left_x = $('left-col').cumulativeOffset(); left_x = left_x[1];
      var button_x = button.cumulativeOffset(); button_x = button_x[1];
      var box_height = $('call-me-now').getHeight();
      var box_margin = ((button_x - left_x)-box_height/2);
      if(box_margin + box_height > $('left-col').getHeight())
      {
        box_margin = $('left-col').getHeight() - box_height;
      }
      $('call-me-now').style.margin = box_margin + 'px 0 0 0';
    }
    
    $('call_name').focus();
    
    return false;
  }
  return true;
}

function hasMortgage()
{
  if($('has_mortgage_yes').checked)
  {
    $('tr_mortgage_repayment').show();
  }
  else
  {
    $('tr_mortgage_repayment').hide();
  }
}

function prepareSurveyQuestionLogic()
{
  observe.each(function(pair){
    if($('element_e2-' + pair.value.condition_element) && $('element_e' + pair.value.condition_element))
    {
      pair.value.event(null, $('element_e2-' + pair.value.condition_element), null);
      $('element_e2-' + pair.value.condition_element).observe('change', pair.value.event);
      pair.value.event(null, $('element_e' + pair.value.condition_element), null);
      $('element_e' + pair.value.condition_element).observe('change', pair.value.event);
    }
    else if($('element_e' + pair.value.condition_element))
    {
      pair.value.event(null, $('element_e' + pair.value.condition_element), null);
      $('element_e' + pair.value.condition_element).observe('change', pair.value.event);
    }
    else if($('element_e' + pair.value.condition_element + '_yes'))
    {
      if($('element_e' + pair.value.condition_element +'_yes').checked)
        pair.value.event(null, null, 'yes');
      else if($('element_e' + pair.value.condition_element +'_no').checked)
        pair.value.event(null, null, 'no');

      $('element_e' + pair.value.condition_element + '_yes').observe('click', pair.value.event);
      $('element_e' + pair.value.condition_element + '_no').observe('click', pair.value.event);
    }
  });

  //Add event to track page changes
  $$('.survey .element input, .survey .element textarea, .survey .element select').each(function(element)
  {
    element.observe('change', function(){changes=true});
  });
  
  //Add event to confirm navigation without saving
  $$('.survey #wrapper a').each(function(element)
  {
    element.observe('click', function(event){if(changes&&!confirm('Information on this page will be lost if you navigate away without submitting your information. Click OK if you want to proceed without saving.'))event.stop()});
  });
}

function surveyRecord(event, element, value, is_dual, element_id, display_id, condition_value)
{
  if (event && event.element)
  {
    var element = event.element();
  }
  if (element)
  {
    var value = element.value;
  }
  var value2 = null;
  if (is_dual && element.id.match(/^element_e2\-/))
  {
    value2 = $('element_e' + element_id).value;
  }
  else if(is_dual && !element.id.match(/^element_e2\-/))
  {
    value2 = $('element_e2-' + element_id).value;
  }
  if(surveyLogicCompare(value, value2, condition_value)) $('wrap-e' + display_id).show(); else $('wrap-e' + display_id).hide();
}

function surveyLogicCompare(value, value2, reference)
{
  var match = false;
  var reference = reference.split(',');
  var value = value.toLowerCase().replace(/\s/g, '');
  if (value2)
  {
    var value2 = value2.toLowerCase().replace(/\s/g, '');
    reference.each(function(test) { if (test==value || test==value2) match = true; },this);
  }
  else
  {
    reference.each(function(test) { if (test==value) match = true; },this);
  }
  return match;
}

sfHover = function() {
  if(document.getElementById("nav")==null) return;
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

function resetDOBField(element)
{
  if(element.value == 'day' || element.value == 'month' || element.value == 'year')
  {
    element.value = '';
  }
}

function cyclingSickPay()
{
  var show = $('sick-pay-yes').checked;
  $$('.cycling-sick-pay').each(function(element)
  {
    if(show)
    {
      element.show();
    }
    else
    {
      element.hide();
    }
  });
}

/*
 * Copyright (c) 2006 Jonathan Weiss <jw@innerewut.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */


/* tooltip-0.2.js - Small tooltip library on top of Prototype
 * by Jonathan Weiss <jw@innerewut.de> distributed under the BSD license.
 *
 * This tooltip library works in two modes. If it gets a valid DOM element
 * or DOM id as an argument it uses this element as the tooltip. This
 * element will be placed (and shown) near the mouse pointer when a trigger-
 * element is moused-over.
 * If it gets only a text as an argument instead of a DOM id or DOM element
 * it will create a div with the classname 'tooltip' that holds the given text.
 * This newly created div will be used as the tooltip. This is usefull if you
 * want to use tooltip.js to create popups out of title attributes.
 *
 *
 * Usage:
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *   <script type="text/javascript">
 *     // with valid DOM id
 *     var my_tooltip = new Tooltip('id_of_trigger_element', 'id_of_tooltip_to_show_element')
 *
 *     // with text
 *     var my_other_tooltip = new Tooltip('id_of_trigger_element', 'a nice description')
 *
 *     // create popups for each element with a title attribute
 *    Event.observe(window,"load",function() {
 *      $$("*").findAll(function(node){
 *        return node.getAttribute('title');
 *      }).each(function(node){
 *        new Tooltip(node,node.title);
 *        node.removeAttribute("title");
 *      });
 *    });
 *
 *   </script>
 *
 * Now whenever you trigger a mouseOver on the `trigger` element, the tooltip element will
 * be shown. On o mouseOut the tooltip disappears.
 *
 * Example:
 *
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *
 *   <div id='tooltip' style="display:none; margin: 5px; background-color: red;">
 *     Detail infos on product 1....<br />
 *   </div>
 *
 *   <div id='product_1'>
 *     This is product 1
 *   </div>
 *
 *   <script type="text/javascript">
 *     var my_tooltip = new Tooltip('product_1', 'tooltip')
 *   </script>
 *
 * You can use my_tooltip.destroy() to remove the event observers and thereby the tooltip.
 */

var Tooltip = Class.create();
Tooltip.prototype = {
  initialize: function(element, tool_tip) {
    var options = Object.extend({
      default_css: false,
      margin: "0px",
	    padding: "5px",
	    backgroundColor: "#d6d6fc",
	    min_distance_x: 5,
      min_distance_y: 5,
      delta_x: 0,
      delta_y: 0,
      zindex: 1000
    }, arguments[2] || {});

    this.element      = $(element);

    this.options      = options;

    // use the supplied tooltip element or create our own div
    if($(tool_tip)) {
      this.tool_tip = $(tool_tip);
    } else {
      this.tool_tip = $(document.createElement("div"));
      document.body.appendChild(this.tool_tip);
      this.tool_tip.addClassName("tooltip");
      this.tool_tip.appendChild(document.createTextNode(tool_tip));
    }

    // hide the tool-tip by default
    this.tool_tip.hide();

    this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
    this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
    this.eventMouseMove  = this.moveTooltip.bindAsEventListener(this);

    this.registerEvents();
  },

  destroy: function() {
    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
    Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
    Event.stopObserving(this.element, "mousemove", this.eventMouseMove);
  },

  registerEvents: function() {
    if (this.element)
    {
      Event.observe(this.element, "mouseover", this.eventMouseOver);
      Event.observe(this.element, "mouseout", this.eventMouseOut);
      Event.observe(this.element, "mousemove", this.eventMouseMove);
    }
  },

  moveTooltip: function(event){
	  Event.stop(event);
	  // get Mouse position
    var mouse_x = Event.pointerX(event);
	  var mouse_y = Event.pointerY(event);

	  // decide if wee need to switch sides for the tooltip
	  var dimensions = Element.getDimensions( this.tool_tip );
	  var element_width = dimensions.width;
	  var element_height = dimensions.height;

	  if ( (element_width + mouse_x) >= ( this.getWindowWidth() - this.options.min_distance_x) ){ // too big for X
		  mouse_x = mouse_x - element_width;
		  // apply min_distance to make sure that the mouse is not on the tool-tip
		  mouse_x = mouse_x - this.options.min_distance_x;
	  } else {
		  mouse_x = mouse_x + this.options.min_distance_x;
	  }

	  if ( (element_height + mouse_y) >= ( this.getWindowHeight() - this.options.min_distance_y) ){ // too big for Y
		  mouse_y = mouse_y - element_height;
	    // apply min_distance to make sure that the mouse is not on the tool-tip
		  mouse_y = mouse_y - this.options.min_distance_y;
	  } else {
		  mouse_y = mouse_y + this.options.min_distance_y;
	  }

	  // now set the right styles
	  this.setStyles(mouse_x, mouse_y);
  },


  showTooltip: function(event) {
    Event.stop(event);
    this.moveTooltip(event);
	  new Element.show(this.tool_tip);
  },

  setStyles: function(x, y){
    // set the right styles to position the tool tip
	  Element.setStyle(this.tool_tip, { position:'absolute',
	 								    top:y + this.options.delta_y + "px",
	 								    left:x + this.options.delta_x + "px",
									    zindex:this.options.zindex
	 								  });

	  // apply default theme if wanted
	  if (this.options.default_css){
	  	  Element.setStyle(this.tool_tip, { margin:this.options.margin,
		 		  						                    padding:this.options.padding,
		                                      backgroundColor:this.options.backgroundColor,
										                      zindex:this.options.zindex
		 								    });
	  }
  },

  hideTooltip: function(event){
	  new Element.hide(this.tool_tip);
  },

  getWindowHeight: function(){
    var innerHeight;
	  if (navigator.appVersion.indexOf('MSIE')>0) {
		  innerHeight = document.body.clientHeight;
    } else {
		  innerHeight = window.innerHeight;
    }
    return innerHeight;
  },

  getWindowWidth: function(){
    var innerWidth;
	  if (navigator.appVersion.indexOf('MSIE')>0) {
		  innerWidth = document.body.clientWidth;
    } else {
		  innerWidth = window.innerWidth;
    }
    return innerWidth;
  }

}

function radioButtonReplacement()
{
  $('quote-form').addClassName('js');
  $$('.radio-group input').each(function(element)
  {
    element.observe('click', function (event) {
      var input_btn = event.element();
      input_btn.up().childElements().each(function(inner_element)
      {
        if (input_btn.id == inner_element.getAttribute('for'))
        {
          inner_element.addClassName('checked');
        }
        else if(inner_element.tagName == 'LABEL')
        {
          inner_element.removeClassName('checked');
        }
      });
    });
  });
}

function bindBuyButtons()
{
  unbindBuyButtons();
  $$('.btn-more-2').each(function(element)
  {
    element.observe('click', function (event) {
      event.stop();
      showModal(Event.element(event));
    });
  });
}
function unbindBuyButtons()
{
  $$('btn-more-2').each(function(element)
  {
    element.stopObserving('click');
  });
}

function loadQuoteResponses(iteration, list_url, token_url)
{
  iteration++;
  if (iteration == 1)
  {
    current_ajax_loader = new Ajax.Updater('quote-form-holder', list_url, {
      evalScripts: true,
      onComplete : loadQuoteResponses.curry(iteration, list_url, token_url)})
  }
  else if(iteration <= 3)
  {
    bindBuyButtons();
    setTimeout( function() {
      current_ajax_loader = new Ajax.Updater('quote-form-holder', list_url, {
        evalScripts: true,
        onComplete : loadQuoteResponses.curry(iteration, list_url, token_url)})
    },2000);
  }
  else
  {
    bindBuyButtons();
    token_timer = new PeriodicalExecuter(function(pe) {
      ajax_token_loader = new Ajax.Request(token_url, {method: 'get'});
    }, 15);
  }
}

function showModal(element)
{
  var semitrans_div;
  var buymodal_div = $('buy-modal');
  if ($('opacitybg'))
  {
    semitrans_div = $('opacitybg');
  }
  else
  {
    semitrans_div = new Element('div', {'id':'opacitybg'});
    document.body.appendChild(semitrans_div);
  }
  $('modal-submit').setAttribute('rel', element.href);
  $('buy-heading').innerHTML = element.getAttribute('rel').split('|').first();
  $('modal-name').value = element.getAttribute('rel').split('|').first();
  $('modal-id').value = element.getAttribute('rel').split('|').last();
  
  positionModal();
  semitrans_div.show();
  buymodal_div.show();
}

function registerModalEvents()
{
  //Event.stopObserving(window, 'scroll');
  Event.observe(window, 'scroll', function() {
    positionModal();
  });
  //Event.stopObserving(window, 'resize');
  Event.observe(window, 'resize', function() {
    positionModal();
  });
  $('opacitybg').observe('click', function() {
    $('buy-modal').hide();
    $('opacitybg').hide();
  });
  $('close-window').observe('click', function(event) {
    event.stop();
    $('buy-modal').hide();
    $('opacitybg').hide();
  });
  $('modal-submit').observe('click', function(event) {
    event.stop();
    
    $('modal-validation').hide();
    $('modal-validation-btm').hide();
    
    if(current_ajax_loader)
    {
      current_ajax_loader.abort();
    }
    if(ajax_token_loader)
    {
      ajax_token_loader.abort();
    }
    if(token_timer)
    {
      token_timer.stop();
    }
    var save_url = $('modal-form').getAttribute('action');
    new Ajax.Request(save_url, {
    evalScripts: true,
    parameters: Form.serialize('modal-form'),
    onComplete : function(transport)
    {
      var json = transport.responseJSON;
      if (json == 1)
      {
        //Redirect to buy location
        document.location = $('modal-submit').getAttribute('rel');
      }
      else
      {
        $$('#modal-validation ul li').each(function(element) { element.remove() });
        
        var error_count = 0;
        for (var key in json) {
          if (json.hasOwnProperty(key)) {
            error_count++;
            $$('#modal-validation ul').first().insert('<li>' + json[key] + '</li>');
          }
        }
        if (error_count > 0)
        {
          $('modal-validation').show();
          $('modal-validation-btm').show();
        }
      }
    }});
  });
}

function positionModal()
{
  var viewport_scroll = document.viewport.getScrollOffsets();
  $('opacitybg').setStyle({'height': document.body.getHeight() + 'px', 'top': viewport_scroll['top'] + 'px'});
  var modal_y = viewport_scroll['top'] + (document.viewport.getHeight() / 2) - ($('buy-modal').getHeight() / 2);
  var modal_x = viewport_scroll['left'] + (document.viewport.getWidth() / 2) - ($('buy-modal').getWidth() / 2);
  $('buy-modal').setStyle({'top': modal_y + 'px', 'left': modal_x + 'px' });
}

/**
 * Ajax.Request.abort
 * Steven Pothoven
 * http://blog.pothoven.net/2007/12/aborting-ajax-requests-for-prototypejs.html
 */
Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // update the request counter
    Ajax.activeRequestCount--;
};
