/**
 * Rijkslogo JavaScript library
 **/
var debug = false;

// Browser checks
document.createElement('abbr');

// Initialiseer de volgende functies
function init(){
  if($.browser.msie){
    try {
      document.execCommand('BackgroundImageCache', false, true);
    } catch(e) {}
  }

  $("a[@rel='external']").attr("target","_blank");

}

function hideMyBox(headerId,boxId) {
    $(headerId).toggle();
    $(headerId).show();
    $(headerId).css({backgroundPosition: '-3994px -67px'});
    $(boxId).hide();
  }


/*
function initGallery(){
  $("#gallerycontent ul li a").fancybox({
    'overlayShow':	true
  });
}
*/


/**
 * Calendar setup, called onDocumentReady which initializes all fields with a .calendar-button
 * class by calling the Calendar object on their IDs.
 *
 * The calendar object is included from js/calendar-setup.js.
 *
 * FIXME
 * Detect if a three field or one field is used.
 * Pass field IDs for three field/one field scenarios
 **/
function calendar_setup() {
  $('.calendar-button').each(function() {
    Calendar.setup({
      inputField : 'day', // id of the input field
      ifFormat : "%d-%m-%Y", // format of the input field
      showsTime : false, // will display a time selector
      button : $(this).attr('id'), // trigger for the calendar (button ID)
      singleClick : true, // double-click mode
      onUpdate : calendar_callback_three_fields
    });
  });
}

/**
 * Calendar callback which splits the response into three fields
 *
 * FIXME
 * Use IDs passed by calendar_setup
 **/
function calendar_callback_three_fields(calendar) {
  var Date = calendar.date;

  var day   = Date.print('%d');
  var month = Date.print('%m');
  var year  = Date.print('%Y');

  $('#day').val(day);
  $('#month').val(month);
  $('#year').val(year);
}

/**
 * FIXME
 * Calendar callback which does not split the response but uses one field
 **/
function calendar_callback_one_field(calendar) {
  return;
}

/**
 * TODO
 **/
function initMenu(){
  $('.collapse').click(
    function() {
      var checkElement = $(this).next().next();
      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        checkElement.slideUp('normal');
        $(this).next().toggleClass("open");
        return false;
      }
      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        checkElement.slideDown('normal');
        $(this).next().toggleClass("open");
        return false;
      }
    }

    );

  $('.collapse').hover(
    function() {
      $(this).next().toggleClass("active");
    },
    function(){
      $(this).next().toggleClass("active");
    }
  );

}

/**
 * TODO
 **/
function initMovies(){

  $(".movie").each(
    function(){

    var moviefile = $("a",this).attr("href");
    var w = $("img",this).width();
    var h = $("img",this).height();

    $(this).flash(
      { src: $("a",this).attr("href"),
        width: $("img",this).width(),
        height: $("img",this).height(),
        flashvars: {}},
        { version: '9.0.0' }, null,
      function(){
      }
    );

  });

}

/**
 * A function from quirksmode to get the pagesize
 **/
function get_page_size()
{

  var x_scroll, y_scroll;

  x_scroll = $(document).width();
  y_scroll = $(document).height();

  var window_width, window_height;

  window_width = $(window).width();
  window_height = $(window).height();

  // for small pages with total height less then height of the viewport
  if(y_scroll < window_height)
  {

    page_height = window_height;

  }
  else
  {

    page_height = y_scroll;

  }

  // for small pages with total width less then width of the viewport
  if(x_scroll < window_width)
  {

    page_width = x_scroll;

  }
  else
  {

    page_width = window_width;

  }

  array_page_size = new Array(page_width,
                              page_height,
                              window_width,
                              window_height);

  return array_page_size;

}

/**
 * A function from quirksmode which determines how far the page has scrolled
 **/
function get_page_scroll()
{

  var x_scroll, y_scroll;

  if (self.pageYOffset)
  {

    y_scroll = self.pageYOffset;
    x_scroll = self.pageXOffset;

  }
  else if (document.documentElement && document.documentElement.scrollTop)
  { // Explorer 6 Strict

    y_scroll = document.documentElement.scrollTop;
    x_scroll = document.documentElement.scrollLeft;

  }
  else if (document.body)
  {// all other Explorers

    y_scroll = document.body.scrollTop;
    x_scroll = document.body.scrollLeft;

  }

  array_page_scroll = new Array(x_scroll,y_scroll);

  return array_page_scroll;

}

// Function to show external popup
function show_ext(title, url)
{

  window.open(url, 'ext_window', 'status=0,toolbar=0,location=false');

}


