jQuery.fn.exists = function(){return jQuery(this).length>0;}

function blockLink(){
  // Make the assigned element link to whatever a href is used within
  $(".blockLink").click(function(){
    linkTo = $(this).find('a').attr("href");
    window.location.href = linkTo;
  });
}

// Open links in new window using rel="external"
function externalLinks() {
  if (!document.getElementsByTagName) return;
  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute("href") &&
        anchor.getAttribute("class") == "newWin")
      anchor.target = "_blank";
  }
}

function eventsFilter(){
  $("#event-nav #checkboxes fieldset ul").addClass('hide').addClass('drop');
  $("#event-nav #checkboxes fieldset legend").hover(function(){
    var ul = "#"+$(this).attr('id')+"-check";
    $(ul).removeClass('hide');
  });
  $("#event-nav #checkboxes fieldset").each(function(){
    $(this).append('<p class="set"></p>');
  }).hover("",function(){
    $(this).children("ul").addClass('hide');
  });
  $("#event-nav #checkboxes input").click(function(){
    var checked = $(this).attr('checked')?1:0;
    if(checked == 1){
      var lbl = '<label for="'+$(this).attr("id")+'" id="'+$(this).attr("id")+'-lbl2">'+$("#"+$(this).attr("id")+"-lbl").text()+'</label>';
      var p = $(this).closest("ul").next().append(lbl).append(" ");
      $("#"+$(this).attr('id')+"-lbl").addClass("checked");
    }else{
      $("#"+$(this).attr('id')+"-lbl2").remove();
      $("#"+$(this).attr('id')+"-lbl").removeClass("checked");
      var str = $(this).closest("ul").next().html();
      str = jQuery.trim(str);
      $(this).closest("ul").next().html(str);
    }
  });
  $("#event-nav #checkboxes input").each(function(){
    var checked = $(this).attr('checked')?1:0;
    if(checked == 1){
      var lbl = '<label for="'+$(this).attr("id")+'" id="'+$(this).attr("id")+'-lbl2">'+$("#"+$(this).attr("id")+"-lbl").text()+'</label>';
      var p = $(this).closest("ul").next().append(lbl).append(" ");
      $("#"+$(this).attr('id')+"-lbl").addClass("checked");
    }else{
      $("#"+$(this).attr('id')+"-lbl2").remove();
      $("#"+$(this).attr('id')+"-lbl").removeClass("checked");
    }
  });
  $("#event-nav #buttons input[type=reset]").click(function(){
    $('#event-nav #checkboxes fieldset p.set').empty();
    $('#event-nav #checkboxes fieldset label.checked').removeClass("checked");
    $("#event-nav #checkboxes input[type=checkbox]").each(function(){
      $(this).removeAttr('checked');
    });
  });
}

function IEBlockLinkHover(){
  // Force IE6 to recognise :hover on .blockLink elements
  $(".blockLink").hover(function(){
    $(this).addClass("hover");
  },function(){
    $(this).removeClass("hover");
  });
}

function IEnlDroplistingHover(){
  // Force IE6 to recognise :hover on .nl-droplisting (for newsletter)
  $("li#nl-droplisting").hover(function(){
    $(this).addClass("hover");
  },function(){
    $(this).removeClass("hover");
  });
}

function editProfileShowHide(){
  // some inputs we can hide to conserve vertical space
  var inputs_to_hide = new Array(
  'business_sector_other',
  'languages_other');
  jQuery.each(inputs_to_hide, function() {
    var target = "#edit-details #"+this+"_text";
    $(target).hide();
    $("#edit-details #"+this).click(function() {
      $(target).toggle();
    });
    var checked = $('#edit-details #'+this).attr('checked')?1:0;
    if(checked == 1){
      $(target).show();
    }
  });

  var areatarget = "#edit-details #area_activity_other_other_text";
  $(areatarget).hide();
  $("#edit-details #area_activity_other").click(function() {
    $(areatarget).toggle();
  });
  var checked = $('#edit-details #area_activity_other').attr('checked')?1:0;
  if(checked == 1){
    $(areatarget).show();
  }

  // Title Select
  $("#edit-details #title").change(function(){
    var target = "#edit-details #title_other_text";
    if($("#edit-details #title").val() == "Other"){
      $(target).show();
    }else{
      $(target).hide();
    }
  });

  if($("#edit-details #title").val() == "Other"){
    $("#edit-details #title_other_text").show();
  }else{
    $("#edit-details #title_other_text").hide();
  }

}

