String.prototype.trim = function () {
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// IE6 Test - IE 6 and below require an IFRAME behind the wordlist container in order to prevent select boxes gaining z-index precidence
temp=navigator.appVersion.split('MSIE');
ieVer=parseInt(temp[1]);
isIE6=(ieVer <= 6)?1:0;
isIE7=(ieVer == 7)?1:0;
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
	isFF = 1;
} else {
	isFF = 0;
}

$(document).ready(function(){
  
//intermittently on page load disableClicks is set to 1 - make sure it is deleted on page load
  $.cookie('disableClicks', null, {path: cookiepath});
  
//show fade message
  if(fadeMessage && fadeMessage!='#FadeMessage'){
    //format fade message text to make message ID less prominent
    fadePosition = fadeMessage.lastIndexOf('[');
    if(fadePosition!='-1'){
      messageID = fadeMessage.substring(fadePosition,(fadeMessage.length));
      messageText = fadeMessage.substring(0,(fadePosition-1)); 
    }  else {
      messageID= '';
      messageText = fadeMessage;
    }
   
    $('#fadeMessage').html("<div class='messageText'>" + messageText + " </div>" + "<div class='circmsgid'>" + messageID + " </div>" + "<img src='"+PublicDir+"/images/brsw.png'/>");
    //CSS not displaying as expected in IE, forcing display in javascript as work around
    if(isIE6 || isIE7){
      $('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0'});
    } else {
			$('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0','marginLeft':'170px'});
		}
    
    setTimeout(function(){
      $('#fadeMessage').fadeOut('slow');
    },4000);
  } else {
    $('#fadeMessage').addClass('hidden');
  }


// select any text already in field for the onFocusSelect field

  $(".onFocusSelect").focus(function(){
    if(this.value == this.defaultValue){
      this.select();
    }
  });
  
// set rating if exists

  $(function(){ 
    $('.rating :radio.star').each(function(){
      $(this).rating();
    });
  });


//Set focus to first input field

  $("input:reset").each(function(){
    $(this).click(function(){
      $("input.button").each(function(){
        $(this).attr('disabled',null);
      });
    });   
  });
  
// Loading message to prevent double requests

  $("form").submit(function(){
    if($(this).attr("name") == "login") {
      var islogin = true;
    } else {
      var islogin = false;
    }
    if($(this).attr("name") == "outputdialog") {
       var isoutput = true;
    } else {
       var isoutput = false;
    }
    if($(this).attr("name") == "email") {
       var emoutput = true;
    } else {
       var emoutput = false;
    }
    if ($(this).attr("action") != null) {
      var hrefdest=$(this).attr("action");
      var nodll = hrefdest.toUpperCase();
      var nodllno =  nodll.indexOf("HAPI.DLL");
      var nosdisub = nodll.indexOf("SDISUBJECTS");
    } else {
       var nodllno =  -1;
       var nosdisub = -1;
    }
    if ((nodllno == -1) || (isoutput == true) || (nosdisub != -1) || (emoutput == true) || (islogin == true)) {
       return;
    } else {
      $("input.button").each(function(){
        $(this).attr('disabled','disabled');
      });
      $(".alert").html(' ');
      $(".alert").append(PageLoadWarning + "<img id='alertIcon' alt='please wait' src='" + PublicDir + "/icons/loader.gif'/>");
      $("div.alert").fadeIn("fast");
      $("span.sessionkind2").fadeIn("fast");
      $.cookie('disableClicks', '1', {path: cookiepath});
      $('#secondaryButton').attr('disabled',null);
    }
  });
  
  $("a").click(function(event){
    var disableClicks = $.cookie('disableClicks');
    if(disableClicks && disableClicks=='1'){
      event.preventDefault();
    } else {
      var aHref = $(this).attr('href');
      if(aHref){
        var hapiTest = aHref.indexOf('Hapi.dll',aHref);
      } else {
        var hapiTest = '0';
      }

      if(hapiTest!=0 && hapiTest!=-1){
        $("input.button").each(function(){
          $(this).attr('disabled','disabled');
        });
        $(".alert").html(' ');
        $(".alert").append(PageLoadWarning + "<img id='alertIcon' alt='please wait' src='" + PublicDir + "/icons/loader.gif'/>");
        $("div.alert").fadeIn("fast");
        $("span.sessionkind2").fadeIn("fast");
        $.cookie('disableClicks', '1', {path: cookiepath});
      }
      
    }

  });
  