// Functions to show and hide the popover
function show_popover(title, url)
{
  var page_size   = get_page_size();
  var page_scroll = get_page_scroll();

  $('select').hide();
  $('#fade').css('height', page_size[1] + page_scroll[1] + 'px');
  $('#fade').css('width', '100%');

  $('#fade').show();

  $('#popover').css({
    top: 10 + page_scroll[1]
  });

  $('#popover h1').html(title);
  $('#popover iframe').attr('src', url);
  $('#popover').show();

}

function hide_popover() {
  $('select').show();
  $('#fade').hide();
  $('#popover').hide();
  $('#popover iframe').attr('src', 'about:blank');
}

/**
 * jQuery on document ready we add a few events.
 **/
$(document).ready(function(){
  init();
  initMenu();

  calendar_setup();

  // if(!admin) initGallery();
  if(!admin) initMovies();

  /**
   * The toggle on the context menu
  **/
  $(".my_title").each(
    function(index) {
    $('#'+this.id).toggle(
      function () {
        $('#'+this.id).css({backgroundPosition: '-3994px -67px'});
        $('#b_'+this.id).hide();
      },
      function() {
        $('#'+this.id).css({backgroundPosition: '-4095px -40px'});
        $('#b_'+this.id).show();
      });
    }
  );

/**
 * A fix for the buttons click event, add it on posterior
 **/
  $('.my_title button').each(
    function(index) {
      $(this).click(
        function() {
          $(this).attr('onclick');
          return false;
        });
    });


  $('#video-full ul.arrows, .video-box ul.arrows, #video-container ul.arrows, #video-home ul.arrows').hide();

  /**
  * This adds events to the video boxes on the homepage
  **/
  $('.video-title, .bbtrefwoorden h3').toggle(
    function() {
      title = $('#' + this.id);
      box   = $('#' + this.id + '_volledig');

      title.css({'border-bottom-width': '0px',
                 'background-position': '-4095px -42px'});
      title.addClass('highlighted');

      box.show();
    },
    function() {
      title = $('#' + this.id);
      box   = $('#' + this.id + '_volledig');

      title.css({'border-bottom-width': '1px',
                 'background-position': '-3994px -69px'});
      title.removeClass('highlighted');

      box.hide();
    });

  /**
  * Generic implementation of helpfloat boxes
  */
  helpfloats = [];

  $('.helpfloat').each(function() {

      helpfloats[$(this)[0].id] = $(this)[0].innerHTML;
      $(this).text('?');

      $(this).click(function(e) {

        $('.helppopup').remove();

        popup = $('<div class="helppopup"><img src="gfx/help_close.jpg" /><div>' + helpfloats[$(this)[0].id] + '</div></div>');

        $(popup.children()[0]).click(function() { popup.remove(); });

        o_top = $(this).offset().top;
        o_left = $(this).offset().left;

        $(popup).css({'position': 'absolute',
                      'left': o_left + 26 + 'px',
                      'top': o_top  - 9 + 'px'});

        $('#volledig').append(popup);

      });

  });

  /* Right placed helpfloats open on the left */
  $('.helpfloat-right').each(function() {

      helpfloats[$(this)[0].id] = $(this)[0].innerHTML;
      $(this).text('?');

      $(this).click(function(e) {

        $('.helppopup').remove();

        popup = $('<div class="helppopup right"><img src="gfx/help_close.jpg" /><div>' + helpfloats[$(this)[0].id] + '</div></div>');

        $(popup.children()[0]).click(function() { popup.remove(); });

        o_top = $(this).offset().top;
        o_left = $(this).offset().left;

        $(popup).css({'position': 'absolute',
                      'left': o_left - 223 + 'px',
                      'top': o_top  - 9 + 'px'});

        $('.popover').append(popup);
        $('#volledig').append(popup);

        return false;

      });

  });

  $('.imagegallery').each(function() {
        id              = this.id;
        hid             = '#' + this.id;
        images          = [];
        selected_images = [];
        selected_key    = 0;
        left_offset     = 0;
        right_offset    = 0;

        $(hid + ' h2 img').click(function() {
            show_popover($(hid + ' h2').attr('title'), $(hid + ' h2 img').attr('href') + '&current=' + key);
        });

        $(hid + ' .imagecontainer').show();
        $(hid + ' .thumbnailcontainer img').addClass('thumb');

        $(hid + ' .thumbnailcontainer li img').each(function() {
            images.push(this);
        });

        // Set initial key
        key = 0;

        // Check for other key
        if(typeof(current_key) != "undefined" && current_key > 0) {
          key = parseInt(current_key);
        }

        function get_left_bound()
        {

            if((key-1) <= 0 || (key-2) <= 0)
            {

                return 0;

            }

            return key - 2;

        }

        function get_right_bound()
        {


            if((key+1) >= images.length || (key+2) >= images.length)
            {

                return images.length;

            }

            return key + 3;

        }

        function check_bounds()
        {

            rv = [];
            lb = get_left_bound();
            rb = get_right_bound();

            if((rb - lb) < 5)
            {

                // Adjust boundaries to show more, see which boundary is over
                if(lb == 0)
                {

                    // add to the right
                    while((rb - lb) < 5)
                    {

                        if((rb + 1) >= images.length)
                        {
                            rb = images.length;
                            break;
                        }

                        rb = rb + 1;

                    }

                }

                if(rb >= images.length)
                {

                    while((rb -lb) < 5)
                    {

                        if((lb - 1) <= 0)
                        {

                            lb = 0;
                            break;

                        }

                        lb = lb - 1;

                    }

                }

            }

            return [lb, rb];

        }


        // Redraw region
        // This draws the items around the current key
        function draw()
        {

            lb = check_bounds()[1];
            rb = check_bounds()[1];

            // Empty .thumbnailcontainer and then draw the controls/images in it
            $(hid + ' .thumbnailcontainer').empty();
            $(hid + ' .thumbnailcontainer').append('<div class="right"><span class="one">&gt;</span>&nbsp;&nbsp;&nbsp;<span class="outer">&gt;&gt;</span></div>');
            $(hid + ' .thumbnailcontainer').append('<div class="left"><span class="outer">&lt;&lt;</span>&nbsp;&nbsp;&nbsp;<span class="one">&lt;</span></div>');

            for(i = lb; i < rb; i++)
            {

                $(images[i]).removeClass('current');

                if(key == i)
                {

                    $(images[i]).addClass('current');

                }

                $(hid + ' .thumbnailcontainer').append($(images[i]).attr('id', id + '_' + i));

            }


            // Set initial current class
            $(images[key]).addClass('current');

            // Set source
            var ar_src = $(hid + ' .imagecontainer img').attr('src').split('/');
            var size = ar_src[ar_src.length-4]+'/'+ar_src[ar_src.length-3]+'/'+ar_src[ar_src.length-2]+'/'+ar_src[ar_src.length-1];
            var src = $(images[key]).attr('src').replace(/height\/[0-9]+$/,size);
            $(hid + ' .imagecontainer img').attr('src', src);

            // Set title
            $(hid + ' h3').html('<span>' + (key+1) + ' van ' + images.length + '</span>' + $(images[key]).attr('alt') + '&nbsp;');
            $(hid + ' .controlcontainer').html('<strong>' + $(images[key]).attr('alt') + '&nbsp;</strong><br />' + $(images[key]).attr('title'));
            $(hid + ' .countercontainer').html('<span>' + (key+1) + ' van ' + images.length + '</span>');
            // $(hid + ' .controlcontainer').html('<button type="submit">Begin Slideshow</button> <span>' + (key+1) + ' van ' + images.length + '</span> - ' + $(images[key]).attr('title'));

            // Add slideshow callback
            $(hid + ' .controlcontainer button').click(function() {
                $(hid + ' .controlcontainer button').text('Stop Slideshow');
                $(document).everyTime(2500, 'slideshow', walk_slideshow);
            });

            // Bind click event to the awesome overview
            $(hid + ' .thumbnailcontainer img').click(function() {
                k = parseInt(this.id.split('_')[1]);
                var ar_src = $(hid + ' .imagecontainer img').attr('src').split('/');
                var size = ar_src[ar_src.length-4]+'/'+ar_src[ar_src.length-3]+'/'+ar_src[ar_src.length-2]+'/'+ar_src[ar_src.length-1];
                var src = $(images[k]).attr('src').replace(/height\/[0-9]+$/,size);
                $(hid + ' .imagecontainer img').attr('src', src);
                $(images[key]).removeClass('current');
                key = k;
                draw();
            });

            $(hid + ' .thumbnailcontainer .left .one').click(move_left);
            $(hid + ' .thumbnailcontainer .right .one').click(move_right);
            $(hid + ' .thumbnailcontainer .left .outer').click(move_outer_left);
            $(hid + ' .thumbnailcontainer .right .outer').click(move_outer_right);

            if($.browser.msie && $.browser.version.substr(0,1) == 7) {

                $(hid + ' .thumbnailcontainer img').css('border-color', '#ffffff');

                $(hid + ' .thumbnailcontainer img').css('padding', '2px');

                // Set hover stuff
                $(hid + ' .thumbnailcontainer img').bind('mouseenter', function() {
                        $(this).css('border-color', $(hid + ' h2',top.document).css('background-color'));
                });

                $(hid + ' .thumbnailcontainer img').bind('mouseout', function() {
                        $(this).css('border-color', '#fff');
                        $(hid + ' .thumbnailcontainer img.current').css('border-color', bg_color);
                });

                // Set current thing
                bg_color = $(hid + ' h2',top.document).css('background-color');
                $(hid + ' .thumbnailcontainer img.current').css('border-color', bg_color);

            }

            // Wrap the image with an IE fix
            if ($.browser.msie && $.browser.version.substr(0,1) == 6) {

                 //make unscaled copy
                $(hid + ' .hiddenimagecontainer .hiddenimage').attr('src', $(images[key]).attr('src'));

                // First remove the conflicting styles
                $(hid + ' .thumbnailcontainer img').css({
                    'margin': '0px'
                });
                $(hid + ' .thumbnailcontainer img').wrap('<span class="imagegalleryoutlinewrapper"></span>');
                $(hid + ' .thumbnailcontainer span').css('margin', '2px');
                $(hid + ' .thumbnailcontainer span').css('border', '2px solid #fff');

                // Set hover stuff
                $(hid + ' .thumbnailcontainer span').bind('mouseenter', function() {
                    $(this).css('border-color', $(hid + ' h2',top.document).css('background-color'));
                });

                $(hid + ' .thumbnailcontainer span').bind('mouseout', function() {
                        $(this).css('border-color', '#fff');
                        $(hid + ' .thumbnailcontainer span img.current').parent().css('border-color', bg_color);
                });

                // Set current thing
                bg_color = $(hid + ' h2',top.document).css('background-color');
                $(hid + ' .thumbnailcontainer span img.current').parent().css('border-color', bg_color);

                // Resize image
                var main_image = $(hid + ' .imagecontainer img');
                var hidden_image = $(hid + ' .hiddenimagecontainer .hiddenimage');

            }

        }

        function walk_slideshow()
        {

            key = key + 1;

            if(key >= images.length)
            {

                key = 0;

            }

            draw();

            $(hid + ' .controlcontainer button').text('Stop Slideshow');
            $(hid + ' .controlcontainer button').unbind('click');
            $(hid + ' .controlcontainer button').click(function() {
                $(document).stopTime();
                draw();
            });

        }



        function move_outer_right()
        {

            key = images.length-1;
            draw();

        }

        function move_outer_left()
        {

            key = 0;
            draw();

        }

        function move_right()
        {

            if(key >= images.length-1)
            {

                return;

            }

            key = key + 1;
            draw();

        }

        function move_left()
        {

            if(key <= 0)
            {

                return;

            }

            key = key - 1;
            draw();

        }

        draw();

    });


});