function directoryShowHide(){
  // some inputs we can hide to conserve vertical space
  var inputs_to_hide = new Array(
  'business_sector_other',
  'languages_other');
  jQuery.each(inputs_to_hide, function() {
    var target = "#directory-search #"+this+"_text";
    $(target).hide();
    $("#directory-search #"+this).click(function() {
      $(target).toggle();
    });
    var checked = $('#directory-search #'+this).attr('checked')?1:0;
    if(checked == 1){
      $(target).show();
    }
  });

  var areatarget = "#directory-search #area_activity_other_other_text";
  $(areatarget).hide();
  $("#directory-search #area_activity_other").click(function() {
    $(areatarget).toggle();
  });
  var checked = $('#directory-search #area_activity_other').attr('checked')?1:0;
  if(checked == 1){
    $(areatarget).show();
  }

}

function studentShowHide()
{
  var other_inputs = new Array(
  'title'
  );

  jQuery.each(other_inputs, function(){
    var select = "#student-affiliate #"+this;
    var target = "#student-affiliate #"+this+"_other";

    $(select).change(function(){
      if($(this).val() == "Other")
      {
        $(target).show();
        $(target+"_lbl").show();
      }
      else
      {
        $(target).hide();
        $(target+"_lbl").hide();
      }
    });

    if($(select).val() != "Other")
    {
      $(target).hide();
      $(target+"_lbl").hide();
    }

  });

  var has_rcp_inputs = '#rcp,#name_of_institution,#name_of_programme,#rcp_lbl,#name_of_institution_lbl,#name_of_programme_lbl';

  var no_rcp_inputs = '#name_of_institution_other,#name_of_programme_other,#name_of_institution_other_lbl,#name_of_programme_other_lbl';

  $('input[name=has_rcp]','#student-affiliate').change(function(){
    if($(this).val() == "No")
    {
      $(has_rcp_inputs,'#student-affiliate').hide();
      $(no_rcp_inputs,'#student-affiliate').show();
    }
    else
    {
      $(has_rcp_inputs,'#student-affiliate').show();
      $(no_rcp_inputs,'#student-affiliate').hide();
    }
  });

  if($('input[name=has_rcp]','#student-affiliate').val() == "No")
  {
    $(has_rcp_inputs,'#student-affiliate').hide();
  }
  else
  {
    $(no_rcp_inputs,'#student-affiliate').hide();
  }
}

function highlightEvents(){
  $('#events-cal td ul li').hover(function(){
  var link = $(this).attr('rel');
  $('#events-cal td ul li[rel='+link+']').addClass("hover");
  },function(){
  var link = $(this).attr('rel');
  $('#events-cal td ul li[rel='+link+']').removeClass("hover");
  });
}

// Other Delagates

function otherDelagates($fieldset){

  // Hide or Show on Page Load
  var $result = $($fieldset).find('.options input:checked').val();
  if ( $result == 'No' ) {
    $($fieldset).find('select').closest('.field').hide();
  } else {
    $($fieldset).find('select').closest('.field').show();
  }

  // Hide or Show on Change
  $($fieldset).find('.options input').click(function(){
    var $new_result = $(this).val();
    if ( $new_result == 'No' ) {
      $($fieldset).find('select').closest('.field').hide();
    } else {
      $($fieldset).find('select').closest('.field').show();
    }
  });

}

