var xmlhttp = false;
try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
		xmlhttp = false;
	}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	xmlhttp = new XMLHttpRequest();
}


var ie=document.all;
var ns6=document.getElementById&&!document.all;
var nodeOpen = false;
var iframe = "";


function ietruebody(){
    return (document.compatMode && document.compatMode!="BackCompat" && !window.opera)? document.documentElement : document.body;
}

function showPopup(id, e, bgcol, bordercol, width) {
  if (nodeOpen === true) {
    closeNode();
  }  

  var popupcloser = document.getElementById? document.getElementById("popupCloser") : document.all.popup;
  popupcloser.style.backgroundColor = ((bordercol == undefined) || (bordercol == "")) ? popupcloser.style.backgroundColor : bordercol;

  var node = document.getElementById? document.getElementById("popup") : document.all.popup;
  var nodeWidth = ((width == undefined) || (width == "")) ? 200 : width;
  var horzpos=ns6? pageXOffset+e.clientX : ietruebody().scrollLeft+e.clientX;
  var vertpos=ns6? pageYOffset+e.clientY : ietruebody().scrollTop+e.clientY;
  var nodeContents = document.getElementById? document.getElementById("popupContents") : document.all.popupContents;

  node.style.position = 'absolute';
  node.style.left = (horzpos-nodeWidth)+"px";
  node.style.backgroundColor = ((bgcol == undefined) || (bgcol == "")) ? '#ffffe1' : bgcol; 	 
  node.style.width = nodeWidth;
  node.style.border = '1px solid black';
  node.style.title = 'Klik om te sluiten';
  node.style.fontSize = '11px';

  nodeContents.innerHTML = document.getElementById(id).innerHTML;
  node.style.display = 'block';

  var topoffset = 0;
  if ((e.clientY + node.offsetHeight) > ietruebody().clientHeight)
    topoffset = 0 - node.offsetHeight;
  
  node.style.top  = (vertpos + topoffset)+"px";
  
  if (nodeOpen === false)
  {
    var popupiframe = document.getElementById? document.getElementById("popupiframe") : document.all.popupiframe;
    popupiframe.innerHTML = '<iframe name="blockSelect" id="blockSelect" src="javascript: false;" style="display: none; position: absolute;z-index: 4;" scrolling="no" frameborder="0"></iframe>';

    var blockSelect = document.getElementById? document.getElementById("blockSelect") : document.all.blockSelect;
    blockSelect.style.width     = nodeWidth+(typeof('ie') != 'undefined' && ie ? 0 : 2);
    blockSelect.style.height    = node.clientHeight+2;
    blockSelect.style.left      = (horzpos-nodeWidth)+"px";
    blockSelect.style.top       = (vertpos + topoffset)+"px";
    blockSelect.style.backgroundColor = '#ffffe1';
    blockSelect.style.display   = 'block';
    
    popupiframe.style.display   = 'block';
  }
  nodeOpen = true;
  return true;
}

function closeNode() {
  if (nodeOpen === true)
  {
    var node = document.getElementById? document.getElementById("popup") : document.all.popup;
    node.style.display = 'none';
    var popupiframe = document.getElementById? document.getElementById("popupiframe") : document.all.popupiframe;
    popupiframe.innerHTML = '';
    popupiframe.style.display = 'none';
    nodeOpen = false;
  }
}

function DetectBrowser()
{
	var a=navigator.userAgent.toLowerCase();
	this.isOpera=(a.indexOf("opera")!=-1);
	this.isKonq=(a.indexOf('konqueror')!=-1);
	this.isSafari=(a.indexOf('safari')!=-1)&&(a.indexOf('mac')!=-1);
	this.isKhtml=this.isSafari || this.isKonq || (a.indexOf('khtml')!=-1);
	this.isFF=(a.indexOf('firefox')!=-1);
  this.isFF2=(a.indexOf('firefox/2')!=-1);
  this.isFF3=(a.indexOf('firefox/3')!=-1);
	this.isIE=(a.indexOf("msie")!=-1)&&!this.isOpera;
	this.isWinIE=this.isIE&&(a.indexOf("win")!=-1);
	this.isWinIE7=this.isWinIE && (a.indexOf("msie 7")!=-1);
	this.isWinIEVista=this.isWinIE && (a.indexOf("windows nt 6")!=-1);
	this.isCSS1Compat=(!this.isIE)||(document.compatMode&&document.compatMode=="CSS1Compat");
	this.isChrome=(a.indexOf("chrome")!=-1);
}

var browserDetect = new DetectBrowser();

