// 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];
    }
  }
}

function initSiteJs() {
  // Initialize history plugin.
  // The callback is called at once by present location.hash.
  $.historyInit(loadHash);
  processLinks('content');
  processLinks('column_left');
  processLinks('column_right');
}

var pages = [];
function fillPagesArray(separator, listStyle, ref) {
  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>";
  }
  $.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);
      loadHash(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) {
  cleft = $("#center").offset().left;
  $(".doRepostion").css({left:cleft});
  offset = $('#content').offset();
  headerHeight = offset.top;
  var footerHeight = 0;
  if($('.footer').height)
    footerHeight = $('.footer').height();
  winHeight = $(window).height()-headerHeight-footerHeight-2; // Some room to prevent unnecessary scrollbars
  // IE6 quirks: gives one pixel to much height for the window
  if (innerScrollbar) {
    $('.doResize').css('overflow','auto');
    var contentHeight = winHeight;
    // Fit content in the window.
    $('.doResize').height(contentHeight);
    // Disable the scrollbars of html and body
    $('html, body').css('overflow','hidden');
  } else {
    var contentHeight=winHeight;
    $('.doResize').height("100%");
    $('.doResize').css('overflow','visible');
    // Find the maximum height of the relevant columns
    $('.doResize').each(function (intIndex) {
      if($(this).height() > contentHeight)
        contentHeight = $(this).height();
    });

    // $('.center').height(contentHeight+headerHeight+footerHeight+2); // Previously subtracted
    // $('.doResize').css('height',contentHeight);
    $('.doResize').height(contentHeight);
    $('.doResize').css('overflow','hidden');
  }
}