function inputLabelShowHide($input){

  $($input).each(function(){
    if ($(this).val() == '') {
        $(this).siblings('label').show();
    } else {
        $(this).siblings('label').hide();
    }
  });

  $($input).focus(function(){
    $(this).siblings('label').hide();
  });

  $($input).blur(function(){
    if ($(this).val() == ''){
        $(this).siblings('label').show();
    }
  });

}

function yearList(){

  $('body.publications #filter').show();

  var $year_list = [];
  $('body.publications .pub_vols .date').each(function(){
    $year_val = $(this).text();
    $year_list.push('<option>' + $year_val + '</option>');
    $('body.publications #filter select').append('<option>' + $year_val + '</option>');
  });

  // Remove duplicate from dropdown list
  var $years = {};
  $('body.publications #filter option').each(function(){
    var txt = $(this).text();
    if ($years[txt]){
      $(this).remove();
    } else {
      $years[txt] = true;
    }
  });

}

function courseFinderCleanup(){
  $('table.courses').each(function(){
      $has_events = $(this).find('tbody').find('tr').length;
      if ($has_events < 1) {
          $(this).hide()
      }
  });
}

$(document).ready(function () {

  jQuery.each(jQuery.browser, function(i) {
    if($.browser.msie && jQuery.browser.version.substr(0,1)=="6"){
      IEBlockLinkHover();
      IEnlDroplistingHover();
    }
  });

  $('body').removeClass('no_js').addClass('js');

  blockLink();
  editProfileShowHide();
  directoryShowHide();
  eventsFilter();
  externalLinks();
  highlightEvents();
  studentShowHide();
  otherDelagates('#fieldset-otherDelegatesGroup');
  inputLabelShowHide('#fieldset-otherDelegatesGroup .col_2 input, #fieldset-otherDelegatesGroup .col_3 input, #fieldset-otherDelegatesGroup .col_4 input');
  $('#fieldset-otherDelegatesGroup').find('.field').addClass('yes_js');
  yearList();
  courseFinderCleanup();

  if ($.browser.msie) {
    $('input:radio').click(function () {
      this.blur();
      this.focus();
    });
  }

  if ($('#volume_switch ul').children().size() >= 1){
    // Show and Hide Dropdown
    $('#volume_switch').hover(function(){
      $(this).children('ul').show();
    },function(){
      $(this).children('ul').hide();
    });
  }

  if ($('#volume_switch ul').children().size() < 1){
    // Hide Arrow if has no list items
    $('#volume_switch h3').addClass('no_arrow');
  }

  $('#filter select').change(function() {
    var v = $(this).val();

    $('.pub_vols').each(function() {
      $(this).removeClass('show').addClass('hide');
      if ($(this).hasClass('y_'+v)) {
        $(this).removeClass('hide').addClass('show');
      }
    });

    if (v == 'All Years') {
      $('.pub_vols').each(function() {
        $(this).addClass('show').removeClass('hide');
      });
    }
  });

  if ($('a#fancybox').exists()) {
    $('a#fancybox').fancybox({'titleShow' : false, 'width' : 600, 'height' : 630});
  }

  if ($('a.fancybox').exists()) {
    $('a.fancybox').fancybox({'titleShow' : false, 'width' : 600, 'height' : 630});
  }

  if ($('.form').exists()) {
    // Detects in the option "other" is currently selected or not
    // This is for when you submit the form if it's selected, it will keep it shown
    if ($('#title').val() === 'Other'){
      $('#titleOther').parent().show();
    }
    else {
      $('#titleOther').parent().hide();
    }

    // Changes the vivibility of the other title box if other option is selected or not
    $('#title').change(function(){
        var selected = $(this).val();
        if(selected == 'Other'){
          $('#titleOther').parent().show();
        }
        else{
          $('#titleOther').parent().hide();
        }
    });

    $('.form .l_col input').focus(function(){
      $(this).parent().siblings('.messages').show();
    });

    $('.form .l_col input').blur(function(){
      $(this).parent().siblings('.messages').hide();
    });

    $('.form .delegates .col_1 label').hide();
    $('.form .delegates .col_2 label').addClass('label_pos');
    $('.form .delegates .col_3 label').addClass('label_pos');
    $('.form .delegates .col_4 label').addClass('label_pos');
  }

  if ($('#edit_profile').exists()) {
    /*
     * Stall user if changes have been made
     */
    var changed = false;

    if ($('.errors', '.form').length > 0) {
      changed = true;
    }

    var section = '<?php echo $this->title ?>';

    $('input, textarea, select', '.form').change(function(){
      changed = true;
    });

    $('a', '#form_nav').click(function(){
      if (changed == true) {
        var check = confirm('You have unsaved changes in the ' + section + ' section. Would you like to discard them and proceed?');

        if (check == false) {
          return false;
        }

        return true;
      }
    });

    /*
     * Add JS powered version
     */
    $('.field', '.form').each(function(){
      if ($('.display_option', this).length > 0) {
        $(this).hide();
        var current = $('input:checked', this).val();

        $(this).prev().append('<div class="do current_' + current + '"><ul><li class="hidden">Hidden</li><li class="members">Members</li><li class="public">Public</li></ul></div>');
      }
    });

    /*
     * Display option show/hide
     */
    $('.do').click(function(){
      $('ul:visible', '.do').hide();
      $('ul', this).show();
    });

    var displayActive = false;

    $('.do').hover(function(){
      displayActive = true;
    }, function(){
      displayActive = false;
    });

    $('body').mouseup(function(){
      if (!displayActive) {
        $('ul:visible', '.do').hide();
      }
    });

    /*
     * Update actual field value on change
     */
    $('li', '.do').click(function(e){
      var opt = '0';
      switch ($(this).text()) {
        case 'Hidden':
          opt = '0';
          break;
        case 'Members':
          opt = '1';
          break;
        case 'Public':
          opt = '2';
          break;
      }

      var parent = $(this).closest('.do');
      $(parent).removeClass('current_0 current_1 current_2');
      $(parent).addClass('current_' + opt);

      var actual_input = $(this).closest('.field').next('.field').get(0);
      $('input:checked', actual_input).attr('checked', false);
      $('input[value=' + opt + ']', actual_input).attr('checked', true);

      changed = true;
      displayActive = false;
      $('ul:visible', '.do').hide();
      e.stopPropagation();
    });
  }

  if ($('#tickets').exists()) {
    /*
     * Ticket total counter
     */
    $('<div class="ticket_total"><h3>Ticket Total</h3><h4>&pound;0</h4></div>').prependTo('#fieldset-buttons');
    var $total_el = $('.ticket_total h4');

    function updateTotal()
    {
      var total = 0;

      $('.ticket:visible').each(function() {
        var add = false;

        if ($(this).is('input') && $(this).is(':checked')) {
          var add = tickets['dinner'];
        } else {
          var add = tickets[$(this).val()];
        }

        if (!isNaN(add)) {
          total = total + add;
        }
      });

      $('.guests:visible').each(function() {
        total = total + (tickets['guest']*$(this).val());
      });

      $total_el.text('£' + total.toFixed(2));
    }
    updateTotal();

    $('select.ticket, select.guests').change(function() {
      updateTotal();
    });

    $('input.ticket').click(function() {
      updateTotal();
    });

    $('#delegateCheck-No').click(function() {
      $('select, input', '#fieldset-otherDelegatesGroup').each(function() {
        if ($(this).attr('id') != 'delegateCheck-Yes' && $(this).attr('id') != 'delegateCheck-No') {
          $(this).val('');
          $(this).blur().change();
        }
      });
    });

    /*
     * Primary Delegate
     */
    if ($('#fieldset-checkGroup input[type=radio]:checked').val() == 'Yes') {
      $('#primaryContactSpecialRequirements, #primaryContactTicket, #primaryContactDinnerTicket, #primaryContactMemberID, #primaryContactGuests, #primaryContactGuest1, #primaryContactGuest2', '#fieldset-primaryContactGroup').closest('.field').show();
      $('.instructions #pri_del', '#fieldset-primaryContactGroup').show();
      $('.instructions #pri_con', '#fieldset-primaryContactGroup').hide();
      $('#fieldset-primaryDelegateGroup').closest('.r_col').hide();
      updateTotal();
    } else {
      $('#primaryContactSpecialRequirements, #primaryContactTicket, #primaryContactDinnerTicket, #primaryContactMemberID, #primaryContactGuests, #primaryContactGuest1, #primaryContactGuest2', '#fieldset-primaryContactGroup').closest('.field').hide();
      $('.instructions #pri_del', '#fieldset-primaryContactGroup').hide();
      $('.instructions #pri_con', '#fieldset-primaryContactGroup').show();
      $('#fieldset-primaryDelegateGroup').closest('.r_col').show();
      updateTotal();
    }

    $('#fieldset-checkGroup input[type=radio]').change(function() {
      if ($(this).val() == 'Yes') {
        $('#primaryContactSpecialRequirements, #primaryContactTicket, #primaryContactDinnerTicket, #primaryContactMemberID, #primaryContactGuests, #primaryContactGuest1, #primaryContactGuest2', '#fieldset-primaryContactGroup').closest('.field').show();
        $('.instructions #pri_del', '#fieldset-primaryContactGroup').show();
        $('.instructions #pri_con', '#fieldset-primaryContactGroup').hide();
        $('#fieldset-primaryDelegateGroup').closest('.r_col').hide();
        updateTotal();
      } else {
        $('#primaryContactSpecialRequirements, #primaryContactTicket, #primaryContactDinnerTicket, #primaryContactMemberID, #primaryContactGuests, #primaryContactGuest1, #primaryContactGuest2', '#fieldset-primaryContactGroup').closest('.field').hide();
        $('.instructions #pri_del', '#fieldset-primaryContactGroup').hide();
        $('.instructions #pri_con', '#fieldset-primaryContactGroup').show();
        $('#fieldset-primaryDelegateGroup').closest('.r_col').show();
        updateTotal();
      }
    });

  }

  if ($('#student.form').exists()) {
    var $hasRCP = $('#institutionNameRCP, #programmeNameRCP, #rcpCode', '#fieldset-studyGroup').closest('.field');
    var $noRCP = $('#institutionNameText, #programmeNameText', '#fieldset-studyGroup').closest('.field');

    if ($('#fieldset-studyGroup input[type=radio]:checked').val() == 1) {
      $hasRCP.show();
      $noRCP.hide();
    } else {
      $noRCP.show();
      $hasRCP.hide();
    }

    $('#fieldset-studyGroup input[type=radio]').change(function() {
      // console.log($(this).val());
      if ($(this).val() == 1) {
        $hasRCP.show();
        $noRCP.hide();
      } else {
        $noRCP.show();
        $hasRCP.hide();
      }
    });
  }

  if ($('#profile_boost').exists()) {
    $('#boost_click').fancybox({
      'titleShow' : false,
      'autoDimensions': false,
      'width' : 550,
      'height' : 600,
      'hideOnOverlayClick': false,
      'showCloseButton': false,
      'enableEscapeButton': false
    }).trigger('click');
  }

  if ($('#upgrade-request').exists()) {
    $('#fieldset-upgradingToGroup input[type=radio]').change(function() {
      if ($('#fieldset-upgradingToGroup input[type=radio]:checked').val() == 'fellow') {
        $('#fieldset-fellowGroup').closest('.r_col').show();
        $('#fieldset-memberGroup').closest('.r_col').hide();
      } else {
        $('#fieldset-fellowGroup').closest('.r_col').hide();
        $('#fieldset-memberGroup').closest('.r_col').show();
      }
    }).filter(':checked').change();
  }
});
