/* Ipark. Content Management Framework - TDCLighthouse.com (info@tdclighthouse.com) Copyright (c) 2002-2003 */
/*  

Standard JS functions for Ipark admin system.

AUTHOR: Uipko Berghuis
EMAIL: uipko@tdclighthouse.com
DATE: 08/10/2003

EDITED: Sjoerd Zonneveld
DATE:   06-12-2004

*/


//////////////////////////////////////////////////////////////////////
//
// FRAME / WINDOW FUNCTIONS 
//
//////////////////////////////////////////////////////////////////////


// DES: checks if we r in a frame set, yes? reload framset with the given url
// PAR: url = The url to bust the frames for
function bustFrame(url) 
{
	
	/* test for solution modaldialog problem */
	/*if (typeof(window.dialogArguments) != 'undefined') {
		opener = window.dialogArguments;
		alert(self.name + ' :: ' + opener.name);
		self.close();
		if(self.name != 'iparkWorkspace') {
			opener.location.href = opener.location.href;
		}

		//opener.bustFrame(url);
	}
	
	if (typeof(window.dialogArguments) != 'undefined') 
  {
		closeDialog();
<!--- 		opener = window.dialogArguments;
		while (typeof(opener.dialogArguments) != 'undefined') {
			opener.close();
			opener = opener.dialogArguments;
		}	
 --->	
  }
	
	alert(opener.name)
	opener.close()	;
	*/
	
	if (top != self && typeof(window.dialogArguments) == 'undefined') 
  {
    top.location.href = url;
  } // if
} // Function


//////////////////////////////////////////////////////////////////////
//
// MODALDIALOG FUNCTIONS 
//
//////////////////////////////////////////////////////////////////////


// DES: Open a modalDialog with a given URL 
// PAR: parUrl    = The url to open in a dialogs
// PAR: resize    = any value to make the dialog resize
// PAR: parWidth  = The width to set for the dialog; 350 default
// PAR: parHeigth = The height to set for the dialog; 500 default
// PAR: parPopup  = Any to make dialog a popup instead of a dialog
// PAR: parEdit   = True or 1 to set additional window stuff. 0 to show window only; Applies only to popup
function openDialog(parUrl, parResize, parWidth, parHeight, parPopup, parModalless)
{
  var lngHeight = 500;
  var lngWidth = 350;
  var lngResize = '0';
  var blnRefresh = true;
  var ret = 0;
  
  if (parModalless == undefined)  { 
    blnRefresh = false; 
  } else if ((parModalless == '0') || (parModalless == 0)) {
    blnRefresh = false; 
  } // if
  if (parWidth != undefined)      { lngWidth = parWidth; }
  if (parHeight != undefined)     { lngHeight = parHeight; }
  if (parResize != undefined) 
  { 
    if ((parResize == '1') || (parResize == 1))
    {
      lngResize = '1'; 
    } // if
  } // if
  
  if ((parPopup != undefined) && ((parPopup == '1') || (parPopup == 1)))
  {
    ret = window.open(parUrl, '_blank', 'status=0,Width=' + lngWidth + 'px;Height=' + lngHeight + 'px,scrollbars=1,resizable='+parResize);
  }
  else
  {
    if (parModalless != undefined) 
    {
      showModelessDialog(parUrl, self, 'dialogHeight:' + lngHeight + 'px; dialogWidth:' + lngWidth + 'px; edge: Raised; center: Yes; help: No; resizable: Yes; status: Yes; scroll: yes');
    } else { 
      ret = showModalDialog(parUrl, self,'status:0;dialogWidth:' + lngWidth + 'px;dialogHeight:' + lngHeight + 'px; help:0; unadorned:0; scroll:no; resizable='+parResize);
    } // if
  } // if
  
	// Reload parent window if modalDialog is closed
	if ((ret != 0) && (blnRefresh == true))
  {
		// Hardcode check on framename not so nice... should be a check if parent is modaldialog... but donno how
		if (this.name == 'iparkWorkspace') 
    {
			//This one works for a normal window
			window.location.reload();
		} 
    else 
    {
      // This one works to refresh a modaldialog
			parent.frames[0].location.href = parent.frames[0].location;
			
      // This one reloads all (i)frames in a modaldialog
			for (i=0; i < parent.frames[0].frames.length;i++) 
      {
				parent.frames[0].frames[i].location.href = parent.frames[0].frames[i].location;
			} // for
		} // if
	} // if
  
  return ret;
} // function


