var splash_accordion = null;
var footer_scroller = null;
var search_box = null;
var g_drop_downs = null;
var dropdown_menu = null;
var stages = ['1', '2', 'privacy', 'disclaimer'];

window.addEvent('domready', function() {

  var rsvp_form = $(document.forms['rsvp_form']);
  if (rsvp_form) {
    new ClearTextInput(rsvp_form.first_name);
    new ClearTextInput(rsvp_form.last_name);
    new ClearTextInput(rsvp_form.age);
    new ClearTextInput(rsvp_form.email);
    new ClearTextInput(rsvp_form.address);
    new ClearTextInput(rsvp_form.postcode);
    new ClearTextInput(rsvp_form.phone);
  }

  var select_boxes = $$('select');
  if (select_boxes) {
    g_drop_downs = [];
    select_boxes.each(function(el) {
      g_drop_downs[el.form.name+'_'+el.name] = new DropDown(el, el.selectedIndex,{selectText:el.options[el.selectedIndex].text, dropDownImageWidth: 17, width: 142});
    });
  }

  var links = $$('a');
  if (links) {
    links.each(function(link) {
      var url = link.getAttribute('href');
      if (url.indexOf('?') != -1 && url.indexOf('s=') != -1) {
        link.addEvent('click', function(e) {
          e = new Event(e).stop();
          var params = url.split('s=');
          showStage(params[1]);
        });
      }
    });
  }

  var checkboxes = $$('.form_row label');
  if (checkboxes) {
    checkboxes.each(function(checkbox) {
      checkbox.addEvent('click', function(e) {
        e = new Event(e).stop();
        var tar = $(e.target);
        var chkbx = tar.form[tar.htmlFor];
        if (chkbx.checked) {
          chkbx.checked = false;
          tar.setStyle('background-image', 'url(images/form/checkbox_off.png)');
        }
        else {
          chkbx.checked = true;
          tar.setStyle('background-image', 'url(images/form/checkbox_on.png)');
        }
      });
    });
  }


  rsvp_form.addEvent('submit', function() {
    why = '';
    if (this.first_name.value == 'First Name' ||
        !this.first_name.value.length) {
      why = 'Please enter your first name\r\n';
    }
    if (this.last_name.value == 'Last Name' ||
        !this.last_name.value.length) {
      why += 'Please enter your last name\r\n';
    }
    if (this.postcode.value == 'Postcode' ||
        !this.postcode.value.length) {
      why += 'Please enter your postcode\r\n';
    }
    // make sure the email address is formatted correctly
    if (!checkEmail(this.email.value)) {
      why += 'Please enter your email address\r\n';
    }
    // make sure a gender is selected
    if (this.gender.selectedIndex == 0) {
      why += 'Please select your gender\r\n';
    }
    // make sure they select who they are
    if (this.who_are_you.selectedIndex == 0) {
      why += 'Please select who you are\r\n';
    }

    if (why) {
      alert(why);
      return false;
    }
    return true;

  });

  if (values) {
    theForm = document.forms[0];
    theForm.first_name.value = values.first_name;
    theForm.last_name.value = values.last_name;
    theForm.age.value = values.age;
    theForm.email.value = values.email;
    theForm.address.value = values.address;
    theForm.postcode.value = values.postcode;
    theForm.phone.value = values.phone;
    $A(theForm.gender.options).each(function(el) {
      if (el.value == values.gender) {
        g_drop_downs[theForm.name+'_'+theForm.gender.name].selectOption(el.index, true);
      }
    });
    $A(theForm.country.options).each(function(el) {
      if (el.value == values.country) {
        g_drop_downs[theForm.name+'_'+theForm.country.name].selectOption(el.index, true);
      }
    });
    $A(theForm.who_are_you.options).each(function(el) {
      if (el.value == values.who_you_are) {
        g_drop_downs[theForm.name+'_'+theForm.who_are_you.name].selectOption(el.index, true);
      }
    });
    if (values.carbon_offset) {
      theForm.carbon_offset.checked = values.carbon_offset;
      $('label_carbon_offset').setStyle('background-image', 'url(images/form/checkbox_on.png)');
    }
    if (values.environmental_offset) {
      theForm.environmental_offset.checked = values.environmental_offset;
      $('label_environmental_offset').setStyle('background-image', 'url(images/form/checkbox_on.png)');
    }
    if (values.renewable_energy) {
      theForm.renewable_energy.checked = values.renewable_energy;
      $('label_renewable_energy').setStyle('background-image', 'url(images/form/checkbox_on.png)');
    }
    if (values.philanthropic_contributions) {
      theForm.philanthropic_contributions.checked = values.philanthropic_contributions;
      $('label_philanthropic_contributions').setStyle('background-image', 'url(images/form/checkbox_on.png)');
    }
  };

});

