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

// 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) {
    var i;
    for (i=0; i<preload_image.arguments.length; i++) {
      img = new Image();
      img.src = preload_image.arguments[i];
    }
  }
}
if(typeof(show_note) != "function") {
  // show a note
  // show_note(text, start_to, hide_to, grace_to, align_x, align_y, x, y, width, height)
  show_note = function() {
    // Set the defaults
    var text = '';
    var start_to = 500;
    var hide_to = 0;
    var grace_to = 500;
    var align_x = 'p';
    var align_y = 'p';
    var x = -160;
    var y = -30;
    var width = 150;
    var height = 20;
    // Get the given parameters
    var argv = show_note.arguments;
    if(argv.length>0) text = argv[0];
    if(argv.length>1) start_to = argv[1];
    if(argv.length>2) hide_to = argv[2];
    if(argv.length>3) grace_to = argv[3];
    if(argv.length>4) align_x = argv[4];
    if(argv.length>5) align_y = argv[5];
    if(argv.length>6) x = argv[6];
    if(argv.length>7) y = argv[7];
    if(argv.length>8) width = argv[8];
    if(argv.length>9) height = argv[9];
    if(text != '')
    {
      // Create a note div, if it doesn't exist yet
      var note=$('#note');
      if(note.length <= 0) {
        var pophtml =  '<div id="note" class="PopStyle"></div>';
        $(document.body).append(pophtml);
        var note = $('#note');
      }
      note.html('<div class="NoteStyle">'+text+'</div>');
      var pos_x = x + window.mouseXPos;
      var pos_y = y + window.mouseYPos;
      note.width(width);
      note.height(height);
      note.css({'top':pos_y,'left':pos_x});
      note.stop(true,true).fadeIn(300);
    }
    else {
      $('#note').stop(true,true).fadeOut(100);
    }
    return false;
  }
  $(document).ready(function(){
    $(document).mousemove(function(e){
      window.mouseXPos = e.pageX;
      window.mouseYPos = e.pageY;
    });
  });
}

function initSiteJs() {
  // Initialize history plugin.
  // The callback is called at once by present location.hash.
  if (typeof($.history.init)=='function') $.history.init(loadHash);
  processLinks('body');
}

