document.observe("dom:loaded", function(event) {
    /* Class name allows us to style for situations with & without javascript */
    $$('body')[0].addClassName('js_on');
    
    /* Get issue background colour */
    if($$('body')[0].getStyle('background-color') == 'rgba(0, 0, 0, 0)'){
      bg_colour = 'white';
    } else {
      bg_colour = $$('body')[0].getStyle('background-color');
    }

    main_navigation();
    issue_browser();
    quick_search();

    Cufon.replace($$('#main_navigation a.primary'));
    /* Don't replace the logo */
    /*
    $$('h1').each(function(element){
      if(!element.hasClassName('logo')){
      Cufon.replace(element);
      }
    })
    Cufon.replace('h2');
    Cufon.replace('h3');
    Cufon.replace('h4');
*/
    obfuscate_mails();
    
  /* Post cookie data etc across to Secure Trading when people enter checkout so that we don't lose users in Analytics at this point 
     See http://code.google.com/apis/analytics/docs/tracking/gaTrackingSite.html#domainAndSubDirectory */
  if (window.location.toString().include('basket')){
    $('submit_to_securetrading').observe('click', function(){
      pageTracker._linkByPost('https://securetrading.net/authorize/form.cgi');
    })
  }

  /* Pick up the mess of IE's useless handling of the accept-charset form tag attribute */
  /* For form submissions from our site to Secure Trading */
  if (window.location.toString().include('basket') && Prototype.Browser.IE){
    force_charset();
  }

  if($$('input[name=relevance]')[0]) {sort_search_by_relevance()};
  if($('web_survey')){web_survey_form();}
  if($('author_index')){author_index();}
});

/* Removes "Search NLR" text from search field when clicked, and replaces it when user clicks elsewhere */
function quick_search(){
    var search_text = $('search_nlr').readAttribute('value');
    $('search_nlr').writeAttribute('value', search_text);
    $('search_nlr').observe('focus', function(event){
    $('search_nlr').writeAttribute('value', '');
    event.stop();
  });
  $('search_nlr').observe('blur', function(event){
    $('search_nlr').writeAttribute('value', search_text);
    event.stop();
  });
}

function issue_browser(){
  $('issue_browser').setStyle({
    backgroundColor: bg_colour
  });
  $$('#issue_browser .label')[0].observe('click', function(event){
    $$('#issue_browser #decades')[0].toggleClassName('open');
    $('issue_browser').toggleClassName('open');
})
  $$('#issue_browser #decades .label').each(function(label){
    label.observe('click', function(event){
      label.next().toggleClassName('open');
    });
  });
}

function main_navigation(){
    /* We set the position on .subnavs here so that they can stay in normal page flow if javascript is disabled */
    $$('.subnav').each(function(element){
        element.hide();
        element.setStyle({
            position: 'absolute',
            backgroundColor: bg_colour
        });
    })
    $$('#main_navigation a.primary').each(function(element){
      if(element.next('ul')){
        element.observe('click',function(event){
            $$('#main_navigation a.primary').each(function(element2){
                  if(element2.next('ul') && element2.next('ul').getStyle('display') == 'block'){
                      element2.next('ul').hide();
                   }
                  });
            element.next().toggle();
            event.stop();
        });
      }
    });
}

/* Fixes IE submission of forms from UTF-8 pages to secure trading's ISO-8859-1 pages */
function force_charset(){
  document.charset = 'ISO-8859-1';
  window.onbeforeunload = function(){
    document.charset = 'UTF-8';
  }
}

function obfuscate_mails(){
    $$('.obfuscated_mail').each(function(element){
        address = element.id + '@newleftreview.org';
        link = "<a href='mailto:" + address + "'>" + address + "</a>"
        element.replace(link);
    });
}

function sort_search_by_relevance(){
  checkbox = $$('input[name=relevance]')[0];
  /* Just in case we're reloading a page where the box is already checked: */
  toggle_sort_dropdown();

  /* Then check status of checkbox and hide/ show dropdown accordingly on every click of checkbox */
  checkbox.observe('click', function(){
	  toggle_sort_dropdown();
	});

  function toggle_sort_dropdown(){
    if(checkbox.checked){
      $$('.relevance_dropdown').invoke('hide');
    } else {
      $$('.relevance_dropdown').invoke('show');
    }
  }
}