// DES: Open a modalDialog with a given URL (width:350, height:500)
// PAR: url = the url to open in the dialog
function openDialogUsers(url) 
{
	var ret = showModalDialog(url,self,'status:0;dialogWidth:350px;dialogHeight:500px;help:0;unadorned:0;scroll:no;');
	
	//Reload parent window if modalDialog is closed
	if (ret != undefined)
  {
		// Hardcode check on framename not so nice... should be a check if parent is modaldialog... but donno how
		if (this.name == 'iparkWork') 
    {
			//This one works for a normal window
			window.location.reload();
		} 
    else 
    {
/*

			// This one works to refresh a modaldialog
			parent.frames[0].location.href = parent.frames[0].location;
      
			// This one reloads all (i)frames in a modaldialog
			for (i=0; i < parent.frames[0].frames.length;i++) 
      {
				parent.frames[0].frames[i].location.href = parent.frames[0].frames[i].location;
			} // for

*/

      document.location.reload();

		} //  if
	} // if
} // function


// DES: Close dialog
// PAR: parValue = Optional the dialog return value.
function closeDialog(parValue)
{
	// Return object to trigger refresh
  if (parValue == undefined)
  {
  	var obj = new Object;
	  window.returnValue = obj;
  } 
  else
  {
	  window.returnValue = parValue;
  } // if
  
	// Close the window
	window.close();
} // function



// DES: This function resizes the window so it just contains the form
function redraw() {
	wrapper = document.getElementById('framewrapper');
	dialogXpos = Math.round(parent.dialogLeft.replace('px',''));
	
	if(wrapper.clientWidth < screen.availWidth-dialogXpos) {
		if (wrapper.clientWidth < screen.availWidth) {
			parent.dialogLeft = (screen.availWidth - wrapper.clientWidth)/2 + 'px';
			parent.dialogTop = (screen.availHeight - wrapper.clientHeight)/2 + 'px';
		}
		else {
			parent.dialogLeft = '0px';
		} // if
	} // if
	
	parent.dialogWidth = wrapper.clientWidth  + 60 + 'px';
	parent.dialogHeight = wrapper.clientHeight + 90 + 'px';
} // function

//show and hide tab's in modaldialogs
function changeTab(nr)
{
	var count = 1;
	arTabs = document.getElementsByTagName('div');

	// Loop over all tables/tabs
	for (i=0;i < arTabs.length;i++) 
  {
		tab = arTabs[i];
		// If table id's contains menu, do your thing
		if (/menu/.test(tab.id)) {
			document.getElementById('menu'+count).style.display = 'none';
			document.getElementById('clss'+count).className = 'dialog-tab-inactv';
			count++;
		} // if
	} // for
	
	// Go to slected tab	
	document.getElementById('menu'+nr).style.display = 'inline';
	document.getElementById('clss'+nr).className = 'dialog-tab-actv';
	// Resize modalDialog
	redraw();
 } // function


//////////////////////////////////////////////////////////////////////
//
// TOOLTIP FUNCTIONS 
//
//////////////////////////////////////////////////////////////////////



// DES: Hide tooltip layer
function hideBubble()
{
	bubble.style.visibility = "hidden";
} // function


// DES: Get the mouse position
// RET: variables mx and my
function getMouse()	
{
	mx = window.event.x + document.body.scrollLeft;
	my = window.event.y + document.body.scrollTop;
} // function

// DES: Show the tooltip on the mouse position
// PAR: text = the text to show in the bubble
function showBubble(text)
{
	getMouse();
	bubble.style.left = mx;
	bubble.style.top  = my +5;
	document.all.bubble.innerHTML = "<span class='BubbleClass'>" + text +"</span>";
	bubble.style.visibility = "visible";
} // function



//////////////////////////////////////////////////////////////////////
//
// STYLE FUNCTIONS 
//
//////////////////////////////////////////////////////////////////////


// Change the class for a element with a given id
function changeClass(id,style)
{
	document.getElementById(id).className=style;
} // function

// Change the class for 1-* HTML elements with the same name
function changeClassOnName(name,style) 
{
	var cells = document.getElementsByName(name);
	
	for (var j=0; j < cells.length; j++) 
  {
		cells[j].className = style;
  } // for
} // function


//////////////////////////////////////////////////////////////////////
//
// FORM VALIDATION 
//
//////////////////////////////////////////////////////////////////////

// DES: Function replaces all occurrences of the string parSearch in parText by parReplace
// PAR: parText    = The text to search in
// PAR: parSearch  = The text or regular expression to search for in the text
// PAR: parReplace = The text to replace
// RET: The text with all occurrences replaced.
function replaceAll(parText, parSearch, parReplace)
{
  if (parText.indexOf(parSearch) >= 0)
  {
    return replaceAll(parText.replace(parSearch, parReplace), parSearch, parReplace);
  }
  else
  {
    return parText;
  } // if
} // replaceAll

