// This file contains global functions used all over the website


/**
 * Function for showing footerNotice at footerbar
 */
function showContributions(e) {

 // store event for later purposes
 marnixkerk.event = new xEvent(e);
 
 // set content
 var content = document.createElement('div');
 content.style.fontSize = 0.8 + 'em';
 
 var today = new Date();
 var startHosting = new Date();
 startHosting.setTime(1104447600000); // 2004-12-31
 var hostingTime = Math.round((today.getTime() - startHosting.getTime()) / (1000 * 60 * 60 * 24));
 content.innerHTML = 	"<span style = 'color: " + marnixkerk.COLORS.GRASS_GREEN + "; font-weight: bold; font-size: 1em;'>Thanks for: </span><br /><hr />" +
 			"- <b>" + hostingTime + " days of generously free hosting</b><br /><a href = 'http://www.dekkerautomatisering.nl' target='_blank'>Dekker Automatisering</a><br /><br />" +
			"- <b>free use of excellent libraries</b><br /><a href = 'http://www.cross-browser.com' target='_blank'>Michael Foster's X Library</a><br /><br />" +
 			"- <b>a JavaScript implementation of the RSA Data Security</b><br /><a href = 'http://pajhome.org.uk/crypt/md5' target='_blank'>Paul Johnston's MD5 for JS</a><br /><br />";
 
 showfooterNotice(content);
}

/**
 * Request visitors information
 */
function requestVisitorsInfo(e) {
 
 // store event for later purposes
 marnixkerk.event = new xEvent(e);
 
 // set request
 var request = new Request("getDefaultVisitorsInfo");
 request.setCallBack(showVisitorsInfo);
 marnixkerk.POSTMAN.postData(request);
}

/**
 * Show visitors information
 */
function showVisitorsInfo(response) {
 var content = document.createElement('div');
 var totalHits = response.getBodyItems()['totalHits'];
 var averageHits = response.getBodyItems()['averageHitsPerDay'];
 var todaysHits = response.getBodyItems()['todaysHits'];
 var yesterdaysHits = response.getBodyItems()['yesterdaysHits'];
 var dateDump = response.getBodyItems()['startDate'].split('-');
 var lifeTime = (new Date().getTime() - new Date(dateDump[0],dateDump[1] - 1,dateDump[2])) / (1000 * 60 * 60 * 24);
 
 var numberOfYears = parseInt(lifeTime / 365.25);
 var numberOfMonths = parseInt((lifeTime % 365.25) / 30.5);
 var months = (numberOfMonths == 1) ? 'maand' : 'maanden';
 var plural = (todaysHits == 0) ? "bezoeker" : "bezoekers";
 var plural2 = (todaysHits == 0) ? "bezoeker" : "bezoekers"; 
 
 content.innerHTML = 	"Vandaag <strong>" + todaysHits + "</strong> " + plural + ". Gisteren <strong>" + yesterdaysHits + "</strong> " + plural2 + ".<br /><hr />" +
 			"Gemiddeld <strong>" + averageHits + "</strong> bezoekers per dag.<br /><hr />" +
 			"Totaal <strong>" + totalHits + "</strong> binnen <strong>" + numberOfYears + "</strong> jaar";
 			
 			if(numberOfMonths > 0) {
 content.innerHTML += 	 " en <b>" + numberOfMonths + "</b> " + months + ".";
 			} else {
  content.innerHTML += 	 ".";			
 			}
 
 showfooterNotice(content);
}

/**
 * Show large image
 */
function showLargeImage() {
 var location = marnixkerk.URL + '/Images/getPicture.php?id=' + this.id.substring(5);
 imageEnlarger.load(location);
}

/**
 * Show large newsletter in pdf-format
 */
function showNewsletter() {
 var location = marnixkerk.URL + '/nieuwsbrieven/' + this.id + '.pdf';
 imageEnlarger.load(location);
}

/**
 * This function searches for images (div class="image") and makes them clickable. 
 * This function also handles newsupdates from missionair people
 * On click it requests an larger image from the database and presents it in a new window
 */