// function for chaining selectboxes via json
(function ($) {
    $.fn.selectChain = function (options) {
        var defaults = {
            key: "id",
            value: "label"
        };

        var settings = $.extend({}, defaults, options);

        if (!(settings.target instanceof $)) settings.target = $(settings.target);

        return this.each(function () {
            var $$ = $(this);

            $$.change(function () {
                var data = '?' + this.id + '=' + $$.val();
                if (typeof settings.data == 'string') {
                    data = data + '&' + settings.data;
                }
                //alert(settings.url);

                settings.target.empty();

              $.getJSON(settings.url+data,
                function(json){
                        $.each(json.category, function(i,item){
                              // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                              o = document.createElement("OPTION");
                              o.value = item[settings.key];
                              o.text = item[settings.value];
                              if (item['selected']!=null) o.selected = item['selected'];
                              settings.target.get(0).options[i] = o;
                        });
                 });
            });
        });
    };
})(jQuery);

        function filledIn () {
           if($('#j_username').attr('value').length ==0) {
             $('#loginUsername').addClass('requiredField');
           }

           if($('#j_username').attr('value').length ==0 && !$('#j_password').attr('value').length ==0) {
             $('#loginPassword').removeClass('requiredField');
             }

           if($('#j_password').attr('value').length ==0) {
             $('#loginPassword').addClass('requiredField');
           }
           if($('#j_password').attr('value').length ==0 && !$('#j_username').attr('value').length ==0) {
             $('#loginUsername').removeClass('requiredField');
           }
          }

        function secureLogin(pwd) {
          if($('#j_password').attr('value').length ==0|| $('#j_username').attr('value').length ==0){
            $('#passworderror').addClass('verborgen');
            $('#usernameerror').addClass('verborgen');
            if($('#errormessagebox').hasClass('verborgen')) $('#errormessagebox').removeClass('verborgen');
            if($('#inputerror').hasClass('verborgen')) $('#inputerror').removeClass('verborgen');
            if($('#j_password').attr('value').length ==0 && !$('#j_password').hasClass('verborgen')) $('#passworderror').removeClass('verborgen');
            if($('#j_username').attr('value').length ==0 && !$('#j_username').hasClass('verborgen')) $('usernameerror').removeClass('verborgen');
            return false;
          }

          document.getElementById("j_password").value=hex_md5(pwd);
          return true;
        }

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

function reloadPage(timeout) {
  setTimeout("window.location.reload()", timeout);
}