// Process any links
function processLinks(target) {
  // Make links to the target 'iframe' aware of ajax...
  var sel='';
  if (target) sel="#"+target+" ";
  $(sel+"a[target='content']").not("a[@rel=lightbox]").click( function(event) {
    if(!loadAjax(this)) event.preventDefault(); return true;
  });
  $(sel+"a[target='']").not("a[@rel=lightbox]").click( function(event) {
    if(!loadAjax(this)) event.preventDefault(); return true;
  });

  // Prevent the form from being sent
  // onsubmit doesn't work as expected with Ajax forms, use the pre-serialize hook
  $("form").each(function() {
    if(!$(this).attr('org_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) {
      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 (ajax post)
  $("form").ajaxForm({
    resetForm: true,
    success: function (responseText, statusText) {
      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) {
  if(pages && pages[sel]) {
    id = pages[sel].id;
    if(id) {
      $('#menu li').removeClass('selected');
      $('#menu li').removeClass('parent');
      $('#'+id).addClass('selected');
      $('#'+id).parents("li").addClass('parent');
    }
  }
}

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;
  }
  if (typeof(link) == 'object') {
    if (link.href && link.protocol!='javascript:'
        && (!link.protocol || link.protocol==top.location.protocol)
        && (!link.hostname || link.hostname==top.location.hostname)
        && (link.port==0 || link.port=='80' || link.port==top.port)) {
      var newHref=link.pathname;
      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) $.historyLoad(newHref);
  // False prevents the normal link to be executed, should be false on succes

  return false;
}

function loadHash(hash) {
  if (hash) {
    // Hide any open zoomed images...
    // Disabled 20100114: Leads to JS-error sometimes ('opts not found')...
    //if ($("#fancy_outer").is(":visible")) $.fn.fancybox.close();

    if (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'];
        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) {
  // No support for IE6
  if ($.browser.msie && $.browser.version.substr(0,1)=="6")
    return;
  var scrollTop = the_container.scrollTop();
  var scrollHeight = the_container.height();
  if(scrollSlipAtTop) {
    var maxHeight = 0;
    $('.doReposition').each(function () {
     if ($(this).height() > maxHeight) maxHeight = $(this).height();
    });
    if($('#header').css('position') == 'fixed')
      headerHeight = 0;
    else
      headerHeight = $('#header').height();
    $(".doReposition").each(function () {
      if(!$(this).attr('orgTop')) $(this).attr('orgTop', $(this).offset().top);
      var orgTop = parseInt($(this).attr('orgTop'));
      fixedRequired = false;
      if(scrollTop-headerHeight < maxHeight - $(this).height())
        fixedRequired = true;
      if(scrollTop < headerHeight)
        fixedRequired = false;
      if(fixedRequired) {
        if($(this).css('position') != 'fixed') {
          newTop = orgTop - headerHeight;
          $(this).css({'position':'fixed', 'top':newTop+"px"});
        }
      }
      else {
        if($(this).css('position') != 'absolute') {
          var newTop = maxHeight - $(this).height() +  $('#header').height();
          if (scrollTop <  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').height();
    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(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"});
        }
      }
    });
  }
}

// Load a single page for one "frame" div using Ajax
function loadOnePage(newHref,target) {
  // Fade away the content frame
  //  $('#'+target).css({opacity:0})        // Stupid IE7 antialiases text to black, with this statement
  $('#'+target+'_fade').remove(); // Remove any previous incarnations of the 'shield'
  $('#'+target).after('<div id="'+target+'_fade" class="fade">');
  // var offset = $('#'+target).offset(); // Do not use position with absolute positions!
  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:   offset.left+marginleft+borderleft+'px',  // Do not use position with absolute positions!
    // top:    offset.top+margintop+bordertop+'px',     // Do not use position with absolute positions!
    left:   position.left+marginleft+borderleft+'px',
    top:    position.top+margintop+bordertop+'px',
    width:  $('#'+target).innerWidth(),
    height: $('#'+target).innerHeight(),
    backgroundColor: backgroundColor
  }).fadeIn('fast');
  // Perform an ajax call
  if (document.location.href.indexOf("?") > -1 ) var QueryString = '&'+document.location.href.substr(document.location.href.indexOf("?")+1);
  href = '/p-ajax'+siteStyle+newHref+'?container='+target; // Pass container as GET-par...
  if (QueryString) href = href+QueryString;
  $('#'+target).load(href,{},function(responseText, textStatus){
    // $('#'+target).animate({opacity:1},'fast')        // Stupid IE7 antialiases text to black, with this statement
    if (textStatus=='success') {
      // If we have an outer scrollbar, resize the target div.
      processLinks(target);
      if (target=='content') resizeDivs(innerScrollbar,target);
      scrollDivs($('#'+target));

      // Assign (optional) jQuery to elements in the content-area...
      if (target=='content') {
        if (typeof($('a.icon_tip').tooltip) == 'function') { // Set tooltips...
          // Flush any onMouse[Over|Out] that may exist for older code that uses show_note()...
          $('a.icon_tip').attr('onMouseOver','');
          $('a.icon_tip').attr('onMouseOut','');
          $('a.icon_tip').tooltip({
            track: true,
            delay: 0,
            showURL: false,
            fade: 300
          });
        }
        if (typeof($('a.zoom_img').fancybox) == 'function') { // Set zoom for images...
          $('a.zoom_img').fancybox({
            zoomSpeedIn: 400,
            zoomSpeedOut: 400,
            zoomOpacity: true,
            centerOnScroll: true,
            hideOnContentClick: true,
            overlayShow: true
          });
        }
      }

      formChanged = false; // Newly loaded page, formChanged may be false again
    }

    top.scroll(0,0); // Start at top with new page...
    $('#'+target+'_fade').stop().fadeOut('fast', function() {
      $(this).remove();
    });
  });
}

function loadHTML(html,target) {
  $('#'+target+'_fade').remove(); // Remove any previous incarnations of the 'shield'
  $('#'+target).after('<div id="'+target+'_fade" class="fade">');
  var offset = $('#'+target).offset();
  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:   offset.left+marginleft+borderleft+'px',
    top:    offset.top+margintop+bordertop+'px',
    width:  $('#'+target).innerWidth(),
    height: $('#'+target).innerHeight(),
    backgroundColor: backgroundColor
  }).fadeIn('fast');
  if(!innerScrollbar)
    $('.doResize').css('height','auto');
  else
    $('#'+target).css('height','auto');
  $('#'+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...
  $('#'+target+'_fade').stop().fadeOut('fast', function() {
    $(this).remove();
  });
}