function handleImages() {

 var images = xGetElementsByTagName('img');
 for (var i=0;i<images.length;i++) {

  if (images[i].className == 'clickableImage') {

   // set function
   images[i].onclick = showLargeImage;
  } else if (images[i].className == 'newsletterImage') {
   
   // set function
   images[i].onclick = showNewsletter;
  }
 }
}

/**
 * Show error
 * @param error string
 */
function showError(errorString) {
 var div = document.createElement('div');
 div.innerHTML = errorString;
 div.style.color = 'red';
 showfooterNotice(div);
}

/**
 * Show footerNotice
 * @param content a domnode with content
 */
function showfooterNotice(content) {

 // close footerNotice first
 if (marnixkerk.FOOTERNOTICE_OPENED) {
  removefooterNotice();
 }
  
 if (! marnixkerk.FOOTERNOTICE_OPENED) {
 
  // set on target animation function
  var ot = function() {
   var fNs = xGetElementById('footerNoticeBody').style;
   var height = xHeight(xGetElementById('footerNotice')) - xHeight(xGetElementById('footerNoticeHeader'));
   fNs.height = height + 'px';
   fNs.overflow = 'auto';
  }
  
  var footerNotice = xGetElementById('footerNotice');
  
  // append content
  var footerNoticeBody = xGetElementById('footerNoticeBody');
  footerNoticeBody.appendChild(content);
 
  // set proper left-position
  var mx = (marnixkerk.event) ? marnixkerk.event.pageX : marnixkerk.WIDTH + 4;
  var contentLeft = xLeft('wContainer');
  var footerNoticeWidth = marnixkerk.FOOTERNOTICE_WIDTH + 2;
  var hl = footerNoticeWidth / 2;
  var left = mx - contentLeft - hl;
  if (left < contentLeft) {
   left = contentLeft + 2;
  }
  var maxPageWidth = contentLeft + marnixkerk.WIDTH;
  var outerfooterNoticeRight = left + footerNoticeWidth;
  if ((left + footerNoticeWidth) > (contentLeft + marnixkerk.WIDTH)) {
   left = contentLeft + marnixkerk.WIDTH - footerNoticeWidth - 4;
  }
  xLeft(footerNotice,left);
 
  var ele = 'footerNotice';
  marnixkerk.ANIMATION.explode(footerNotice,marnixkerk.FOOTERNOTICE_HEIGHT,marnixkerk.FOOTERNOTICE_RUN_TIME,marnixkerk.FOOTERNOTICE_ACCELERATION_TYPE,ot);
  marnixkerk.FOOTERNOTICE_OPENED = true;
 }
}

/**
 * Remove footerNotice
 * @param content a domnode with content
 */
function removefooterNotice() {
 var footerNotice = xGetElementById('footerNotice');
 var footerNoticeBody = xGetElementById('footerNoticeBody');
 footerNotice.removeChild(footerNoticeBody);
 footerNoticeBody = document.createElement('div');
 footerNoticeBody.id = 'footerNoticeBody';
 footerNotice.appendChild(footerNoticeBody);
 var tts = footerNotice.style;
 tts.height = 0;
 tts.top = marnixkerk.FOOTERNOTICE_TOP + 'px';
 marnixkerk.FOOTERNOTICE_OPENED = false;
}

/**
 * Function for showing footerNotice at footerbar
 * @param node an dom node
 * @param onclick function when clicked at given node
 * @param underline true for underline decoration
 */
function setHyperlink(node,onclick,underscore) {
 if (underscore) {
  node.style.textDecoration = 'underline';
 }
 node.onmouseover = nodeOnMouseOver;
 node.onmouseout = nodeOnMouseOut;
 node.onclick = onclick;
}

/**
 * Default onmouseover
 */
function nodeOnMouseOver(event) {
 var color = (this.onmouseovercolor) ? this.onmouseovercolor : marnixkerk.COLORS.RED;
 this.style.color = color;
 this.style.cursor = "pointer";
}

/**
 * Default onmouseout
 */