function showStage(idx)
{
  stages.each(function(stage){
    if (stage == idx) {
      $('content_'+stage).setStyle('display', 'block');
      if (idx == 'privacy' || idx == 'disclaimer') {
        $('form_wrapper').setStyle('display', 'none');
      }
      else {
        $('form_wrapper').setStyle('display', 'block');
      }
    }
    else {
      $('content_'+stage).setStyle('display', 'none');
    }
  });
}


function checkEmail (strng) {
  var valid = true;
  if (strng == "") {
     valid = false;
  }
  else if (!isRFC822ValidEmail(strng)) {
     valid = false;
  }
  return valid;
}

function isRFC822ValidEmail(sEmail) {

  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string

  var reValidEmail = new RegExp(sValidEmail);

  if (reValidEmail.test(sEmail)) {
    return true;
  }

  return false;
}

var ClearTextInput = new Class({

	Implements: [Events, Options],

  options: {
/*  onFocus: $function,
    onBlur: $function  */
  },

  element: null,

  initialize: function(element, options)
  {
    this.setOptions(options);
    this.element = $(element);
    this.element.addEvent('focus', function(e) {
      if (this.element.value == this.element.defaultValue) {
        this.element.value = '';
      }
      this.fireEvent('focus', [this.element]);
    }.bind(this));
    this.element.addEvent('blur', function(e) {
      if (this.element.value == '') {
        this.element.value = this.element.defaultValue;
      }
      this.fireEvent('blur', [this.element]);
    }.bind(this));
  }

});


