$(document).ready(function(){
   
   Array.prototype.sum = function() {
      var s = 0;
      for (var i = 0; i < this.length; i++) {
        s += (typeof this[i] == 'number') ? this[i] : 0;
      }
      return s;
   };
   
   // For IE's benefit
   if (!Array.prototype.indexOf)
   {
     Array.prototype.indexOf = function(elt /*, from*/)
     {
       var len = this.length;
   
       var from = Number(arguments[1]) || 0;
       from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
       if (from < 0)
         from += len;
   
       for (; from < len; from++)
       {
         if (from in this &&
             this[from] === elt)
           return from;
       }
       return -1;
     };
   }
   
   /* Prevent premature submission of form by pressing return key */
   if($('form#booking').length){
      $('textarea').addClass('textarea');
      $(document).keypress(function(e){
         if($(document.activeElement).hasClass('textarea') || e.keyCode!=13)
         {
            return true;
         }else{
            e.preventDefault();
            return false;
         }
      })
   }
   
   
   /* Front page accordion */
   $('#events').accordion();
   
   $('h3.ui-accordion-header').hover(
      function(){
         if(!$(this).hasClass('ui-state-active'))
         {
            $(this).children('span').addClass('down-active-black');
         }
      },
      function(){
         $(this).children('span').removeClass('down-active-black');
      }
   );
   
   $()
   
   /* Event page tabs */
   $('#event-tabs').tabs()
   
   $("#dialog").dialog({
      autoOpen:   false,
      bgiframe:   true,
      height:     140,
      modal:      true
   });
   
   $("#validation").dialog({
      autoOpen:   false,
      bgiframe:   true,
      modal:      true,
      buttons:    {
         "OK" : function(){
            $(this).dialog("close");
         }
      }
   });
   
   var worldpayMsgShown = new Boolean(false);
   $('#worldpay').dialog({
      autoOpen:   false,
      bgiframe:   true,
      modal:      true,
      close:      function(event, ui){
          $('form#booking').submit();
      },
      open:       function(event, ui){
         $('button.ui-state-focus').removeClass('ui-state-focus').css('outlineColor', '#717171');
      },
      buttons:    {
          "Ok" : function(){
              $('form#booking').submit();
          }
      }      
   });
   
   $('form#booking').submit(function(e){
      var elements = $('#invoiceAddressDiv .required');
      if(checkRequired(e, elements))
      {
         if(worldpayMsgShown == false && $('input[name="paymentmethod"]:checked').val() == 'worldpay')
         {
            e.preventDefault();
            $('#worldpay').dialog('open');
            worldpayMsgShown = true;
         }
      }else{
         e.preventDefault();
      }      
   });
   
   /* control booking form links */
   var lastClicked = 0;
   $('a.form-nav').click(function(event){
      
      var clicked = $(this).attr('rel');
      var links = $("ul.ui-tabs-nav a");
      
      if(clicked > lastClicked)
      {
         var formfields = $(this).parents('fieldset').children('input.required, select.required, textarea.required');
         
         if(checkRequired(event, formfields))
         {
            var myLink = $(links[clicked]);
            myLink.click();
            $('.ui-state-error').remove();
            // we have to preventDefault here in case if the email / phone number is wrong. This prevents the page jumping. 
            event.preventDefault();
         }else{
            return false;
            event.preventDefault();
         }
      }else{
         var myLink = $(links[clicked]);
         myLink.click();
         return true;
      }
      return true;
   });
   
   /* Booking form tabs - different functionality to events page tabs.*/
   
   $('#form-tabs').tabs({
      select: function(e, ui){
         if(ui.index > lastClicked)
         {
            // check everything
            var formfields = $('input.required, select.required').not(":hidden");
            if(checkRequired(e, formfields))
            {
               if(checkInput(e))
               {
                  lastClicked = ui.index;
                  $('.ui-state-error').remove();
                  return true;
               }else{
                  e.preventDefault();
                  return false;
               }
            }else{
               return false;
            }
         }else{
            lastClicked = ui.index;
            return true;
         }
      }
   });
   
   /* End booking form links */
   
   $('input[value="invoice"]').live('click', function(){
      $('div#invoiceAddressDiv').fadeIn();
      $('#invoiceAddressDiv>input[type="text"]').not('.notrequired').addClass('required');
   });
   
   $('input[value="worldpay"]').live('click', function(){
      $('div#invoiceAddressDiv').fadeOut();
      // remove required class from each child input
      $('div#invoiceAddressDiv input.required').removeClass('required');
   })
   
   /* Calculate totals */   
   if($('span#grandTotal').length)
   {
      changeTotal();
   }
   
   if ($.browser.msie && $.browser.version <= 6 )
   {    
      // This allows the calculator to work in IE6. If this is not included, IE6 only calculates the new total on blur (not onChange!) 
      $('input.changeTotal').click(function(){
         changeTotal();
         $(this).blur();
      })
      
   }
   
   //min-width hack for home page
   function checkResize(el, minWidth){
      var width = $(el).width();
      if(width<minWidth)
      {
          var newWidth = minWidth + 'px';
          $(el).css('width', newWidth);
      }      
   }; 
      
   if($.browser.msie && $.browser.version <= 6 )
   {
    if($('div.smallMinWidth').length)
    {
      checkResize($('div.smallMinWidth'), 800);
      checkResize($('div#content'), 1000);
      checkResize($('div#header'), 1000);
      var headers = $('h3.ui-accordion-header');
      
      $(headers[1]).hover(); // hack to fix IE6 float issue
      
      $(window).resize(function(){
        checkResize($('div.smallMinWidth'), 800);
        checkResize($('div#content'), 1000);
        checkResize($('div#header'), 1000);
      });
    }else if($('div.bigMinWidth').length){
      //checkResize($('div#content'), 1200);
      //checkResize($('div#header'), 800);
      
      $(window).resize(function(){
        //checkResize($('div#content'), 1200);
        //checkResize($('div#header'), 800);
      });
      
    }
    
   }
   
   $('.changeTotal').change(changeTotal);   
   function changeTotal(){      
      var priceInputs = $('.changeTotal');
      var totalChange = 0;
      var prices = [];
      var re = new RegExp(/[x|*|X]([\d])/); // this matches a value of *2 or x2
      
      $.each(priceInputs, function(i, input){
         if(input.checked==true)
         {
            // it's a radio, or checkbox, and it's checked
            
            var rel = $(this).attr('rel');
            
            if(rel.match(re))
            {
               prices.push(rel);
            }else{
               prices.push(parseFloat(rel));
            }
         }else{
            // If it's a dropdown, return the selected value, otherwise return 0
            
            if($(this).attr('type') == 'select-one')
            {
              //dropdown
              var options = $(this).children('option');
              var option = options[$(this).attr('selectedIndex')];
              var rel = $(option).attr('rel');
              
              if(rel!==undefined && rel.match(re))
              {
                prices.push(rel);
              }else{
                var price = input.options ? parseFloat(input.options[input.selectedIndex].getAttribute('rel')):0;
                
                if(price > 0)
                {
                   prices.push(price);
                }
              }
            }
         }
      })
      
      var matched = new Boolean(false);
      var matchLoc;
      $.each(prices, function(i, price){
         if(String(price).match(re))
         {
            matched = true;
            matchLoc = i;
         }
      })
      
      if(matched===true)
      {
         var multiplier = parseFloat(prices[matchLoc].replace(/([^\d])/, ''));
         var toAdd = (parseFloat(prices[0]) * multiplier);
         prices.splice(0, 1); // remove first element
         prices.splice(matchLoc-1, 1); //remove multiplier
         
         toAdd = toAdd + prices.sum();
      }else{
         var toAdd = prices.sum();
      }
      
      var newTotal = parseFloat($('input[name="basePrice"]').val()) + toAdd;
      
      if(newTotal < 0 || isNaN(newTotal))
      {
         newTotal = 0;
      }      
      
      $('input[name="grandTotal"]').val(newTotal);
      $('span#grandTotal').html(newTotal);
      $('p#runningTotal span').fadeOut('fast', function(){
         $(this).html('&#163;' + newTotal).fadeIn('fast');
      });
      
      // replace form field elements      
      if(newTotal==0)
      {
         $('div#payment-choice').text('');
         var text = '<label for="paymentmethod">Please select your preferred payment method</label>';
         text += '<input type="radio" name="paymentmethod" value="free" checked="checked" /><span class="radioLabel"> Free event - Click proceed to receive your booking ID</span><br />';
         
      }else{
         
         $('div#payment-choice').text('');
         var text = '<label for="paymentmethod">Please select your preferred payment method:</label>';
         text += '<input type="radio" name="paymentmethod" value="worldpay" checked="checked" /> Pay using the secure online payment gateway<br />';
         text += '<input type="radio" name="paymentmethod" value="invoice" /> Request an invoice<br />'
         text += '<div id="invoiceAddressDiv" style="display:none">';
         
         text += '<p>Please enter the name and address of the person we should send the invoice to.</p>';
         text += '<label for="invoice_contact">Contact Name:<span class="req-field">*</span></label>';
         text += '<input class="text" type="text" name="invoice_contact" value="" /><br />';
         text += '<label for="invoice_address1">Organisation/Department:<span class="req-field">*</span></label>';
         text += '<input class="text " type="text" name="invoice_address1" value="" /><br />';
         text += '<label for="invoice_address2">Invoice Address:<span class="req-field">*</span></label>';
         text += '<input class="text" type="text" name="invoice_address2" value="" /><br />';
         text += '<label for="invoice_town">Invoice Town / City:<span class="req-field">*</span></label>';
         text += '<input class="text" type="text" name="invoice_town" value="" /><br />';
         text += '<label for="invoice_postcode">Invoice Postcode:<span class="req-field">*</span></label>';
         text += '<input class="text" type="text" name="invoice_postcode" value="" /><br />';
         text += '</div>';
      }
      
      $('div#payment-choice').html(text);
   }
   
   /* end calculate totals */
   
   function checkValidEmail(str)
   {
      var re = new RegExp(/^([a-zA-Z0-9_\.\-+])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,8})+$/);
      return str.match(re);
   }
   
   function checkValidPhone(str)
   {
      // matches numbers, whitespace, and pluses (To cover numbers like +44 141 123 1234)
      var re = new RegExp(/[\+0-9\s]{6,22}/);
      return str.match(re);
   }
   
   function checkInput(event)
   {
      var email = $('input[name="email"]').val();
      var phone = $('input[name="telephone"]').val();
      
      if(!checkValidEmail(email))
      {
         var failMessage = '<p>Your email address does not seem to be valid - please check and re-enter.</p>';
         event.preventDefault();
         $('#validation').html(failMessage);
         $('#validation').dialog('open');
         return false;
      
      }else if(!checkValidPhone(phone)){
         var failMessage = '<p>Your telephone number does not seem to be valid - please check and re-enter.</p>';
         event.preventDefault();
         $('#validation').html(failMessage);
         $('#validation').dialog('open');
         return false;
      
      }
      return true;
   }
   
   function checkRequired(e, elements)
   {
      var failMessage= "<p>Please make sure you've filled in the following required fields:</p>";
      var fail = new Boolean(false);
      var inputArray = [];
      var failNames = [];
      
      $.each(elements, function(i, item){
         if(item.type=='radio' || item.type=='checkbox')
         {
            // move the name of the element to the inputArray if it's not already there
            var name = item.name;
            if(inputArray.indexOf(name) == -1)
            {
               inputArray.push(name);
            }
         }else{
            if($(item).val()=='')
            {
               fail = true;
               var name=$(item).prev('label').text();
               failNames.push(name);
            }
         }
      });
      
      // check that at least one element is checked (radio buttons)
      $.each(inputArray, function(i, inputName){
         var groupIsChecked = new Boolean(false);
         var inputsToCheck = $('input[name="' + inputName + '"]');
         $.each(inputsToCheck, function(i, input){
            if(input.checked===true)
            {
               groupIsChecked = true;
            }
         })
         
         if(groupIsChecked==false)
         {
            failNames.push($('input[name="' + inputName + '"]').prev('label').text());
            fail = true;
         }
         
      })
      
      failNames.reverse();
      if(fail==true)
      {
         $.each(failNames, function(i, item){
            failMessage = failMessage + '<strong>'+ item.replace(':', '') + '</strong>' + '<br />';
         })
         
         $('#validation').html(failMessage).dialog('open');
         e.preventDefault();
         return false;
      }else{   
         return true;
      }
   }
   
   $('a[class="pop"]').click(function(e){
      e.preventDefault();
      
      var href = $(this).attr("href");
      window.open(href, "docwindow", "status=0,location=0,toolbar=0,resizable=0,scrollbars=1,width=800,height=600"); 
   })
   
})

$(function(){
  var items = $('ui-tabs a');
  $(items[0]).hover();
  
  // fixes for IE
  $('input[type="radio"]').css('border', 'none');
  
})