function nodeOnMouseOut(event) {
 var color = (this.onmouseoutcolor) ? this.onmouseoutcolor : 'black';
 this.style.color = color;
 this.style.cursor = "pointer";
}

/**
 * On navigationbar button mouse over
 */
function navBarMouseOver(event) {
 if (! this.selected) {
  this.style.color = this.onmouseovercolor;
  this.style.cursor = "pointer";
 }
}

/**
 * On navigationbar button mouse out
 */
function navBarMouseOut(event) {
 if (this.selected) {
  this.style.color = this.activebuttoncolor;
 } else { 
  this.style.color = this.onmouseoutcolor;
 }
 this.style.cursor = "default";
}

/**
 * On navigationbar button click
 */
function navBarMouseClick(event) {
 if (! this.selected) {

  // set proper button selected
  restoreButtons(this.id);
 
  // handle buttonclick
  handleButtonClick(this.id);
 }
}

/**
 * On navigationbar cms-button click
 */
function navBarCMSClick(event) {
 if (! this.selected) {
 
  // set proper button selected
  restoreButtons(this.id);
 
  // load page
  marnixkerk.CMSloader.loadPage(this.id);
 }
}

/**
 * Restore buttons
 * This function is called when a button is pressed
 */
function restoreButtons(buttonID) {

 // retrieve buttons, both management-buttons and navigation-buttons
 var tagName = 'span';
 var parent = xGetElementById('navBar');
 var navButtons = xGetElementsByTagName(tagName,parent);
 
 parent = xGetElementById('mngButtonsBar');
 var mngButtons = xGetElementsByTagName(tagName,parent);
 
 var buttons = an_concatArray(navButtons,mngButtons);
 var curButton = xGetElementById(buttonID);
 
 // restore the current selected button except when login- and sermonsbutton is pressed
 for (var i=0;i<buttons.length;i++) {
  if (buttonID != 'login68') {
   if (buttons[i].selected) {
    buttons[i].selected = false;
    buttons[i].style.color = buttons[i].onmouseoutcolor;
    buttons[i].style.fontWeight = 'normal';
   }
  }
 }
 
 // set current button selected
 if (buttonID != 'login68' && curButton) {
  curButton.selected = true;
  curButton.style.color = curButton.onclickcolor;
 }
}

/**
 * Handle the button click i.e. load page
 */
function handleButtonClick(buttonID) {

 // load needed scripts first
 var type = 'script';
 for (var i=0;i<marnixkerk.SCRIPT[buttonID].length;i++) {
  marnixkerk.LOADER.setUrl(marnixkerk.SCRIPT[buttonID][i],type,marnixkerk.VERIFY_ID[buttonID][i]);
 }
 
 // load needed styles
 type = 'link';
 for (var j=0;j<marnixkerk.STYLE[buttonID].length;j++) {
  marnixkerk.LOADER.setUrl(marnixkerk.STYLE[buttonID][j],type,false);
 }
 
 marnixkerk.LOADER.setOnload(marnixkerk.BUTTON_EVENT[buttonID]);
 marnixkerk.LOADER.loadList();
}

/**
 * Change loadingimage
 */
function setLoadingImageOnload(bool) {
 var loadingImage = xGetElementById("loadingImage");
 if(bool) {
  loadingImage.src = marnixkerk.IMAGE_LOADING;
 } else {
  loadingImage.src = marnixkerk.IMAGE_IDLE;
 }
}

/**
 * Change loadingimage
 */
function handleSessionError(msg) {
 setSessionID(false);
 
 // remove dialog if active
 if (marnixkerk.dialog) {
  marnixkerk.dialog.remove();
  marnixkerk.dialog = false;
 }
 var content = document.createTextNode("You have been logged out due to the following reason: " + msg);
 showfooterNotice(content);
}

/**
 * Set session id
 * @param valid session id or false
 */
