// --------- First the compatibility patches --------------//

// Form compatibility (only tested with email_response_form)
var formChanged = false;
var defaultValues = [];

var logo_state = 'big';
var content_state = 'visible';
var logo2_big = { width:"527px", height:"325px", marginLeft:"300px", marginTop:"135px" };
var logo2_small = { width:"96px", height:"62px", marginLeft:"0px", marginTop:"-80px" }
var logo2_big_src = "/p-httpd/_style/images/logo-groot.png";
var logo2_small_src = "/p-httpd/_style/images/logo-klein.png";
var num_blinds = 40;
var headerHeight = 0;

// OpenSatellite(Url,width,height,scrollbars,status,WindowName)
var SatelliteNames = new Array();
var SatelliteRefs  = new Array();
function OpenSatellite() {
  var argv = OpenSatellite.arguments;
  if(argv.length>0) SatUrl = argv[0]; else SatUrl='';
  if(argv.length>1) SatWidth = argv[1]; else SatWidth=400;
  if(argv.length>2) SatHeight = argv[2]; else SatHeight=400;
  if(argv.length>3) SatScrollbars = argv[3]; else SatScrollbars='no';
  if(argv.length>4) SatStatus = argv[4]; else SatStatus='no';
  if(argv.length>5) WindowName = argv[5];  // Optional WindowName to allow multiple satellites to be open...
  else WindowName = "DefaultSatellite";    // Default handle-/windowname...
  if(argv.length>6) WindowParms = argv[6]; // Optional additional window.open parameters...
  else WindowParms = "menubar=no";

  // Try to find already existing handle for this window...
  delete SatelliteWin;
  WindowExist = false;
  for (var FoundWin=0; FoundWin<SatelliteNames.length; FoundWin++) {
    if (SatelliteNames[FoundWin]==WindowName) {
      SatelliteWin = SatelliteRefs[FoundWin];
      WindowExist = true;
      break;
    }
  }

  if (typeof(SatelliteWin)=="undefined" || SatelliteWin.closed) {
    if (navigator.appName == 'Microsoft Internet Explorer') {
      SatWidth += 20;
      SatHeight += 20;
    }
    var SatLeft = (screen.width-SatWidth)/2;
    var SatTop = (screen.height-SatHeight)/2;
    var SatResizable = SatScrollbars;
    if(SatResizable == 'auto') SatResizable='yes';
    SatelliteWin = window.open(SatUrl,WindowName,"status="+SatStatus+",resizable="+SatResizable+",scrollbars="+SatScrollbars+","+WindowParms+",width="+SatWidth+",height="+SatHeight+",screenX="+SatLeft+",screenY="+SatTop+",left="+SatLeft+",top="+SatTop);
    if (SatelliteWin && SatelliteWin.opener==null) SatelliteWin.opener = self;

    // Store handle. Refresh reference if window was already opened this session (but closed)...
    if (WindowExist) {
      SatelliteRefs[FoundWin] = SatelliteWin;  // Refresh handle...
    } else {
      NextWin = SatelliteNames.length;
      SatelliteNames[NextWin] = WindowName;
      SatelliteRefs[NextWin]  = SatelliteWin; // New store...
    }
  } else {
    //cur_loc = SatelliteWin.location.pathname+SatelliteWin.location.search;
    //if (cur_loc!=SatUrl) SatelliteWin.location.href=SatUrl; // Refresh...
    SatelliteWin.location.href=SatUrl; // Refresh...
    SatelliteWin.focus();
  }
}

function cms_formchange() {
  formChanged=true;
}

function mark_submitted() {
  if(document.theForm && document.theForm._submitted)
    document.theForm._submitted.value = 1;
}

function check_form(form) {
  return check_form_fields(form);
}

// Other compatibility
function preload_image() {
  if(document.images) {
    for (var i=0; i<preload_image.arguments.length; i++) {
      img = new Image();
      img.src = preload_image.arguments[i];
    }
  }
}

// --------- Initialisation code for this website --------------//

function initSiteJs() {
  // Initialize history plugin.
  // The callback is called at once by present location.hash.
  $('html, body').css('overflow','hidden');

  //initialise the history plug-in;
  if (typeof($.history.init)=='function') $.history.init(loadHash);
  processLinks('body');
  var theParent=$('#content').parent().parent();
  var marginTop = parseInt($(theParent).css('margin-top')+0);
  if (!$(theParent).attr('orgTop'))
    $(theParent).attr('orgTop', ($(theParent).offset().top - marginTop) );
  var h=theParent.height()+10;
  theParent.css({'top':-h, 'opacity':0});
  content_state = 'invisible';
  fadeIn('content');

  // ---   Start the eitjes
  // Preload images
  for(var i=0; i<5; i++)
    $("<img>").attr("src","/p-httpd/_style/images/jump"+i+".png");
  // Create the eggs
  for(var i=0; i<3; i++)
    $("<img style=\"position:fixed; left:"+(xPos[i]-xOffs[i])+"px; top:"+(yPos[i]-yOffs[i])+"px\" id=\"jump"+(i+1)+"\" class=\"egg\">").attr("src","/p-httpd/content/jump/jump0.png").appendTo('body');
  eitjes();
  $(document).mousemove(function(e){
    mouseX = e.pageX;
    mouseY = e.pageY;
  }); 
  $("body").bind("touchmove", function (event) {
    var e = event.originalEvent;
    mouseX = e.targetTouches[0].pageX;
    mouseY = e.targetTouches[0].pageY;
  });
  $(".egg").draggable({
       start: function() {
         var id = parseInt(this.id.replace('jump',''));
         var idx = id-1;
         dragState[idx] = 1;
         $(this).attr("src","/p-httpd/_style/images/jump-drag1.png");
       },
       stop: function(event) {
         var id = parseInt(this.id.replace('jump',''));
         var idx = id-1;
         xPos[idx] = event.pageX;
         if(event.pageY < 110) yPos[idx] = 110;
         else yPos[idx] = event.pageY;
         $("#jump"+id).css('top', Math.floor(yPos[idx]-yOffs[idx]));
         dragState[idx] = 0;
       }
  });

}