function isEmail(string) {
	var regexpEmail = /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/;
	return regexpEmail.test(string);
}

var colorCount = 1;

function addRowToTable() {
	// aantal rijen om toe te voegen
	var numRows = 1;
	var tbl = document.getElementById('contactsTable');
	var contactName = document.getElementById('cname').value;		
	var emailCell = document.getElementById('cemail').value;		
	

	// rijen toevoegen
	for (var i = 1; i <= numRows; i++) {

		var lastRow = tbl.rows.length;
		var iteration = lastRow+1;
		var bgColor = (colorCount % 2) ? '#EEEEEE' : '#DDDDDD';
		colorCount++;
				
		var row = tbl.insertRow(0);

		row.bgColor = bgColor;
		
	
		// checkbox toevoegen
		var cellLeft = row.insertCell(0);
		var checkbox = document.createElement('input');
		/**
		* Internet explorer heeft het moeilijk met het toekennen van
		* parameters aan JS-generated elementen.
		* zie: http://blueshadow.no-ip.com/sites/other/ee/dyncheck.html
		*/
		checkbox.setAttribute('type', 'checkbox');
		checkbox.setAttribute('name', 'friends['+iteration+']');
		checkbox.setAttribute('id', 'friends['+iteration+']');
		checkbox.setAttribute('checked', 'true');
		
		checkbox.setAttribute('value', contactName+'|'+emailCell);
		
		cellLeft.appendChild(checkbox);
		checkbox.checked = true;
		cellLeft.style.width = 22;
		
		var contactCell = row.insertCell(1);
		
		var table = document.createElement('table');
		table.cellSpacing = "0";
		table.cellPadding = "0";
		
		contactCell.appendChild(table);
		
		var tableLastRow = table.rows.length;
		var tableIteration = tableLastRow+1;
		var tableRow = table.insertRow(tableLastRow);

		// naam	
		var nameCell = tableRow.insertCell(0);
		nameCell.style.width = 250;
		var nameNode = document.createTextNode(contactName);
		nameCell.appendChild(nameNode);
		nameCell.style.fontSize = "10px";
		// email
		var cellRight = tableRow.insertCell(1);
		cellRight.style.width = 250;
		var emailNode = document.createTextNode(emailCell);
		cellRight.appendChild(emailNode);
		cellRight.style.fontSize = "10px";		
		cellRight.style.fontWeight = "bold";
	}
}

function in_array(needle, haystack) {
	var n = haystack.length;
	for (var i=0; i<n; i++) {
		if (haystack[i]==needle) {
			return i;
		}
	}
	return false;
}