var pages = [];
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(innerScrollbar,target) {
  if ($("#canvas").width() < $(window).width()) { // SlipScroll allowed: No horizontal scrollbar...
    $('.noReposition').addClass('doReposition').removeClass('noReposition');
    if (typeof(bodyBgCentered)!="undefined" && bodyBgCentered==true) $('body').css({'background-position':'center top'});
    $('html').css('width','100%'); // Reset to default CSS value...
  } else { // Supress (optional) SlipScroll...
    $('.doReposition').css({'position':'absolute'}).addClass('noReposition').removeClass('doReposition');
    if (typeof(bodyBgCentered)!="undefined" && bodyBgCentered==true) $('body').css({'background-position':'left top'});
    $('html').outerWidth($("#canvas").width(), false); // Set to max so <html> can be used for full width/height backgrounds...
  }
  $(".doReposition").each(function () {
    orgTop = $(this).attr('orgTop');
    if (orgTop) $(this).css({'top':orgTop+"px"});
  });
  var headerHeight = 0;
  if ($('#header').outerHeight) headerHeight = $('#header').outerHeight(true);
  else headerHeight = $('#content').offset().top;
  var footerHeight = 0;
  if ($('#footer').outerHeight) footerHeight = $('#footer').outerHeight(true);
  var contentHeight = $(window).height()-headerHeight-footerHeight;
  if (innerScrollbar) {
    $('.doResize').css('overflow','auto');
    // Fit content in the window.
    $('.doResize').outerHeight(contentHeight, true);
    // Disable the scrollbars of html and body
    $('html, body').css('overflow','hidden');
  } else {
    $('.doResize').height("100%");
    $('.doResize').css('overflow','visible');
    // Find the maximum height of the relevant columns
    $('.doResize').each(function (intIndex) {
      if ($(this).outerHeight(true) > contentHeight)
        contentHeight = $(this).outerHeight(true);
    });
    // Respect 'stretchers' for content DIV that positions the footer...
    if (target=='content') {
      $('.isContentStretcher').each(function (intIndex) {
        var bottomLine = parseInt($(this).outerHeight(true)) - footerHeight;
        if (bottomLine > contentHeight) contentHeight = bottomLine;
      });
    }
    $('.doResize').outerHeight(contentHeight, true);
    if (typeof(HideOverflow)=="undefined" || HideOverflow==true) $('.doResize').css('overflow','hidden');
    // AvD on 12-12-2010: Also stretch <html> and <body> height so they can be used for full-height backgrounds
    $('html').outerHeight(headerHeight+contentHeight+footerHeight, true);
    $('body').outerHeight(headerHeight+contentHeight+footerHeight, true);
  }
}

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) {
  // 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]").not(".noAjax").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]").not(".noAjax").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]").not(".noAjax").click( function(event) {
    if (  !$(this).attr('href') || ( $(this).attr('href') &&
         (!$(this).attr('href').match(/^mailto/i) && !$(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").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) {
      if (!jqForm.hasClass("noTransistion")) 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);
    if (typeof(setPageInfo) == 'function') setPageInfo('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 part 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;
  var scrollTop = the_container.scrollTop();
  var scrollHeight = the_container.height();
  var footerHeight = 0;
  if ($('.footer').outerHeight) footerHeight = $('.footer').outerHeight(true);

  if (scrollSlipAtTop) {
    var maxHeight = 0;
    $('.doReposition').each(function () {
      var bottomLine = parseInt($(this).outerHeight(true));
      if (bottomLine > maxHeight) maxHeight = bottomLine;
    });
    if ($('#header').css('position') == 'fixed')
      headerHeight = 0;
    else
      headerHeight = $('#header').outerHeight(true);
    $(".doReposition").each(function () {
      var marginTop = parseInt($(this).css('margin-top')+0);
      var marginBot = parseInt($(this).css('margin-bottom')+0);
      if (!$(this).attr('orgTop'))
        $(this).attr('orgTop', ($(this).offset().top - marginTop) );
      var orgTop = parseInt($(this).attr('orgTop'));
      fixedRequired = false;
      if ((scrollTop-headerHeight) < (maxHeight-$(this).height()) - marginBot)
        fixedRequired = true;
      if ((scrollTop-marginTop) < (headerHeight))
        fixedRequired = false;
      if (fixedRequired) { // Column will not scroll anymore...
        if ($(this).css('position') != 'fixed') {
          newTop = orgTop - headerHeight - marginTop;
          $(this).css({'position':'fixed', 'top':newTop+"px" });
        }
      } else { // Column may scroll again, set to correct height...
        if ($(this).css('position') && $(this).css('position')!='absolute') {
          var newTop = maxHeight + $('#header').outerHeight(true) - $(this).height() - marginTop - marginBot;
          if ((scrollTop-marginTop) <  headerHeight) newTop = headerHeight;
          $(this).css({'position':'absolute', 'top':newTop+"px"});
        }
      }
    });
  } else {
    var scrollBottom = scrollTop + scrollHeight;
    var gap = 8;
    if ($('#header').css('position') == 'fixed')
      var headerHeight = $('#header').outerHeight(true);
    else
      var headerHeight = 0;
    $(".doReposition").each(function () {
      if (!$(this).attr('orgTop')) $(this).attr('orgTop', $(this).offset().top);
      var orgTop = parseInt($(this).attr('orgTop'));
      var orgBottom = orgTop + $(this).height()
      var fixedRequired = true;
      if (orgBottom >= scrollBottom-gap)
        fixedRequired = false;
      else if (orgTop >= (scrollTop+headerHeight))
        fixedRequired = false;
      if (headerHeight && (scrollHeight-headerHeight>$(this).height()) && scrollTop==0) fixedRequired = true; // Prevent wobble in FF...
      if (fixedRequired) {
        if ($(this).css('position') != 'fixed') {
          var newTop = scrollHeight - $(this).height() - gap ;
          if (newTop > headerHeight) newTop = headerHeight;
          $(this).css({'position':'fixed', 'top':newTop+"px"});
        }
      } else {
        if ($(this).css('position') != 'absolute') {
          var newTop = orgTop;
          $(this).css({'position':'absolute', 'top':newTop+"px"});
        }
      }
    });
  }
}

function fadeOut(target) {
  if (pageTransitions) { // Fade away the content frame
    if ($.browser.msie) {
      $('#'+target+'_fade').remove(); // Remove any previous incarnations of the 'shield'
      $('#'+target).after('<div id="'+target+'_fade" class="fade">');
      var position = $('#'+target).position();
      marginleft = parseInt($('#'+target).css('marginLeftWidth'));
      margintop  = parseInt($('#'+target).css('marginTopWidth'));
      borderleft = parseInt($('#'+target).css('borderLeftWidth'));
      bordertop  = parseInt($('#'+target).css('borderTopWidth'));
      if (!marginleft) marginleft = 0;
      if (!margintop)  margintop  = 0;
      if (!borderleft) borderleft = 0;
      if (!bordertop)  bordertop  = 0;
      // Find the correct backgroundcolor for the fade screen: content div or parent backgroundcolor
      var backgroundColor;
      $('#'+target).parents().each( function() {
        if(!backgroundColor || backgroundColor=='transparent' || backgroundColor=='rgba(0, 0, 0, 0)') {
          backgroundColor=$(this).css('background-color');
        }
      });
      $('#'+target+'_fade').hide().css({
        position: 'absolute',
        left:   position.left+marginleft+borderleft+'px',
        top:    position.top+margintop+bordertop+'px',
        width:  $('#'+target).innerWidth(),
        height: $('#'+target).innerHeight(),
        backgroundColor: backgroundColor
      }).fadeIn('fast');
    } else {
      $('#'+target).animate({'opacity':0},'fast');
    }
  }
}

function fadeIn(target) {
  if (pageTransitions) {
    if ($.browser.msie) {
      $('#'+target+'_fade').stop().fadeOut('fast', function() { $(this).remove(); });
    } else {
      $('#'+target).stop().animate({'opacity':1},'fast');
    }
  }
}

// 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') {
      // Only rework links if Ajax-pageloads are used for the site...
      if (typeof(AjaxLoads)=="undefined" || AjaxLoads==true) processLinks('#'+target);
      // If we have an outer scrollbar, resize the target div.
      if (target=='content') {
        $('#content img').load(function(){ resizeDivs(innerScrollbar, 'content'); });
        resizeDivs(innerScrollbar,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...
    if (pageTransitions && target=='content') fadeIn(target);
  });
}

function loadHTML(html,target) {
  if (pageTransitions && target=='content') fadeOut(target);
  if(!innerScrollbar)
    $('.doResize').css('height','auto');
  else
    $('#'+target).css('height','auto');
  // EdM 2012-01-12: empty en remove the contents of html, first empty en then remove is faster!
  $('#'+target).children().empty().remove();
  $('#'+target).html(html);
  resizeDivs(innerScrollbar,target);
  processLinks('#'+target);
  formChanged = false; // Newly loaded page, formChanged may be false again
  top.scroll(0,0); // Start at top with new page...
  if (pageTransitions && target=='content') fadeIn(target);
}


// 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);

