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


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.
  
  if(!$.browser.msie || $.browser.version > 6) // Seems to fail with IE6? fired twice, loosing any GET parms!
    $.history.init(loadHash);
  processLinks('content');
  processLinks('column_left');
  processLinks('column_right');
}

var pages = [];
function fillPagesArray(separator, listStyle, ref, sessId) {
  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: '/i-'+sessId+'/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) {
  offset = $('#content').offset();
  headerHeight = offset.top;
  if($('.footer').height)
    footerHeight = $('.footer').height();
  else
    footerHeight = 0;
  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 {
    $('.doResize').css('overflow','visible');
    // Find the maximum height of the relevant columns
    var contentHeight=0;
    if(target)
      contentHeight = $('#'+target).height();
    else {
      $('.doResize').each(function (intIndex) {
        if($(this).height() > contentHeight)
          contentHeight = $(this).height();
      });
    }
    if(winHeight>contentHeight)
      contentHeight=winHeight;
    $('.center').height(contentHeight+headerHeight+footerHeight+2); // Previously subtracted
    $('.doResize').css('height',contentHeight);
    $('.doResize').css('overflow','hidden');
  }
  var left=parseInt(($(window).width()-$('.center').width())/2);
  if(left<0) left=0;
  $('.center').css('margin-left',left+'px');

}

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+" ";
  $(sel+"a[target='content']").not("a[rel=lightbox]").click( function(event) {
    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").not("a[target]").not("a[rel=lightbox]").click( function(event) {
    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 (ajax post)
  $("form").not(".noAjax").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) {
  $('#menu li').removeClass('selected');
  $('#menu li').removeClass('parent');
  id = $('#menu a[href='+sel+']').parent().attr('id');
  if (id) {
    $('#'+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)
  newHref = newHref.replace(/\/i\-[^\/]*/,'');         // Remove any session (we'll add it later)
  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) {
    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;
          }
      });
    }
  }
}

// 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();
  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');
  // Perform an ajax call
  if(!innerScrollbar)
    $('.doResize').css('height','auto');
  else
    $('#'+target).css('height','auto');
  if (newHref.indexOf("?") > -1 ) var QueryString = '&'+newHref.substr(newHref.indexOf( "?")+1);
  href = '/p-ajax'+siteStyle+newHref+'?container='+target; // Pass container as GET-par...
  if (QueryString) href = href+QueryString;
  // Add a session, if any available
  if(sessId)
    href = '/i-'+sessId+href;
  $('#'+target).load(href,{},function(responseText, textStatus){
    //    $('#'+target).animate({opacity:1},'fast')        // Stupid IE7 antialiases text to black, with this statement
    $('#'+target+'_fade').stop().fadeOut('fast', function() {
      $(this).remove();
    });
    if (textStatus=='success') {
      // If we have an outer scrollbar, resize the target div.
      processLinks(target);
      // Set tooltips, if used...
      if(typeof($('.goto_pagetop a').tooltip) == 'function') {
        $('.goto_pagetop a').tooltip({
          track: true,
          delay: 0,
          showURL: false,
          fade: 300
        });
      }
      resizeDivs(innerScrollbar,target);
      // Newly loaded page, formChanged may be false again
      formChanged=false;
    }
  });
}

function loadHTML(html,target) {
  $('#'+target+'_fade').remove(); // Remove any previous incarnations of the 'shield'
  $('#'+target).after('<div id="'+target+'_fade">');
  var offset = $('#'+target).offset();
  // 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+4+'px',
    top:    offset.top+4+'px',
    width:  $('#'+target).outerWidth()-8,
    height: $('#'+target).outerHeight()-8,
    backgroundColor: backgroundColor
  }).fadeIn('fast');
  if(!innerScrollbar)
    $('.doResize').css('height','auto');
  else
    $('#'+target).css('height','auto');
  $('#'+target).html(html);
  resizeDivs(innerScrollbar,target);
  processLinks(target);

  // Newly loaded page, formChanged may be false again
  formChanged=false;
  $('#'+target+'_fade').stop().fadeOut('fast', function() {
    $(this).remove();
  });
}
