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 dynamicRate(country){
  $.get("ajaxrate.php", { c: country },function(data){
    if(data != ""){
      $("p.dynamic_rate").text("Your fee will be £"+data+"");
    }else{
      $("p.dynamic_rate").text("");
    }
  });
}

function applicationShowHide(){
  // some inputs we can hide to conserve vertical space
  var inputs_to_hide = new Array(
  'profile_business_sector_other',
  'languages_other',
  'hear_about_newspaper',
  'hear_about_branch',
  'hear_about_online',
  'hear_about_advertisement',
  'hear_about_other');
  jQuery.each(inputs_to_hide, function() {
    var target = "#application #"+this+"_text";
    $(target).hide();
    $("#application #"+this).click(function() {
      $(target).toggle();
    });
    var checked = $('#application #'+this).attr('checked')?1:0;
    if(checked == 1){
      $(target).show();
    }
  });
  // some chunks to hide
  var chunks_to_hide = new Array(
  'profile_arbitration_experience',
  'prior_conduct_expelled',
  'prior_conduct_bankruptcy',
  'prior_conduct_outstanding_judgements',
  'prior_conduct_convictions',
  'profile_qualifications',
  'profile_institute_member');
  jQuery.each(chunks_to_hide, function() {
    var target = "#application #"+this+"_yes_details";
    var radio_name = "#application #"+this;
    $(radio_name+"_yes").click(function() {
      $(target).show();
    });
    $(radio_name+"_no").click(function() {
      $(target).hide();
    });
    $('input:radio[name='+this+']:checked').click();
  });
  // Title Select
  $("#application #name_title").change(function(){
    var target = "#application #name_title_other_text";
    if($("#application #name_title").val() == "Other"){
      $(target).show();
    }else{
      $(target).hide();
    }
  });

  if($("#application #name_title").val() == "Other"){
    $("#application #name_title_other_text").show();
  }else{
    $("#application #name_title_other_text").hide();
  }

  $("#application #correspondence_country").change(function(){
    dynamicRate($("#application #correspondence_country").val());
  });

  if($("#application #correspondence_country").length > 0)
  {
    dynamicRate($("#application #correspondence_country").val());
  }

}

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 upgradeShowHide()
{

  var inputs_to_hide = new Array(
  'module-1',
  'module-2',
  'module-3',
  'module-4',
  'peer-interview',
  'recognised-course');
  jQuery.each(inputs_to_hide, function() {
    if(this == 'recognised-course')
    {
      var target = "#upgrade-request .recognised-course-details";
    }
    else
    {
      var target = "#upgrade-request #"+this+"-date";
    }
    $(target).hide();
    $("#upgrade-request #"+this).click(function() {
      $(target).toggle();
    });
    var checked = $('#upgrade-request #'+this).attr('checked')?1:0;
    if(checked == 1){
      $(target).show();
    }
  });

  var fellow_checked = $('#upgrade-request #upgrading-to-fellow').attr('checked')?1:0;
  if(fellow_checked == 0){
    $("#upgrade-request .fellow-only").hide();
  }

  $("#upgrade-request input[name='upgrading-to']").change(function() {
    if($("#upgrade-request input[name='upgrading-to']:checked").val() == "Fellow")
    {
      $("#upgrade-request .fellow-only").show();
    }
    else
    {
      $("#upgrade-request .fellow-only").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");
  });
}


$(document).ready(function () {
  jQuery.each(jQuery.browser, function(i) {
    if($.browser.msie && jQuery.browser.version.substr(0,1)=="6"){
      // Force IE6 to use PNGs with transparency
      DD_belatedPNG.fix('.featured,#search-btn,#course-finder input,#actions li,#browse-months a,#event-nav #buttons input,#my-actions li');
      IEBlockLinkHover();
      IEnlDroplistingHover();
    }
  });
  blockLink();
  $.validator.setDefaults({
    debug: false
  });
  $("#application.join").validate(
    {
      rules: {
        correspondence_email: {
          required: true,
          email: true
        },
        date_of_birth: {
          required: true,
          date: true
        }
      }
    }
  );
  applicationShowHide();
  editProfileShowHide();
  directoryShowHide();
  eventsFilter();
  externalLinks();
  highlightEvents();
  studentShowHide();
  upgradeShowHide();
  $(function () {
    if ($.browser.msie) {
        $('input:radio').click(function () {
            this.blur();
            this.focus();
        });
    }
  });

  jQuery.fn.exists = function(){return jQuery(this).length>0;}

  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();
        }
    });

    // jquery validate
    if ($('body.interest').exists()) {
      $('#interested').validate({
        rules: {
          firstName: "required",
          surname: "required",
          email: { required: true, email: true }
        },
        messages: {
          firstName: "Please enter your first name",
          surname: "Please enter your Family name (surname)",
          email: "Please enter a valid email address"
        }
      });
    }

    $('.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');
  }
});