// ------------------------- Code of the eitjes
// Code copyright Creagraphy, by E.F. de Moor.

// settings
var xPos  = [90,180,580];
var yPos  = [130,230,130];
var xOffs = [90,90,90];
var yOffs = [40,40,40];
var xRati = [0.5,1,1.5];
var yRati = [1.5,1,0.5];
var stepsize = 8; //in pixels
// states
var state = [0,0,0];
var dragState = [0,0,0];
var mouseX = 0;
var mouseY = 0;
var timer;

function eitjes()
{
  CheckState(1);
  CheckState(2);
  CheckState(3);
  clearTimeout(timer); // In case it was fired twice
  timer = setTimeout(arguments.callee, 100);  // Call ourselves repetitvely
}

function CheckState(id)
{
  var height = $(document).height();
  var width = $(document).width();
  var index = id-1;
  var imageId = 0;
  var move = false;
  if (!mouseX) mouseX = width/2;
  if (!mouseY) mouseY = height/2;
  if(mouseY < 110) mouseY = 110;
  var xDif = mouseX - xPos[index];
  var yDif = mouseY - yPos[index];
  switch(state[index])
  {
    case 0:
      imageId = 0;
      if (xDif > 30 || yDif > 30 || xDif < -30 || yDif < -30)
      {
        var alreadyStarted = false;
        for(var i = 0; i<3; i++)
        {
          if(state[i] < 4 && state[i] != 0)
            alreadyStarted = true;
        }
        if(!alreadyStarted)
          state[index] = 1;
      }
      break;
    case 1:
      imageId = 1;
      state[index] = 2;
      break;
    case 2: 
      imageId = 0;
      state[index] = 3;
      break;
    case 3:
      imageId = 2;
      move = true;
      state[index] = 4;
      break;
    case 4:
      imageId = 3;
      move = true;
      state[index] = 5;
      break;
    case 5:
      imageId = 4;
      move = true;
      state[index] = 6;
      break;
    case 6:
      imageId = 3;
      move = true;
      state[index] = 7;
      break;
    case 7:
      imageId = 2;
      move = true;
      state[index] = 8;
      break;
    case 8:
      imageId = 0;
      state[index] = 9;
      break;
    case 9:
      imageId = 1;
       state[index] = 10;
      break;
    case 10:
      imageId = 0;
      state[index] = 0;
      break;
  }
  if(dragState[index]) {
    if(dragState[index]==1) dragState[index]=2;
    else dragState[index]=1;
    imageId = "-drag"+dragState[index];
  }
  else {
    if(move) {
      var Dist = Math.sqrt(xDif*xDif + yDif*yDif) / stepsize;
      xPos[index] += xRati[index] * (xDif / Dist);
      yPos[index] += yRati[index] * (yDif / Dist);
      $("#jump"+id).css('left', Math.floor(xPos[index]-xOffs[index]));
      $("#jump"+id).css('top', Math.floor(yPos[index]-yOffs[index]));
      $("#jump"+id).css('z-index', 1000 + Math.floor(yPos[index]));
    }
  }
  $("#jump"+id).attr("src","/p-httpd/_style/images/jump"+imageId+".png");
}

// --------------------   Page navigation code


var pages = [];             // Array with page information
var transitioning = false;  // Flag is true during page animation
function fillPagesArray(separator, listStyle, ref, enableAjax) {
  var level;
  var navRef;
  var pathStr;
  var navLink = [];
  var navText = [];

  if (listStyle) {
    Prefix    = "<ul><li><a href=\"/\">Home</a></li><li>";
    Postfix   = "</li></ul>";
    separator = "</li><li>";
  } else {
    Prefix    = "<p>";
    Postfix   = "</p>";
  }
  if (enableAjax) {
    $.ajax({
      url: '/p-xml_data/pages_info',
      type: 'GET',
      dataType: 'xml',
      success: function(returnedXMLResponse){
        $('node', returnedXMLResponse).each(function() {
          level = $(this).find("level:first").text();
          navRef = $(this).find("ref:first").text();
          if (navRef) {
            navLink[level] = navRef;
            navText[level] = $(this).find("title:first").text();
            pathStr = Prefix;
            for (i=0; i<=level; i++) {
              if (i>0) pathStr = pathStr + separator;
              if (i<level)
                pathStr = pathStr + "<a href=\""+navLink[i]+"\" target=content>"+navText[i]+"</a>";
              else
                pathStr = pathStr + navText[i];
            }
            pathStr = pathStr + Postfix;
            pages[navRef] = [];
            pages[navRef].pathStr = pathStr;
            $(this).children().each(function(i){
              if(this.childNodes && this.childNodes[0] && this.childNodes[0].nodeValue)
                var value=this.childNodes[0].nodeValue;
              else
                var value = '';
              pages[navRef][this.nodeName] = value;
            });
          }
        })
        setNavPath(ref);
      } // End success
    }); // End ajax
  }
}

