// begin js/1010_checkbox.js

(function($){
 $.fn.checkbox = function(checked_src, unchecked_src) {  
  return this.each(function(){
    var label = $('label[for="' + this.id + '"]');
    var initial_src = $(this).is(':checked')?checked_src:unchecked_src;
    var container = $(document.createElement('div')).addClass('checkbox');
    var link = $(document.createElement('a')).attr('href', 'javascript:void(0)');
    var img = $(document.createElement('img')).attr('src', initial_src);
    var text = $(document.createElement('span')).text(label.text());
    
    link.append(img).append(text);
    container.append(link);
    $(this).after(container).hide();
    label.hide();
    var checkbox = $(this);
    
    var update_function = function(checked) {
      if(checked){
        checkbox.attr('checked', 'true');
        img.attr('src', checked_src);
      }else{
        checkbox.removeAttr('checked');
        img.attr('src', unchecked_src);
      }
      link.blur();
    };
    container.click(
      function(){
        update_function(!checkbox.is(':checked'));
      }
    ).data("update", function() {
      update_function(checkbox.is(':checked'));
    });
  });
 };
})(jQuery);

(function($){
 $.fn.rollover = function() {  
  return this.each(function(){
    var rollover = $(this);
    var checkbox = $('div.checkbox', rollover.parent());
    var parent_form = rollover.parents('form');
    rollover.hide();
    rollover.css({'position':'absolute', 'z-index':'999'});
    
    checkbox.mouseenter(
      function(){
        var bottom = parent_form.position().top + checkbox.position().top;
        var left = parent_form.position().left + checkbox.position().left;
        rollover.css({'top':bottom - rollover.height(), 'left':left}).show();
      }
    );
    
    checkbox.mouseleave(
      function(){
        rollover.hide();
      }
    );
    
    $('body').prepend(rollover);
  });
 };
})(jQuery);

// end js/1010_checkbox.js
// begin js/1010_dhtmltabs.js