var DropDown = new Class({

  options: {
    width: null,
    padding: 4,
    dropdownDivClass:'select_div',
    dropdownBoxClass:'select_dropdown_container',
    dropdownClass:'select_dropdown',
    dropdownImageClass:'select_image',
    dropDownImage: base_url+'images/form/butt_arrow.gif',
    dropDownImageWidth: 17,
    dropDownImageHeight: 14,
    selectText: 'Select Option..',
    scrollbarBoxClass:'ddselect_dropdown_slider',
    sliderClass:'ddslider',
    sliderBackgroundClass:'ddslider_knob_bg',
    sliderKnobClass:'ddslider_knob',
    sliderKnobTopClass:'ddslider_knob_top',
    sliderKnobBottomClass:'ddslider_knob_bottom',
    scrollbarUpClass:'ddslider_up',
    scrollbarDownClass:'ddslider_down'
  },

  element: null,
  dropdown_status: false,
  dropdown: null,
  inputDiv: null,
  imageButton: null,
  dropDownOptions: [],
  selectOptions: null,
  coords: null,
  toggled: false,
  dropdownCreated: false,

  initialize: function(el, selectedIndex, options)
  {
    this.setOptions(options);

    this.element = el;
    this.element.style.display = 'inline';
    if (!this.options.width) {
      this.element.setStyle('display', 'block');
      this.options.width = this.element.getWidth()-this.options.dropDownImageWidth;
      this.element.setStyle('display', 'none');
    }
    this.element.style.display = 'none';
    this.selectedIndex = selectedIndex;

    this.selectDiv = $(this.element.nextSibling.nextSibling);
    this.inputDiv = $(this.selectDiv.childNodes[0]).set('html',this.options.selectText);
    this.imageButton = $(this.selectDiv.childNodes[1]);

    this.inputDiv.addEvent('click', function(e) {
      e = new Event(e).stop();
      this.toggleDropDown();
      this.toggled = true;
      document.fireEvent('click');
    }.bind(this));
    this.imageButton.addEvent('click', function(e) {
      e = new Event(e).stop();
      this.toggleDropDown();
      this.toggled = true;
      document.fireEvent('click');
    }.bind(this));

    document.addEvent('click', function(e) {
      if (this.dropdown_status && !this.toggled) {
        this.toggleDropDown();
      }
      this.toggled = false;
    }.bind(this));

		new Asset.image(base_url+'images/form/bg_dropdown.png');
  },

  toggleDropDown: function()
  {
    if (!this.dropdownCreated) {
      this.createDropDown();
    }
    if (this.dropdown_status) {
      this.dropdownBox.setStyles({'display':'none','z-index':'1'});
      this.dropdown_status = false;
    }
    else {
      // are any of my parents scrolled?
      var coords = this.selectDiv.getCoordinates();

      this.dropdownBox.setStyles({'display':'block','z-index':'1000','left':coords.left+'px','top':(coords.top+this.inputDiv.offsetHeight)+'px'});
      if (this.element.options.length > 8 && !this.dropdown_contentslider) {
        this.dropdown_contentslider = new ContentSlider(this.dropdown, this.scrollbarBox,
          {max_height: 154,
          sliderTrackClass: 'ddslider',
          sliderUpClass: 'ddslider_up',
          sliderDownClass: 'ddslider_down',
          sliderKnobClass: 'ddslider_knob',
          sliderKnobMin: 31,
          updateWidth: false});
      }
      this.dropdown_status = true;
    }
  },

  selectOption: function(index, show) {
//    if (Browser.Engine.name == 'trident') {
//      this.inputDiv.innerText = this.element.options[index].text;
//    }
//    else {
      this.inputDiv.innerHTML = this.element.options[index].text;
//    }
    if (!show) {
      this.toggleDropDown();
      this.dropdown.childNodes[this.selectedIndex].setStyles({'background':'#f0f0f0','color':'#464545'});
    }
    this.selectedIndex = index;
    this.element.selectedIndex = index;
    this.element.fireEvent('change');
  },

  createDropDown: function() {
    this.dropdownBox = new Element('div', {'class':this.options.dropdownBoxClass,
                                       'styles':{'display':'none','position':'absolute'}});
    this.dropdown = new Element('div', {'class':this.options.dropdownClass,
                                       'styles':{'position':'relative'}});
    for (var i = 0; i < this.element.options.length; i++) {
      var new_li = new Element('div').set('html', this.element.options[i].text);

      new_li.addEvent('click', function(e) {
        e = new Event(e).stop();
        var tar = $(e.target);
        var found = false;
        var j = 0;
        var p = tar.getParent();
        while (!found && j < this.element.options.length) {
          if (tar == p.childNodes[j]) {
            found = true;
          }
          else {
            j++;
          }
        }
        this.selectOption(j);
      }.bind(this));

      new_li.addEvent('mouseenter', function() {
        this.setStyles({'background':'#f0f0f0','color':'#464545'});
      });
      new_li.addEvent('mouseleave', function(e) {
        e = new Event(e).stop();
        var found = false;
        var j = 0;
        var tar = $(e.target);
        var p = tar.getParent();
        while (!found && j < this.element.options.length) {
          if (tar == p.childNodes[j]) {
            found = true;
          }
          else {
            j++;
          }
        }
        if (found && j != this.selectedIndex) {
          tar.setStyles({'background':'transparent','color':'#464545'});
        }
      }.bind(this));
      new_li.injectInside(this.dropdown);
      if (this.element.options[i].selected) {
        new_li.setStyles({'background':'#f0f0f0','color':'#464545'});
      }
    }
    this.dropdown.inject(this.dropdownBox);
    this.dropdownBox.inject(document.body);


    this.dropdownBox.addEvent('click', function(e) {
      e = new Event(e).stop();
    }.bind(this));

    dropdown_width = (this.options.width+this.options.dropDownImageWidth);
    this.scrollbarBox = new Element('div', {'class':this.options.scrollbarBoxClass});

    var scrollbar_width = 10;
    var scrollbar_height = 0;
    if (this.element.options.length > 8) {
      dropdown_height = '154';
      scrollbar_height = '154';
//      scrollbar_width = 10;
      this.dropdownBox.setStyle('height', dropdown_height+'px');

      // add the scrollbar
      this.slider = new Element('div', {'class':this.options.sliderClass});
      this.sliderKnob = new Element('div', {'class':this.options.sliderKnobClass});
      this.scrollbarUp = new Element('img', {'class':this.options.scrollbarUpClass,'src':base_url+'images/form/scroll_up.gif',width:6,height:6});
      this.scrollbarDown = new Element('img', {'class':this.options.scrollbarDownClass,'src':base_url+'images/form/scroll_down.gif',width:6,height:6});

      this.scrollbarUp.inject(this.scrollbarBox);
      this.slider.inject(this.scrollbarBox);
      this.sliderKnob.inject(this.slider);
      this.scrollbarDown.inject(this.scrollbarBox);
//      select_width = dropdown_width - 14;
    }
    else {
//      scrollbar_height = 27 * this.element.options.length + 2;
//      select_width = dropdown_width - 4;
    }
    select_width = dropdown_width - scrollbar_width - this.options.padding;
    this.dropdown.setStyle('width',select_width+'px');

    this.scrollbarBox.inject(this.dropdownBox);
    this.dropdownBox.setStyle('width', dropdown_width+'px');

    if (!scrollbar_height) {
      this.dropdownBox.setStyle('display', 'block');
      scrollbar_height = this.dropdown.getSize().y;
      this.dropdownBox.setStyle('display', 'none');
    }

    this.scrollbarBox.setStyles({width: scrollbar_width+'px', height: scrollbar_height+'px'});

    this.dropdownCreated = true;
  },

  destroyDropDown: function()
  {
    if (this.dropdownCreated) {
      // clear events
      this.dropdownBox.removeEvent('click');
      this.dropdownBox.getElements('li').each(function(li) {
        li.removeEvents(['click', 'mouseenter', 'mouseleave']);
      });
      if (this.dropdown_contentslider) {
        this.dropdown_contentslider = null;
      }
      this.dropdownBox.destroy();
      this.dropdownCreated = false;
    }
  }

});
DropDown.implement(new Options);