function setNavPath(ref) {
  // Set navpath/breadcrumbs...
  var Text = '';
  if (ref && pages[ref]) Text = pages[ref].pathStr;
  if (Text) {
    $(".navpath").html(Text);
    $(".navpath").each( function () {
      processLinks('#'+this.id);
    });
  }
  if (typeof($.fn.jBreadCrumb) == 'function')
    $(".navpath").jBreadCrumb({previewWidth:25});
}

function addToFavorites() {
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
    window.external.AddFavorite(pageUrl, pageTitle);
  } else if (navigator.appName == "Netscape" && navigator.userAgent.indexOf('Safari')<=0) {
    window.sidebar.addPanel(pageTitle, pageUrl, "");
  } else {
    alert("Houd de CTRL-toets (op een Mac de CMD-toets) ingedrukt en druk 'D' of 'T' (Opera) om de pagina toe te voegen aan de favorieten.");
  }
}

// Make sure the sizes are calculated correctly
function resizeDivs(target) {
  if(!$('.doResize').length)
    return;
  // Fit content in the window.
  if(navigator.userAgent.match(/iPad/i) != null) {
    $('#footer').css('display','none');
    $('.doDepth').css('z-index', 3000);
  }
  else {
    if ($('#header').outerHeight) headerHeight = $('#header').outerHeight(true);
    else headerHeight = $('#content').offset().top;
    var footerHeight = 0;
    if ($('#footer').outerHeight) footerHeight = $('#footer').outerHeight(true);
    var hallmarkHeight = 0;
    if ($('#hallmarks').outerHeight) hallmarkHeight = $('#hallmarks').outerHeight(true);
    var contentHeight = $(window).height()-headerHeight-footerHeight-hallmarkHeight;
    $('.doResize').outerHeight(contentHeight, true);
    $('.doDepth').css('z-index', 1000+headerHeight+contentHeight+25);
    // Disable the scrollbars of html and body
    $('html, body').css('overflow','hidden');
  }
}