function setSessionID(sessionID) {
 
 // assign sessionid - value
 marnixkerk.sessionID = sessionID;
 
 if (! sessionID) {
 
  // set the loginbutton
  var button= xGetElementById('login68');
  button.innerHTML = "login";
  button.onclick = requestLogin;
  
  // set the managementbar
  setMngBarVisible(false);
  activateHomepage();
 } else {
 
  // set the loginbutton
  var button= xGetElementById('login68');
  button.innerHTML = "logout";
  button.onclick = logout;
  
  // set the managementbar
  setMngBarVisible(true);
 }
 
 // set button to logout
}

/**
 * load homepage
 */
function activateHomepage() {
 
 // restore homepage
 restoreButtons('homepage24');
 handleButtonClick('homepage24');
 var homebutton = xGetElementById('homepage24');
 homebutton.style.color = homebutton.onclickcolor;
 homebutton.selected = true;
}

/**
 * Load new content in body
 * @param newContent must be a dom-node (JS)
 */
function loadContent(newContent) {

 // close popup when open
 marnixkerk.homepage.removePopup();
 
 // set new content
 var contentSpace = xGetElementById('wContentSpace');
 removeContent(contentSpace);
 contentSpace.appendChild(newContent);
 handleImages();
}

/**
 * function to align a content by using a table
 * Each array given will be a column or row
 * @param mode true: each array will be a column, false: each array will be a row
 * @param array1, array2, array3, etc. - the values must be dom-nodes!
 */
function alignContentByTable(mode) {
 var table = document.createElement('table');
 var bod = document.createElement('tbody');
 table.appendChild(bod);
 
 var al = arguments.length;
 var arl = arguments[1].length;
 var t = (mode) ? al : arl;
 var u = (mode) ? arl : al;
 var s1 = (mode) ? 0 : 1;
 var s2 = (mode) ? 1 : 0;
 
 if (al>1) {
  for (var i=s1;i<u;i++) {
   var tr = document.createElement('tr');
   for (var ii=s2;ii<t;ii++) {
    td = document.createElement('td');
    var child = (mode) ? arguments[ii][i] : arguments[i][ii];
    td.appendChild(child);
    tr.appendChild(td);
   }
   bod.appendChild(tr);
  }
 }
 return table;
}

/**
 * Remove content from given dom-element
 * @param ele domnode where all content must be removed
 */
function removeContent(ele) {
  while (ele.hasChildNodes()) {
   ele.removeChild(ele.firstChild);
  }
  ele.innerHTML = "";
}

/**
 * Function foo
 * Sometimes needed though
 */
function foo() {
 // foo
}


// -- Objects

/**
 * Set the new Window object
 */
var imageEnlarger = new xWindow(
  'imageEnlarger',      // target name
  750, 550,  		// size: width, height
  200, 200, 		// position: left, top
  0,                    // location field
  0,                    // menubar
  1,                    // resizable
  1,                    // scrollbars
  0,                    // statusbar
  0);                   // toolbar

/**
 * The headline shower object
 */