function web_survey_form(){
  add_comment_togglers();
  /*show_elements_on_true($$("input[name='current_subscriber']"), $$('.subscriber_questions'), $$('.non-subscriber_questions'));*/
  show_elements_on_values($$("input[name='current_subscriber']"), ['0'], $$('.purchase_route'));
  show_elements_on_true($$("input[name='bookshop_purchaser']"), $$('.bookshop_difficulties'), []);
  show_elements_on_true($$("input[name='bookshop_difficulties']"), $$('.bookshop_details'), []);
/*  show_elements_on_true($$("input[name='website_user']"), $$('.website_user_questions'), $$('.non-subscriber_questions'));*/
  show_elements_on_values($$("input[name='how_do_you_read_nlr']"), ['website via other device'], $$('.specify_other_devices'));
  show_elements_on_values($$("input[name='how_do_you_read_nlr']"), ['mixture'], $$('.specify_mixture_of_reading_ways'));
  show_elements_on_values($$("input[name='website_usability']"), ['moderate', 'hard', 'very hard'], $$('.describe_website_difficulties'));
  show_elements_on_values($$("input[name='website_usage_type']"), ['other'], $$('.specify_website_usage_type'));
  show_elements_on_true($$("input[name='satisfied_with_packaging_mailing']"), $$('.packaging_mailing_comments'), []);
  show_elements_on_values($$("input[name='subscription_quality']"), ['average', 'poor'], $$('.subscription_service_comments'));
  show_elements_on_values($$("input[name='educational_level']"), ['first degree', 'masters degree', 'phd'], $$('.which_first_degree'));
  show_elements_on_values($$("input[name='occupational_status']"), ['in paid employment', 'self-employed', 'student', 'other'], $$('.employment_questions'));
  show_elements_on_values($$("input[name='reader_citizen_of_resident_country']"), ['0'], $$('.reader_which_country_citizen'));
  show_elements_on_values($$("input[name='nlr_site_available_through_library']"), ['0'], $$('.library_used'));
  show_elements_on_values($$("input[name='educational_level']"), ['other'], $$('.other_educational_level'));
  show_elements_on_values($$("input[name='website_functionality_requests']"), ['other'], $$('.specify_website_functionality_request'));
  
  /* Shows/ hides specific form elements depending on non-boolean value responses */
  function show_elements_on_values(trigger_elements, values, showable_elements){
    showable_elements.invoke('hide');
    
    trigger_elements.each(function(e){
      e.checked = false;
      e.observe('click', function(){
          /* Show elements on a matching response */
          if(matching_response_for(trigger_elements, values)){
            showable_elements.invoke('show');
          } else {
          /* Hide elements on a non-matching response */
            showable_elements.invoke('hide');
          }
        });
      });
  }

/* Shows/ hides specific form elements depending on positive/ negative responses
   arg1: array of "trigger" elements - i.e. the parts of the form from which we expect a positive or negative result
   arg2: array of "yes" elements - i.e. items to show if we get a "yes" response
   arg3(optional): array of "no" elements - i.e. items to show if we get a "no" response */
  function show_elements_on_true(trigger_elements, yes_elements, no_elements){
    /* Hide any "no" elements that have been defined */
    if(no_elements != 'undefined'){
      no_elements.invoke('hide');
    } else {
      no_elements = [];
    }
    /* Also start with "yes" elements hidden */
    yes_elements.invoke('hide');

    /* Set event listeners on trigger elements*/
    trigger_elements.each(function(e){
      e.checked = false;
      e.observe('click', function(){
        /* Show "yes" elements on a positive response */
        if(true_response_for(trigger_elements)){
          yes_elements.invoke('show');
          no_elements.invoke('hide');
        } else {
        /* Show "no" elements on a negative response */
          no_elements.invoke('show');
          yes_elements.invoke('hide');
        }
      });
    });
  }

  function true_response_for(elements){
    /* Iterate through array of elements, and set value if any are checked */
    elements.each(function(e){if(e.checked){value = e.value}})
    /* Return true if value has been set to true */
    if(value == 'true' || value == '1'){
      return true
    } else {
      return false
    }
  }

  function matching_response_for(elements, match_values){
    /* Iterate through array of elements, and set value if any are checked */
    elements.each(function(e){if(e.checked){selected_value = e.value}})
    /* Set match to true if selected_value matches a match_value */
    match = false;
    match_values.each(function(e){if(e == selected_value){match = true;}})
    return match;
  }

  function add_comment_togglers(){
    /* Hide togglable comment fields */
    $$('.togglable_comment').each(function(e){e.hide()});
    var togglers = $$('.comment_toggler');
    /* Iterate through array of elements, and set value if any are checked */
    togglers.each(function(e){
        var togglable_comment = e.next();
        e.observe('click', function(){
            togglable_comment.toggle();
        });
    });
  }
}

function author_index(){
  /* Pre-hide sections then set up the event listeners */
  $$('.letter').each(function(e){e.hide()});
  $$('.togglers').each(function(element){
    element.observe('click', function(event){
      var anchor;
      element.href.gsub(/[A-Z]_authors/, function(match){ anchor = match[0] });
      $$('.letter').each(function(e){e.hide()});
      $(anchor).toggle();
      event.stop();
    });
  });
  /* Add hide/ show all option */
  $('alphabetic_buttons').insert({ before: '<a href="#view_all" class="hidden" id="view_all">Hide/show all contributors</a>' });
  $('view_all').observe('click',function(event){
    if($('view_all').hasClassName('hidden')){
      $$('.letter').each(function(e){e.show()});
      $('view_all').removeClassName('hidden');
    } else {
      $$('.letter').each(function(e){e.hide()});
      $('view_all').addClassName('hidden');
    }
    event.stop();
  });
}

/* Add browser version sniffing to Prototype */
/* From http://stackoverflow.com/questions/209043/browser-version-in-prototype-library */
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