// DES: Function check for required and validation fields
// PAR: FORM = A reference to the form object
function checkForm(FORM, parLanguage) 
{
	

	
	// Start of the error message
	var msg = "The form was not succesfully validated.\n\nValues are required and missing or values have an invalid format:\n\n";
  if (parLanguage != undefined){
    if (parLanguage.length > 0){
      if (parLanguage == 'nl'){
        msg = "Het formulier is niet succesvol gevalideerd.\n\nDe volgende waarden ontbreken of zijn ongeldig:\n\n";
      } // if
    } // if
  } // if
  
	var isOk = true; // Start positive ;)
	var arFields = new Array(1);
	var root;

	// Get all the fields in the form, if no form is given get all fields from the page
	if (FORM != null) 
  {
		// If FORM is a form name instead of a form object
		if (typeof(FORM) == 'string') 
      root = document.forms[0];
		else 
      root = FORM;

		// Use start message from form if available
		if(root.msg) msg=root.msg + '\n\n';
	} 
  else 
    root = document;
    
	// Get all input,select and textfields for given form	
	arInputFields = root.getElementsByTagName("input");
	arSelectFields = root.getElementsByTagName("select");
	arTextFields = root.getElementsByTagName("textarea");


	// Quickfix: Can this be done in a better way ?? like concatenating objects orso....
	if (arInputFields[0])  for (i=0;i < arInputFields.length ;i++) arFields[i] = arInputFields[i];
	if (arTextFields[0])   for (i=0;i < arTextFields.length  ;i++) arFields[arFields.length] = arTextFields[i];
	if (arSelectFields[0]) for (i=0;i < arSelectFields.length;i++) arFields[arFields.length] = arSelectFields[i];
  
  var blnNextField;
  
	// Loop over all the fields
	for (i=0; i < arFields.length; i++) 
  {
    blnNextField = false;
		field = arFields[i];

		// Check if field is required
		if (field.getAttribute('required') == 'true') 
    {
			rtn = field.value.validate('required');
			if (!rtn)
      {
        strMsg = field.getAttribute('msg');
				// Remove Line feeds and \' escape chars from message!
        strMsg = replaceAll(strMsg, '\\n', ' ');
        strMsg = replaceAll(strMsg, '\\\'', '\'');
				msg += '* ' + strMsg + '\n';
				
				
				isOk = false;
        blnNextField = false;
				continue; 
			} // if 
		} //if 
		
    if (blnNextField)
    {
    
  		// Check if the input is ok
  		if (field.getAttribute('validation') != null)
      {
  			rtn = field.value.validate(field.validation);
  			if (!rtn) 
        {
          strMsg = field.getAttribute('msg');
  				// Remove Line feeds and \' escape chars from message!
          strMsg = replaceAll(strMsg, '\\n', ' ');
          strMsg = replaceAll(strMsg, '\\\'', '\'');
  				msg += '* ' + strMsg + '\n';
  				
				
				isOk = false;
  				continue; 
  			} // if
  		} // if
    } // if
	} // for
	
	// Alert message

	if(!isOk) 
  { 
    alert(msg); 
  } // if
  
	return isOk;
} // function