var CMSloader = function(obj_ref) {
 this.obj_ref = obj_ref;
 this.view = document.createElement('table');
 this.buttonSpace = document.createElement('div');
 this.contentSpace = document.createElement('div');
 
 this.currentSubpageID = false;
 this.tab = false;
 
 this.init();
};
CMSloader.prototype = {
 /**
  * initiate this
  */
 init : function() {
  
  // set layout
  var tbod = document.createElement('tbody');
  this.view.className = 'cms_layout_table';
  this.view.appendChild(tbod);
  
  var tr = document.createElement('tr');
  tbod.appendChild(tr);
  
  var td1 = document.createElement('td');
  td1.className = 'cms_left_cell';
  var td2 = document.createElement('td');
  tr.appendChild(td1);
  tr.appendChild(td2);
  
  this.buttonSpace.className = 'cms_buttonSpace';
  td1.appendChild(this.buttonSpace);
  this.contentSpace.className = 'cms_contentSpace';
  td2.appendChild(this.contentSpace);
 },
 /**
  * Load page
  * @param pageID the id of the (root) page
  */
 loadPage : function(pageID) {
 
  // remove content first
  removeContent(this.buttonSpace);
  removeContent(this.contentSpace);

  // load new content
  loadContent(this.view);
  
  if (typeof(marnixkerk.subpages[pageID]) == 'undefined') {
   
   this.currentPageID = pageID;
   
   // load subpages first
   var request = new Request('getPages',this.obj_ref);
   request.addParam('pageID',pageID);
   request.addParam('pageType','subPage');
   request.setCallBack(this.loadSubpages);
   marnixkerk.POSTMAN.postData(request);
  } else {
   this.setSubpages(pageID);
  }
 },
 /**
  * Load sub pages
  */
 loadSubpages : function(response) {
  var obj = eval(response.getHeaderItems()['obj_ref']);
  var bodyItems = response.getBodyItemsNum();
  var pageID = response.getBodyItems()['pageID'];
  marnixkerk.subpages[pageID] = [];
  for (var i=0;i<bodyItems.length;i++) {
   if (typeof(bodyItems[i].id) != 'undefined') {
    marnixkerk.subpages[pageID][i] = bodyItems[i];
   }
  }
  
  // set the subpages
  obj.setSubpages(pageID);
 },
 /**
  * set sub pages
  * @param pageID the id of the page
  */
 setSubpages : function(pageID) {
  
  // add new buttons
  var subpages = (typeof(marnixkerk.subpages[pageID]) == 'undefined') ? false : marnixkerk.subpages[pageID];
  if (subpages) {
   for (var i=0;i<subpages.length;i++) {
    var pageButton = document.createElement('div');
    pageButton.className = 'cms_pageButton';
    pageButton.type = 'cms_pageButton';
    pageButton.p = this.obj_ref;
    pageButton.id = subpages[i].id;
    pageButton.onclick = this.loadTabs;
    pageButton.innerHTML = '<br />' + subpages[i].name;
    this.buttonSpace.appendChild(pageButton);
   }
  }
  
  // adjust size
  var cs = this.contentSpace.style;
  cs.width = marnixkerk.WIDTH - 230 + 'px';
  
  var image = new Image(576,360);
  image.src = marnixkerk.URL + '/Images/getPicture.php?id=55';
  xOpacity(image,0.2);
  this.contentSpace.appendChild(image);
 },
 /**
  * Load tab pages
  * @param id the subpageID of the subpage
  * @param obj_ref the ref of the object
  */
 loadTabs : function(event,p_subpageID,p_obj_ref) {
  
  // make this function accessable from multiple sources
  var subpageID = (p_subpageID) ? p_subpageID : this.id;
  var obj_ref = (p_obj_ref) ? p_obj_ref : this.p;
  
  marnixkerk.CMSloader.currentSubpageID = subpageID;
  var obj = eval(obj_ref);
  var buttons = xGetElementsByTagName('div');

  // reset buttons
  for (var i=0;i<buttons.length;i++) {
   if (buttons[i].type == 'cms_pageButton') {
    if (buttons[i].id == subpageID) {
     buttons[i].className = 'cms_activePageButton';
    } else {
     buttons[i].className = 'cms_pageButton';
    }
   }
  }
  
  // load tabs
  if (typeof(marnixkerk.tabpages[subpageID]) == 'undefined') {

   // load tabpages first
   var request = new Request('getPages',this.p);
   request.addParam('pageID',subpageID);
   request.addParam('pageType','tabPage');
   request.setCallBack(obj.loadTabpages);
   marnixkerk.POSTMAN.postData(request);
  } else {
   obj.setTabpages(subpageID);
  }
 },
 /**
  * Load tab pages
  */
 loadTabpages : function(response) {
  var obj = eval(response.getHeaderItems()['obj_ref']);
  var pageID = response.getBodyItems()['pageID'];
  var bodyItems = response.getBodyItemsNum();
  marnixkerk.tabpages[pageID] = [];
  for (var i=0;i<bodyItems.length;i++) {
   if (typeof(bodyItems[i].id) != 'undefined') {
    marnixkerk.tabpages[pageID][i] = bodyItems[i];
   }
  }

  // set the tabpages
  obj.setTabpages(pageID);
 },
 /**
  * set tab pages
  * @param pageID the id of the subpage
  */
 setTabpages : function(subpageID) {
 
  // remove old content
  removeContent(this.contentSpace);

  // add new tabs
  var tabpages = (marnixkerk.tabpages[subpageID].length == 0) ? false : marnixkerk.tabpages[subpageID];
  if (tabpages) {
  
   // set new tab
   this.tab = new an_TabbedPane();
   for (var i=0;i<tabpages.length;i++) {
   
    // add all articles for current page
    this.tab.setTab(tabpages[i].id,tabpages[i].name,'loading content...');
   }
   this.contentSpace.appendChild(this.tab.getView());
   
   // load tab data
   for (var i=0;i<tabpages.length;i++) {
    if (typeof(marnixkerk.articles[tabpages[i].id]) == 'undefined') {
     var request = new Request('getArticlesByPage',this.obj_ref);
     request.setCallBack(this.loadTabdata);
     request.addParam('tabIndex',i);
     request.addParam('pageID',tabpages[i].id);
     marnixkerk.POSTMAN.postData(request);
    } else {
     this.setTabdata(tabpages[i].id,i);
    }
   }
  } else {
   var p = document.createElement('p');
   p.className = 'cms_no_content';
   p.appendChild(document.createTextNode('Geen inhoud gevonden.'));
   this.contentSpace.appendChild(p);
  }
 },
 /**
  * Set data (articles)
  */
 loadTabdata : function(response) {
  var obj = eval(response.getHeaderItems()['obj_ref']);
  var pageID = response.getBodyItems()['pageID'];
  var tabIndex = response.getBodyItems()['tabIndex'];
  
  if (typeof(response.getBodyItems()['emptySet']) == 'undefined') {
   
   // extract the articles and the tabpageID
   var bodyItems = response.getBodyItemsNum();
   marnixkerk.articles[pageID] = [];
   for (var i=0;i<bodyItems.length;i++) {
    if (typeof(bodyItems[i].id) != 'undefined') {
     marnixkerk.articles[pageID][i] = bodyItems[i];
    }
   }
  }
  obj.setTabdata(pageID,tabIndex);
  if (tabIndex == 0) {
   handleImages();
  }
 },
 /**
  * Add data (articles to tabs)
  * @param tabID the id of the (tab) page
  * @param tabIndex the index of the current tab
  */
 setTabdata : function(tabID,tabIndex) {

  var container = document.createElement('div');
  
  // set space for management purposes
  var managementDiv = document.createElement('div');
  managementDiv.id = 'cms_managementDiv';
  container.appendChild(managementDiv);

  // add each article to the scene
  if (typeof(marnixkerk.articles[tabID]) != 'undefined') {
   var articles = marnixkerk.articles[tabID];
   for (var i=0;i<articles.length;i++) {
    var articleDiv = document.createElement('div');
    articleDiv.className = 'cms_articleDiv';
    var titleDiv = document.createElement('div');
    titleDiv.className = 'cms_titleDiv';
    var contentDiv = document.createElement('div');
    contentDiv.className = 'cms_contentDiv';
    
    titleDiv.innerHTML = (articles[i].title == 'emptySet') ? '' : articles[i].title;
    contentDiv.innerHTML = (articles[i].content == 'emptySet') ? '' : articles[i].content;
    articleDiv.id = 'article' + articles[i].id;
    articleDiv.type = 'cms_articleDiv';
   
    articleDiv.appendChild(titleDiv);
    articleDiv.appendChild(contentDiv);
   
    container.appendChild(articleDiv);
   }
  } else {
   
   // no content set
   var p = document.createElement('p');
   p.appendChild(document.createTextNode('Geen inhoud gevonden'));
   p.className = 'cms_no_content';
   container.appendChild(p);
  }
  var n = marnixkerk.tabpages[this.currentSubpageID][tabIndex].name;
  this.tab.addData(tabID,false,container);
  this.tab.setCallback(tabID, handleImages);
  
  // check for clickable images
  
       
  // set article management if logged in
  if (marnixkerk.sessionID) {
   this.tab.setCallback(tabID,setArticleManagement);
   setArticleManagement(tabID);
  }
 }
}