var ContentSlider = new Class({

  options: {
    steps: 100,
    max_height: 400,
    sliderTrackClass: 'slider',
    sliderUpClass: 'sliderUp',
    sliderDownClass: 'sliderDown',
    sliderKnobClass: 'sliderknob',
    sliderKnobMin: 26,
    updateWidth: true,
    fadeInSlider: false
  },

  old_step: 0,
  scroll: null,
  step_delta: 0,
  knobmousedown: false,
  content_box: null,
  sliderContainer: null,
  slider: null,
  sliderUp: null,
  sliderDown: null,
  sliderKnob: null,

  initialize: function(content, sliderContainer, options) {
    this.content_box = content;
    this.sliderContainer = sliderContainer;
    this.setOptions(options);
    if (this.options.fadeInSlider) {
      this.sliderContainer.setOpacity(0);
    }

    this.sliderTrack = this.sliderContainer.getElement('.'+this.options.sliderTrackClass);
    this.sliderUp = this.sliderContainer.getElement('.'+this.options.sliderUpClass);
    this.sliderDown = this.sliderContainer.getElement('.'+this.options.sliderDownClass);
    this.sliderKnob = this.sliderContainer.getElement('.'+this.options.sliderKnobClass);

    box_sh = this.content_box.scrollHeight;
    if (box_sh > this.options.max_height) {
      this.content_box.setStyle('height', this.options.max_height+'px');
      if (this.options.updateWidth) {
        this.content_box.setStyle('width', (this.content_box.getScrollSize().x-40)+'px');
      }
      this.content_box.setStyle('overflow', 'hidden');
      this.sliderTrack.setStyle('display', 'block');
      this.sliderTrack.setStyle('height', (this.options.max_height-2*15)+'px');
      this.sliderTrack.setStyle('margin-bottom', '0px');
      this.sliderUp.setStyle('display', 'block');
      this.sliderDown.setStyle('display', 'block');
      this.sliderknob_h = this.sliderTrack.getStyle('height').toInt() * this.content_box.getStyle('height').toInt() / box_sh;
      if (this.sliderknob_h < this.options.sliderKnobMin) { this.sliderknob_h = this.options.sliderKnobMin; }
      this.sliderKnob.setStyle('height', Math.floor(this.sliderknob_h)+'px');
      if (this.options.fadeInSlider) {
        this.sliderContainer.set('tween', {duration: 1000});
        this.sliderContainer.tween('opacity', 1);
      }
      this.scroll = new Fx.Scroll(this.content_box, {
        wait: false,
        duration: 1000
      });

      this.slider = new Slider(this.sliderTrack, this.sliderKnob, {
        steps: this.options.steps,
        mode: 'vertical',
        onChange:this.sliderChange.bind(this)
      }).set(0);

      this.sliderKnob.addEvent('mousedown', function(e) {if (e.target == this.sliderKnob) {this.knobmousedown = true;}}.bind(this));
      this.sliderKnob.addEvent('mouseup', function(e) {if (e.target == this.sliderKnob) {this.knobmousedown = false;}}.bind(this));

      this.step_delta = this.options.steps * 100/this.content_box.scrollHeight
      this.slider.addEvent('mousewheel', function(e) {
        e = new Event(e).stop();
        var delta_steps = Math.floor(e.wheel * this.step_delta);
        this.slider.set(this.slider.step-delta_steps);
      }.bind(this));

      this.content_box.addEvent('mousewheel', function(e) {
        e = new Event(e).stop();
        var delta_steps = Math.floor(e.wheel * this.step_delta);
        this.slider.set(this.slider.step-delta_steps);
      }.bind(this));

      this.sliderUp.addEvent('click', function(e) {
        e = new Event(e).stop();
        var delta_steps = 2 * this.step_delta;
        this.slider.set(this.slider.step-delta_steps);
      }.bind(this));

      this.sliderDown.addEvent('click', function(e) {
        e = new Event(e).stop();
        var delta_steps = 2 * this.step_delta;
        this.slider.set(this.slider.step+delta_steps);
      }.bind(this));

      this.content_box.getElements('a').each(function(el){
        href = el.getAttribute('href');
        if (href && String.contains(href, '#')) {
          parts = href.split('#');
          if (parts.length > 1 && parts[1] != '') {
            el.addEvent('click', function(e){
              e = new Event(e).stop();
              this.knobmousedown = false;
              var target = el.getAttribute('href').split('#')[1];
              this.scrollToTarget(target);
            }.bind(this));
          }
        }
      }.bind(this));

    }
    else {
      this.content_box.setStyle('height', this.options.max_height+'px');
    }

    if(this.options.initialize) this.options.initialize.call(this);
  },

  changeScrollHeight: function() {
    if (this.content_box.scrollHeight > this.options.max_height) {
      this.sliderknob_h = this.sliderTrack.getStyle('height').toInt() * this.content_box.getStyle('height').toInt() / this.content_box.scrollHeight;
      if (this.sliderknob_h < 26) { this.sliderknob_h = 26; }
      this.sliderKnob.setStyle('height', Math.floor(this.sliderknob_h)+'px');
      this.step_delta = this.options.steps * 100/this.content_box.scrollHeight
    }
  },

  sliderChange: function () {

    if (this.scroll && this.slider) {
      this.scroll.cancel();
      var y = (this.content_box.scrollHeight-this.content_box.getStyle('height').toInt())*this.slider.step/this.options.steps;
        this.content_box.scrollTo(0, y)
      this.old_step = this.slider.step;
    }
  },

  scrollToTarget: function (target) {
    found = false;
    as = this.content_box.getElements('a');
    ao = null;
    j = 0;
    while (!found && j < as.length) {
      if (as[j].getAttribute('name') == target) {
        found = true;
        ao = as[j];
      }
      j++;
    }
    if (ao) {
      this.scroll.cancel();
      this.slider.set(this.options.steps*ao.offsetTop/(this.content_box.scrollHeight-this.content_box.offsetHeight));
    }
  }


});
ContentSlider.implement(new Options);