// DES: Function validates a value against a pattern
// PAR: parPattern = The pattern to validate
// PAR: parMessage = Optional; The message to display when the validation failed.
// RET: True if the pattern is approved
function validate(parPattern) 
{
	// Define regex patterns
	// alert('|'+this+'|');
	required = /^(\w(.|\s|\w)*|(.|\s|\w)*(\w|.))$/; // /^.+\s*.*$/ (.|\s|\w)+
	alfa = /^([a-zA-Z0-9]+)?$/;
	integer = /^(\d*)+$/;
	numeric = /^(\d*([.,]\d+)?)?$/;	
	price = /^(\d*[,]\d\d)?$/; //Dutch pricing without points for thousands.
	time = /^(([01]\d|2[0-4]):(0[1-9]|[1-5]\d|))?$/; //24 hour time check, this will match 24:00 as well as 00:00
	lettersonly = /^([a-zA-Z_]+)?$/; //Only letters and _ usefull for cf vars
	cfvar = /^[A-Za-z][A-Za-z0-9_]*&/; // Coldfusion variable
  
	string = /^(.*)?$/;
	string_required = /^.*$/;
  date           = /^([0-9]{1}\d{1}(\-|\/)[0-9]{1}\d{1}(\-|\/)(20|19)\d{2,2})?$/; //dd-mm-jjjj
  date_required  = /^[0-9]{1}\d{1}(\-|\/)[0-9]{1}\d{1}(\-|\/)(20|19)\d{2,2}$/; //dd-mm-jjjj
	postcode          = /^(([1-9]{1}\d{3})(\d{1}|\ ?[A-Za-z]{2}))?$/i; // XXXX YY or XXXXYY or XXXXX
	postcode_required = /^([1-9]{1}\d{3})(\d{1}|\ ?[A-Za-z]{2})$/i; // XXXX YY or XXXXYY or XXXXX
  
	// This pattern is not yet finished, so don't use it before changing it!!
	//telephone = /^[-\d\s]{10,}$/;
	
	// The start of the email must have at least one character before the @ sign. There may be either a . or a -,
	// but not together before the @ sign There must be an @ sign At least once character must follow the @ sign
	// There may be either a . or a -, but not together in the address The address must end with a . followed by
	// at least 2 characters
  email = /(^\w+([\.-]|\w)*\@(\w|\-)+\.((\w|\-)+\.)?\w{2,})?$/;
  email_required = /^\w+([\.-]|\w)*\@(\w|\-)+\.((\w|\-)+\.)?\w{2,}$/;

  gender = /(m|M|f|F)?$/;
  gender_required = /(m|M|f|F)$/;
  
	objPattern = eval(parPattern);
  var strText = "";

	blntestResult = objPattern.test(this);
	return blntestResult;
}	// function

// Assign validate() to string object
String.prototype.validate = validate;




// DES: Function validates a value against a pattern
// PAR: parPattern = The pattern to validate
// PAR: parMessage = Optional; The message to display when the validation failed.
// RET: True if the pattern is approved
function validateField(parPattern, parMessage, parValue) 
{
	// Define regex patterns
	// alert('|'+this+'|');
	required          = /^(\w(.|\s|\w)*|(.|\s|\w)*(\w|.))$/; // /^.+\s*.*$/ (.|\s|\w)+
	alfa              = /^([a-zA-Z0-9]+)?$/;
	integer           = /^(\d*)+$/;
	numeric           = /^(\d*([.,]\d+)?)?$/;	
	price             = /^(\d*[,]\d\d)?$/; 							// Dutch pricing without points for thousands.
	time              = /^(([01]\d|2[0-4]):(0[1-9]|[1-5]\d|))?$/; 				// 24 hour time check, this will match 24:00 as well as 00:00
	lettersonly       = /^([a-zA-Z_]+)?$/; 							// Only letters and _ usefull for cf vars
	cfvar             = /^[A-Za-z][A-Za-z0-9_]*&/; 						// Coldfusion variable

	string            = /^(.*)?$/;
	string_required   = /^.*$/;
	date              = /^([0-9]{1}\d{1}(\-|\/)[0-9]{1}\d{1}(\-|\/)(20|19)\d{2,2})?$/; 	// dd-mm-jjjj
	date_required     = /^[0-9]{1}\d{1}(\-|\/)[0-9]{1}\d{1}(\-|\/)(20|19)\d{2,2}$/; 	// dd-mm-jjjj
	postcode          = /^(([1-9]{1}\d{3})(\d{1}|\ ?[A-Za-z]{2}))?$/i; 			// XXXX YY or XXXXYY or XXXXX
	postcode_required = /^([1-9]{1}\d{3})(\d{1}|\ ?[A-Za-z]{2})$/i; 			// XXXX YY or XXXXYY or XXXXX
  
	// This pattern is not yet finished, so don't use it before changing it!!
	//telephone = /^[-\d\s]{10,}$/;
	
	// The start of the email must have at least one character before the @ sign. There may be either a . or a -,
	// but not together before the @ sign There must be an @ sign At least once character must follow the @ sign
	// There may be either a . or a -, but not together in the address The address must end with a . followed by
	// at least 2 characters
  	
  	email             = /(^\w+([\.-]|\w)*\@(\w|\-)+\.((\w|\-)+\.)?\w{2,})?$/;
	email_required    = /^\w+([\.-]|\w)*\@(\w|\-)+\.((\w|\-)+\.)?\w{2,}$/;

	gender            = /(m|M|f|F)?$/;
	gender_required   = /(m|M|f|F)$/;
    
	objPattern        = eval(parPattern);
        var strText       = "";

 	if (parValue != undefined){
    		strText = parValue;
  	}
  
	blntestResult = objPattern.test(strText);
  
  	if((!blntestResult) && (parMessage != undefined)){
    		alert(parMessage);
  	}
  
	return blntestResult;
}