function doTabs(){
  $('#info_panel a.sidenav_menu_item').click(
    function() {
      var href = this.href.replace(/^https?:\/\/[^\/]+\/[^\/]+\//, '');
      $(this).addClass('selected');
      $.historyLoad(href);
      return false;
    }
  );
  configureDynamicRevealNews();
  configureDynamicReveal('thanks_menu_item', 'thanks_section');
}

function configureDynamicReveal(menu_item_class, content_container_class) {
  var i = 0;
  $('.' + menu_item_class).each(
    function(){
      var o = new Object();
      o.index = i++;
      $(this).click(
        function(){
          $('.' + content_container_class).hide();
          $('.' + content_container_class + ':eq(' + o.index + ')').show();
          $('.' + menu_item_class).removeClass('selected');
          $('.' + menu_item_class + ':eq(' + o.index + ')').addClass('selected');
          doSIFR();
          return false;
        }
      );
    }
  );
  $('.' + content_container_class + ':gt(0)').hide();
}

function configureDynamicRevealNews(){
    var section = window.location.href.match(/https?:\/\/[^\/]+\/+([^\/#]*)/)[1];
    var current_location = window.location.search;
    var current_location = current_location.split("?");
    $('div.news_item').hide();
     if(current_location[1]){
        $('div.news_item#' + current_location[1]).show();
    }else{
       $('div.news_item:eq(0)').show();
    }
    $('a.news_item_menu_item').click(function(){
        $('div.news_item').fadeOut();
        $('a.news_item_menu_item').removeClass('selected');
         var newsurl = $(this).addClass('selected').attr('href').split("?");
         var newsdiv = 'div.news_item#news-item-' + newsurl[1];
         $(newsdiv).fadeIn();
         window.location.hash = "whats_going_on?" + newsurl[1];
          doSIFR();
          return false;
        }
      );
}


// end js/1010_dhtmltabs.js
// begin js/1010_dropdown.js
/*  1010_dropdown.js
 *
 * This code converts HTML select elements to DHTML dropdowns
 *
 */
 
(function($){
 $.fn.dropdown = function(_click_function, _width) {
  var defaults = {
    click_function:null,
    width:'200px'
  };
  
  var options = {
    click_function:_click_function,
    width:_width
  };
  
  var options = $.extend(defaults, options);
  
  return this.each(function() {
    el = $(this);
    var el_options = $('option', el);
    
    //Make the various elements
    var container = $(document.createElement('div'))
              .attr({'class':'dd_container', 'id':'1010_dd_' + el.attr('id')})
              .css('width', options.width);
    var dropdown_options = $(document.createElement('div'))
              .attr({'class':'dd_options'})
              .css({
                'position':'absolute',
                'display':'none', 
                'width':options.width,
                'z-index':999
              });
    var selected_item = $(document.createElement('div'))
              .attr({'class':'dd_current_item'});
    var selected_link = $(document.createElement('a'))
              .attr({'href':'javascript:void(0)'})
              .text(el_options.filter(':selected').text());
    
    //Add elements to the page
    el.after(container).hide();
    container.append(selected_item).append(dropdown_options);
    selected_item.append(selected_link);
  
    //Add the options to the dropdown
    for(i = 0; i < el_options.length; i++){
      var opt = el_options.eq(i)
      if(opt.is(':disabled')) continue;
      dropdown_item = $(document.createElement('a'))
                .attr({'id':'1010_dd_option' + opt.val(), 'href':'javascript:void(0)'})
                .text(opt.text().trim()).css('display', 'block');
      if(opt.text().trim().length > 28) dropdown_item.addClass('small');
      dropdown_options.append(dropdown_item);
    }  
  
    //Set up the dropdown item
    dropdown_options.css({'left':selected_item.position().left});
    selected_item.css('margin-bottom',-1)
           .click(function(event){ 
            $('.dd_container[id!=' + container.attr('id')  + '] .dd_options').hide();
             dropdown_options.slideToggle(100);
             event.stopPropagation();
             return false;
           });

    if(options.click_function != undefined){
      $('a', dropdown_options).click(
        function(){
          option_val = $(this).attr('id').replace('1010_dd_option', '');
          sel_id = $(this).parent().parent().attr('id').replace('1010_dd_', '');
          sel = $('#' + sel_id);
          $('option', sel).removeAttr('selected');
          $('option[value=' + option_val + ']', sel).attr('selected', 'selected');
          options.click_function($(this));
          return false;
        }
      );
    }
    
    $('body').click(function(){dropdown_options.slideUp(100);});    
    $('input').focus(function(){dropdown_options.slideUp(100); return true; });
    $('body') .focus(function(){dropdown_options.slideUp(100); return true; });
    $('a', dropdown_options).click(
      function(){
        selected_link.text($(this).text());
        dropdown_options.slideUp();
        return false;
      }
    );
    
    selected_item.keypress(function(e){
      e.stopPropagation();
      if(e.keyCode == 40){
        $('a:first', dropdown_options).focus();
      }
    });
    
    $('a', dropdown_options).focus(function(e){e.stopPropagation();});
    
    $('a:first',dropdown_options).keypress(function(e){
      e.stopPropagation();
      if(e.keyCode == 38){
        $('a', selected_item).focus();
      }
    });
    
    $('a',dropdown_options).keypress(function(e){
      e.stopPropagation();
      if(e.keyCode == 38){
        $(this).prev().focus();
      }else if(e.keyCode == 40){
        $(this).next().focus();
      }
    });
  });
 };
})(jQuery);

var signee_name = '';
var resizeTimer = null;
var start_count = 0; //Declaration only. This is defined in master.tmpl

$(document).ready(function(){
  $.historyInit(AJAXContent);
  
  $('a.ajax_content').click(function(){
    var page_template = $(this).attr('href').split('/', 3)[2];
    $.historyLoad(page_template);
    $('a.ajax_content').removeClass('selected');
    $(this).addClass('selected').blur();
    return false;
  });
  
  var facebox_elements = $('a[rel*=facebox]');
  if (facebox_elements.length > 0) {
    facebox_elements.facebox({
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.gif'
    });
  }
  
  $('.rounded').corners("5px");
});

function embedVideo(clip_id, element_id, width, height, colour){
  var params = {
    clip_id:clip_id,
    video_width:width,
    video_height:height,
    colour:colour
  }
  swfobject.embedSWF("/flash/vimeoPlayer.swf", element_id, width + 53.4, height + 80, "9.0.0", 
            "/flash/expressInstall.swf", params, {'salign':'l', 'allowscriptaccess':'true', 'wmode':'transparent'});
}

function AJAXContent(page_template) {
  if (page_template == '' || page_template[0] == '_')
    return;

  var section = window.location.href.match(/https?:\/\/[^\/]+\/+([^\/#]*)/)[1];
  var path = '/ajax/content/' + (section || '1010') + '/' + page_template;
  $.getJSON(path, function(result){
    if (result.ok) {
      $('#info_panel .content').html(result.content);
      document.title = result.title;
      $('#sub_nav #_ajax_' + result.page).addClass('selected');
      if (result.item) {
        $('.two_col_right_inner a[href="/1010/' + page_template + '"]').addClass('selected');
      }
      $('#sub_nav a[href=/' + result.section + '/' + result.page + ']').addClass('selected');

      if (page_template == 'whos_in') {
        initAdminTools();
      }
      initChecklist();
      doSIFR();
      var facebox_elements = $('a[rel*=facebox]');
      if (facebox_elements.length > 0) {
        facebox_elements.facebox({
          loadingImage : '/facebox/loading.gif',
          closeImage   : '/facebox/closelabel.gif'
        });
      }
      //checkCookieSetFields();
      pageTracker._trackPageview(path);
    }
  });
}

function initAdminTools() {
  $('.delete-signee').css('cursor', 'pointer').click(function() {
    var key = this.id;
    if (confirm("Really delete " + $('#span-' + key).text().trim() + "? This can't be undone.")) {
      $.post("/a/ajax/signee/delete", {
        'signee_key': key
      }, function(response_string) {
        var response = eval('(' + response_string + ')');
        if (!response['ok']) {
          alert("Error: " + response['error']);
          return;
        }
        $('#span-' + key).remove();
      });
    }
  });
}

var checklistInitialised = false;
function initChecklist() {
  if (checklistInitialised) {
    return;
  }
  var expander_elements = $('.checklist_qualifier, .checklist_headline');
  if (expander_elements.length == 0) {
    return;
  }
  expander_elements.click(function() {
    var a = '(less)';
    var b = '(read more)';
    var y = $(this).children('a.checklist_more');
    var x = $(this).parent().find('.checklist_expanded');
    if (x.is(':hidden')) {
      $('.checklist_expanded').slideUp();
    }
    x.slideToggle();
    if (y.html() == '(read more)'){
        y.html('(less)');
    }else{
        y.html('(read more)');
    }
  });
  $('.checklist_expanded').hide();
  $('.checklist_tickbox').toggle( function() {
      checklist_itemid = $(this).attr('id');
      $(this).css('background-position', '-75px 0');
      return false;
    }, function() {
      $(this).css('background-position', '-0px 0');
      return false;
    });
  $('.checklist_item').corners("5px");

  checklistInitialised = true;
}

function doSIFR(){
  sIFR.replace(genesis, { 
    selector: 'h2.news_title', 
    css: '.sIFR-root { color: #363427; font-size: 40px; text-transform: uppercase }', wmode: 'transparent' 
  });
  
  sIFR.replace(genesis, { 
    selector: '.news_date', 
    css: '.sIFR-root { color: #FFFFFF; font-size:16px; text-align:center; text-transform: uppercase }', 
    wmode:'transparent' 
  });
  sIFR.replace(genesis, { selector: 'h1.altcolor', css: '.sIFR-root { color: #BFBFBF; text-transform:uppercase;}', wmode: 'transparent' });
  sIFR.replace(genesis, { selector: 'h1.coloured_text_people', css: '.sIFR-root { color: #F83195; text-transform:uppercase; }', wmode: 'transparent' });
  sIFR.replace(genesis, { selector: 'h1.big', css: '.sIFR-root { color: #363427; font-size: 60px; text-transform:uppercase; }', wmode: 'transparent' });
  sIFR.replace(genesis, { selector: 'h2.home', css: '.sIFR-root { color: #777777; font-size: 25px; text-transform:uppercase; text-align:center }', wmode: 'transparent' });
  sIFR.replace(genesis, { selector: 'h2', css: '.sIFR-root { color: #BFBFBF; font-size: 25px; text-transform:uppercase; }', wmode: 'transparent' });
  sIFR.replace(genesis, { selector: 'h1', css: '.sIFR-root { color: #363427; text-transform:uppercase;}', wmode: 'transparent' });
  sIFR.replace(genesis, { selector: 'h1.theme', css: '.sIFR-root { font-size: 50px; color: #BFBFBF; text-transform:uppercase;}', wmode: 'transparent' });
}

/*Begin the styling for the monthly themes
*
*/
function initialiseThemeList() {
    $('div.theme_list').hide();
    $('ul#theme_list li').click(function() {
        $(this).siblings().children('div.theme_list').slideUp();
        $(this).siblings("li").removeClass('active');
        $(this).toggleClass('active').find("div.theme_list").slideToggle('fast');
          $('ul#theme_list li.active').css("height", "auto");
        $('ul#theme_list li:not(.active)').css("height", "42px");
    });
}

/*
*
*/
 
// end js/1010_frontpage.js
// begin js/1010_slideform.js
/*  1010_slideform.js
 *
 * This code implements slideable forms.
 *
 */
 
(function($){
 $.fn.slideform = function() {
   return this.each(function() {
     var width = 0;
     var panel_index = 0;
     
    $('fieldset').each(
      function(){
        width += $(this).css('float', 'left').width();
      }
    );
    var container = $(document.createElement('div')).addClass('slider').width(width * 2);
    var clear = $(document.createElement('div')).addClass('clearfix');
    container.append($(this).children()).append(clear);
    $(this).append(container);
    $._enableslide(0, $(this));
  });
 };
})(jQuery);

(function($){
 $.fn.slidenext = function() {
  var width = $(this).width() + 15;
  var margin = $('.slider', $(this)).css('margin-left').replace('px', '');
  if(margin == 'auto') margin = 0;
  var to_slide = -1 * Math.floor(margin/width) + 1;
  $._enableslide(to_slide, $(this));  
  $('.slider', $(this)).animate({'marginLeft':margin - width});
 };
})(jQuery);

(function($){
 $.fn.slideprev = function() {
  var width = $(this).width() + 15;
  var margin = $('.slider', $(this)).css('margin-left').replace('px', '');
  if(margin == 'auto') margin = 0;
  var to_slide = -1 * Math.floor(margin/width) - 1;
  $._enableslide(to_slide, $(this));
  $('.slider', $(this)).animate({'marginLeft':parseInt(margin) + parseInt(width)});
 };
})(jQuery);

(function($){
 $.fn.currentslide = function() {
  var width = $(this).width() + 15;
  var margin = $('.slider', $(this)).css('margin-left').replace('px', '');
  if(margin == 'auto') margin = 0;
  var current_slide = -1 * Math.floor(margin/width);
  return current_slide;
 };
})(jQuery);

jQuery.extend( {
  _enableslide: function(slideIndex, form) { 
    //Disable all inputs and links to prevent tabbing issues
    $(':input', form).attr('tabIndex', '-1');
    $('a', form).attr('tabIndex', '-1');
  
    //Enable links and tabbing on the frame were sliding to
    $('fieldset:eq(' + slideIndex + ') :input', form).removeAttr('tabIndex');
    $('fieldset:eq(' + slideIndex + ')  a', form).removeAttr('tabIndex');
  }
});
// end js/1010_slideform.js
// begin js/1010_signup.js
/*  1010_signup.js
 *
 * This code implements the signup form.
 */

String.prototype.trim = function(){
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
}

$(function(){
  $('label.watermark').watermark();
  $('.show').show();
  $('.hide').hide();
  $('#signup').slideform();
  
  $('#signup_type').dropdown(
    function(el){
      window.location = $('#signup_type option:selected').val();
    }
  , '210px');
});

function ajaxSubmitForm(form, func, submitURL){
  var items = $(':input', form);
  var params = new Object();
  
  items.each(
    function(){
      var el = $(this);
      var type = el.attr('type');
      var param_id = el.attr('name') != ''?el.attr('name'):el.attr('id');
      switch(type){
        case 'submit':
        case 'button':
        case 'image':
          break;
        case  'checkbox':
          // If the checkbox name contains an = sign, we treat it as part of a checkbox group.
          // The form is name=value; if no boxes with that name are checked, no parameter of that
          // name is included. Otherwise all checked values are included.
          var equalsIndex = param_id.indexOf('=');
          if (equalsIndex >= 0) {
            if (el.is(':checked')) {
              _addParam(params, param_id.substring(0, equalsIndex), param_id.substring(equalsIndex + 1));
            }
          } else {
            var el_val =  el.is(':checked')?'true':'false';
            _addParam(params, param_id, el_val);
          }
          break;
        default:
          var el_val = el.val();
          if(el_val == _watermarks[el.attr('id')]) el_val = '';
          _addParam(params, param_id, el_val);
          //params[param_id] = el_val;
          break;
      }
    }
  );

  $.post(submitURL, params, func, 'json');
}

function _addParam(params, param_id, value) {
  if(params[param_id]){
    if(params[param_id] instanceof Array){
      params[param_id].push(value);
    }else{
      param_array = [params[param_id], value];
      params[param_id] = param_array;
    }
  }else{
    // FIXME
    if (param_id == 'name') {
      signee_name = value;
    }
    // FIXME
    params[param_id] = value;
  }
}
// end js/1010_signup.js
// begin js/1010_validation.js
/*  1010_validation.js
 *
 * This code implements the javascript validation for the 1010 signup forms.
 *
 */
var widget_error_please_select = "Please select a type";
var widget_error_must_tick = "You must tick this box";
var widget_error_required = "This is a required field";
var widget_error_email = "Not a valid email address";

jQuery.extend( {
  validate: function(items) {
    var errors_shown = 0;  
    for(el_id in items){
      var el = $(el_id);
      if(el.length == 0) continue;
      var el_val = el.val().trim();
      if(el_val == _watermarks[el_id.replace('#','')]) {
        el_val = '';
      }
      var rules = items[el_id];
      
      if(errors_shown == 0 && rules.required){          
        if(el_val == 'default') {
                _1010_set_error(el, widget_error_please_select);
                errors_shown++;
                continue;
        }
        if(el.is('input[type=checkbox]')){
          if(!el.is(':checked')){
            _1010_set_error(el, widget_error_must_tick);
            errors_shown++;
            continue;
          }
        }else{
          if(el_val == ''){
            _1010_set_error(el, widget_error_required);
            errors_shown++;
            continue;
          }
        }
      }
      if(errors_shown == 0 && rules.email && !(el_val == '' && rules.optional)){
        var pattern = /^([a-zA-Z0-9+_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z]){2,}$/;
        if(el_val == '' || !pattern.test(el_val)){
          _1010_set_error(el, widget_error_email);
          errors_shown++;
          continue;
        }
      }

      // if(errors_shown == 0 && rules.postcode){
      //   var pattern = /^\s*(([A-Z]{1,2}\d[A-Z0-9]?|GIR)\s+(\d[A-Z]{2}))\s*$/i;
      //   if(el_val == '' || !pattern.test(el_val)){
      //     _1010_set_error(el, 'Not a valid postcode');
      //     errors_shown++;
      //     continue;
      //   }
      // }

      var error_el = $('#error_for_' + el.attr('id'));
      error_el.slideUp();
    }
    //console.log("%d errors", errors_shown);
    return errors_shown == 0;
  }
});
 
function _1010_set_error(el, message){
  var el_parent = el.parents('fieldset:first');
  var error_el = $('.error_holder', el_parent);
  if(error_el.length == 0){  
    error_el = $(document.createElement('div')).addClass('error_holder').hide();
    el_parent.append(error_el);
  }
  var er_top = 0; var er_left = 0;  
  if(el.is(':checkbox')){
    el = $('div.checkbox', el.el_parent());
    er_top -= el.height() * .5;
  }
  
  er_top += el.offset().top - el_parent.offset().top + el.height();
  er_left += el.offset().left - el_parent.offset().left + 6;
  
  if(el.is('select#subtype')){
      error_el.text(message).css({'top':'60px', 'left':'0px'});
  }else{
      error_el.text(message).css({'top':er_top, 'left':er_left});
  }
  error_el.click(function(){$(this).fadeOut();el.focus();});
  el.focus(function(){$('.error_holder', $(this).parents('fieldset')).fadeOut();});
  error_el.fadeIn();
}
// end js/1010_validation.js
// begin js/1010_watermark.js
/*  1010_watermark.js
 *
 * This code takes labels with the css class 'watermark' and sets them as
 * a watermark for their 'for' element.
 *
 */
 
 var _watermarks = new Array();
 
 (function($){
 $.fn.watermark = function() {
    return this.each(function() {
      $(this).hide();
      
      var my_input = $('#' + $(this).attr('for'));
      my_input.val($(this).text());
      
      my_input.focus(function() {
        var el = $(this);
        if (el.val() == _watermarks[el.attr('id')]) {
          el.val('');
        }
      });
      
      my_input.blur(function() {
        var el = $(this);
        if (el.val().trim() == '') {
          el.val(_watermarks[el.attr('id')]);
        }
      });
      
      _watermarks[my_input.attr('id')] = my_input.val();
    });
 };
})(jQuery);
// end js/1010_watermark.js
// begin js/jQuery.corners.js
jQuery.fn.corners = function(options) {
  var doneClass = 'rounded_by_jQuery_corners'; /* To prevent double rounding */
  var settings = parseOptions(options);
  var webkitAvailable = false;
  try {
  webkitAvailable = (document.body.style.WebkitBorderRadius !== undefined);
  /* Google Chrome corners look awful */
  var versionIndex = navigator.userAgent.indexOf('Chrome');
  if (versionIndex >= 0) webkitAvailable = false;
  } catch(err) {}
  var mozillaAvailable = false;
  try {
  mozillaAvailable = (document.body.style.MozBorderRadius !== undefined);
  /* Firefox 2 corners look worse */
  var versionIndex = navigator.userAgent.indexOf('Firefox');
  if (versionIndex >= 0 && parseInt(navigator.userAgent.substring(versionIndex+8)) < 3) mozillaAvailable = false;
  } catch(err) {}
  return this.each(function(i,e){
  $e = jQuery(e);
  if ($e.hasClass(doneClass)) return;
  $e.addClass(doneClass);
  var classScan = /{(.*)}/.exec(e.className);
  var s = classScan ? parseOptions(classScan[1], settings) : settings;
  var nodeName = e.nodeName.toLowerCase();
  if (nodeName=='input') e = changeInput(e);
  if (webkitAvailable && s.webkit) roundWebkit(e, s);
  else if(mozillaAvailable && s.mozilla && (s.sizex == s.sizey)) roundMozilla(e, s);
  else {
    var bgColor = backgroundColor(e.parentNode);
    var fgColor = backgroundColor(e);
    switch (nodeName) {
    case 'a':
    case 'input':
      roundLink(e, s, bgColor, fgColor);
      break;
    default:
      roundDiv(e, s, bgColor, fgColor);
      break;
    }
  }
  });
  
  function roundWebkit(e, s) {
  var radius = '' + s.sizex + 'px ' + s.sizey + 'px';
  var $e = jQuery(e);
  if (s.tl) $e.css('WebkitBorderTopLeftRadius', radius);
  if (s.tr) $e.css('WebkitBorderTopRightRadius', radius);
  if (s.bl) $e.css('WebkitBorderBottomLeftRadius', radius);
  if (s.br) $e.css('WebkitBorderBottomRightRadius', radius);
  }
  
  function roundMozilla(e, s)
  {  
  var radius = '' + s.sizex + 'px';
  var $e = jQuery(e);
  if (s.tl) $e.css('-moz-border-radius-topleft', radius);
  if (s.tr) $e.css('-moz-border-radius-topright', radius);
  if (s.bl) $e.css('-moz-border-radius-bottomleft', radius);
  if (s.br) $e.css('-moz-border-radius-bottomright', radius);  
  }
  
  function roundLink(e, s, bgColor, fgColor) {
  var table = tableElement("table");
  var tbody = tableElement("tbody");
  table.appendChild(tbody);
  var tr1 = tableElement("tr");
  var td1 = tableElement("td", "top");
  tr1.appendChild(td1);
  var tr2 = tableElement("tr");
  var td2 = relocateContent(e, s, tableElement("td"));
  tr2.appendChild(td2);
  var tr3 = tableElement("tr");
  var td3 = tableElement("td", "bottom");
  tr3.appendChild(td3);
  if (s.tl||s.tr) {
    tbody.appendChild(tr1);
    addCorners(td1, s, bgColor, fgColor, true);
  }
  tbody.appendChild(tr2);
  if (s.bl||s.br) {
    tbody.appendChild(tr3);
    addCorners(td3, s, bgColor, fgColor, false);
  }
  e.appendChild(table);
  /* Clicking on $('a>table') in IE will trigger onclick but not the href  */
  if (jQuery.browser.msie) table.onclick = ieLinkBypass;
  /* Firefox 2 will render garbage unless we hide the overflow here */
  e.style.overflow = 'hidden';
  }
  
  function ieLinkBypass() {
  if (!this.parentNode.onclick) this.parentNode.click();
  }
  
  function changeInput(e) {
  var a1 = document.createElement("a");
  a1.id = e.id;
  a1.className = e.className;
  if (e.onclick) {
    a1.href = 'javascript:'
    a1.onclick = e.onclick;
  } else {
    jQuery(e).parent('form').each(function() {a1.href = this.action;});
    a1.onclick = submitForm;
  }
  var a2 = document.createTextNode(e.value);
  a1.appendChild(a2);
  e.parentNode.replaceChild(a1, e);
  return a1;
  }

  function submitForm() {
  jQuery(this).parent('form').each(function() {this.submit()});
  return false;
  }

  function roundDiv(e, s, bgColor, fgColor) {
  var div = relocateContent(e, s, document.createElement('div'));
  e.appendChild(div);
  if (s.tl||s.tr) addCorners(e, s, bgColor, fgColor, true);
  if (s.bl||s.br) addCorners(e, s, bgColor, fgColor, false);
  }
  
  function relocateContent(e, s, d) {
  var $e = jQuery(e);
  var c;
  while(c=e.firstChild) d.appendChild(c);
  if (e.style.height) {
    var h = parseInt($e.css('height'));
    d.style.height = h + 'px';
    h += parseInt($e.css('padding-top')) + parseInt($e.css('padding-bottom'));
    e.style.height = h + 'px';
  }
  if (e.style.width) {
    var w = parseInt($e.css('width'));
    d.style.width = w + 'px';
    w += parseInt($e.css('padding-left')) + parseInt($e.css('padding-right'));
    e.style.width = w + 'px';
  }
  d.style.paddingLeft = $e.css('padding-left');
  d.style.paddingRight = $e.css('padding-right');
  if (s.tl||s.tr) {
    d.style.paddingTop = adjustedPadding(e, s, $e.css('padding-top'), true);
  } else {
    d.style.paddingTop = $e.css('padding-top');
  }
  if (s.bl||s.br) {
    d.style.paddingBottom = adjustedPadding(e, s, $e.css('padding-bottom'), false);
  } else {
    d.style.paddingBottom = $e.css('padding-bottom');
  }
  e.style.padding = 0;
  return d;
  }
  
  function adjustedPadding(e, s, pad, top) {
  if (pad.indexOf("px") < 0) {
    try {
    //TODO Make this check work otherwise remove it
    console.error('%s padding not in pixels', (top ? 'top' : 'bottom'), e);
    }
    catch(err) {}
    pad = s.sizey + 'px';
  }
  pad = parseInt(pad);
  if (pad - s.sizey < 0) {
    try {
    console.error('%s padding is %ipx for %ipx corner:', (top ? 'top' : 'bottom'), pad, s.sizey, e);
    }
    catch(err) {}
    pad = s.sizey;
  }
  return pad - s.sizey + 'px';
  }

  function tableElement(kind, valign) {
  var e = document.createElement(kind)
  e.style.border = 'none';
  e.style.borderCollapse = 'collapse';
  e.style.borderSpacing = 0;
  e.style.padding = 0;
  e.style.margin = 0;
  if (valign) e.style.verticalAlign = valign;
  return e;
  }
  
  function backgroundColor(e) {
  try {
    var c = jQuery.css(e, "background-color");
    if ( c.match(/^(transparent|rgba\(0,\s*0,\s*0,\s*0\))$/i) && e.parentNode )
     return backgroundColor(e.parentNode);
    if (c==null)
    return "#ffffff";
    if (c.indexOf("rgb") > -1)
      c = rgb2hex(c);
    if (c.length == 4)
      c = hexShort2hex(c);
    return c;
  } catch(err) {
    return "#ffffff";
  }
  }
  
  function hexShort2hex(c) {
  return '#' +
  c.substring(1,2) +
  c.substring(1,2) +
  c.substring(2,3) +
  c.substring(2,3) +
  c.substring(3,4) +
  c.substring(3,4);
  }

  function rgb2hex(c) {
    var x = 255;
    var hex = '';
    var i;
    var regexp=/([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;
    var array=regexp.exec(c);
    for(i=1;i<4;i++) hex += ('0'+parseInt(array[i]).toString(16)).slice(-2);
    return '#'+hex;
  }
  
  function parseOptions(options, settings) {
  var options = options || '';
  var s = {sizex:5, sizey:5, tl: false, tr: false, bl: false, br: false, webkit:true, mozilla: true, transparent:false};
  if (settings) {
    s.sizex = settings.sizex;
    s.sizey = settings.sizey;
    s.webkit = settings.webkit;
    s.transparent = settings.transparent;
    s.mozilla = settings.mozilla;
  }
  var sizex_set = false;
  var corner_set = false;
  jQuery.each(options.split(' '), function(idx, option) {
    option = option.toLowerCase();
    var i = parseInt(option);
    if (i > 0 && option == i + 'px') {
    s.sizey = i;
    if (!sizex_set) s.sizex = i;
    sizex_set = true;
    } else switch (option) {
    case 'no-native': s.webkit = s.mozilla = false; break;
    case 'webkit': s.webkit = true; break;
    case 'no-webkit': s.webkit = false; break;
    case 'mozilla': s.mozilla = true; break;
    case 'no-mozilla': s.mozilla = false; break;
    case 'anti-alias': s.transparent = false; break;
    case 'transparent': s.transparent = true; break;
    case 'top': corner_set = s.tl = s.tr = true; break;
    case 'right': corner_set = s.tr = s.br = true; break;
    case 'bottom': corner_set = s.bl = s.br = true; break;
    case 'left': corner_set = s.tl = s.bl = true; break;
    case 'top-left': corner_set = s.tl = true; break;
    case 'top-right': corner_set = s.tr = true; break;
    case 'bottom-left': corner_set = s.bl = true; break;
    case 'bottom-right': corner_set = s.br = true; break;
    }
  });
  if (!corner_set) {
    if (!settings) {
    s.tl = s.tr = s.bl = s.br = true;
    } else {
    s.tl = settings.tl;
    s.tr = settings.tr;
    s.bl = settings.bl;
    s.br = settings.br;
    }
  }
  return s;
  }
  
  function alphaBlend(a, b, alpha) {
  var ca = Array(
    parseInt('0x' + a.substring(1, 3)),
    parseInt('0x' + a.substring(3, 5)),
    parseInt('0x' + a.substring(5, 7))
  );
  var cb = Array(
    parseInt('0x' + b.substring(1, 3)),
    parseInt('0x' + b.substring(3, 5)),
    parseInt('0x' + b.substring(5, 7))
  );
  r = '0' + Math.round(ca[0] + (cb[0] - ca[0])*alpha).toString(16);
  g = '0' + Math.round(ca[1] + (cb[1] - ca[1])*alpha).toString(16);
  b = '0' + Math.round(ca[2] + (cb[2] - ca[2])*alpha).toString(16);
  return '#'
    + r.substring(r.length - 2)
    + g.substring(g.length - 2)
    + b.substring(b.length - 2);
  }

  function addCorners(e, s, bgColor, fgColor, top) {
  if (s.transparent) addTransparentCorners(e, s, bgColor, top);
  else addAntiAliasedCorners(e, s, bgColor, fgColor, top);
  }
  
  function addAntiAliasedCorners(e, s, bgColor, fgColor, top) {
  var i, j;
  var d = document.createElement("div");
  d.style.fontSize = '1px';
  d.style.backgroundColor = bgColor;
  var lastarc = 0;
  for (i = 1; i <= s.sizey; i++) {
    var coverage, arc2, arc3;
    // Find intersection of arc with bottom of pixel row
    arc = Math.sqrt(1.0 - Math.pow(1.0 - i / s.sizey, 2)) * s.sizex;
    // Calculate how many pixels are bg, fg and blended.
    var n_bg = s.sizex - Math.ceil(arc);
    var n_fg = Math.floor(lastarc);
    var n_aa = s.sizex - n_bg - n_fg;
    // Create pixel row wrapper
    var x = document.createElement("div");
    var y = d;
    x.style.margin = "0px " + n_bg + "px";
    x.style.height = '1px';
    x.style.overflow = 'hidden';
    // Create the pixel divs for a row (at least one)
    for (j = 1; j <= n_aa; j++) {
    // Calculate coverage per pixel (approximates arc within the pixel)
    if (j == 1) {
      if (j == n_aa) {
      // Single pixel
      coverage = ((arc + lastarc) * .5) - n_fg;
      }
      else {
      // First in a run
      arc2 = Math.sqrt(1.0 - Math.pow(1.0 - (n_bg + 1) / s.sizex, 2)) * s.sizey;
      coverage = (arc2 - (s.sizey - i)) * (arc - n_fg - n_aa + 1) * .5;
      }
    }
    else if (j == n_aa) {
      // Last in a run
      arc2 = Math.sqrt(1.0 - Math.pow((s.sizex - n_bg - j + 1) / s.sizex, 2)) * s.sizey;
      coverage = 1.0 - (1.0 - (arc2 - (s.sizey - i))) * (1.0 - (lastarc - n_fg)) * .5;
    }
    else {
      // Middle of a run
      arc3 = Math.sqrt(1.0 - Math.pow((s.sizex - n_bg - j) / s.sizex, 2)) * s.sizey;
      arc2 = Math.sqrt(1.0 - Math.pow((s.sizex - n_bg - j + 1) / s.sizex, 2)) * s.sizey;
      coverage = ((arc2 + arc3) * .5) - (s.sizey - i);
    }
    
    addCornerDiv(s, x, y, top, alphaBlend(bgColor, fgColor, coverage));
    y = x;
    var x = y.cloneNode(false);
    x.style.margin = "0px 1px";
    }
    addCornerDiv(s, x, y, top, fgColor);
    lastarc = arc;
  }
  if (top)
    e.insertBefore(d, e.firstChild);
  else
    e.appendChild(d);
  }
  
  function addCornerDiv(s, x, y, top, color) {
  if (top && !s.tl) x.style.marginLeft = 0;
  if (top && !s.tr) x.style.marginRight = 0;
  if (!top && !s.bl) x.style.marginLeft = 0;
  if (!top && !s.br) x.style.marginRight = 0;
  x.style.backgroundColor = color;
  if (top)
    y.appendChild(x);
  else
    y.insertBefore(x, y.firstChild);
  }

  function addTransparentCorners(e, s, bgColor, top) {
  var d = document.createElement("div");
  d.style.fontSize = '1px';
  var strip = document.createElement('div');
  strip.style.overflow = 'hidden';
  strip.style.height = '1px';
  strip.style.borderColor = bgColor;
  strip.style.borderStyle = 'none solid';
  var sizex = s.sizex-1;
  var sizey = s.sizey-1;
  if (!sizey) sizey = 1; /* hint for 1x1 */
  for (var i=0; i < s.sizey; i++) {
    var w = sizex - Math.floor(Math.sqrt(1.0 - Math.pow(1.0 - i / sizey, 2)) * sizex);
    if (i==2 && s.sizex==6 && s.sizey==6) w = 2; /* hint for 6x6 */
    var x = strip.cloneNode(false);
    x.style.borderWidth = '0 '+ w +'px';
    if (top) x.style.borderWidth = '0 '+(s.tr?w:0)+'px 0 '+(s.tl?w:0)+'px';
    else x.style.borderWidth = '0 '+(s.br?w:0)+'px 0 '+(s.bl?w:0)+'px';
    top ? d.appendChild(x) : d.insertBefore(x, d.firstChild);
  } 
  if (top)
    e.insertBefore(d, e.firstChild);
  else
    e.appendChild(d);
  }


}
// end js/jQuery.corners.js
// begin js/jQuery.cookie.js
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *     used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *               If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *               If set to null or omitted, the cookie will be a session cookie and will not be retained
 *               when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *            require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
  if (typeof value != 'undefined') { // name and value given, set cookie
    options = options || {};
    if (value === null) {
      value = '';
      options.expires = -1;
    }
    var expires = '';
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
      var date;
      if (typeof options.expires == 'number') {
        date = new Date();
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } else {
        date = options.expires;
      }
      expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
    }
    // CAUTION: Needed to parenthesize options.path and options.domain
    // in the following expressions, otherwise they evaluate to undefined
    // in the packed version for some reason...
    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else { // only name given, get cookie
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
};
// end js/jQuery.cookie.js
// start js/customFields.js
jQuery.fn.customInput = function(){
  $(this).each(function(i){  
    if($(this).is('[type=checkbox],[type=radio]')){
      var input = $(this);
      
      // get the associated label using the input's id
      var label = $('label[for='+input.attr('id')+']');
      
      //get type, for classname suffix 
      var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
      
      // wrap the input + label in a div 
      $('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input, label);
      
      // find all inputs in this set using the shared name attribute
      var allInputs = $('input[name='+input.attr('name')+']');
      
      // necessary for browsers that don't support the :hover pseudo class on labels
      label.hover(
        function(){ 
          $(this).addClass('hover'); 
          if(inputType == 'checkbox' && input.is(':checked')){ 
            $(this).addClass('checkedHover'); 
          } 
        },
        function(){ $(this).removeClass('hover checkedHover'); }
      );
      
      //bind custom event, trigger it, bind click,focus,blur events
      input.bind('updateState', function(){
        if (input.is(':checked')) {
          if (input.is(':radio')) {
            allInputs.each(function() {
              $('label[for='+$(this).attr('id')+']').removeClass('checked');
            });
          }
          label.addClass('checked');
        }
        else {
          label.removeClass('checked checkedHover checkedFocus');
        }
      })
      .trigger('updateState')
      .click(function(){ 
        $(this).trigger('updateState');
      })
      .focus(function(){
        label.addClass('focus');
        if(inputType == 'checkbox' && input.is(':checked')) {
          $(this).addClass('checkedFocus');
        }
      })
      .blur(function(){
        label.removeClass('focus checkedFocus');
      });
    }
  });
};

function addCommas(nStr){
  nStr += '';
  var x = nStr.split('.');
  var x1 = x[0];
  var x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