function htmlspecialchars(string) {
   string = string.replace(/&/g,"&amp;");
   string = string.replace(/\"/g,"&quot;");
   string = string.replace(/\'/g,"&#039;");
   string = string.replace(/</g,"&lt;");
   string = string.replace(/>/g,"&gt;");
   return string;
}

function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   return temp;
}

function makeAjaxContentSafe(str)
{
  str = str.replace(/\%/gi, "%25"); //%
  str = str.replace(/&/gi, "%26"); //&
  str = str.replace(/\+/gi, "%2B"); //+
  return str;
}

function request(url, querystring, callBack, caching) {
	if (xmlhttp) {
		if (!caching) {
			querystring += '&' + (new Date()).getTime();						
		}
		xmlhttp.open("GET", url+querystring, true);
		if (callBack) {xmlhttp.onreadystatechange = function() {callBack(xmlhttp);}}				
 		xmlhttp.send(null);
	}
}

var noContacts = false;
function addContact(method) {
	var cname = htmlspecialchars(trim(document.getElementById('cname').value));		
	var cemail = htmlspecialchars(trim(document.getElementById('cemail').value));	
	var tbl = document.getElementById('contactsTable');
	var tblLength = tbl.rows.length;
	var emails = [];
	
	if (document.getElementById('noContacts')) {
		noContacts = true;
	}
	
	switch (method) {
		
		// share
		case '1':
		var method = 1;
		break;
		
		// ecard
		case '2':
		var method= 2;
		break;
		
		case '4':
		var method = 4;
		break;
		
		default:
		var method = 0;
	}
			
		
	
	if (noContacts === false) {
		for (var iteration  = 1; iteration <= tblLength; iteration++) {
			el = document.getElementById('friends['+iteration+']');
			info = el.value.split('|');
			emails[iteration] = info[1];
		}
	}
	
	
	if ((cname != '') && (cemail != '') && isEmail(cemail)) {
		if (noContacts === false) {
			if (in_array(cemail, emails)) {
				alert('Dit email-adres staat reeds in de lijst met contactpersonen!');
				return false;
			}
		}
			
		if (xmlhttp) {
			if (xmlhttp.readyState >= 1 && xmlhttp.readyState <= 3) {
				xmlhttp.abort();
			}
			
			xmlhttp.open("GET", "/index.php?m=fto&a=51&cname="+cname+"&cemail="+cemail+"&method="+method, true);
			xmlhttp.onreadystatechange = function () {
				if(xmlhttp.readyState == 4){
					if (noContacts === true) {
						el = document.getElementById('noContacts');
						el.parentNode.removeChild(el); 
						noContacts = false;
					}
					addRowToTable();
				}
			}
			xmlhttp.send(null);
		}
		
	} else {
		alert('U heeft geen geldige naam en/of emailadres ingevuld!');
		return false;
	}
}

function windowPopup(url,name,config)
{
  var isTrue = function(value) {
    if (value == true || value == 1 || ( typeof value == 'string' && value.toLowerCase() == 'yes' ) )
      return 'yes';
    return 'no';
  }
  
  var configArray= {'toolbar':'no',
                    'location':'no',
                    'directories':'no',
                    'status':'no',
                    'menubar':'no',
                    'personalbar':'no',
                    'resizable':'no',
                    'scrollbars':'no',
                    'copyhistory':'no',
                    'titlebar':'no',
                    'dialog':'yes',
                    'modal':'yes',
                    'alwaysRaised':'yes',
                    'minimizable':'no',
                    'dependent':'yes'
                   };

  for (var option in config)
    if (configArray[option] != undefined)
      configArray[option] = isTrue(config[option]);

  configArray['width']  = (config.width  != undefined) ?  config.width  : '350';
  configArray['height'] = (config.height != undefined) ?  config.height : '350';

  if  ( (config.left == undefined) && (config.top == undefined) )  {
    var align  = (config.align  != undefined) ?  config.align.toLowerCase()   : 'center';
    var valign = (config.valign != undefined) ?  config.valign.toLowerCase()  : 'middle';
    
    //browser position{belangrijk bij dubbele schermen of niet gemaximaliseerde browsers}}
    try {
      var browserLeft = (typeof(window.screenX) != 'undefined') ? window.screenX  : window.screenLeft;
      var browserTop  = (typeof(window.screenY) != 'undefined') ? window.screenY  : window.screenTop;
    } catch(e) {
      var browserLeft = 0;
      var browserTop = 0;
    }
    
    switch(align)
    {
      case 'left':
        var windowLeft = browserLeft;
      break;
      case 'right':
        var windowLeft =  browserLeft+document.body.clientWidth-configArray['width'];
      break;
      case 'center':
      default:
        var windowLeft = browserLeft+((document.body.clientWidth-configArray['width'])/2);
    }
    
    switch(valign)
    {
      case 'top':
        var windowTop = browserTop;
      break;
      case 'bottom':
        var windowTop =  browserTop+document.body.clientHeight-configArray['height'];
      break;
      case 'center':
      case 'middle':
      default:
        var windowTop = browserTop+((document.body.clientHeight-configArray['height'])/2);
    }
    configArray['left'] = Math.round(windowLeft);
    configArray['top'] = Math.round(windowTop);
  }
  var configOut =  new Array();
  for (var option in configArray)
    configOut.push(option+'='+configArray[option]);


  return window.open(url, name, configOut.join(','));
}

function addInputPreview(elem, text, submitbutton)
{
  elem.setAttribute('previewText', text);
  elem.value = text;
  elem.style.color = "#999999";
  
  addEvent(elem, 'focus', function ()
  {
    var text = elem.getAttribute('previewText');
    if(elem.value == text)
    {
      elem.value = "";
      elem.style.color = "#000000";
    }
  });
  
  addEvent(elem, 'blur', function ()
  {
    var text = elem.getAttribute('previewText');
    if(elem.value == "")
    {
      elem.value = text;
      elem.style.color = "#999999";
    }
  });
  
  if(submitbutton)
  {
    addEvent(submitbutton, 'click', function ()
    {
      var text = elem.getAttribute('previewText');
      if(elem.value == text)
      {
        elem.value = "";
        elem.style.color = "#000000";
      }
    });
  }
}

function addEvent(elem, evt, func)
{
  if (elem.addEventListener)
    elem.addEventListener (evt, func, false);
  else if (elem.attachEvent)
    elem.attachEvent ("on" + evt, func);
}