// Perform ajax request for data and re-direct (to prevent reposts on use of browser back button)
// Convert checkboxes from checkboxName=on & NULL to checkboxName=1 and checkboxName=0
// Supply the submit button as submitName=1
  $("form.ajax").submit(function(ajaxEvent){
    $("input.button").each(function(){
        $(this).attr('disabled','disabled');
    });
  
    ajaxEvent.preventDefault();
    sourceUrl = $(this).attr('action');
    sourceForm = $(this).attr('name');
    selectedInput = $(this).find('input:submit').attr('name');
    row='0';
    $("input").each(function(){
      var currentForm = $(this).parents('form').attr('name');
      //check form parent
      if(sourceForm==currentForm){
        row++;
        inputName = $(this).attr('name');
        inputType = $(this).attr('type');
       
        if(inputType=='checkbox'){  
          var inputValue = $(this).attr('checked');
          if(inputValue){
            inputValue='1';
          } else {
            inputValue='0';
          }
        } else if(inputType=='radio'){  
          var inputValue = $(this).attr('checked');
          if(inputValue){
            inputValue= $(this).attr('value');
          } else {
            row--;
            inputName='';
          }
        } else if(inputType=='submit') {
          if(selectedInput==inputName){
            var inputValue = '1';
          } else {
            row--;
            inputName='';
          }
        } else if(inputType=='button') {
            row--;
            inputName='';
        } else {
          var inputValue = $(this).attr('value');
        }
        if(row > 1  && inputName){
          formParameters = formParameters + '&' + inputName + "=" + inputValue;
        } else if(inputName){
          formParameters = inputName + "=" + inputValue;
        }
      }
    });
    
    $("select").each(function(){
      var currentForm = $(this).parents('form').attr('name');
      //check form parent
      if(sourceForm==currentForm){
        row++;
        inputName = $(this).attr('name');
        inputValue = $(this).attr('value');
        if(row > 1){
          formParameters = formParameters + '&' + inputName + "=" + inputValue;
        } else {
          formParameters = inputName + "=" + inputValue;
        }
      }
    });
    
    $('textarea').each(function(){
      row++;
      var currentForm = $(this).parents('form').attr('name');
      //check form parent
      if(sourceForm==currentForm){
        inputName = $(this).attr('name');
        inputValue = $(this).attr('value');
        serializedText = $(this).serialize();
        if(row > 1){
          formParameters = formParameters + '&' + serializedText;
        } else {
          formParameters = inputName + "=" + serializedText;
        }
      }
    });

    ajaxRequest = $.ajax({
      'url': sourceUrl,
      'data': formParameters,
      'dataType': 'json',
      'type': 'POST',
      'success': function(data) {
        if(data.message){
          if(data.status){
            Regexp2 = new RegExp("\[[A-za-z]{1,6}[0-9]{1,3}\]|\[[A-za-z]{1,6}[0-9]{1,3}-S\]");
            var regMatch = data.message.match(Regexp2);
            alertMsg = data.message.replace(Regexp2, '\n\n' + regMatch);
  
            Regexp = new RegExp("<br[ \t\n\r\f\v]/>", "gim");
            alertMsg = alertMsg.replace(Regexp, '\n');
            alert(alertMsg);

          } else {
            $('#fadeMessage').html("<div class='messageText'>" + data.message + " </div><img src='"+PublicDir+"/images/brsw.png'/>");
            //CSS not displaying as expected in IE, forcing display in javascript as work around
            $('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0'});
            $('#fadeMessage').removeClass('hidden');
            setTimeout(function(){
              $('#fadeMessage').fadeOut('slow');
            },4000);
          }
        }
        if(data.redirect){
          document.location = data.redirect;
        }
        $("input.button").each(function(){
          $(this).attr('disabled',null);
        });
      }
    });
    $.cookie('disableClicks', null, {path: cookiepath}); 

  });
  
  $("input.ajax").click(function(ajaxEvent){
    
    $("input.button").each(function(){
        $(this).attr('disabled','disabled');
    });
  
    ajaxEvent.preventDefault();
    selectedInput = $(this).attr('name');
    sourceUrl = $(this).parents('form').attr('action');
    sourceForm = $(this).parents('form').attr('name');
    row='0';
    $("input").each(function(){
      var currentForm = $(this).parents('form').attr('name');
      //check form parent
      if(sourceForm==currentForm){
        row++;
        inputName = $(this).attr('name');
        inputType = $(this).attr('type');
       
        if(inputType=='checkbox'){  
          var inputValue = $(this).attr('checked');
          if(inputValue){
            inputValue='1';
          } else {
            inputValue='0';
          }
        } else if(inputType=='radio'){  
          var inputValue = $(this).attr('checked');
          if(inputValue){
            inputValue= $(this).attr('value');
          } else {
            row--;
            inputName='';
          }
        } else if(inputType=='submit') {
          if(selectedInput==inputName){
            var inputValue = '1';
          } else {
            row--;
            inputName='';
          }
        } else if(inputType=='button') {
            row--;
            inputName='';
        } else {
          var inputValue = $(this).attr('value');
        }
        if(row > 1  && inputName){
          formParameters = formParameters + '&' + inputName + "=" + inputValue;
        } else if(inputName){
          formParameters = inputName + "=" + inputValue;
        }
      }
    });
    
    $("select").each(function(){
      var currentForm = $(this).parents('form').attr('name');
      //check form parent
      if(sourceForm==currentForm){
        row++;
        inputName = $(this).attr('name');
        inputValue = $(this).attr('value');
        if(row > 1){
          formParameters = formParameters + '&' + inputName + "=" + inputValue;
        } else {
          formParameters = inputName + "=" + inputValue;
        }
      }
    });
    
    $('textarea').each(function(){
      row++;
      var currentForm = $(this).parents('form').attr('name');
      //check form parent
      if(sourceForm==currentForm){
        inputName = $(this).attr('name');
        inputValue = $(this).attr('value');
        serializedText = $(this).serialize();
        if(row > 1){
          formParameters = formParameters + '&' + serializedText;
        } else {
          formParameters = inputName + "=" + serializedText;
        }
      }
    });
    
    ajaxRequest = $.ajax({
      'url': sourceUrl,
      'data': formParameters,
      'dataType': 'json',
      'type': 'POST',
      'success': function(data) {
        if(data.message){
          if(data.status){
            Regexp2 = new RegExp("\[[A-za-z]{1,6}[0-9]{1,3}\]|\[[A-za-z]{1,6}[0-9]{1,3}-S\]");
            var regMatch = data.message.match(Regexp2);
            alertMsg = data.message.replace(Regexp2, '\n\n' + regMatch);
  
            Regexp = new RegExp("<br[ \t\n\r\f\v]/>", "gim");
            alertMsg = alertMsg.replace(Regexp, '\n');
            alert(alertMsg);

          } else {
						Regexp2 = new RegExp("\[[A-za-z]{1,6}[0-9]{1,3}\]|\[[A-za-z]{1,6}[0-9]{1,3}-S\]");
            var regMatch = data.message.match(Regexp2);
            messageText = data.message.replace(Regexp2, '');
				    $('#fadeMessage').html("<div class='messageText'>" + messageText + " </div>" + "<div class='circmsgid'>" + regMatch + " </div>" + "<img src='"+PublicDir+"/images/brsw.png'/>");
            //CSS not displaying as expected in IE, forcing display in javascript as work around
            if(isIE6 || isIE7){
              $('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0'});
            } else {
              $('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0','marginLeft':'170px'});
            }
            $('#fadeMessage').removeClass('hidden');
            if(data.redirect){
              var pausedRedirect=data.redirect;
              data.redirect='';
              setTimeout(function(){
                $('#fadeMessage').fadeOut('slow');
                setTimeout(function(){
                  document.location = pausedRedirect;
                },500);
              },2000);
            } else {
              setTimeout(function(){
                $('#fadeMessage').fadeOut('slow');
              },4000);
            }
            
          }
        }
        if(data.redirect){
          document.location = data.redirect;
        }
        $("input.button").each(function(){
          $(this).attr('disabled',null);
        });
      }
    });
    $.cookie('disableClicks', null, {path: cookiepath}); 

  });
  
  $("a.ajax").click(function(ajaxEvent){
    
    ajaxEvent.preventDefault();
    sourceUrl = $(this).attr('href');
    
    ajaxRequest = $.ajax({
      'url': sourceUrl,
      'dataType': 'json',
      'type': 'POST',
      'success': function(data) {
        if(data.status){
          Regexp2 = new RegExp("\[[A-za-z]{1,6}[0-9]{1,3}\]|\[[A-za-z]{1,6}[0-9]{1,3}-S\]");
          var regMatch = data.message.match(Regexp2);
          alertMsg = data.message.replace(Regexp2, '\n\n' + regMatch);
          Regexp = new RegExp("<br[ \t\n\r\f\v]/>", "gim");
          alertMsg = alertMsg.replace(Regexp, '\n');
          alert(alertMsg);
        } else {
          $('#fadeMessage').html("<div class='messageText'>" + data.message + " </div><img src='"+PublicDir+"/images/brsw.png'/>");
          //CSS not displaying as expected in IE, forcing display in javascript as work around
          if(isIE6 || isIE7){
            $('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0'});
          } else {
            $('#fadeMessage').css({'background':'url('+PublicDir+'/images/blsw.png) no-repeat #fff1a8','color':'black','margin':'0','top':'0','marginLeft':'170px'});
          }
          $('#fadeMessage').removeClass('hidden');
          setTimeout(function(){
            $('#fadeMessage').fadeOut('slow');
          },4000);
        }
        if(data.redirect){
          document.location = data.redirect;
        }
      }
    });
    
    $.cookie('disableClicks', null, {path: cookiepath}); 
    
  });
  
  //set breadcrumb cookie to help adjust search cookies
  $("a.breadcrumb").click(function(){
    $.cookie('isBreadcrumb', '1', {path: cookiepath}); 
  });

  temp=navigator.appVersion.split('MSIE');
  ieVer=parseInt(temp[1]);
  var isIE6=(ieVer <= 6)?1:0;

  //Firefox back button returns to page in final state (i.e with disabled buttons)  need to re-enable on page exit
  $(window).unload(function () {
    $.cookie('disableClicks', null, {path: cookiepath}); 
    $("input.button").each(function(){
      $(this).attr('disabled',null);
    });
  });

  
  //Escape activates back button
  currentFocus = null;
  $('select').focus( function() {
    currentFocus = this.id;
  }).click(function(){
    currentFocus = this.id;
  }).blur( function() {
    currentFocus = null;
  });
  
  $('.srchbox').focus( function() {
    if(wordListOn=='1'){
      currentFocus = 'wordlist';
    } else {
      currentFocus = null;
    }
  }).blur( function() {
    currentFocus = null;
  });
  
  $('html').keydown(function(eventBody){
    if(eventBody.keyCode==27){
      eventBody.preventDefault();
      if(currentFocus!='wordlist'){
        var backUrl = $('.backbtn').find('a').attr('href');
        if(currentFocus){
          backUrl = null;
          currentFocus = null;
        }
        if(backUrl){
          document.location = backUrl;
        }
      }
    }
  });
  
  //reveal spoiler
  
  $('.revealSpoiler').click(function(event){
    event.preventDefault();
    $('.revealSpoiler').fadeOut();
    $('.spoiler').fadeIn();
  });
  
  //Display site information from cookie
  
  var SiteName = $.cookie('SiteName');
  if(SiteName!==null){
    SiteName = SiteName.replace(/\+/g," ");
    $(".sitename").html(SiteName);
  }
  
  $('.readerPref td select').each(function(){
    $(this).children().each(function(){
      var titleChange = $(this).text();
      $(this).attr('title',titleChange);
    });
  });
  
  $('li.socialBookmark a').each(function(){
    $(this).click(function(event){
      event.preventDefault();
      var baseURL = $(this).attr('href');
      var windowID = 'test';
      var bookmarkURL = baseURL + location.href + '&amp;title=' + escape(document.title);
      window.open(bookmarkURL, windowID, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1');
    });
  });
  
});