function setVisited(hash) {
  if (hash && hash.match(/^http/i)==null) {
    var urlref = hash.replace(/\/p-content\//gm,"\/");
    if (urlref && pages[urlref]) pages[urlref].Visited = 1;
  }
}

function isVisited(hash) {
  if (hash && hash.match(/^http/i)==null) {
    var urlref = hash.replace(/\/p-content\//gm,"\/");
    if (urlref && pages[urlref] && pages[urlref].Visited) return true;
  }
  return false;
}

// Process any links
function processLinks(target) {
  // Give images a caption
  $('#content').addCaptions({ 'allowBlankCaption': true, 'attributes': ['caption'] } );
  // Make links to the target 'iframe' aware of ajax...
  var sel='';
  if (target) sel = target+" ";
  // Lossy test below seems necessary for IE7 because exceptions match, only when not applicable?!?!
  $(sel+"a[target='content']").not("a[rel=lightbox]").click( function(event) {
    if (!$(this).attr('href').match(/\/p-httpd\/multimedia\//i)) {
      setVisited($(this).attr('href')); // Signal page visited in the pages array...
      if (!loadAjax(this)) event.preventDefault(); return true;
    }
  });
  //$(sel+"a[target='_top']").not("a[rel=lightbox]").click( function(event) {
  //  if (!$(this).attr('href').match(/^http/i)) {
  //    setVisited($(this).attr('href')); // Signal page visited in the pages array...
  //    if (!loadAjax(this)) event.preventDefault(); return true;
  //  }
  //});
  $(sel+"a[target]").not("a[rel=lightbox]").click( function(event) {
    if (!$(this).attr('href').match(/^http/i) && 
        !$(this).attr('href').match(/\/p-httpd\/multimedia\//i) &&
        !$(this).attr('href').match(/^mailto/i)) {
      setVisited($(this).attr('href')); // Signal page visited in the pages array...
      if (!loadAjax(this)) event.preventDefault(); return true;
    }
  });
  $(sel+"a").not("a[target]").not("a[rel=lightbox]").click( function(event) {
    if (!$(this).attr('href') || !$(this).attr('href').match(/^mailto/i)) {
      setVisited($(this).attr('href')); // Signal page visited in the pages array...
      if (!loadAjax(this)) event.preventDefault(); return true;
    }
  });

  $(sel+"a").each(function() {
    if (isVisited($(this).attr('href'))) $(this).addClass('visited');
  });

  // Prevent the form from being sent
  // onsubmit doesn't work as expected with Ajax forms, use the pre-serialize hook
  $("form").not(".noAjax").each(function() {
    if(!$(this).attr('org_onsubmit') && $(this).attr('onsubmit')) {
      $(this).attr('org_onsubmit',$(this).attr('onsubmit'));
      $(this).attr('onsubmit','return false;'); // Prevent actually sending the form, it is handled by Ajax
    }
    $(this).bind('form-pre-serialize', function(event, form, options, veto) {
      var onsubmit = $(this).attr('org_onsubmit');
      if(onsubmit) {
        eval('var veto_func=function(){'+onsubmit+'}');
        veto.veto=!veto_func();
      }
      else veto.veto=false;
    });
  });

  // Make any 'theForm' object Ajax aware...
  $("form").not(".noAjax").ajaxForm({
    resetForm: true,
    beforeSubmit: function(formData, jqForm, options) {
      fadeOut('content');
      return(true);
    },
    success: function (responseText, statusText, form) { 
      if (this.type.toLowerCase()=='get') $.history.add(this.url.replace(/\/p-ajax/,''));
      formChanged=false;
      if (responseText.match(/document.location.href/i)) {
        var location = responseText.replace(/\n/gm,' ');
        var location2 = location.replace(/^.*location.href\s*=/im,'');
        if (location2 != location) { // 'location.href' matched, refresh to the found location!
          var relocate = true;
          var location = location2.replace(/^\s+('|")/,'');
          var location = location.replace(/('|").*$/m,'');
          loadAjax(location);
        }
      }
      if (!relocate) loadHTML(responseText,'content');
    }
  });
}

function setSelected(sel) {
  $('#menu li').removeClass('cms_selected');
  $('#menu li a').removeClass('cms_selected');
  $('#menu li').removeClass('cms_expanded');
  id = $('#menu a[href$='+sel+']').parent().attr('id');
  if (id) {
    $('#'+id).addClass('cms_selected');
    $('#'+id+' a').addClass('cms_selected');
    $('#'+id).parents("li").addClass('cms_expanded');
  }
}

function loadAjax(link) {
  // If it is a direct bookmark link, don't process..
  // AvD 20090528: Anchors with JS as action should not have a loadAjax call. Solve this in processLinks() ?
  if ((link.pathname && link.pathname.indexOf('(')>0) || (link.hash && link.hash!='#') || link.pathname=='' || link.pathname=='/') {
    return(true);
  }

  pageUrl = link;
  if (formChanged) {
    if (!confirm('Het formulier is gewijzigd, weet u zeker dat u de pagina wilt verlaten?'))
      // False prevents the normal link to be executed, should be false on succes
      return false;
  }
  var newHref='';
  if (typeof(link) == 'object') {
    newHref = link.pathname;
    if (link.href && link.protocol!='javascript:'
        && (!link.protocol || link.protocol==':' || link.protocol==top.location.protocol)
        && (!link.hostname || link.hostname==top.location.hostname)
        && (link.port==0 || link.port=='80' || link.port==top.port)) {
      newHref += link.search;
      if (link.hash != '#') newHref += link.hash;
    }
  } else {
    newHref = link;
  }
  if (newHref.substr(0,1) != '/') newHref = '/'+newHref; // Make sure it starts with a slash, indicates loadable page
  newHref = newHref.replace(/\/p\-[^\/]*/,'');           // Remove any processor (should be Ajax anyway
  newHref = newHref.replace(/\/s\-[^\/]*/,'');           // Remove any style (known from site.php)
  if (newHref) $.history.load(newHref);
  // False prevents the normal link to be executed, should be false on succes

  return false;
}

function loadHash(hash) {
if (!hash || hash.substr(0,1)=='/') {    // if the hash doesn't start with '/', it's a regular anchor.
    var curValues = [];
    loadOnePage(hash,'content');
    setNavPath(hash);
    setSelected(hash);
    var pageInfo = pages[hash];
    if (pageInfo) {
      pageTitle = siteTitle + ' - ' + pageInfo['title'];
      document.title = pageTitle;
      for(property in pageInfo) {  // traverse the properties
        if(property.match(/^load_/)) { // We need to load something!
          curValues[property] = pageInfo[property];
        }
      }
    }
    // Actually load the found values, or the defaults
    $(".doRefresh").each( function () {
      var parts = this.id.split('_');
      var type = parts[parts.length-1];   // Last party is type of data
      switch(type) {
        case 'html':
          if (!defaultValues[this.id])
            defaultValues[this.id] = $(this).html();
          if (curValues[this.id]) {
            var newHref = curValues[this.id];
            if(newHref.substr(0,1) != '/') newHref = '/'+newHref; // Make sure it starts with a slash, indicates loadable page
            newHref = newHref.replace(/\/p\-[^\/]*/,'');         // Remove any processor (should be Ajax anyway
            newHref = newHref.replace(/\/s\-[^\/]*/,'');         // Remove any style (known from site.php)
            loadOnePage(newHref, this.id);
          }
          else {
            if ($(this).html() != defaultValues[this.id]) loadHTML(defaultValues[this.id], this.id);
          }
          break;
        case 'src':
          if (!defaultValues[this.id]) defaultValues[this.id] = this.src;
          value = curValues[this.id] ? curValues[this.id] : defaultValues[this.id];
          if (this.src != value) this.src = value;
          break;
        case 'bg':
          if (!defaultValues[this.id]) defaultValues[this.id] = $(this).css('background-image');
          value = curValues[this.id] ? 'url(/p-httpd/images/'+curValues[this.id]+')' : defaultValues[this.id];
          if ($(this).css('background-image') != value) $(this).css('background-image',value);
          break;
       }
    });
  }
}

function scrollDivs(the_container) {
  if ($.browser.msie && $.browser.version.substr(0,1)=="6") // IE6 not supported...
    return;
}

function fadeOut(target) {
  if (pageTransitions && target=='content') { // Fade away the content frame
    if(content_state == 'visible' && $('.blind').length==0) {
      // Fade away by showing blinds (luxaflex)
      var theParent = $('#'+target).parent().parent();
      var parentWidth = theParent.width()-2;
      var blindWidth = Math.round(parentWidth/num_blinds);
      var leftOffset = Math.round((blindWidth)/2);
      var height = theParent.height() - parseInt(theParent.css('borderBottomWidth')) - $('#hallmarks').height() - 1;
      for(var i=0; i<num_blinds; i++) {
        var left = Math.round(i*parentWidth/num_blinds)+leftOffset;
        var blind =
        $('<div>', {
          'blindWidth'  : blindWidth,
          'class'       : 'blind'
        });
        blind.css({
          'left'        : left,
          'width'       : 0,
          'height'      : height
        });
        blind.appendTo(theParent);
      }
      
      $('.blind').animate({'left':'-='+leftOffset, 'width':blindWidth},300,function () {
        $('#'+target).parent().scrollTop(0); // Start at top with new page...
      });
    }
    // Code below animates the screen up. Is too "wild" for every page.
    //var h=$('#'+target).parent().height()+100;
    //transitioning = true;
    //$('#'+target).parent().animate({'top':-h, 'opacity':0},'slow', function() {
    //  transitioning = false;
    //});
  }
}

function fadeIn(target) {
  if (pageTransitions && target=='content') {
    var theParent = $('#'+target).parent().parent();
    // Text is visible. We might need to move the content screen (parent) to the correct position
    if($('#'+target).text().replace(/\s*/,"")) {
      if(content_state == 'invisible') {
        $('#footer').css({'display':'block'});
        var orgTop = parseInt(theParent.attr('orgTop'));
        content_state = 'transitioning';
        theParent.css({'display':'block'});
        theParent.animate({'top':orgTop, 'opacity':1},{'easing':'WOMBounce', 'duration':1500,
          complete:function() {
            content_state = 'visible';
            // Make sure the footer is at the correct place, in case of an fast (incomplete) animation
            // Opacity goes wrong in IE8 :o(
            if ($.browser.msie && $.browser.version.substr(0,1)<"9") // IE6 not supported...
              $('#footer').css({'bottom':0});
            else
              $('#footer').css({'bottom':0, 'opacity':1});
          },
          step: function(now, fx) {
            $('#footer').css({'bottom':fx.elem.offsetTop-headerHeight, 'opacity':fx.elem.style.opacity});
          }
        });
      }
      // Make the logo small, in case it wasn't
      if(logo_state == 'big') {
        logo_state = 'transistioning';
        $("#logo2s").hide();
        $("#logo2").animate(logo2_small, 1200, function () {
          $("#logo2").css('marginLeft', '-6px');
          $("#logo2").attr("src", logo2_small_src);
          logo_state = 'small';
        });
      }
      // Make a "blinds" animation, to open the curtain (in case it was closed).
      var height = theParent.height() - parseInt(theParent.css('borderBottomWidth')) - $('#hallmarks').height() - 1;
      var blindWidth = $('.blind').attr('blindWidth');
      var leftOffset = parseInt(blindWidth/2);
      if(height) $('.blind').css({'height':height});
      $('.blind').animate({'left':'+='+leftOffset, 'width':0},300,function () {
        $('.blind').remove();
      });
    }
    // Special case: a new page was load without any content. Make room on the screen, by animating the content (parent) away
    else {
      if(content_state != 'invisible') {
        var h=theParent.height()+10;
        content_state = 'transitioning';
        theParent.animate({'top':-h, 'opacity':0},{'duration':'slow',
          complete:function() {
            theParent.css({'display':'none'});
            content_state = 'invisible';
          },
          step: function(now, fx) {
            $('#footer').css({'bottom':fx.elem.offsetTop-headerHeight});
          }
        });
      }
      if(logo_state == 'small') {
        logo_state = 'transistioning';
        // Also make the logo big again
        $("#logo2").css('marginLeft', "0px");
        $("#logo2").attr("src",logo2_big_src);
        $("#logo2").animate(logo2_big, 1200, function () {
          $("#logo2s").show();
          logo_state = 'big';
        });
      }
    }
  }
}

// Load a single page for one "frame" div using Ajax
function loadOnePage(newHref,target) {
  if(!newHref) newHref='/'; // Make sure there is a valid URL
  if (pageTransitions && target=='content') fadeOut(target);
  // Perform an ajax call
  if (newHref.indexOf("?")>-1) // Already GET-pars...
    href = '/p-ajax'+siteStyle+newHref+'&container='+target; // Pass container as GET-par...
  else
    href = '/p-ajax'+siteStyle+newHref+'?container='+target; // Pass container as GET-par...
  $('#'+target).load(href,{},function(responseText, textStatus){
      if (textStatus=='success') {
        // If we have an outer scrollbar, resize the target div.
        processLinks('#'+target);
        if (target=='content') {
          $('#content img').load(function(){ resizeDivs('content'); });
          resizeDivs(target);
        }
        scrollDivs($('#'+target));
        if (typeof(SiteProcessPage)=='function') SiteProcessPage(target);
        formChanged = false; // Newly loaded page, formChanged may be false again
      }
    top.scroll(0,0); // Start at top with new page...
    fadeIn(target);
  });
}

function loadHTML(html,target) {
  if (pageTransitions && target=='content') fadeOut(target);
  $('#'+target).css('height','auto');
  $('#'+target).html(html);
  resizeDivs(target);
  processLinks('#'+target);
  formChanged = false; // Newly loaded page, formChanged may be false again
  top.scroll(0,0); // Start at top with new page...
  fadeIn(target);
}


// ------------------------------------- Add captions to images
(function($) {
  $.fn.addCaptions = function(options) {
    // if the options aren't set, set them to an empty object
    options = options || {};

    // the default settings
    var settings = {
      // attributes to check for caption (these are checked in order)
      attributes: [
        'longdesc',
        'title',
        'alt'
      ],

      // whether or not to add the caption box to images with no caption
      allowBlankCaption: true,

      // fins options (change these to match other elements eg a.fullSizeImage or whatever)
      findElement: 'img',
      findClass: '',

      // remove the float directly on the image?
      removeFloat: true,

      // options for respective elements
      containerElement: 'div',
      containerClass: 'caption',
      // 
      titleElement: 'p',
      titleClass: 'caption-title',
      // 
      imageClass: '',
      // 
      discardClass: 'no_caption'
    }

    // update the settings
    $.extend(settings, options);

    // get all the images in the current element
    if (settings.findClass) {
      if(settings.discardClass)
        var images = $(this).find(settings.findElement + '.' + settings.findClass).not('.' + settings.discardClass);
      else
        var images = $(this).find(settings.findElement + '.' + settings.findClass);

    } else {
      if(settings.discardClass)
        var images = $(this).find(settings.findElement).not('.' + settings.discardClass);
      else
        var images = $(this).find(settings.findElement);
    }

    // if there are some images
    if (images.length) {
      // loop through each
      $.each(images, function() {
        // get the parent object
        var parent = $(this).parent().get(0);

        // check it's not already got a caption
        if (parent.tagName.toLowerCase() == settings.containerElement && $(parent).hasClass(settings.containerClass)) {
          return true;
        }

        // initialize the caption variable
        var caption = '';

        // determine the image caption
        for (var i = settings.attributes.length - 1; i >= 0; i--) {
          caption = $(this).attr(settings.attributes[i]);
          
          if (caption) {
            break;
          }
        }

        // if the caption is empty, return unless explicitly allowed
        if (!caption && !settings.allowBlankCaption) {
          return true;
        }

        // get the float
        var location = $(this).css('float');
        var margin = "";
        if(!location || location=='none')
          var location = $(this).attr('align');
        switch (location) {
          case 'middle':
          case 'center':
            location = "margin-left: auto; margin-right:auto;";
            break;
          default:
            location = "float:" + location;
        }

        // remove the float
        if (settings.removeFloat || location=="none") {
          $(this).css('float', 'none');
        }

        // if we;ve got to add a class...
        if (settings.imageClass) {
          $(this).addClass(settings.imageClass);
        }

        // wrap the image in a div with the correct styling
        $(this).wrap('<' + settings.containerElement + ' class="' + settings.containerClass + '" style="' + location + '"></' + settings.containerElement + '>');

        if (caption) {
          // add the caption in after the current element
          $(this).after('<' + settings.titleElement + ' class="' + settings.titleClass + '">' + caption + '</' + settings.titleElement + '>');
        }
      });
    }
  }
})(jQuery);



// ----------------------------------- Add our own easing
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be in frames or seconds/milliseconds
$.extend( $.easing,
{
  easeOutBounce: function (x, t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
      return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
      return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
      return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
      return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
  },

  WOMBounce: function (x, t, b, c, d) {
    var bounceheight = 1/4;
    var bounces = 8;
    // calculate total duration of the steps (timedivision)
    var rel_time = t/d;
    var steptimediv = 1
    var stepheight = bounceheight;
    for(var i=0; i < bounces; i++) {
      steptimediv += 2*stepheight;
      stepheight /= 2;
    }
    // Determine the current step
    var curstep = 0;  // 0 = initial animation, 1 is first bounce, etc.
    var stepheight = bounceheight;
    var steptime = 1;
    for(var i=0; i <= bounces; i++) {
      if(rel_time < steptime/steptimediv) {
        curstep = i;
        break;
      }
      steptime  += 2*stepheight;
      stepheight /= 2;
    }
    // Initial animation
    if(curstep == 0)
      return c*(steptimediv*steptimediv*rel_time*rel_time) + b;
    // bounce animation
    else 
      return c*(steptimediv*steptimediv*(rel_time-((steptime-2*stepheight)/steptimediv))*(rel_time-((steptime-2*stepheight)/steptimediv)) + 1 - 4*stepheight*stepheight) + b;


    // Internal variables:
    // rel_time : relative time (current time relative to the total animation duration in milliseconds
    // curstep : current step, 0 is initial animation, 1 first bounce, etc.
    // stepheight : bounceheight of the current step
    // steptimediv : timedivision, total animation duration in steps (initial fall is duration 1, first bounce up 1.5, first bounce down 2, etc.)
    // steptime : (end) time of the current step, relative to steptimediv

    // 1,2,3: return c*(steptimediv*steptimediv*(rel_time-=((steptime-2*stepheight)/steptimediv))*rel_time + 1-bounceheight/Math.pow(2,2*curstep-1)) + b;
    // 0: return c*(timediv*timediv*t*t) + b;
    // 1: return c*(timediv*timediv*(t-=((1+bounceheight)/timediv))*t + 1-bounceheight/2) + b;
    // 2: return c*(timediv*timediv*(t-=((1+2.5*bounceheight)/timediv))*t + 1-bounceheight/8) + b;
    // 3: return c*(timediv*timediv*(t-=((1+3.25*bounceheight)/timediv))*t + 1-bounceheight/32) + b;
  }

});

// jQuery outerHeight etc. extension
// Zie: http://jupiterit.com/news/set-inner-outer-width-height-with-jquery-dimensions-etc-plugin

// jquery/dom/cur_styles/cur_styles.js

(function($){

var getComputedStyle = document.defaultView && document.defaultView.getComputedStyle,
  rupper = /([A-Z])/g,
  rdashAlpha = /-([a-z])/ig,
  fcamelCase = function(all, letter) {
    return letter.toUpperCase();
  },
  getStyle = function(elem) {
    if (getComputedStyle) {
      return getComputedStyle(elem, null);
    }
    else if (elem.currentStyle) {
      return elem.currentStyle
    }
  },
  rfloat = /float/i,
  rnumpx = /^-?\d+(?:px)?$/i,
  rnum = /^-?\d/;
/**
 * @add jQuery
 */
//
/**
 * @function curStyles
 * @param {HTMLElement} el
 * @param {Array} styles An array of style names like <code>['marginTop','borderLeft']</code>
 * @return {Object} an object of style:value pairs.  Style names are camelCase.
 */
$.curStyles = function(el, styles) {
  if(!el){
    return null;
  }
  var currentS = getStyle(el), 
           oldName, 
           val, 
           style = el.style,
           results = {},
           i=0,
           name;

  for(; i < styles.length; i++){
    name = styles[i];
    oldName = name.replace(rdashAlpha, fcamelCase);
    if ( rfloat.test( name ) ) {
      name = jQuery.support.cssFloat ? "float" : "styleFloat";
      oldName = "cssFloat"
    }
    if (getComputedStyle) {
      name = name.replace(rupper, "-$1").toLowerCase();
      val = currentS.getPropertyValue(name);
      if ( name === "opacity" && val === "" ) {
        val = "1";
      }
      results[oldName] = val;
    } else {
      var camelCase = name.replace(rdashAlpha, fcamelCase);
      results[oldName] = currentS[name] || currentS[camelCase];


      if (!rnumpx.test(results[oldName]) && rnum.test(results[oldName])) { //convert to px
        // Remember the original values
        var left = style.left, 
          rsLeft = el.runtimeStyle.left;

        // Put in the new values to get a computed value out
        el.runtimeStyle.left = el.currentStyle.left;
        style.left = camelCase === "fontSize" ? "1em" : (results[oldName] || 0);
        results[oldName] = style.pixelLeft + "px";

        // Revert the changed values
        style.left = left;
        el.runtimeStyle.left = rsLeft;
      }
    }
  }
  return results;
};
/**
 *  @add jQuery.fn
 */

$.fn.
/**
 * @parent dom
 * @plugin jquery/dom/cur_styles
 * @download jquery/dist/jquery.curstyles.js
 * @test jquery/dom/cur_styles/qunit.html
 * Use curStyles to rapidly get a bunch of computed styles from an element.
 * <h3>Quick Example</h3>
 * @codestart
 * $("#foo").curStyles('float','display') //-> 
 * // {
 * //  cssFloat: "left", display: "block"
 * // }
 * @codeend
 * <h2>Use</h2>
 * <p>An element's <b>computed</b> style is the current calculated style of the property.
 * This is different than the values on <code>element.style</code> as
 * <code>element.style</code> doesn't reflect styles provided by css or the browser's default
 * css properties.</p>
 * <p>Getting computed values individually is expensive! This plugin lets you get all
 * the style properties you need all at once.</p>
 * <h2>Demo</h2>
 * <p>The following demo illustrates the performance improvement curStyle provides by providing
 * a faster 'height' jQuery function called 'fastHeight'.</p>
 * @demo jquery/dom/cur_styles/cur_styles.html
 * @param {String} style pass style names as arguments 
 * @return {Object} an object of style:value pairs
 */
curStyles = function(){
  return $.curStyles(this[0], $.makeArray(arguments))
}

})(jQuery);


// jquery/dom/dimensions/dimensions.js

(function($){

/**
 * @page dimensions dimensions
 * @parent dom
 * <h1>jquery/dom/dimensions <span class="Constructor type">Plugin</span></h1>
 * The dimensions plugin adds support for setting+animating inner+outer height and widths.
 * <h3>Quick Examples</h3>
@codestart
$('#foo').outerWidth(100).innerHeight(50);
$('#bar').animate({outerWidth: 500});
@codeend
 * <h2>Use</h2>
 * <p>When writing reusable plugins, you often want to 
 * set or animate an element's width and height that include its padding,
 * border, or margin.  This is especially important in plugins that
 * allow custom styling.
 * The dimensions plugin overwrites [jQuery.fn.outerHeight outerHeight],
 * [jQuery.fn.outerWidth outerWidth], [jQuery.fn.innerHeight innerHeight] 
 * and [jQuery.fn.innerWidth innerWidth]
 * to let you set and animate these properties.
 * </p>
 * <h2>Demo</h2>
 * @demo jquery/dom/dimensions/dimensions.html
 */

var weird = /button|select/i, //margin is inside border
  getBoxes = {},
  checks = {
    width: ["Left", "Right"],
    height: ['Top', 'Bottom'],
    oldOuterHeight: $.fn.outerHeight,
    oldOuterWidth: $.fn.outerWidth,
    oldInnerWidth: $.fn.innerWidth,
    oldInnerHeight: $.fn.innerHeight,
    oldHeight : $.fn.height,
    oldWidth: $.fn.width
  };
/**
 *  @add jQuery.fn
 */
$.each({

/*
 * @function outerWidth
 * @parent dimensions
 * Lets you set the outer height on an object
 * @param {Number} [height] 
 * @param {Boolean} [includeMargin]
 */
width:
/*
 * @function innerWidth
 * @parent dimensions
 * Lets you set the inner height of an object
 * @param {Number} [height] 
 */
"Width",
/*
 * @function outerHeight
 * @parent dimensions
 * Lets you set the outer height of an object where: <br/> 
 * <code>outerHeight = height + padding + border + (margin)</code>.  
 * @codestart
 * $("#foo").outerHeight(100); //sets outer height
 * $("#foo").outerHeight(100, true); //uses margins
 * $("#foo").outerHeight(); //returns outer height
 * $("#foo").outerHeight(true); //returns outer height with margins
 * @codeend
 * When setting the outerHeight, it adjusts the height of the element.
 * @param {Number|Boolean} [height] If a number is provided -> sets the outer height of the object.<br/>
 * If true is given ->  returns the outer height and includes margins.<br/>
 * If no value is given -> returns the outer height without margin.
 * @param {Boolean} [includeMargin] Makes setting the outerHeight adjust for margin.
 * @return {jQuery|Number} If you are setting the value, returns the jQuery wrapped elements.
 * Otherwise, returns outerHeight in pixels.
 */
height:
/*
 * @function innerHeight
 * @parent dimensions
 * Lets you set the outer width on an object
 * @param {Number} [height] 
 */
"Height" }, function(lower, Upper) {

  //used to get the padding and border for an element in a given direction
  getBoxes[lower] = function(el, boxes) {
    var val = 0;
    if (!weird.test(el.nodeName)) {
      //make what to check for ....
      var myChecks = [];
      $.each(checks[lower], function() {
        var direction = this;
        $.each(boxes, function(name, val) {
          if (val)
            myChecks.push(name + direction+ (name == 'border' ? "Width" : "") );
        })
      })
      $.each($.curStyles(el, myChecks), function(name, value) {
        val += (parseFloat(value) || 0);
      })
    }
    return val;
  }
  //getter / setter
  $.fn["outer" + Upper] = function(v, margin) {
    if (typeof v == 'number') {
      this[lower](v - getBoxes[lower](this[0], {padding: true, border: true, margin: margin}))
      return this;
    } else {
      return checks["oldOuter" + Upper].call(this, v)
    }
  };
  $.fn["inner" + Upper] = function(v) {
    if (typeof v == 'number') {
      this[lower](v - getBoxes[lower](this[0], { padding: true }))
      return this;
    } else {
      return checks["oldInner" + Upper].call(this, v)
    }
  };
  $.fn[lower] = function(v){
    var dim;
    if (v === undefined 
      && this[0] 
      && this[0] !== window 
      && (dim = this[0]["offset" + Upper] )) {
      return dim - getBoxes[lower](this[0], { padding: true, border: true });
    } else {
      return checks["old" + Upper].call(this, v)
    }
  };
  //provides animations
  var animate = function(boxes){
    return function(fx){
      if (fx.state == 0) {
        fx.start = $(fx.elem)[lower]();
        fx.end = fx.end - getBoxes[lower](fx.elem,boxes);
      }
      fx.elem.style[lower] = (fx.pos * (fx.end - fx.start) + fx.start) + "px"
    }
  }
  $.fx.step["outer" + Upper] = animate({padding: true, border: true})
  $.fx.step["outer" + Upper+"Margin"] =  animate({padding: true, border: true, margin: true})
  $.fx.step["inner" + Upper] = animate({padding: true})
})

})(jQuery);