//////////////////////////////////////////////////////////////////////
//
// SHOW OBJECT INFO
//
//////////////////////////////////////////////////////////////////////


// DES: Display all the properties of an object
// PAR: obj  = object, the object u want to have the properties
// PAR: expd = boolean default = false, expand proterties which contains objects
// PAR: lvl  = int default = 0, The level of displayd props that contain objects.
//                              Watch it even 1 level can get realy heavy.
function jsDump (obj,expd,lvl) 
{
  // Set default values
  if(!lvl) lvl = 0;
  else if (lvl.length == 0) lvl = 0;
  if(!expd) expd = false;
  else if (expd.length == 0) expd = false;
    
  // Open window
  //win = popupWindow('',1000,800);
  //if(win) alert('weg ermee'); win.close();
  win = window.open();

  // Open the main table
  var html = '<table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#009900" style="background-color:#97F9A4;font-weight:bold;">';
  html += '<tr>';
  html += '<td onclick="opener.showHideDisplay(0)" style="padding: 5px;vertical-align:top;">' + obj.nodeName + '</td>';
  html += '<td width="99%" id="0" bgcolor="#009900" style="border: 2px solid #009900;">';
  win.document.write(html);  
  
  // Display properties
  dspProps(obj,win,expd,lvl);
  
  //close the main table
  win.document.write('</td></tr></table>');
} // function 


// DES:Generate html table with property info
// PAR: obj  = object, the object u want to have the properties
// PAR: w    = window, the destination new window to write to.
// PAR: expd = boolean default = 0, expand proterties which contains objects
// PAR: lv l = int default = 0, The level of displayd props that contain objects.
//                            Watch it even 1 level can get realy heavy.
function dspProps(obj,w,expd,lvl)
{
  var tableCount = 0;

  var html = '<table width="100%" border="1" bordercolor="#009900" bgcolor="#009900" cellpadding="0" cellspacing="0">';
  w.document.write(html);

  // Loop over the properties of this object
  for(name in obj) {
    tableCount ++;
    // Create unique id
    id = uniqueId();
    html = '<tr><td bgcolor="#97F9A4" onclick="opener.showHideDisplay(\'' + id + '\')" valign="top" style="padding: 5px">';
    html += name + '</td><td bgcolor="#97F9A4" width="99%" id="' + id + '"';
    w.document.write(html);
    

    // Check if property is an object, hmmm can be done nicer i think but it works ;)
    if (typeof(obj[name]) == 'object') {
      // Recusive sjit to show props of objectprops, watch it even 1 level can get realy heavy.
      if (lvl > 0 && false) {
        if (!expd)  html = 'style="display:none">';
        else html = '>';
        w.document.write(html);
        lvl--;
        lvl = dspProps(obj[name],w,expd,lvl);
        lvl++;
        html = "";
      } else {
        // Create unique id
        html = ' style="padding: 5px;"><div style="font-weight:bold;cursor:hand;">[Object]</div>';
      }
    }
    // Just a normal value
    else {
      html = ' style="padding: 5px;">';
      // Don't show real HTML, show HTML code only
      if (/^\w{3}erHTML$/.test(name)) {
        html += obj[name].replace(/<([^>]*)>/g,'&lt;$1&gt;');
      } else {
        html += obj[name];
      }
      
      html += '&nbsp;';
    }
    
    html += '</td></tr>';
    w.document.write(html);
  }

  w.document.write('</table>');
  return lvl; 
} // function


// DES: Returns an unique ID
function uniqueId() 
{
  id =  new Date();
  id = id.getTime()*Math.random();
  return id;
} // function

/**** /SHOW OBJECT INFO ****/


//---------------------------------------------------------------------------------------------------------------------------
// DES: Function checks if both values are equal.
// PAR: parValue1 = The first password
// PAR: parValue2 = The second password
// RET: If equal it returns true.
function CheckPassword(parValue1, parValue2, parMessageEmpty, parMessageNotEqual)
{

  var blnResult = false;

  if (parValue1 == undefined){
    alert(replaceAll(parMessageEmpty, '{0}', 'first'));
  } else {
    if (parValue2 == undefined){ 
      alert(replaceAll(parMessageEmpty, '{0}', 'second'));
    } else {
      if (parValue1 != parValue2) {
        alert(parMessageNotEqual);
      } else {
        blnResult = true;
      } // if
    } // if
  } // if

  return blnResult;
} //RefreshForm


