/********************************************************************************************************
 *	Browser prüfen
 ********************************************************************************************************/
function IE()
{
	return ( (navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4) );
}
function Netscape()
{
	return ( (navigator.appName == "Netscape") && (parseInt(navigator.appVersion) >= 3) );
}
function Opera()
{
	return ( navigator.appName == "Opera" );
}


try
{
	if ( portalArea ) throw 'ok';
	else throw 'init';
}
catch (error)
{
	if ( error == 'init' ) var portalArea = new Array();
}
//if( IE() ) portalArea['resObj'] = new ActiveXObject("MSXML2.XMLHTTP"); 
//else 	portalArea['resObj'] = new XMLHttpRequest(); 
//http://design-noir.de/webdev/JS/XMLHttpRequest-IE/
/*@cc_on @if (@_win32 && @_jscript_version >= 5) if (!window.XMLHttpRequest)
window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
@end @*/
portalArea['resObj'] = new XMLHttpRequest(); 

function setPortalArea(area)
{

	if ( portalArea['last_name'] == area ) return;

	var parameters = 'set_area=' + area;
	portalArea['resObj'].open('post', '/content_page.php',true);
	portalArea['resObj'].onreadystatechange = function() {};
	portalArea['resObj'].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	portalArea['resObj'].setRequestHeader("Content-length", parameters.length);
	portalArea['resObj'].setRequestHeader("Connection", "close");
	portalArea['resObj'].send(parameters);
	if ( portalArea['last_name'] != area ) portalArea['last_name'] = area;
}

function unsetPortalArea(area)
{
	var parameters = 'set_area=' + portalArea['last_name'];
	portalArea['resObj'].open('post', '/content_page.php',true);
	portalArea['resObj'].onreadystatechange = function() {};
	portalArea['resObj'].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	portalArea['resObj'].setRequestHeader("Content-length", parameters.length);
	portalArea['resObj'].setRequestHeader("Connection", "close");
	portalArea['resObj'].send(parameters);
}
function returnPortalArea()
{
	if( portalArea['resObj'].readyState != 4 ) return;
	var ajaxResponse = portalArea['resObj'].responseText;
	if ( portalArea['last_name'] != ajaxResponse ) portalArea['last_name'] = ajaxResponse;
}


function allow_alpha_numeric2(obj) {
	if ( !obj.value ) return;

	var New = "";

	var IgnoreString = "";
	var Test = "";

	for (var i=0; i<obj.value.length; ++i) {
		Test = obj.value.charAt(i);
		if ( IgnoreString.indexOf(Test) == -1 ) {
			New += Test;
//		} else {
//			alert(Test);
		}
	}
	obj.value = New;

}


function allow_alpha_numeric(obj) {
	if ( !obj.value ) return;
	if ( /[^\wüöäüÜÖÄÜß@§\s\(\)\]\[=*&.!?#+\/\-]/i.test(obj.value) )
	{
		obj.value = obj.value.replace(/[^\wüöäüÜÖÄÜß@§\s\(\)\]\[=*&.!?#+\/\-]/gi,'');
		alert('Please do not use this Sign!');
		obj.value += '';
		obj.focus();
	}
}


function allow_alpha_numeric_test_loose(obj) {
	if ( !obj.value ) return;
	if ( /[^\w\-üöäüÜÖÄÜß@.!?#+\/]/i.test(obj.value) )
	{
		obj.value = obj.value.replace(/[^\w\-üöäüÜÖÄÜß@.!?#+\/]/gi,'');
		alert('');
	}
}
 
function allow_alpha_numeric_test(obj) {
	if ( !obj.value ) return;

	if ( /[^\x00-\xff]|[<>'"%]/i.test(obj.value) )
	{
		obj.value = obj.value.replace(/[^\x00-\xff]|[<>'"%]/g,'');
		alert('Test');
	}
}




function allow_alpha_numeric_strict(obj) {
	if ( !obj.value ) return;
	if ( /[^\w\040@_.\-]/i.test(obj.value) )
	{
		obj.value = obj.value.replace(/[^\w\040@_.\-]/gi,'');
		alert("Please do not use this Sign!\nOnly Characters (a-z, A-Z), Numbers (0-9), '-', '_', '@', '.' and space allowed!");
		obj.value += '';
		obj.focus();
	}
}
function allow_alpha(obj) {
	if ( !obj.value ) return;
	if ( /[^a-zA-Z\040\-üöäüÜÖÄÜß]/i.test(obj.value) )
	{
		obj.value = obj.value.replace(/[^a-zA-Z\040\-üöäüÜÖÄÜß]/gi,'');
		alert('Please do not use this Sign!');
		obj.value += '';
		obj.focus();
	}
}
  
function allow_alpha_strict(obj) {
	if ( !obj.value ) return;
	if ( /[^a-zA-Z\040\-]/i.test(obj.value) )
	{
		obj.value = obj.value.replace(/[^a-zA-Z\040\-]/gi,'');
		alert("Please do not use this Sign!\nOnly Characters (a-z, A-Z), '-' and space allowed!");
		obj.value += '';
		obj.focus();
	}
}
    
		  
function allow_numeric(obj) {
	if ( !obj.value ) return;

	if (/[^0-9\040\-._]/i.test(obj.value))
	{
		obj.value = obj.value.replace(/[^0-9\040\-._]/g,'');
		alert("Only Numbers, '-', '_' and '.' allowed!");
		obj.value += '';
		obj.focus();
	}
}

function allow_numeric_strict(obj) {
	if ( !obj.value ) return;
	if (/[^0-9\-]/i.test(obj.value))
	{
		obj.value = obj.value.replace(/[^0-9\-]/g,'');
		alert('Only Numbers allowed!');
		obj.value += '';
		obj.focus();
	}

}

function copyToClipboard(ID)
{
	if ( !IE() ) {alert('Sorry, this only works in Internet Explorer. Please copy the code manually.'); return false;}		// Das geht nur im IE
	ctrlRange = document.body.createControlRange();
	ctrlRange.add(document.all(ID));
	ctrlRange.execCommand("Copy");
	return true;
}

function MM_openBrWindow(theURL,winName,features) 
{
	window.open(theURL,winName,features);
}

function checkAll (id, checked) {
	var el = document.getElementById(id);
	for (var i = 0; i < el.elements.length; i++) {
	  el.elements[i].checked = checked;
	}
}

function uncheckAll (id, checked) {
	var el = document.getElementById(id);
	for (var i = 0; i < el.elements.length; i++) {
	  el.elements[i].checked = unchecked;
	}
}

function ShowPicture()  {
    window.open('', 'pictureBox', 'width=1,height=1,resizable=no,scrollbars=no,statusbar=no');
}

function Popup (file) 
{
	window1 = window.open(file, "popup", "width=600,height=400,left=10, top=10,dependent=yes,scrollbars=yes");
	window1.focus();
}

function Popup_taf (file) 
{
	window1 = window.open(file, "popup", "width=470 ,height=480,left=10, top=10,dependent=yes,scrollbars=yes");
	window1.focus();
}

function Popup_lost_pwd (file) 
{
	window1 = window.open(file, "popup", "width=470 ,height=480,left=10, top=10,dependent=yes,scrollbars=yes");
	window1.focus();
}

function scroll(pix) {
	window.scrollBy(0, pix); 
}

function Complete(obj, evt) {
	 if ((!obj) || (!evt) || (vStrg.length == 0)) {
 	 	return;
  }

  if (obj.value.length == 0) {
  		return;
  }

  var elm = (obj.setSelectionRange) ? evt.which : evt.keyCode;

  if ((elm < 32) || (elm >= 33 && elm <= 46) || (elm >= 112 && elm <= 123)) {
  		return;
  }

  var txt = obj.value.replace(/;/gi, ",");
  elm = txt.split(",");
  txt = elm.pop();
  txt = txt.replace(/^\s*/, "");

  if (txt.length == 0) {
  		return;
  }

  if (obj.createTextRange) {
   	var rng = document.selection.createRange();
  		if (rng.parentElement() == obj) {
   			elm = rng.text;
  	 		var ini = obj.value.lastIndexOf(elm);
  		}
  } else if (obj.setSelectionRange) {
  		var ini = obj.selectionStart;
  }

  for (var i = 0; i < vStrg.length; i++) {
   	elm = vStrg[i].toString();
  		if (elm.toLowerCase().indexOf(txt.toLowerCase()) == 0) {
   			obj.value += elm.substring(txt.length, elm.length);
  	 		break;
  		}
  }

  if (obj.createTextRange) {
  		rng = obj.createTextRange();
  		rng.moveStart("character", ini);
  		rng.moveEnd("character", obj.value.length);
  		rng.select();
  } else if (obj.setSelectionRange) {
  		obj.setSelectionRange(ini, obj.value.length);
  }
}

function in_array(obj,arr) {
	for(p=0;p<arr.length;p++) 
	{
		if (obj.value == arr[p]) 
		{
			//obj.focus();
			alert("Number " + obj.value + " is used!!! Please select another one!");
			//document.write("Number " + obj.value + " is used! wir sind hier: " + p);
			return false;
		}
	}
	//alert(obj.value + "<<- Nummer is free and OK!");	
	return true;
}


/******************************************************************************************
 *	Funktionen hinzugefügt von Wolfgang Lorenz nach dem 01.08.2007
 ******************************************************************************************/
function readCookie(sName) { return ReadCookie(sName); }
function ReadCookie(sName) {
	var sValue = '';
	var iSemi = 0;

	if (document.cookie) {
		var cookieArray = document.cookie.split('; ');
		var cookieElements = new Array();
		for ( var i=0; i<cookieArray.length; i++ ) {
			cookieElements = cookieArray[i].split('=');
			if ( cookieElements[0].toLowerCase() == sName.toLowerCase() )
			{
				sValue = cookieElements[1];
				break;
			}
		}
	}
	return sValue;

}


function writeCookie(sName, sValue, iDays) { WriteCookie(sName, sValue, iDays); }
function WriteCookie(sName, sValue, iDays) {

	var iMilliSec = iDays * 24 * 60 * 60 * 1000;							// Umrechnung von Tagen in Millisekunden
	var dNow = new Date();
	var dExpdate = new Date(dNow.getTime() + iMilliSec);

	document.cookie = sName + '=' + sValue + ';';
	document.cookie += ' expires=' + dExpdate.toGMTString() + ';';

}

function CheckUploadFile(name) 
{

	document.getElementById('error_ext').style.display = 'none';
	document.getElementById('error_name').style.display = 'none';

	var oF = document.forms['odin_facility_ext_picture_'+name];
	if ( !oF.elements['picture'].value ) return;


	var Path = oF.elements['picture'].value.split('\\');
	if ( Path.length < 2 ) Path = oF.elements['picture'].value.split('/');
	if ( Path.length < 2 ) Path = oF.elements['picture'].value.split(',');
	var FileName = Path[Path.length-1].split('.');
	if ( FileName.length < 2 ) return;

	var Ext =FileName[FileName.length-1].toLowerCase();
	if ( (Ext!='jpg') && (Ext!='jpeg') && (Ext!='png') && (Ext!='gif') ) {
		document.getElementById('error_ext').style.display = 'block';
	} else if ( Path[Path.length-1] != escape(Path[Path.length-1]) ) {
		document.getElementById('error_name').style.display = 'block';
	} else {
		oF.elements['cmd'].value = 'upload';
		oF.action = "/code/process/pic_upload_process.php";
		oF.submit();
	}

}

function CheckUploadFileDiver(name)
{

	document.getElementById('ext_error').style.display = 'none';
	document.getElementById('ascii_error').style.display = 'none';

	var oF = document.forms['odin_diver_picture_'+name];
	if ( !oF.elements['picture'].value ) return;

	var Path = oF.elements['picture'].value.split('\\');
	if ( Path.length < 2 ) Path = oF.elements['picture'].value.split('/');
	if ( Path.length < 2 ) Path = oF.elements['picture'].value.split(',');
	var FileName = Path[Path.length-1].split('.');
	if ( FileName.length < 2 ) return;

	var type_test_name = Path[Path.length-1].replace(/\s/g, "_");

	var Ext =FileName[FileName.length-1].toLowerCase();
	if ( (Ext!='jpg') && (Ext!='jpeg') && (Ext!='png') && (Ext!='gif') && (Ext!='pdf') ) {
		document.getElementById('ext_error').style.display = 'block';
	} else if ( type_test_name != escape(type_test_name) ) {
		document.getElementById('ascii_error').style.display = 'block';
	} else {
		oF.elements['cmd'].value = 'upload';
		oF.action = "/code/process/pic_upload_process_diver.php";
		oF.submit();
	}

}


function DeleteFile(name) 
{
	var oF = document.forms['odin_facility_ext_picture_'+name];
	oF.elements['cmd'].value = 'delete';
	oF.action = "/code/process/pic_upload_process.php";
	oF.submit();

}
function DeleteFileDiver(name) 
{
	var oF = document.forms['odin_diver_picture_'+name];
	oF.elements['cmd'].value = 'delete';
	oF.action = "/code/process/pic_upload_process_diver.php";
	oF.submit();

}


/********************************************************************************************************
 *	Radiobuttons prüfen
 ********************************************************************************************************/
function checkRadios(FormName, RadioName) {

	var radio, oE, input;
	var ReturnValue = '';

	if ( document.forms[FormName].elements[RadioName] ) {
		oE = document.forms[FormName].elements[RadioName];
	} else if ( document.forms[FormName].elements[RadioName+'[]'] ) {
		oE = document.forms[FormName].elements[RadioName+'[]'];
	}

	// IE und Mozilla
	if ( oE ) {
		for ( var i=0; i<oE.length; ++i ) {
			if ( oE[i].checked ) {
				ReturnValue = oE[i].value;
				break;
			}
		}

	// Opera
	} else {
		oE = document.forms[FormName];
		for ( input in oE ) {
			if ( oE.elements[input] ) {
				if ( ( oE.elements[input].name==RadioName) || (oE.elements[input].name==RadioName+'[]') ) {
					if ( oE.elements[input].checked ) {
						ReturnValue = oE.elements[input].value;
						break;
					}
				}
			}
		}

	}

	return ReturnValue;

}

/********************************************************************************************************
 *	Datum auf Gueltigkeit pruefen
 ********************************************************************************************************/
function checkDate(dateName) {

	var day = document.getElementById(dateName+'-dd').value;
	var month = document.getElementById(dateName+'-mm').value;
	var year = document.getElementById(dateName).value;
	var returnValue = true;

	if ( !(day && month && year)  ) return true;

//	alert(year+'.'+month+'.'+day);
	var datum = new Date(year, month, day);

	if ( datum == 'NaN' || datum == 'Invalid Date' )
	{
		alert('Invalid Date Format');
		returnValue = false;
	}
	else
	{
		

		var iMonth = parseInt(String(month));

		if ( month == '8' || month == '08' ) iMonth = 7;		// Die 8 macht Probleme ??????!!!!!!!!!!!!!!
		else if ( month == '9' || month == '09' ) iMonth = 8;		// Die 9 macht Probleme ??????!!!!!!!!!!!!!!
		else iMonth -= 1;
		var iYear = parseInt(year);
		if ( iYear < 51 )	iYear += 2000;
		else if ( iYear > 50 && iYear < 1000 ) iYear += 1900;

//	alert('Date entered: ' + day + '-' + month + '-' + year );
//		alert('Month: ' + month);
//		alert(iYear+'.'+iMonth+'.'+day);
		datum = new Date(iYear, iMonth, day);
//		alert(datum.getDate()+'.'+datum.getMonth()+'.'+datum.getFullYear());
		if ((datum.getDate()!=day)||(datum.getMonth()!=iMonth)||(datum.getFullYear()!=iYear))
		{
			alert('Invalid Date. Please Check Date.');
			returnValue = false;
		}
	}

	if ( !returnValue )
	{
		document.getElementById(dateName+'-dd').value = '';
		document.getElementById(dateName+'-mm').value = '';
		document.getElementById(dateName).value = '';
	}

	return returnValue;

}


/********************************************************************************************************
 *	JavaScript-Object als String verpacken (serialisieren)
 ********************************************************************************************************/
function serialize(elem)
{
  if (elem == null || elem == undefined || elem.constructor == Function) return 'N;';

  switch ( typeof(elem) ) {
    case String:  return 's:' + elem.length + ':"' + elem + '";';
    case Number:  return (elem % 1 ? 'd:' : 'i:') + elem + ';';
    case Boolean: return 'b:' + (elem ? '1' : '0') + ';';     
    case Date:    return serialize(elem.getTime());
    case RegExp:  return serialize(elem.toSource());
    case Error:   return serialize(elem.message);
    case Array:
    case Object:
      var content = '', i = 0;
      for (var j in elem) { content += serialize(j) + serialize(elem[j]); i++; }
      return 'a:' + i + ':{' + content + '}';
    default:
      return serialize(elem.toString());
  }
}


function checkMailAddress(address)
{
	var return_value = ( address.length > 0 );
	if ( return_value ) return_value = ( address.indexOf('@') > 0 );
	if ( return_value ) return_value = (( address.lastIndexOf('.') > 2 ) && ( address.lastIndexOf('.') < (address.length - 1) ));
	return return_value;
}



var useSearchWord = false;

function onSiteSearchSetFocus(currentvalue)
{
	var searchField = document.getElementById('sitesearch-field');
	searchField.style.color = 'black';
	if(searchField.value == currentvalue)	searchField.value = '';
	useSearchWord = true;
}

function onSiteSearchLostFocus(currentvalue)
{
	var searchField = document.getElementById('sitesearch-field');
		
	if(searchField.value == '')
	{
		searchField.style.color = 'gray';
		searchField.value = currentvalue;
		useSearchWord = false;
	}
}


function onDCSearchSetFocus(currentvalue)
{
	var searchField = document.getElementById('dcsearch-field');
	searchField.style.color = 'black';
	if(searchField.value == currentvalue)	searchField.value = '';
	
	useSearchWord = true;
}

function onDCSearchLostFocus(currentvalue)
{
	var searchField = document.getElementById('dcsearch-field');
	if(searchField.value == '')
	{
		searchField.style.color = 'gray';
		searchField.value = currentvalue;
		useSearchWord = false;
	}
}


function setSiteSearchString()
{
	var searchField = document.getElementById('sitesearch-field');
	if(useSearchKeyword == false  )
	{
		var searchField = document.getElementById('sitesearch-field');
		searchField.value = '';
	}
}

function addEvent(oneEvent, obj, handler)
{
	if(document.body.addEventListener) obj.addEventListener(oneEvent, handler, false);
	if(document.body.attachEvent) obj.attachEvent("on" + oneEvent, handler);
}


function encodeUtf8(rohText)
{

  return decodeURIComponent(encodeURIComponent(rohText));

	 // dient der Normalisierung des Zeilenumbruchs
	 rohText = rohText.replace(/\r\n/g,"\n");
	 var utfText = "";
	 for(var n=0; n<rohText.length; n++)
	 {
	 // ermitteln des Unicodes des  aktuellen Zeichens
	 var c=rohText.charCodeAt(n);

	 if (c<128) utfText += String.fromCharCode(c);	// alle Zeichen von 0-127 => 1byte
	 else if( c > 127 && c < 2048)
	 {	// alle Zeichen von 127 bis 2047 => 2byte
		 utfText += String.fromCharCode((c>>6)|192);
		 utfText += String.fromCharCode((c&63)|128);}
	 
	 else
	 {	// alle Zeichen von 2048 bis 66536 => 3byte
		 utfText += String.fromCharCode((c>>12)|224);
		 utfText += String.fromCharCode(((c>>6)&63)|128);
		 utfText += String.fromCharCode((c&63)|128);}
	 }
	 return utfText;
}


function decodeUtf8(utfText)
{
  return decodeURIComponent(encodeURIComponent(utfText));

	var plainText = "";
	var i=0;
	var c=c1=c2=0;
	// while-Schleife, weil einige Zeichen uebersprungen werden
	while(i<utfText.length)
	{
		c = utfText.charCodeAt(i);
		if (c<128)
		{
			plainText += String.fromCharCode(c);
			i++;
		}
		else if((c>191) && (c<224))
		{
			c2 = utfText.charCodeAt(i+1);
			plainText += String.fromCharCode(((c&31)<<6) | (c2&63));
			i+=2;
		}
		else
		{
			c2 = utfText.charCodeAt(i+1); c3 = utfText.charCodeAt(i+2);
			plainText += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
			i+=3;
		}
	}
	return plainText;
}

function alertText(text)
{
	if ( !document.charset ) return text;
	if ( document.charset.toUpperCase() == "UTF-8" ) return text;
	else return decodeUtf8(text);
}

function bookmark(url,title)
{
	if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) 
	{
		window.external.AddFavorite(url,title);
	}
	else 
	{
		var msg = "Sorry! Your browser doesn't support this function. Please add the Link manually!";
		if(navigator.appName == "Netscape") msg += " (CTRL-D)";
		alert(msg);
	}
}


function setCountryOptionsUniversal(formname, countryfieldname, stateselectname)
{
	var country = document.forms[formname].elements[countryfieldname].value;
	if ( (country != "AUS") && (country != "CAN") && (country != "ESP") &&( country != "ITA") && (country != "JPN") && (country != "USA") )
	{
		if ( document.getElementById('state_list') ) document.getElementById('state_list').style.display = 'none';
		document.getElementById('state_item').style.display = 'none';
		document.getElementById('state_data').style.display = 'none';
		return;
	}

	var parameters = '&command=get_state_list' + 
									 '&country=' + country + 
									 '&required=required' + 
									 '&select_name=' + stateselectname;
	//alert (parameters);

	portalArea['resObj'].open('post', '/code/process/ajax_requests_universal.php',true);
	portalArea['resObj'].onreadystatechange = returnStateListUniversal;
	portalArea['resObj'].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	portalArea['resObj'].setRequestHeader("Content-length", parameters.length);
	portalArea['resObj'].setRequestHeader("Connection", "close");
	portalArea['resObj'].send(parameters);

}

function returnStateListUniversal()
{
	if( portalArea['resObj'].readyState != 4 ) return;
	var ajaxResponse = portalArea['resObj'].responseText;

	document.getElementById('state_data').innerHTML = ajaxResponse;

	if ( IE() ) {
		if ( document.getElementById('state_list') ) document.getElementById('state_list').style.display = 'block';
		document.getElementById('state_item').style.display = 'block';
		document.getElementById('state_data').style.display = 'block';
	} else {
		if ( document.getElementById('state_list') ) document.getElementById('state_list').style.display = 'table-row';
		document.getElementById('state_item').style.display = 'table-cell';
		document.getElementById('state_data').style.display = 'table-cell';
	}

}

function textDirection(val) {
	if (val == "ltr") {
		document.getElementById("left_content").dir = "ltr";
	} else {
		document.getElementById("left_content").dir = "rtl";
	}
	return;
}


function popupform(myform, windowname) 
{ 
	if (! window.focus)return true; 
	window.open('', windowname, 'height=350,width=400,scrollbars=yes'); 
	myform.target=windowname; 
	return true; 
} 


function evalScript(scripts)
{	try
	{	if(scripts != '')	
		{	var script = "";
			scripts = scripts.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
	       	                         if (scripts !== null) script += arguments[1] + '\n';
 	        	                        return '';});
			if(script) (window.execScript) ? window.execScript(script) : window.setTimeout(script, 0);
		}
		return false;
	}
	catch(e)
	{	alert(e)
	}
}

function get_cookie(Name) 
{
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) { 
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}


function datosServidor() {
};
datosServidor.prototype.iniciar = function() {
	try {
		// Mozilla / Safari
		this._xh = new XMLHttpRequest();
	} catch (e) {
		// Explorer
		var _ieModelos = new Array(
		'MSXML2.XMLHTTP.5.0',
		'MSXML2.XMLHTTP.4.0',
		'MSXML2.XMLHTTP.3.0',
		'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'
		);
		var success = false;
		for (var i=0;i < _ieModelos.length && !success; i++) {
			try {
				this._xh = new ActiveXObject(_ieModelos[i]);
				success = true;
			} catch (e) {
				// Implementar manejo de excepciones
			}
		}
		if ( !success ) {
			alert("Ajax could not be implemented ... sorry");
			// Implementar manejo de excepciones, mientras alerta.
			return false;
		}
		return true;
	}
}

datosServidor.prototype.ocupado = function() {
	estadoActual = this._xh.readyState;
	return (estadoActual && (estadoActual < 4));
}

datosServidor.prototype.procesa = function() {
	if (this._xh.readyState == 4 && this._xh.status == 200) {
		this.procesado = true;
	}
}

datosServidor.prototype.enviar = function(urlget,datos) {
	if (!this._xh) {
		this.iniciar();
	}
	if (!this.ocupado()) {
		this._xh.open("GET",urlget,false);
		this._xh.send(datos);
		if (this._xh.readyState == 4 && this._xh.status == 200) {
			return this._xh.responseText;
		}
		
	}
	return false;
}


// Este es un acceso rapido, le paso la url y el div a cambiar
function _gr(reqseccion,divcont) {
	remotos = new datosServidor;
	nt = remotos.enviar(reqseccion,"");
	document.getElementById(divcont).innerHTML = nt;
}



//Estas dos son para guardar

function rateItem(rating,itemId,itemType)  
{
	itemId =  itemId.replace(/[^a-zA-Z0-9_-]+/g,'');
	var keks_name  = 'SSI_rated_'+itemId;
	//ACHTUNG: itemID darf nur Plain Text sein, keine Sonderzeichen erlaubt!
	//var keks = get_cookie(keks_name);
	//alert("COOKIE: " + keks_name);
	//alert("RATING ItemId: " + itemId);
	remotos = new datosServidor;
	nt = remotos.enviar('/code/process/stars_update.php?rating='+rating+'&itemId='+itemId+'&itemType='+itemType); 
	rating = rating * 25;
	document.getElementById('current-rating'+itemId).style.width = rating+'px';
	disableItem(itemId);	
	document.getElementById('ratingtext'+itemId).innerHTML = 'Thanks for your Vote!';
	document.cookie=keks_name+"=true_"+itemId; 
}

function disableItem(itemId)  
{
	//alert("Item: " + itemId) ;
	document.getElementById('1_'+itemId).innerHTML = "";
	document.getElementById('2_'+itemId).innerHTML = "";
	document.getElementById('3_'+itemId).innerHTML = "";
	document.getElementById('4_'+itemId).innerHTML = "";
	document.getElementById('5_'+itemId).innerHTML = ""; //was: <a href='#' class='five-stars'>5</a>
	document.getElementById('ratingtext'+itemId).innerHTML = 'Already voted!';
}


function changeUserSiteStatus(odin_user_master_id,siteId,status,action )  
{
	remotos = new datosServidor;
	alert('omid='+odin_user_master_id+'&siteId='+siteId+'&status='+status+'&action='+action);
	nt = remotos.enviar('/code/process/user_site_status_update.php?omid='+odin_user_master_id+'&siteId='+siteId+'&status='+status+'&action='+action);
	var infoSpan = document.getElementById('status_change_'+status+siteId);
	infoSpan.innerHTML = "New Status is set";
}

function hinzu(element) 
{
	var neu = document.createElement('div');
	neu.innerHTML = '<input type="file" class="datei" name="datei[]"  size="45"/> <a href="#" class="weg" onclick="loeschen(this); return false">remove</a><span> &nbsp;<select name="tag[]" style="font-size:11px;"><option value="">please select</option><option value="medical">Medical</option><option value="cpr">CPR</option><option value="firstaid">First Aid</option><option value="oxygen">Oxygen</option><option value="history">Diving History</option><option value="other">Please supply details:</option></select> Details:</span> &nbsp;<input type="text" name="info[]" />';
	element.parentNode.parentNode.appendChild(neu);
}

function loeschen(element) 
{
	element.parentNode.parentNode.removeChild(element.parentNode);
}


function getSize() {
   var myWidth = 0, myHeight = 0;
 
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    //return [ myWidth, myHeight ];
		return [ myWidth ];
}

function setSizeVar() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
	window.alert( 'Width = ' + myWidth );
	document.size.width.value = myWidth;
	document.size.submit();
	window.alert( 'Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );
}

function P(file) 
{
	//easy popup
	var eigenschaften="width=550,height=600,left=100, top=100"; //"screenX=100,screenY=100,w";
	// weitere Attribute hinzufügen
	eigenschaften= eigenschaften + ",resizable=yes,dependent=yes,scrollbars=yes,status='Preview Window',menubar=0,toolbar=0,location=0,directories=0,menubar=0,scrollbars=0,copyhistory=0";
	window1 = window.open(file, "imgView",eigenschaften);
	window1.focus();
}

function validateEmail(email) 
{
	if( /^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$/.test(email) ) 
	{
  	return (true); // Valid
  } 
	else 
	{
  	return(false); // Invalid
  }
}



//****************************
//log.js --> start
//****************************


wmtt = null;
document.onmousemove = updateTT;

function showTT(id){
	wmtt = document.getElementById(id);
	wmtt.style.display = "block"
}

function updateTT(e) {
	x = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
	y = (document.all) ? window.event.y + document.body.scrollTop  : e.pageY;
	if (wmtt != null) {
		wmtt.style.left = (x + 20) + "px";
		wmtt.style.top 	= (y + 10) + "px";
	}
}

function hideTT() {
	wmtt.style.display = "none";
}

function ChangeSelectByValue(ddlID, value, change) 
{
	var ddl = document.getElementById(ddlID);
	for (var i = 0; i < ddl.options.length; i++) 
	{
		if (ddl.options[i].value == value) 
	 	{
			if (ddl.selectedIndex != i) 
			{
				ddl.selectedIndex = i;
				if (change)
					ddl.onchange();
			}
			break;
		}
 	}
}

function checkRadio(rObj) 
{
	for (var i=0; i<rObj.length; i++)
	{
		if (rObj[i].checked) return rObj[i].value;
	}
	return false;
}	


function change_to_metric()
{
	setElementsByClass('imperial','readonly');
	setElementsByClass('metric','remove_readonly');
}

function change_to_imperial()
{
	setElementsByClass('imperial','remove_readonly');
	setElementsByClass('metric','readonly');
}

function setElementsByClass(myClass, action)
{
	var myEls = getElementsByClass(myClass);
	for ( i=0;i<myEls.length;i++ ) 
	{
		// do stuff here with myEls[i]
		if (action=='remove_readonly') { myEls[i].removeAttribute('readOnly','readOnly'); }
		if (action=='readonly')				 { myEls[i].readOnly = true;}
		//document.forms['formadddive'].myEls[i].value = 'XXX';
	}
}

function getElementsByClass(searchClass,node,tag) 
{
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			//alert(classElements[j]);
			j++;
		}
	}
	return classElements;
}

function checkNitrox() {
	if (document.formadddive.nitrox.checked) {
		document.formadddive.eanpercent.disabled = false;
	} else {
		document.formadddive.eanpercent.disabled = true;
		document.formadddive.eanpercent.value = "21";
	}
}

function roundit(which)
{
	//return Math.round(which*10000)/10000
	return Math.round(which*10)/10
}

function m_to_ft(formname, fieldname)
{
	//alert(formname);
	//alert(fieldname);
	//alert(document.forms[f].getElementById('depth_m'));
	var m  = document.forms[formname].elements[fieldname + '_m'].value;
	var ft = roundit(m/0.3048);
	//alert("m: " + m + " - Ft.: " + ft);
	document.forms[formname].elements[fieldname + '_ft'].value = ft;
}

function ft_to_m(formname, fieldname)
{
	var ft  = document.forms[formname].elements[fieldname + '_ft'].value;
	var m = roundit(ft*0.3048);
	document.forms[formname].elements[fieldname + '_m'].value = m;
}

function c_to_f(formname, fieldname)
{
	var c  = document.forms[formname].elements[fieldname + '_c'].value;
	var f = roundit(c*1.8+32);
	document.forms[formname].elements[fieldname + '_f'].value = f;
}

function f_to_c(formname, fieldname)
{
	var f  = document.forms[formname].elements[fieldname + '_f'].value;
	var c = roundit((f-32)/1.8);
	document.forms[formname].elements[fieldname + '_c'].value = c;
}

function bar_to_psi(formname, fieldname)
{
	var bar = document.forms[formname].elements[fieldname + '_bar'].value;
	var psi = roundit(bar * 14.50377);
	document.forms[formname].elements[fieldname + '_psi'].value = psi;
}

function psi_to_bar(formname, fieldname)
{
	var psi = document.forms[formname].elements[fieldname + '_psi'].value;
	var bar = roundit(psi / 14.50377);
	document.forms[formname].elements[fieldname + '_bar'].value = bar;
}

function kg_to_lb(formname, fieldname)
{
	var kg = document.forms[formname].elements[fieldname + '_kg'].value;
	var lb = roundit(kg  * 2.204623);
	document.forms[formname].elements[fieldname + '_lb'].value = lb;
}

function lb_to_kg(formname, fieldname)
{
	var lb = document.forms[formname].elements[fieldname + '_lb'].value;
	var kg = roundit(lb * 0.453592);
	document.forms[formname].elements[fieldname + '_kg'].value = kg;
}

function l_to_cuft(formname, fieldname)
{
	var l = document.forms[formname].elements[fieldname + '_l'].value;
	var cuft = roundit( (l * 200 ) * 0.0353083);
	document.forms[formname].elements[fieldname + '_cuft'].value = cuft;
}

function cuft_to_l(formname, fieldname)
{
	var cuft = document.forms[formname].elements[fieldname + '_cuft'].value;
	var l = roundit( (cuft / 0.0353083)/200 );
	document.forms[formname].elements[fieldname + '_l'].value = l;
}

function calcAMV_l(formname)
{
	var verbrauch_bar = document.forms[formname].elements['pressure_start_bar'].value - document.forms[formname].elements['pressure_end_bar'].value;
	var volumen_l			= document.forms[formname].elements['tank_vol_l'].value;
	var tiefe_m				= document.forms[formname].elements['depth_m'].value;
	var zeit_min			= document.forms[formname].elements['divetime'].value;
	if(verbrauch_bar && volumen_l && tiefe_m && zeit_min)
	{
		var udruck = (tiefe_m / 10) + 1;
		var unten  = (udruck * zeit_min); 
		var oben   = (verbrauch_bar * volumen_l);
		var amv    = roundit( oben / unten );
		//alert ("AMV: " + amv);
	}	
	var targetfield = "amv_l";
	document.forms[formname].elements[targetfield].value = amv;
	document.getElementById('show_' + targetfield).style.display = 'block';
	calcAMV_psi(formname);
}


function calcAMV_psi(formname)
{
	//SCR = Surface Consumption rate psi
	//   (psi / bottomtime) * 33ft
	//   ---------------------------
	//        depth (ft) + 33 ft
	
	var verbrauch_psi = document.forms[formname].elements['pressure_start_psi'].value - document.forms[formname].elements['pressure_end_psi'].value;
	//var volumen_l			= document.forms[formname].elements['tank_vol_l'].value;
	var tiefe_ft			= document.forms[formname].elements['depth_ft'].value;
	var zeit_min			= document.forms[formname].elements['divetime'].value;
	if(verbrauch_psi && tiefe_ft && zeit_min)
	{
		var unten = (tiefe_ft + 33);
		var oben  = (verbrauch_psi / zeit_min) * 33;
		var amv_psi = roundit( oben / unten );
		//alert ("AMV PSI: " + amv_psi);
	}	
	var targetfield = "amv_psi";
	document.forms[formname].elements[targetfield].value = amv_psi;
	document.getElementById('show_' + targetfield).style.display = 'block';
}

//l_to_cuft
//bar_to_psi  	faktor 14.50377
//kg_to_lb  2.204623

//m to inch = roundit(m.value/0.0254);
//feet.value = roundit(cm.value/30.48);
//inch.value = roundit(cm.value/2.54);
//m.value = roundit(inch.value*0.0254);
//feet.value=roundit(inch.value/12);
//cm.value=roundit(inch.value*2.54);
//cm.value=roundit(feet.value*30.48);
//inch.value=roundit(feet.value*12);
//m.value=roundit(feet.value*0.3048);

function checkForm()
{
	answer = true;
	if (siw && siw.selectingSomething) answer = false;
	return answer;
}//


//Show Hide (Divelog inputs)
function filter(imagename,objectsrc){
	if (document.images){
		document.images[imagename].src=eval(objectsrc+".src");
	}
}

function ShowHideTest(id) 
{ 
	
	alert(id);
}


function ShowHide(id) 
{ 
	
	imgout=new Image(9,9);
	imgin=new Image(9,9);

	imgout.src="/data/Image/system/u.gif";
	imgin.src="/data/Image/system/d.gif";
	
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == "none"){
			document.getElementById(id).style.display = 'block';
			filter(("img"+id),'imgin');			
		} else {
			filter(("img"+id),'imgout');
			document.getElementById(id).style.display = 'none';			
		}	
	} else { 
		if (document.layers) {	
			if (document.id.display == "none"){
				document.id.display = 'block';
				filter(("img"+id),'imgin');
			} else {
				filter(("img"+id),'imgout');	
				document.id.display = 'none';
			}
		} else {
			if (document.all.id.style.visibility == "none"){
				document.all.id.style.display = 'block';
			} else {
				filter(("img"+id),'imgout');
				document.all.id.style.display = 'none';
			}
		}
	}
}



function diveSites()
{
		var select_entry_text = document.forms['getDiveSites'].elements['select_entry'].value; 
		var resObj = null;
		var ajaxCallStack = new Array();
		var ajaxRequestFile = '/snip/includes/dive_sites.inc.php'
		
		this.selectDiveSite = function()
		{
			//alert("selected Dive Site ID: "+document.forms['getDiveSites'].elements['odin_dive_sites'].value);
			//alert("2: " + document.getElementById('odin_dive_sites').options[document.getElementById('odin_dive_sites').selectedIndex].text);
			document.getElementById('myDiveSiteNameInfo').value = document.getElementById('odin_dive_sites').options[document.getElementById('odin_dive_sites').selectedIndex].text;
			document.getElementById('dive_site_id').value			  = document.forms['getDiveSites'].elements['odin_dive_sites'].value;
			document.getElementById('date-sel2-dd').focus();
		//	document.getElementById('myDiveSiteNameInfo').value = document.getElementById('odin_dive_sites').options[document.getElementById('odin_dive_sites').selectedIndex].text;
		//	if ( IE() ) document.getElementById('myDiveSiteNameInfo').style.display = 'block';
		//	else document.getElementById('myDiveSiteNameInfo').style.display = 'table-row';
		}
		
		this.setCountry = function()
		{
			var form = document.forms['getDiveSites'];
	
			var params = 'command=getRegionList&country=' + form.elements['odin_dive_sites_country_iso3'].value;
			sendAjax(ajaxRequestFile, returnSetCountry, params, true);
		};
		
		this.setCountryPreloaded = function(odin_dive_sites_country_iso3)
		{
			var params = 'command=getRegionList&country=' + odin_dive_sites_country_iso3;
			sendAjax(ajaxRequestFile, returnSetCountry, params, true);
		};
	
		function returnSetCountry()
		{
			if( resObj.readyState != 4 ) return;
			var ajaxResponse = resObj.responseText;
			var regionList = eval('('+ajaxResponse+')');

			var oS = document.forms['getDiveSites'].elements['odin_dive_sites_region'];
			oS.options.length = 0;
			oS.options[0] = new Option(select_entry_text, '', false, false);
		
			for (var i=0; i<regionList.length; ++i) oS.options[i+1] = new Option(regionList[i].long, regionList[i].short, false, false);

			if ( IE() ) document.getElementById('region_list').style.display = 'block';
			else document.getElementById('region_list').style.display = 'table-row';

			document.getElementById('area_list').style.display = 'none';
			document.getElementById('divesite_list').style.display = 'none';
			document.getElementById('country_name').innerHTML  =  document.getElementById('odin_dive_sites_country_iso3').options[document.getElementById('odin_dive_sites_country_iso3').selectedIndex].text;

			//clear Dive Site austosuggest field
			document.getElementById('divesite_misc').value	= '';
			//hide autosuggest result field
			document.getElementById('results').style.display = 'none';
			
			clearAjaxCall();
		}


		this.setRegion = function()
		{
			var form = document.forms['getDiveSites'];
			//alert('region_id: '+form.elements['odin_dive_sites_region'].value);
			var params = 'command=getAreaList&region=' + form.elements['odin_dive_sites_region'].value;
			sendAjax(ajaxRequestFile, returnSetRegion, params, true);
		};

		this.setRegionPreloaded = function(odin_dive_sites_region)
		{
			var params = 'command=getAreaList&region=' + odin_dive_sites_region;
			sendAjax(ajaxRequestFile, returnSetRegion, params, true);
		};


		function returnSetRegion()
		{
			if( resObj.readyState != 4 ) return;
			var ajaxResponse = resObj.responseText;
			var areaList = eval('('+ajaxResponse+')');

			var oS = document.forms['getDiveSites'].elements['odin_dive_sites_area'];
			oS.options.length = 0;
			oS.options[0] = new Option(select_entry_text, '', false, false);
			for (var i=0; i<areaList.length; ++i) oS.options[i+1] = new Option(areaList[i].long, areaList[i].short, false, false);

			if ( IE() ) document.getElementById('area_list').style.display = 'block';
			else document.getElementById('area_list').style.display = 'table-row';
	
			document.getElementById('country_name2').innerHTML = document.getElementById('odin_dive_sites_country_iso3').options[document.getElementById('odin_dive_sites_country_iso3').selectedIndex].text;
			document.getElementById('region_name').innerHTML   = document.getElementById('odin_dive_sites_region').options[document.getElementById('odin_dive_sites_region').selectedIndex].text;

			//now, let's try to get the Dive Sites for the selected values ... 
			//ds.setArea();			
			//we also show the dive site list in case a dive site is not added to a region
			//if ( IE() ) document.getElementById('divesite_list').style.display = 'block';
			//else document.getElementById('divesite_list').style.display = 'table-row';

			clearAjaxCall();
		}

		this.setArea = function()
		{
			var form   = document.forms['getDiveSites'];
			var params = 'command=getDivesiteList&area=' + form.elements['odin_dive_sites_area'].value;
			sendAjax(ajaxRequestFile, returnSetArea, params, true);
		};

		this.setAreaPreloaded = function(odin_dive_sites_area)
		{
			var params = 'command=getDivesiteList&area=' + odin_dive_sites_area;
			sendAjax(ajaxRequestFile, returnSetArea, params, true);
		};
		
		function returnSetArea()
		{
			if( resObj.readyState != 4 ) return;
			var ajaxResponse = resObj.responseText;
			var siteList = eval('('+ajaxResponse+')');
			//alert ("returnSetArea sitelist : " + siteList);
			var oS = document.forms['getDiveSites'].elements['odin_dive_sites'];
			oS.options.length = 0;
			oS.options[0] = new Option(select_entry_text, '', false, false);
			for (var i=0; i<siteList.length; ++i) oS.options[i+1] = new Option(siteList[i].long, siteList[i].short, false, false);

			//var oS = document.forms['getDiveSites'].elements['divesite'];
			//var divesiteString ='';
			
			//if ( IE() ) 
			//{
				document.getElementById('divesite_list').style.display 	 = 'block';
				document.getElementById('addDiveSiteLink').style.display = 'inline';
			//}
			//else 
			//{
			//	document.getElementById('divesite_list').style.display 	 = 'table-row';
			//	document.getElementById('addDiveSiteLink').style.display = 'inline';				
			//}
			
			
			document.getElementById('country_name3').innerHTML 	= document.getElementById('odin_dive_sites_country_iso3').options[document.getElementById('odin_dive_sites_country_iso3').selectedIndex].text;
			document.getElementById('region_name2').innerHTML   = document.getElementById('odin_dive_sites_region').options[document.getElementById('odin_dive_sites_region').selectedIndex].text;
			document.getElementById('area_name').innerHTML   		= document.getElementById('odin_dive_sites_area').options[document.getElementById('odin_dive_sites_area').selectedIndex].text;

			//if ( document.getElementById("wickStatus") ) document.getElementById("wickStatus").innerHTML = 'Loaded <b>' + wk.collection.length + '</b> entries <br><span style=" font-size:9px;">' + wk.collection +'</span>';
			//if ( document.getElementById("wickStatus") ) { alert('Loaded ' + wk.collection.length + ' Dive Sites: \n' + wk.collection +''); document.getElementById("wickStatus").innerHTML =''; }
			//document.getElementById('divesite').value ='';
			clearAjaxCall();
		}

		this.showPreloads = function(country, region, area, site)
		{
			//make fields visible
			if ( IE() ) 
			{
				document.getElementById('region_list').style.display 		= 'block';
				document.getElementById('area_list').style.display 			= 'block';
				document.getElementById('divesite_list').style.display 	= 'block';
			}
			else 
			{
				document.getElementById('region_list').style.display 	 	= 'table-row';
				document.getElementById('area_list').style.display 			= 'table-row';				
				document.getElementById('divesite_list').style.display 	= 'table-row';
			}
			//select Values:
		 //ChangeSelectByValue(ddlID, value, change) 
			this.setCountryPreloaded(country); 
			//Area

			this.setRegionPreloaded(region);
			//alert("Area: " + area);
			//Dive Site
			this.setAreaPreloaded(area);
			//alert("Site: " + site);
			
		}

		this.setPreloads = function(country, region, area, site)
		{
			//ChangeSelectByValue('odin_dive_sites_country_iso3', country);			
			alert("Preselecting Dive Site");
			ChangeSelectByValue('odin_dive_sites_region', region);			
			ChangeSelectByValue('odin_dive_sites_area', area);			
			ChangeSelectByValue('odin_dive_sites', site);	
			document.getElementById('myDiveSiteNameInfo').value = document.getElementById('odin_dive_sites').options[document.getElementById('odin_dive_sites').selectedIndex].text;
			document.getElementById('dive_site_id').value			  = document.forms['getDiveSites'].elements['odin_dive_sites'].value;
		}

		this.getRegionSites = function()
		{
			var form = document.forms['getDiveSites'];
			//alert('hier samma:getRegionSites region=' + form.elements['odin_dive_sites_region'].value);
			var params = 'command=getDivesiteListRegion&region=' + form.elements['odin_dive_sites_region'].value;
			sendAjax(ajaxRequestFile, returngetRegionSites, params, true);
		};

		function returngetRegionSites()
		{
			if( resObj.readyState != 4 ) return;
			var ajaxResponse = resObj.responseText;
			var siteList = eval('('+ajaxResponse+')');

			var oS = document.forms['getDiveSites'].elements['odin_dive_sites'];
			oS.options.length = 0;
			oS.options[0] = new Option(select_entry_text, '', false, false);
			for (var i=0; i<siteList.length; ++i) oS.options[i+1] = new Option(siteList[i].long, siteList[i].short, false, false);

			//var oS = document.forms['getDiveSites'].elements['divesite'];
			//var divesiteString ='';
			
			if ( IE() ) document.getElementById('divesite_list').style.display = 'block';
			else document.getElementById('divesite_list').style.display = 'table-row';
			clearAjaxCall();
		}
		
		this.getCountrySites = function()
		{
			var form = document.forms['getDiveSites'];
			//alert('hier samma: getCountrySites country =' + form.elements['odin_dive_sites_country_iso3'].value);
			var params = 'command=getDivesiteListCountry&country=' + form.elements['odin_dive_sites_country_iso3'].value;
			sendAjax(ajaxRequestFile, returngetCountrySites, params, true);
		};

		function returngetCountrySites()
		{
			if( resObj.readyState != 4 ) return;
			var ajaxResponse = resObj.responseText;
			var siteList = eval('('+ajaxResponse+')');
			//alert ("returngetCountrySites sitelist : " + siteList);
			var oS = document.forms['getDiveSites'].elements['odin_dive_sites'];
			oS.options.length = 0;
			oS.options[0] = new Option(select_entry_text, '', false, false);
			for (var i=0; i<siteList.length; ++i) oS.options[i+1] = new Option(siteList[i].long, siteList[i].short, false, false);

			//var oS = document.forms['getDiveSites'].elements['divesite'];
			//var divesiteString ='';
			
			//Anzeige vom Feld Dive Site Drop Down
			//if ( IE() ) document.getElementById('divesite_list').style.display = 'block';
			//else document.getElementById('divesite_list').style.display = 'table-row';
		
			clearAjaxCall();
		}

		function sendAjax(ajaxRequestFile, returnFunction, params, async)
		{
			var callString = "sendAjaxNow('"+ajaxRequestFile+"', "+String(returnFunction)+", '"+params+"', "+async+")";
			if ( !resObj ) sendAjaxNow(ajaxRequestFile, returnFunction, params, async);
			else ajaxCallStack.push(callString);
		}

		//ACHTUNG: Nachfolgende Funktionen sind auch in der AJA dive_sites.inc.php nochmals mit drinnen!!!
		function newDiveSiteRegion(country)
		{
			window.open('/code/process/divesite_new_item.php?&country='+country, 'Dive Sites', 'top=200,left=100,width=400,height=250,menubar=no,toolbar=no,location=no,dependent=yes' );
		}

		function newDiveSiteArea(country, region)
		{
			window.open('/code/process/divesite_new_item.php?&country='+country+'&region='+region, 'Dive Sites', 'top=200,left=100,width=400,height=250,menubar=no,toolbar=no,location=no,dependent=yes' );
		}

		function newDiveSiteSite(country, region, area)
		{
			window.open('/code/process/divesite_new_item.php?&country='+country+'&region='+region+'&area='+area, 'Dive Sites', 'top=200,left=100,width=400,height=250,menubar=no,toolbar=no,location=no,dependent=yes' );
		}


		function sendAjaxNow(ajaxRequestFile, returnFunction, params, async)
		{
			if ( resObj ) return;
			document.getElementsByTagName('body')[0].style.cursor = 'wait';

			//if( IE() ) resObj = new ActiveXObject("MSXML2.XMLHTTP");
			//else  resObj = new XMLHttpRequest();

			/*@cc_on @if (@_win32 && @_jscript_version >= 5) if (!window.XMLHttpRequest)
			window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
			@end @*/
			resObj = new XMLHttpRequest(); 

			resObj.open('post', ajaxRequestFile, true);
			resObj.onreadystatechange = returnFunction;
			resObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			resObj.setRequestHeader("Content-length", params.length);
			resObj.setRequestHeader("Connection", "close");
			resObj.send(params);
			//alert(params);
		}

		function clearAjaxCall()
		{
			resObj = null;
			if ( ajaxCallStack.length > 0 )     eval(ajaxCallStack.shift());
			else if ( document )    document.getElementsByTagName('body')[0].style.cursor = 'auto';
		}

}


//****************************
//log.js --> end
//****************************


//****************************
//gear.js --> start
//****************************

function gear()
{

	var resObj;
	var ajaxRequestFile = '/code/process/gear.request.php';

	//if( IE() ) 	{ 		resObj = new ActiveXObject("MSXML2.XMLHTTP"); 	}
	//else { 		resObj = new XMLHttpRequest(); 	}
	//http://design-noir.de/webdev/JS/XMLHttpRequest-IE/
	/*@cc_on @if (@_win32 && @_jscript_version >= 5) if (!window.XMLHttpRequest)
	window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
	@end @*/
	resObj = new XMLHttpRequest(); 	


	// Formular fuer bestimmte Kategorie anzeigen
	this.showCategoryForm = function()
	{
		var params = '&command=show_form&category=' + encodeURIComponent(document.forms['categorySelection'].elements['mainCat'].value);
		resObj.open('post', ajaxRequestFile,true);  
		
		resObj.onreadystatechange = returnShowCategoryForm;
		resObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		resObj.setRequestHeader("Content-length", params.length);
		resObj.setRequestHeader("Connection", "close");
		resObj.send(params);
	}
	var returnShowCategoryForm = function()
	{
		if( resObj.readyState != 4 ) return;
		var ajaxResponse = resObj.responseText;
		var response = ajaxResponse.split('|&|');

		if ( response == 'no diver id' )
		{
			alert('Please login as Diver or Dive Leader');
			return;
		}
		
		document.getElementById('gear_edit').innerHTML = response;
		evalScript(resObj.responseText);
		datePickerController.create();
		document.getElementById('gear_edit').title = 'Add'
		document.getElementById('gear_edit').style.display = 'block';

	}

	// Formular fuer bestimmte Kategorie mit Inhalt anzeigen
	this.editItem = function(odin_user_gear_id)
	{
		//alert('EDIT ' + odin_user_gear_id);
		var params = '&command=edit_item&edit_item_id=' + odin_user_gear_id;
		resObj.open('post', ajaxRequestFile,true);  
		
		resObj.onreadystatechange = returnEditItem;
		resObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		resObj.setRequestHeader("Content-length", params.length);
		resObj.setRequestHeader("Connection", "close");
		resObj.send(params);
	}
	var returnEditItem = function()
	{
		if( resObj.readyState != 4 ) return;
		var ajaxResponse = resObj.responseText;
		var response = ajaxResponse.split('|&|');

		if ( response == 'no diver id' )
		{
			alert('Please login as Diver or Dive Leader');
			return;
		}

		//document.getElementById('categorySelection').style.display = 'none';

		document.getElementById('gear_edit').innerHTML = response;
		evalScript(resObj.responseText);
		datePickerController.create();
		document.getElementById('gear_edit').title = 'Update'
		document.getElementById('gear_edit').style.display = 'block';
	}
	
	
	// Formular fuer bestimmte Kategorie mit Inhalt anzeigen
	this.deleteItem = function(odin_user_gear_id)
	{
		
		if ( !confirm('Do you really want to delete this item?') ) return;

		var params = '&delete_item_id=' + odin_user_gear_id + '&command=delete_item';
		resObj.open('post', ajaxRequestFile,true);  
		
		resObj.onreadystatechange = returnDeleteItem;
		resObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		resObj.setRequestHeader("Content-length", params.length);
		resObj.setRequestHeader("Connection", "close");
		resObj.send(params);
	}
	
	var returnDeleteItem = function()
	{
		if( resObj.readyState != 4 ) return;
		var ajaxResponse = resObj.responseText;
		var response = ajaxResponse.split('|&|');

		if ( response == 'no item id' )
		{
			alert('Please select Item you want to Delete first');
			return;
		}

		window.location.replace('/myequipment');
		//document.getElementById('categorySelection').style.display = 'none';
	}

	// Speichern des Formularinhalts
	this.saveItem = function ()
	{
		var oE = document.forms['gear_edit'];

		if ( this.checkUploadFile('gear_edit') )
		{
			oE.action = '/code/process/gear.request.php';
			oE.submit();
		}
		else
		{
				alert('Please use only standard Characters in Picture File Name');
		}

	}


	this.deletePicture= function(odin_user_gear_id, odin_user_master_id)
	{

		if ( !confirm('Do you really want to delete this Picture? ID:(' + odin_user_gear_id + '|' + odin_user_master_id + ')' ) ) return;

		var params = '&command=delete_picture' + '&odin_user_gear_id=' + odin_user_gear_id+ '&odin_user_master_id=' + odin_user_master_id;
		resObj.open('post', ajaxRequestFile,true);  
		
		resObj.onreadystatechange = returnDeletePicture;
		resObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		resObj.setRequestHeader("Content-length", params.length);
		resObj.setRequestHeader("Connection", "close");
		resObj.send(params);
	}
	var returnDeletePicture = function()
	{
		if( resObj.readyState != 4 ) return;
		var response = resObj.responseText;
	
		if ( response == 'no item id' )
		{
			alert('Please select Item you want to Delete first');
			return;
		}
		document.getElementById('picture').innerHTML = "";
	}

	this.checkUploadFile = function(formName)
	{
	
		var oF = document.forms[formName];
		if ( !oF.elements['picture'].value ) return true;
	
		var Path = oF.elements['picture'].value.split('\\');
		if ( Path.length < 2 ) Path = oF.elements['picture'].value.split('/');
		if ( Path.length < 2 ) Path = oF.elements['picture'].value.split(',');
		var FileName = Path[Path.length-1].split('.');
		if ( FileName.length < 2 ) return false;
	
		var type_test_name = Path[Path.length-1].replace(/\s/g, "_");
	
		var Ext =FileName[FileName.length-1].toLowerCase();
		if ( (Ext!='jpg') && (Ext!='jpeg') && (Ext!='png') && (Ext!='gif') && (Ext!='pdf') ) return false;

		return true;
	
	}

}

//*****************************
//GEAR.js	--> end
//****************************/

//*****************************
///thickbox-compressed.js
//****************************/
  /*
 * Thickbox 3 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "/data/Image/system/2010/loadingAnimation.gif";

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(o).2S(9(){1u(\'a.18, 3n.18, 3i.18\');1w=1p 1t();1w.L=2H});9 1u(b){$(b).s(9(){6 t=X.Q||X.1v||M;6 a=X.u||X.23;6 g=X.1N||P;19(t,a,g);X.2E();H P})}9 19(d,f,g){3m{3(2t o.v.J.2i==="2g"){$("v","11").r({A:"28%",z:"28%"});$("11").r("22","2Z");3(o.1Y("1F")===M){$("v").q("<U 5=\'1F\'></U><4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}n{3(o.1Y("B")===M){$("v").q("<4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}3(1K()){$("#B").1J("2B")}n{$("#B").1J("2z")}3(d===M){d=""}$("v").q("<4 5=\'K\'><1I L=\'"+1w.L+"\' /></4>");$(\'#K\').2y();6 h;3(f.O("?")!==-1){h=f.3l(0,f.O("?"))}n{h=f}6 i=/\\.2s$|\\.2q$|\\.2m$|\\.2l$|\\.2k$/;6 j=h.1C().2h(i);3(j==\'.2s\'||j==\'.2q\'||j==\'.2m\'||j==\'.2l\'||j==\'.2k\'){1D="";1G="";14="";1z="";1x="";R="";1n="";1r=P;3(g){E=$("a[@1N="+g+"]").36();25(D=0;((D<E.1c)&&(R===""));D++){6 k=E[D].u.1C().2h(i);3(!(E[D].u==f)){3(1r){1z=E[D].Q;1x=E[D].u;R="<1e 5=\'1X\'>&1d;&1d;<a u=\'#\'>2T &2R;</a></1e>"}n{1D=E[D].Q;1G=E[D].u;14="<1e 5=\'1U\'>&1d;&1d;<a u=\'#\'>&2O; 2N</a></1e>"}}n{1r=1b;1n="1t "+(D+1)+" 2L "+(E.1c)}}}S=1p 1t();S.1g=9(){S.1g=M;6 a=2x();6 x=a[0]-1M;6 y=a[1]-1M;6 b=S.z;6 c=S.A;3(b>x){c=c*(x/b);b=x;3(c>y){b=b*(y/c);c=y}}n 3(c>y){b=b*(y/c);c=y;3(b>x){c=c*(x/b);b=x}}13=b+30;1a=c+2G;$("#8").q("<a u=\'\' 5=\'1L\' Q=\'1o\'><1I 5=\'2F\' L=\'"+f+"\' z=\'"+b+"\' A=\'"+c+"\' 23=\'"+d+"\'/></a>"+"<4 5=\'2D\'>"+d+"<4 5=\'2C\'>"+1n+14+R+"</4></4><4 5=\'2A\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4>");$("#Z").s(G);3(!(14==="")){9 12(){3($(o).N("s",12)){$(o).N("s",12)}$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1D,1G,g);H P}$("#1U").s(12)}3(!(R==="")){9 1i(){$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1z,1x,g);H P}$("#1X").s(1i)}o.1h=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}n 3(I==3k){3(!(R=="")){o.1h="";1i()}}n 3(I==3j){3(!(14=="")){o.1h="";12()}}};16();$("#K").C();$("#1L").s(G);$("#8").r({Y:"T"})};S.L=f}n{6 l=f.2r(/^[^\\?]+\\??/,\'\');6 m=2p(l);13=(m[\'z\']*1)+30||3h;1a=(m[\'A\']*1)+3g||3f;W=13-30;V=1a-3e;3(f.O(\'2j\')!=-1){1E=f.1B(\'3d\');$("#15").C();3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4></4><U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\' > </U>")}n{$("#B").N();$("#8").q("<U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\'> </U>")}}n{3($("#8").r("Y")!="T"){3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\'>1l</a> 1k 1j 1s</4></4><4 5=\'F\' J=\'z:"+W+"p;A:"+V+"p\'></4>")}n{$("#B").N();$("#8").q("<4 5=\'F\' 3c=\'3b\' J=\'z:"+W+"p;A:"+V+"p;\'></4>")}}n{$("#F")[0].J.z=W+"p";$("#F")[0].J.A=V+"p";$("#F")[0].3a=0;$("#1H").11(d)}}$("#Z").s(G);3(f.O(\'37\')!=-1){$("#F").q($(\'#\'+m[\'26\']).1T());$("#8").24(9(){$(\'#\'+m[\'26\']).q($("#F").1T())});16();$("#K").C();$("#8").r({Y:"T"})}n 3(f.O(\'2j\')!=-1){16();3($.1q.35){$("#K").C();$("#8").r({Y:"T"})}}n{$("#F").34(f+="&1y="+(1p 33().32()),9(){16();$("#K").C();1u("#F a.18");$("#8").r({Y:"T"})})}}3(!m[\'1A\']){o.21=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}}}}31(e){}}9 1m(){$("#K").C();$("#8").r({Y:"T"})}9 G(){$("#2Y").N("s");$("#Z").N("s");$("#8").2X("2W",9(){$(\'#8,#B,#1F\').2V("24").N().C()});$("#K").C();3(2t o.v.J.2i=="2g"){$("v","11").r({A:"1Z",z:"1Z"});$("11").r("22","")}o.1h="";o.21="";H P}9 16(){$("#8").r({2U:\'-\'+20((13/2),10)+\'p\',z:13+\'p\'});3(!(1V.1q.2Q&&1V.1q.2P<7)){$("#8").r({38:\'-\'+20((1a/2),10)+\'p\'})}}9 2p(a){6 b={};3(!a){H b}6 c=a.1B(/[;&]/);25(6 i=0;i<c.1c;i++){6 d=c[i].1B(\'=\');3(!d||d.1c!=2){39}6 e=2a(d[0]);6 f=2a(d[1]);f=f.2r(/\\+/g,\' \');b[e]=f}H b}9 2x(){6 a=o.2M;6 w=1S.2o||1R.2o||(a&&a.1Q)||o.v.1Q;6 h=1S.1P||1R.1P||(a&&a.2n)||o.v.2n;1O=[w,h];H 1O}9 1K(){6 a=2K.2J.1C();3(a.O(\'2I\')!=-1&&a.O(\'3o\')!=-1){H 1b}}',62,211,'|||if|div|id|var||TB_window|function||||||||||||||else|document|px|append|css|click||href|body||||width|height|TB_overlay|remove|TB_Counter|TB_TempArray|TB_ajaxContent|tb_remove|return|keycode|style|TB_load|src|null|unbind|indexOf|false|title|TB_NextHTML|imgPreloader|block|iframe|ajaxContentH|ajaxContentW|this|display|TB_closeWindowButton||html|goPrev|TB_WIDTH|TB_PrevHTML|TB_iframeContent|tb_position||thickbox|tb_show|TB_HEIGHT|true|length|nbsp|span|Math|onload|onkeydown|goNext|Esc|or|close|tb_showIframe|TB_imageCount|Close|new|browser|TB_FoundURL|Key|Image|tb_init|name|imgLoader|TB_NextURL|random|TB_NextCaption|modal|split|toLowerCase|TB_PrevCaption|urlNoQuery|TB_HideSelect|TB_PrevURL|TB_ajaxWindowTitle|img|addClass|tb_detectMacXFF|TB_ImageOff|150|rel|arrayPageSize|innerHeight|clientWidth|self|window|children|TB_prev|jQuery|frameborder|TB_next|getElementById|auto|parseInt|onkeyup|overflow|alt|unload|for|inlineId||100||unescape|1000|round|hspace|TB_closeAjaxWindow|TB_title|undefined|match|maxHeight|TB_iframe|bmp|gif|png|clientHeight|innerWidth|tb_parseQuery|jpeg|replace|jpg|typeof|which|keyCode|event|tb_getPageSize|show|TB_overlayBG|TB_closeWindow|TB_overlayMacFFBGHack|TB_secondLine|TB_caption|blur|TB_Image|60|tb_pathToImage|mac|userAgent|navigator|of|documentElement|Prev|lt|version|msie|gt|ready|Next|marginLeft|trigger|fast|fadeOut|TB_imageOff|hidden||catch|getTime|Date|load|safari|get|TB_inline|marginTop|continue|scrollTop|TB_modal|class|TB_|45|440|40|630|input|188|190|substr|try|area|firefox'.split('|'),0,{}))

//*****************************
///thickbox-compressed.js ==> end
//****************************/



//*************************************
///code/date-picker/datepicker.js START
//***********************************/

/*
        DatePicker v4.4 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency-decoder in any derivative work - thanks.
        
        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/
var datePickerController;

(function() {

// Detect the browser language
datePicker.languageinfo = navigator.language ? navigator.language : navigator.userLanguage;
datePicker.languageinfo = datePicker.languageinfo ? datePicker.languageinfo.toLowerCase().replace(/-[a-z]+$/, "") : 'en';

// Load the appropriate language file
var scriptFiles = document.getElementsByTagName('head')[0].getElementsByTagName('script');
var loc = scriptFiles[scriptFiles.length - 1].src.substr(0, scriptFiles[scriptFiles.length - 1].src.lastIndexOf("/")) + "/code/js/date-picker/lang/" + datePicker.languageinfo + ".js";

var loc = "/code/js/date-picker/lang/" + datePicker.languageinfo + ".js";

var script  = document.createElement('script');
script.type = "text/javascript";
script.src  = loc;
script.setAttribute("charset", "utf-8");
/*@cc_on
/*@if(@_win32)
        var bases = document.getElementsByTagName('base');
        if (bases.length && bases[0].childNodes.length) {
                bases[0].appendChild(script);
        } else {
                document.getElementsByTagName('head')[0].appendChild(script);
        };
@else @*/
document.getElementsByTagName('head')[0].appendChild(script);
/*@end
@*/
script  = null;

// Defaults should the locale file not load
datePicker.months       = ["January","February","March","April","May","June","July","August","September","October","November","December"];
datePicker.fullDay      = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
datePicker.titles       = ["Previous month","Next month","Previous year","Next year", "Today", "Show Calendar"];

datePicker.getDaysPerMonth = function(nMonth, nYear) {
        nMonth = (nMonth + 12) % 12;
        return (((0 == (nYear%4)) && ((0 != (nYear%100)) || (0 == (nYear%400)))) && nMonth == 1) ? 29: [31,28,31,30,31,30,31,31,30,31,30,31][nMonth];
};

function datePicker(options) {

        this.defaults          = {};
        for(opt in options) { this[opt] = this.defaults[opt] = options[opt]; };
        
        this.date              = new Date();
        this.yearinc           = 1;
        this.timer             = null;
        this.pause             = 1000;
        this.timerSet          = false;
        this.fadeTimer         = null;
        this.interval          = new Date();
        this.firstDayOfWeek    = this.defaults.firstDayOfWeek = this.dayInc = this.monthInc = this.yearInc = this.opacity = this.opacityTo = 0;
        this.dateSet           = null;
        this.visible           = false;
        this.disabledDates     = [];
        this.enabledDates      = [];
        this.nbsp              = String.fromCharCode( 160 );
        var o = this;

        o.events = {
                onblur:function(e) {
                        o.removeKeyboardEvents();
                },
                onfocus:function(e) {
                        o.addKeyboardEvents();
                },
                onkeydown: function (e) {
                        o.stopTimer();
                        if(!o.visible) return false;

                        if(e == null) e = document.parentWindow.event;
                        var kc = e.keyCode ? e.keyCode : e.charCode;

                        if( kc == 13 ) {
                                // close (return)
                                var td = document.getElementById(o.id + "-date-picker-hover");
                                if(!td || td.className.search(/out-of-range|day-disabled/) != -1) return o.killEvent(e);
                                o.returnFormattedDate();
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 27) {
                                // close (esc)
                                o.hide();
                                return o.killEvent(e);
                        } else if(kc == 32 || kc == 0) {
                                // today (space)
                                o.date =  new Date();
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        // Internet Explorer fires the keydown event faster than the JavaScript engine can
                        // update the interface. The following attempts to fix this.
                        /*@cc_on
                        @if(@_win32)
                                if(new Date().getTime() - o.interval.getTime() < 100) return o.killEvent(e);
                                o.interval = new Date();
                        @end
                        @*/

                        if ((kc > 49 && kc < 56) || (kc > 97 && kc < 104)) {
                                if (kc > 96) kc -= (96-48);
                                kc -= 49;
                                o.firstDayOfWeek = (o.firstDayOfWeek + kc) % 7;
                                o.updateTable();
                                return o.killEvent(e);
                        };

                        if ( kc < 37 || kc > 40 ) return true;

                        var d = new Date( o.date ).valueOf();

                        if ( kc == 37 ) {
                                // ctrl + left = previous month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() - 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 1 );
                                };
                        } else if ( kc == 39 ) {
                                // ctrl + right = next month
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth() + 1,d.getFullYear())) );
                                        d.setMonth( d.getMonth() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 1 );
                                };
                        } else if ( kc == 38 ) {
                                // ctrl + up = next year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() + 1)) );
                                        d.setFullYear( d.getFullYear() + 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 7 );
                                };
                        } else if ( kc == 40 ) {
                                // ctrl + down = prev year
                                if( e.ctrlKey ) {
                                        d = new Date( o.date );
                                        d.setDate( Math.min(d.getDate(), datePicker.getDaysPerMonth(d.getMonth(),d.getFullYear() - 1)) );
                                        d.setFullYear( d.getFullYear() - 1 );
                                } else {
                                        d = new Date( o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 7 );
                                };
                        };

                        var tmpDate = new Date(d);

                        if(o.outOfRange(tmpDate)) return o.killEvent(e);
                        
                        var cacheDate = new Date(o.date);
                        o.date = tmpDate;

                        if(cacheDate.getFullYear() != o.date.getFullYear() || cacheDate.getMonth() != o.date.getMonth()) o.updateTable();
                        else {
                                o.disableTodayButton();
                                var tds = o.table.getElementsByTagName('td');
                                var txt;
                                var start = o.date.getDate() - 6;
                                if(start < 0) start = 0;

                                for(var i = start, td; td = tds[i]; i++) {
                                        txt = Number(td.firstChild.nodeValue);
                                        if(isNaN(txt) || txt != o.date.getDate()) continue;
                                        o.removeHighlight();
                                        td.id = o.id + "-date-picker-hover";
                                        td.className = td.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                                };
                        };
                        return o.killEvent(e);
                },
                gotoToday: function(e) {
                        o.date = new Date();
                        o.updateTable();
                        return o.killEvent(e);
                },
                onmousedown: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        var found = false;
                        while(el.parentNode) {
                                if(el.id && (el.id == "fd-"+o.id || el.id == "fd-but-"+o.id)) {
                                        found = true;
                                        break;
                                };
                                try {
                                        el = el.parentNode;
                                } catch(err) {
                                        break;
                                };
                        };
                        if(found) return true;
                        o.stopTimer();
                        datePickerController.hideAll();
                },
                onmouseover: function(e) {
                        o.stopTimer();
                        var txt = this.firstChild.nodeValue;
                        if(this.className == "out-of-range" || txt.search(/^[\d]+$/) == -1) return;
                        
                        o.removeHighlight();
                        
                        this.id = o.id+"-date-picker-hover";
                        this.className = this.className.replace(/date-picker-hover/g, "") + " date-picker-hover";
                        
                        o.date.setDate(this.firstChild.nodeValue);
                        o.disableTodayButton();
                },
                onclick: function(e) {
                        if(o.opacity != o.opacityTo || this.className.search(/out-of-range|day-disabled/) != -1) return false;
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;
                        while ( el.nodeType != 1 ) el = el.parentNode;
                        var d = new Date( o.date );
                        var txt = el.firstChild.data;
                        if(txt.search(/^[\d]+$/) == -1) return;
                        var n = Number( txt );
                        if(isNaN(n)) { return true; };
                        d.setDate( n );
                        o.date = d;
                        o.returnFormattedDate();
                        if(!o.staticPos) o.hide();
                        o.stopTimer();
                        return o.killEvent(e);
                },
                incDec: function(e) {
                        if ( e == null ) e = document.parentWindow.event;
                        var el = e.target != null ? e.target : e.srcElement;

                        if(el && el.className && el.className.search('fd-disabled') != -1) { return false; }
                        datePickerController.addEvent(document, "mouseup", o.events.clearTimer);
                        o.timerInc      = 800;
                        o.dayInc        = arguments[1];
                        o.yearInc       = arguments[2];
                        o.monthInc      = arguments[3];
                        o.timerSet      = true;

                        o.updateTable();
                        return true;
                },
                clearTimer: function(e) {
                        o.stopTimer();
                        o.timerInc      = 1000;
                        o.yearInc       = 0;
                        o.monthInc      = 0;
                        o.dayInc        = 0;
                        datePickerController.removeEvent(document, "mouseup", o.events.clearTimer);
                }
        };
        o.stopTimer = function() {
                o.timerSet = false;
                window.clearTimeout(o.timer);
        };
        o.removeHighlight = function() {
                if(document.getElementById(o.id+"-date-picker-hover")) {
                        document.getElementById(o.id+"-date-picker-hover").className = document.getElementById(o.id+"-date-picker-hover").className.replace("date-picker-hover", "");
                        document.getElementById(o.id+"-date-picker-hover").id = "";
                };
        };
        o.reset = function() {
                for(def in o.defaults) { o[def] = o.defaults[def]; };
        };
        o.setOpacity = function(op) {
                o.div.style.opacity = op/100;
                o.div.style.filter = 'alpha(opacity=' + op + ')';
                o.opacity = op;
        };
        o.fade = function() {
                window.clearTimeout(o.fadeTimer);
                o.fadeTimer = null;
                delete(o.fadeTimer);
                
                var diff = Math.round(o.opacity + ((o.opacityTo - o.opacity) / 4));

                o.setOpacity(diff);

                if(Math.abs(o.opacityTo - diff) > 3 && !o.noTransparency) {
                        o.fadeTimer = window.setTimeout(o.fade, 50);
                } else {
                        o.setOpacity(o.opacityTo);
                        if(o.opacityTo == 0) {
                                o.div.style.display = "none";
                                o.visible = false;
                        } else {
                                o.visible = true;
                        };
                };
        };
        o.killEvent = function(e) {
                e = e || document.parentWindow.event;
                
                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };
                
                /*@cc_on
                @if(@_win32)
                e.cancelBubble = true;
                e.returnValue = false;
                @end
                @*/
                return false;
        };
        o.getElem = function() {
                return document.getElementById(o.id.replace(/^fd-/, '')) || false;
        };
        o.setRangeLow = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.low = o.defaults.low = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setRangeHigh = function(range) {
                if(String(range).search(/^(\d\d?\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/) == -1) range = '';
                o.high = o.defaults.high = range;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDays = function(dayArray) {
                o.disableDays = o.defaults.disableDays = dayArray;
                if(o.staticPos) o.updateTable(true);
        };
        o.setDisabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01])$/) != -1) fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = fin;
                        o.enabledDates = [];
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.setEnabledDates = function(dateArray) {
                var fin = [];
                for(var i = dateArray.length; i-- ;) {
                        if(dateArray[i].match(/^(\d\d\d\d|\*\*\*\*)(0[1-9]|1[012]|\*\*)(0[1-9]|[12][0-9]|3[01]|\*\*)$/) != -1 && dateArray[i] != "********") fin[fin.length] = dateArray[i];
                };
                if(fin.length) {
                        o.disabledDates = [];
                        o.enabledDates = fin;
                        if(o.staticPos) o.updateTable(true);
                };
        };
        o.getDisabledDates = function(y, m) {
                if(o.enabledDates.length) return o.getEnabledDates(y, m);
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                for(var i = o.disabledDates.length; i-- ;) {
                        var tmp = o.disabledDates[i].replace("****", y).replace("**", m);
                        if(tmp < Number(String(y)+m+"01") || tmp > Number(y+String(m)+d)) continue;
                        obj[tmp] = 1;
                };
                return obj;
        };
        o.getEnabledDates = function(y, m) {
                var obj = {};
                var d = datePicker.getDaysPerMonth(m - 1, y);
                m = m < 10 ? "0" + String(m) : m;
                var day,tmp,de,me,ye,disabled;
                for(var dd = 1; dd <= d; dd++) {
                        day = dd < 10 ? "0" + String(dd) : dd;
                        disabled = true;
                        for(var i = o.enabledDates.length; i-- ;) {
                                tmp = o.enabledDates[i];
                                ye  = String(o.enabledDates[i]).substr(0,4);
                                me  = String(o.enabledDates[i]).substr(4,2);
                                de  = String(o.enabledDates[i]).substr(6,2);

                                if(ye == y && me == m && de == day) {
                                        disabled = false;
                                        break;
                                }
                                
                                if(ye == "****" || me == "**" || de == "**") {
                                        if(ye == "****") tmp = tmp.replace(/^\*\*\*\*/, y);
                                        if(me == "**")   tmp = tmp = tmp.substr(0,4) + String(m) + tmp.substr(6,2);
                                        if(de == "**")   tmp = tmp.replace(/\*\*/, day);

                                        if(tmp == String(y + String(m) + day)) {
                                                disabled = false;
                                                break;
                                        };
                                };
                        };
                        if(disabled) obj[String(y + String(m) + day)] = 1;
                };
                return obj;
        };
        o.setFirstDayOfWeek = function(e) {
                if ( e == null ) e = document.parentWindow.event;
                var elem = e.target != null ? e.target : e.srcElement;
                if(elem.tagName.toLowerCase() != "th") {
                        while(elem.tagName.toLowerCase() != "th") elem = elem.parentNode;
                };
                var cnt = 0;
                while(elem.previousSibling) {
                        elem = elem.previousSibling;
                        if(elem.tagName.toLowerCase() == "th") cnt++;
                };
                o.firstDayOfWeek = (o.firstDayOfWeek + cnt) % 7;
                o.updateTableHeaders();
                return o.killEvent(e);
        };
        o.truePosition = function(element) {
                var pos = o.cumulativeOffset(element);
                if(window.opera) { return pos; }
                var iebody      = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
                var dsocleft    = document.all ? iebody.scrollLeft : window.pageXOffset;
                var dsoctop     = document.all ? iebody.scrollTop  : window.pageYOffset;
                var posReal     = o.realOffset(element);
                return [pos[0] - posReal[0] + dsocleft, pos[1] - posReal[1] + dsoctop];
        };
        o.realOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.scrollTop  || 0;
                        l += element.scrollLeft || 0;
                        element = element.parentNode;
                } while (element);
                return [l, t];
        };
        o.cumulativeOffset = function(element) {
                var t = 0, l = 0;
                do {
                        t += element.offsetTop  || 0;
                        l += element.offsetLeft || 0;
                        element = element.offsetParent;
                } while (element);
                return [l, t];
        };
        o.resize = function() {
                if(!o.created || !o.getElem()) return;
                
                o.div.style.visibility = "hidden";
                if(!o.staticPos) { o.div.style.left = o.div.style.top = "0px"; }
                o.div.style.display = "block";
                
                var osh = o.div.offsetHeight;
                var osw = o.div.offsetWidth;
                
                o.div.style.visibility = "visible";
                o.div.style.display = "none";
                
                if(!o.staticPos) {
                        var elem          = document.getElementById('fd-but-' + o.id);
                        var pos           = o.truePosition(elem);
                        var trueBody      = (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body;
                        var scrollTop     = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollTop;
                        var scrollLeft    = window.devicePixelRatio || window.opera ? 0 : trueBody.scrollLeft;

                        if(parseInt(trueBody.clientWidth+scrollLeft) < parseInt(osw+pos[0])) {
                                o.div.style.left = Math.abs(parseInt((trueBody.clientWidth+scrollLeft) - osw)) + "px";
                        } else {
                                o.div.style.left  = pos[0] + "px";
                        };

                        if(parseInt(trueBody.clientHeight+scrollTop) < parseInt(osh+pos[1]+elem.offsetHeight+2)) {
                                o.div.style.top   = Math.abs(parseInt(pos[1] - (osh + 2))) + "px";
                        } else {
                                o.div.style.top   = Math.abs(parseInt(pos[1] + elem.offsetHeight + 2)) + "px";
                        };
                };
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(o.staticPos) return;
                o.iePopUp.style.top    = o.div.style.top;
                o.iePopUp.style.left   = o.div.style.left;
                o.iePopUp.style.width  = osw + "px";
                o.iePopUp.style.height = (osh - 2) + "px";
                @end
                @*/
        };
        o.equaliseDates = function() {
                var clearDayFound = false;
                var tmpDate;
                for(var i = o.low; i <= o.high; i++) {
                        tmpDate = String(i);
                        if(!o.disableDays[new Date(tmpDate.substr(0,4), tmpDate.substr(6,2), tmpDate.substr(4,2)).getDay() - 1]) {
                                clearDayFound = true;
                                break;
                        };
                };
                if(!clearDayFound) o.disableDays = o.defaults.disableDays = [0,0,0,0,0,0,0];
        };
        o.outOfRange = function(tmpDate) {
                if(!o.low && !o.high) return false;

                var level = false;
                if(!tmpDate) {
                        level = true;
                        tmpDate = o.date;
                };
                
                var d  = (tmpDate.getDate() < 10) ? "0" + tmpDate.getDate() : tmpDate.getDate();
                var m  = ((tmpDate.getMonth() + 1) < 10) ? "0" + (tmpDate.getMonth() + 1) : tmpDate.getMonth() + 1;
                var y  = tmpDate.getFullYear();
                var dt = String(y)+String(m)+String(d);

                if(o.low && parseInt(dt) < parseInt(o.low)) {
                        if(!level) return true;
                        o.date = new Date(o.low.substr(0,4), o.low.substr(4,2)-1, o.low.substr(6,2), 5, 0, 0);
                        return false;
                };
                if(o.high && parseInt(dt) > parseInt(o.high)) {
                        if(!level) return true;
                        o.date = new Date( o.high.substr(0,4), o.high.substr(4,2)-1, o.high.substr(6,2), 5, 0, 0);
                };
                return false;
        };
        o.createButton = function() {
                if(o.staticPos) { return; };
                
                var but;
                
                if(!document.getElementById("fd-but-" + o.id)) {
                        var inp = o.getElem();
                        
                        but = document.createElement('a');
                        but.href = "#";

                        var span = document.createElement('span');
                        span.appendChild(document.createTextNode(String.fromCharCode( 160 )));

                        but.className = "date-picker-control";
                        but.title = (typeof(fdLocale) == "object" && options.locale && fdLocale.titles.length > 5) ? fdLocale.titles[5] : "";

                        but.id = "fd-but-" + o.id;
                        but.appendChild(span);

                        if(inp.nextSibling) {
                                inp.parentNode.insertBefore(but, inp.nextSibling);
                        } else {
                                inp.parentNode.appendChild(but);
                        };
                } else {
                        but = document.getElementById("fd-but-" + o.id);
                };

                but.onclick = but.onpress = function(e) {
                        e = e || window.event;
                        var inpId = this.id.replace('fd-but-','');
                        try { var dp = datePickerController.getDatePicker(inpId); } catch(err) { return false; };

                        if(e.type == "press") {
                                var kc = e.keyCode != null ? e.keyCode : e.charCode;
                                if(kc != 13) { return true; };
                                if(dp.visible) {
                                        hideAll();
                                        return false;
                                };
                        };

                        if(!dp.visible) {
                                datePickerController.hideAll(inpId);
                                dp.show();
                        } else {
                                datePickerController.hideAll();
                        };
                        return false;
                };
                but = null;
        },
        o.create = function() {
                
                function createTH(details) {
                        var th = document.createElement('th');
                        if(details.thClassName) th.className = details.thClassName;
                        if(details.colspan) {
                                /*@cc_on
                                /*@if (@_win32)
                                th.setAttribute('colSpan',details.colspan);
                                @else @*/
                                th.setAttribute('colspan',details.colspan);
                                /*@end
                                @*/
                        };
                        /*@cc_on
                        /*@if (@_win32)
                        th.unselectable = "on";
                        /*@end@*/
                        return th;
                };
                
                function createThAndButton(tr, obj) {
                        for(var i = 0, details; details = obj[i]; i++) {
                                var th = createTH(details);
                                tr.appendChild(th);
                                var but = document.createElement('span');
                                but.className = details.className;
                                but.id = o.id + details.id;
                                but.appendChild(document.createTextNode(details.text));
                                but.title = details.title || "";
                                if(details.onmousedown) but.onmousedown = details.onmousedown;
                                if(details.onclick)     but.onclick     = details.onclick;
                                if(details.onmouseout)  but.onmouseout  = details.onmouseout;
                                th.appendChild(but);
                        };
                };
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(!document.getElementById("iePopUpHack")) {
                                o.iePopUp = document.createElement('iframe');
                                o.iePopUp.src = "javascript:'<html></html>';";
                                o.iePopUp.setAttribute('className','iehack');
                                o.iePopUp.scrolling="no";
                                o.iePopUp.frameBorder="0";
                                o.iePopUp.name = o.iePopUp.id = "iePopUpHack";
                                document.body.appendChild(o.iePopUp);
                        } else {
                                o.iePopUp = document.getElementById("iePopUpHack");
                        };
                @end
                @*/
                
                if(typeof(fdLocale) == "object" && o.locale) {
                        datePicker.titles  = fdLocale.titles;
                        datePicker.months  = fdLocale.months;
                        datePicker.fullDay = fdLocale.fullDay;
                        // Optional parameters
                        if(fdLocale.dayAbbr) datePicker.dayAbbr = fdLocale.dayAbbr;
                        if(fdLocale.firstDayOfWeek) o.firstDayOfWeek = o.defaults.firstDayOfWeek = fdLocale.firstDayOfWeek;
                };
                
                o.div = document.createElement('div');
                o.div.style.zIndex = 9999;
                o.div.id = "fd-"+o.id;
                o.div.className = "datePicker";
                
                if(!o.staticPos) {
                        document.getElementsByTagName('body')[0].appendChild(o.div);
                } else {
                        elem = o.getElem();
                        if(!elem) {
                                o.div = null;
                                return;
                        };
                        o.div.className += " staticDP";
                        o.div.setAttribute("tabIndex", "0");
                        o.div.onfocus = o.events.onfocus;
                        o.div.onblur  = o.events.onblur;
                        elem.parentNode.insertBefore(o.div, elem.nextSibling);
                        if(o.hideInput && elem.type && elem.type == "text") elem.setAttribute("type", "hidden");
                };
                
                //var nbsp = String.fromCharCode( 160 );
                var tr, row, col, tableHead, tableBody;

                o.table = document.createElement('table');
                o.div.appendChild( o.table );
                
                tableHead = document.createElement('thead');
                o.table.appendChild( tableHead );
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                // Title Bar
                o.titleBar = createTH({thClassName:"date-picker-title", colspan:7});
                tr.appendChild( o.titleBar );
                tr = null;
                
                var span = document.createElement('span');
                span.className = "month-display";
                o.titleBar.appendChild(span);

                span = document.createElement('span');
                span.className = "year-display";
                o.titleBar.appendChild(span);

                span = null;
                
                tr  = document.createElement('tr');
                tableHead.appendChild(tr);

                createThAndButton(tr, [{className:"prev-but", id:"-prev-year-but", text:"\u00AB", title:datePicker.titles[2], onmousedown:function(e) { o.events.incDec(e,0,-1,0); }, onmouseout:o.events.clearTimer },{className:"prev-but", id:"-prev-month-but", text:"\u2039", title:datePicker.titles[0], onmousedown:function(e) { o.events.incDec(e,0,0,-1); }, onmouseout:o.events.clearTimer },{colspan:3, className:"today-but", id:"-today-but", text:datePicker.titles.length > 4 ? datePicker.titles[4] : "Today", onclick:o.events.gotoToday},{className:"next-but", id:"-next-month-but", text:"\u203A", title:datePicker.titles[1], onmousedown:function(e) { o.events.incDec(e,0,0,1); }, onmouseout:o.events.clearTimer },{className:"next-but", id:"-next-year-but", text:"\u00BB", title:datePicker.titles[3], onmousedown:function(e) { o.events.incDec(e,0,1,0); }, onmouseout:o.events.clearTimer }]);

                tableBody = document.createElement('tbody');
                o.table.appendChild( tableBody );

                for(var rows = 0; rows < 7; rows++) {
                        row = document.createElement('tr');

                        if(rows != 0) tableBody.appendChild(row);
                        else          tableHead.appendChild(row);
                        
                        for(var cols = 0; cols < 7; cols++) {
                                col = (rows == 0) ? document.createElement('th') : document.createElement('td');

                                row.appendChild(col);
                                if(rows != 0) {
                                        col.appendChild(document.createTextNode(o.nbsp));
                                        col.onmouseover = o.events.onmouseover;
                                        col.onclick = o.events.onclick;
                                } else {
                                        col.className = "date-picker-day-header";
                                        col.scope = "col";
                                };
                                col = null;
                        };
                        row = null;
                };

                // Table headers
                var but;
                var ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                for ( var y = 0; y < 7; y++ ) {
                        if(y > 0) {
                                but = document.createElement("span");
                                but.className = "fd-day-header";
                                but.onclick = ths[y].onclick = o.setFirstDayOfWeek;
                                but.appendChild(document.createTextNode(o.nbsp));
                                ths[y].appendChild(but);
                                but = null;
                        } else {
                                ths[y].appendChild(document.createTextNode(o.nbsp));
                        };
                };
                
                o.ths = o.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th');
                o.trs = o.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
                
                o.updateTableHeaders();
                
                tableBody = tableHead = tr = createThAndButton = createTH = null;

                if(o.low && o.high && (o.high - o.low < 7)) { o.equaliseDates(); };
                
                o.created = true;
                
                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.addEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');
                                datePickerController.addEvent(mmN, "change", o.changeHandler);
                                datePickerController.addEvent(ddN, "change", o.changeHandler);
                        };
                        
                        o.show();
                } else {
                        o.createButton();
                        o.resize();
                        o.fade();
                };
        };
        o.changeHandler = function() {
                o.setDateFromInput();
                o.updateTable();
        };
        o.setDateFromInput = function() {
                function m2c(val) {
                        return String(val).length < 2 ? "00".substring(0, 2 - String(val).length) + String(val) : val;
                };

                o.dateSet = null;
                
                var elem = o.getElem();
                if(!elem) return;

                if(!o.splitDate) {
                        var date = datePickerController.dateFormat(elem.value, o.format.search(/m-d-y/i) != -1);
                } else {
                        var mmN = document.getElementById(o.id+'-mm');
                        var ddN = document.getElementById(o.id+'-dd');
                        var tm = parseInt(mmN.tagName.toLowerCase() == "input"  ? mmN.value  : mmN.options[mmN.selectedIndex].value, 10);
                        var td = parseInt(ddN.tagName.toLowerCase() == "input"  ? ddN.value  : ddN.options[ddN.selectedIndex].value, 10);
                        var ty = parseInt(elem.tagName.toLowerCase() == "input" ? elem.value : elem.options[elem.selectedIndex || 0].value, 10);
                        var date = datePickerController.dateFormat(tm + "/" + td + "/" + ty, true);
                };

                var badDate = false;
                if(!date) {
                        badDate = true;
                        date = String(new Date().getFullYear()) + m2c(new Date().getMonth()+1) + m2c(new Date().getDate());
                };

                var d,m,y;
                y = Number(date.substr(0, 4));
                m = Number(date.substr(4, 2)) - 1;
                d = Number(date.substr(6, 2));

                var dpm = datePicker.getDaysPerMonth(m, y);
                if(d > dpm) d = dpm;

                if(new Date(y, m, d) == 'Invalid Date' || new Date(y, m, d) == 'NaN') {
                        badDate = true;
                        o.date = new Date();
                        o.date.setHours(5);
                        return;
                };

                o.date = new Date(y, m, d);
                o.date.setHours(5);

                if(!badDate) o.dateSet = new Date(o.date);
                m2c = null;
        };
        o.setSelectIndex = function(elem, indx) {
                var len = elem.options.length;
                indx = Number(indx);
                for(var opt = 0; opt < len; opt++) {
                        if(elem.options[opt].value == indx) {
                                elem.selectedIndex = opt;
                                return;
                        };
                };
        },
        o.returnFormattedDate = function() {

                var elem = o.getElem();
                if(!elem) return;
                
                var d                   = (o.date.getDate() < 10) ? "0" + o.date.getDate() : o.date.getDate();
                var m                   = ((o.date.getMonth() + 1) < 10) ? "0" + (o.date.getMonth() + 1) : o.date.getMonth() + 1;
                var yyyy                = o.date.getFullYear();
                var disabledDates       = o.getDisabledDates(yyyy, m);
                var weekDay             = ( o.date.getDay() + 6 ) % 7;

                if(!(o.disableDays[weekDay] || String(yyyy)+m+d in disabledDates)) {

                        if(o.splitDate) {
                                var ddE = document.getElementById(o.id+"-dd");
                                var mmE = document.getElementById(o.id+"-mm");

                                if(ddE.tagName.toLowerCase() == "input") { ddE.value = d; }
                                else { o.setSelectIndex(ddE, d); /*ddE.selectedIndex = d - 1;*/ };
                                
                                if(mmE.tagName.toLowerCase() == "input") { mmE.value = m; }
                                else { o.setSelectIndex(mmE, m); /*mmE.selectedIndex = m - 1;*/ };
                                
                                if(elem.tagName.toLowerCase() == "input") elem.value = yyyy;
                                else {
                                        o.setSelectIndex(elem, yyyy); /*
                                        for(var opt = 0; opt < elem.options.length; opt++) {
                                                if(elem.options[opt].value == yyyy) {
                                                        elem.selectedIndex = opt;
                                                        break;
                                                };
                                        };
                                        */
                                };
                        } else {
                                elem.value = o.format.replace('y',yyyy).replace('m',m).replace('d',d).replace(/-/g,o.divider);
                        };
                        if(!elem.type || elem.type && elem.type != "hidden"){ elem.focus(); }
                        if(o.staticPos) {
                                o.dateSet = new Date( o.date );
                                o.updateTable();
                        };
                        
                        // Programmatically fire the onchange event
                        if(document.createEvent) {
                                var onchangeEvent = document.createEvent('HTMLEvents');
                                onchangeEvent.initEvent('change', true, false);
                                elem.dispatchEvent(onchangeEvent);
                        } else if(document.createEventObject) {
                                elem.fireEvent('onchange');
                        };
                };
        };
        o.disableTodayButton = function() {
                var today = new Date();
                document.getElementById(o.id + "-today-but").className = document.getElementById(o.id + "-today-but").className.replace("fd-disabled", "");
                if(o.outOfRange(today) || (o.date.getDate() == today.getDate() && o.date.getMonth() == today.getMonth() && o.date.getFullYear() == today.getFullYear())) {
                        document.getElementById(o.id + "-today-but").className += " fd-disabled";
                        document.getElementById(o.id + "-today-but").onclick = null;
                } else {
                        document.getElementById(o.id + "-today-but").onclick = o.events.gotoToday;
                };
        };
        o.updateTableHeaders = function() {
                var d, but;
                var ths = o.ths;
                for ( var y = 0; y < 7; y++ ) {
                        d = (o.firstDayOfWeek + y) % 7;
                        ths[y].title = datePicker.fullDay[d];

                        if(y > 0) {
                                but = ths[y].getElementsByTagName("span")[0];
                                but.removeChild(but.firstChild);
                                but.appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                                but.title = datePicker.fullDay[d];
                                but = null;
                        } else {
                                ths[y].removeChild(ths[y].firstChild);
                                ths[y].appendChild(document.createTextNode(datePicker.dayAbbr ? datePicker.dayAbbr[d] : datePicker.fullDay[d].charAt(0)));
                        };
                };
                o.updateTable();
        };

        o.updateTable = function(noCallback) {

                if(o.timerSet) {
                        var d = new Date(o.date);
                        d.setDate( Math.min(d.getDate()+o.dayInc, datePicker.getDaysPerMonth(d.getMonth()+o.monthInc,d.getFullYear()+o.yearInc)) );
                        d.setMonth( d.getMonth() + o.monthInc );
                        d.setFullYear( d.getFullYear() + o.yearInc );
                        o.date = d;
                };
                
                if(!noCallback && "onupdate" in datePickerController && typeof(datePickerController.onupdate) == "function") datePickerController.onupdate(o);

                o.outOfRange();
                o.disableTodayButton();
                
                // Set the tmpDate to the second day of this month (to avoid daylight savings time madness on Windows)
                var tmpDate = new Date( o.date.getFullYear(), o.date.getMonth(), 2 );
                tmpDate.setHours(5);

                var tdm = tmpDate.getMonth();
                var tdy = tmpDate.getFullYear();

                // Do the disableDates for this year and month
                var disabledDates = o.getDisabledDates(o.date.getFullYear(), o.date.getMonth() + 1);

                var today = new Date();

                // Previous buttons out of range
                var b = document.getElementById(o.id + "-prev-year-but");
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy - 1), Number(tdm), datePicker.getDaysPerMonth(Number(tdm), tdy-1)))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == -1) o.stopTimer();
                };

                b = document.getElementById(o.id + "-prev-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, (Number(tdm) - 1), datePicker.getDaysPerMonth(Number(tdm)-1, tdy)))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == -1)  o.stopTimer();
                };

                // Next buttons out of range
                b= document.getElementById(o.id + "-next-year-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date((tdy + 1), Number(tdm), 1))) {
                        b.className += " fd-disabled";
                        if(o.yearInc == 1)  o.stopTimer();
                };

                b = document.getElementById(o.id + "-next-month-but")
                b.className = b.className.replace("fd-disabled", "");
                if(o.outOfRange(new Date(tdy, Number(tdm) + 1, 1))) {
                        b.className += " fd-disabled";
                        if(o.monthInc == 1)  o.stopTimer();
                };

                b = null;
                
                var cd = o.date.getDate();
                var cm = o.date.getMonth();
                var cy = o.date.getFullYear();
                
                // Title Bar
                var span = o.titleBar.getElementsByTagName("span");
                while(span[0].firstChild) span[0].removeChild(span[0].firstChild);
                while(span[1].firstChild) span[1].removeChild(span[1].firstChild);
                span[0].appendChild(document.createTextNode(datePicker.months[cm] + o.nbsp));
                span[1].appendChild(document.createTextNode(cy));

                tmpDate.setDate( 1 );
                        
                var dt, cName, td, tds, i;
                var weekDay = ( tmpDate.getDay() + 6 ) % 7;
                var firstColIndex = (( (weekDay - o.firstDayOfWeek) + 7 ) % 7) - 1;
                var dpm = datePicker.getDaysPerMonth(cm, cy);

                var todayD = today.getDate();
                var todayM = today.getMonth();
                var todayY = today.getFullYear();
                
                var c = "class";
                /*@cc_on
                @if(@_win32)
                c = "className";
                @end
                @*/

                var stub = String(tdy) + (String(tdm+1).length < 2 ? "0" + (tdm+1) : tdm+1);
                
                for(var row = 0; row < 6; row++) {

                        tds = o.trs[row].getElementsByTagName('td');

                        for(var col = 0; col < 7; col++) {
                        
                                td = tds[col];
                                td.removeChild(td.firstChild);

                                td.setAttribute("id", "");
                                td.setAttribute("title", "");

                                i = (row * 7) + col;
                        
                                if(i > firstColIndex && i <= (firstColIndex + dpm)) {
                                        dt = i - firstColIndex;

                                        tmpDate.setDate(dt);
                                        td.appendChild(document.createTextNode(dt));
                                        
                                        if(o.outOfRange(tmpDate)) {
                                                td.setAttribute(c, "out-of-range");
                                        } else {

                                                cName = [];
                                                weekDay = ( tmpDate.getDay() + 6 ) % 7;

                                                if(dt == todayD && tdm == todayM && tdy == todayY) {
                                                        cName.push("date-picker-today");
                                                };

                                                if(o.dateSet != null && o.dateSet.getDate() == dt && o.dateSet.getMonth() == tdm && o.dateSet.getFullYear() == tdy) {
                                                        cName.push("date-picker-selected-date");
                                                };
                                                
                                                if(o.disableDays[weekDay] || stub + String(dt < 10 ? "0" + dt : dt) in disabledDates) {
                                                        cName.push("day-disabled");
                                                } else if(o.highlightDays[weekDay]) {
                                                        cName.push("date-picker-highlight");
                                                };
                                                
                                                if(cd == dt) {
                                                        td.setAttribute("id", o.id + "-date-picker-hover");
                                                        cName.push("date-picker-hover");
                                                };
                                                
                                                cName.push("dm-" + dt + '-' + (tdm + 1) + " " + " dmy-" + dt + '-' + (tdm + 1) + '-' + tdy);
                                                td.setAttribute(c, cName.join(' '));
                                                td.setAttribute("title", datePicker.months[cm] + o.nbsp + dt + "," + o.nbsp + cy);
                                        };
                                } else {
                                        td.appendChild(document.createTextNode(o.nbsp));
                                        td.setAttribute(c, "date-picker-unused");
                                };
                        };
                };

                if(o.timerSet) {
                        o.timerInc = 50 + Math.round(((o.timerInc - 50) / 1.8));
                        o.timer = window.setTimeout(o.updateTable, o.timerInc);
                };
        };
        o.addKeyboardEvents = function() {
                datePickerController.addEvent(document, "keypress", o.events.onkeydown);
                /*@cc_on
                @if(@_win32)
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                @end
                @*/
                if(window.devicePixelRatio) {
                        datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                        datePickerController.addEvent(document, "keydown", o.events.onkeydown);
                };
        };
        o.removeKeyboardEvents =function() {
                datePickerController.removeEvent(document, "keypress", o.events.onkeydown);
                datePickerController.removeEvent(document, "keydown",  o.events.onkeydown);
        };
        o.show = function() {
                var elem = o.getElem();
                if(!elem || o.visible || elem.disabled) return;

                o.reset();
                o.setDateFromInput();
                o.updateTable();
                
                if(!o.staticPos) o.resize();
                
                datePickerController.addEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);

                if(!o.staticPos) { o.addKeyboardEvents(); };
                
                o.opacityTo = o.noTransparency ? 99 : 90;
                o.div.style.display = "block";
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                if(!o.staticPos) o.iePopUp.style.display = "block";
                @end
                @*/

                o.fade();
                o.visible = true;
        };
        o.hide = function() {
                if(!o.visible) return;
                o.stopTimer();
                if(o.staticPos) return;
                
                datePickerController.removeEvent(document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",  o.events.clearTimer);
                o.removeKeyboardEvents();
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp.style.display = "none";
                @end
                @*/
                
                o.opacityTo = 0;
                o.fade();
                o.visible = false;
                var elem = o.getElem();
                if(!elem.type || elem.type && elem.type != "hidden") { elem.focus(); };
        };
        o.destroy = function() {
                // Cleanup for Internet Explorer
                datePickerController.removeEvent(o.staticPos ? o.table : document, "mousedown", o.events.onmousedown);
                datePickerController.removeEvent(document, "mouseup",   o.events.clearTimer);
                o.removeKeyboardEvents();

                if(o.staticPos) {
                        var yyN = document.getElementById(o.id);
                        datePickerController.removeEvent(yyN, "change", o.changeHandler);
                        if(o.splitDate) {
                                var mmN = document.getElementById(o.id+'-mm');
                                var ddN = document.getElementById(o.id+'-dd');

                                datePickerController.removeEvent(mmN, "change", o.changeHandler);
                                datePickerController.removeEvent(ddN, "change", o.changeHandler);
                        };
                        o.div.onfocus = o.div.onblur = null;
                };
                
                var ths = o.table.getElementsByTagName("th");
                for(var i = 0, th; th = ths[i]; i++) {
                        th.onmouseover = th.onmouseout = th.onmousedown = th.onclick = null;
                };
                
                var tds = o.table.getElementsByTagName("td");
                for(var i = 0, td; td = tds[i]; i++) {
                        td.onmouseover = td.onclick = null;
                };

                var butts = o.table.getElementsByTagName("span");
                for(var i = 0, butt; butt = butts[i]; i++) {
                        butt.onmousedown = butt.onclick = butt.onkeypress = null;
                };
                
                o.ths = o.trs = null;
                
                clearTimeout(o.fadeTimer);
                clearTimeout(o.timer);
                o.fadeTimer = o.timer = null;
                
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                o.iePopUp = null;
                @end
                @*/
                
                if(!o.staticPos && document.getElementById(o.id.replace(/^fd-/, 'fd-but-'))) {
                        var butt = document.getElementById(o.id.replace(/^fd-/, 'fd-but-'));
                        butt.onclick = butt.onpress = null;
                };
                
                if(o.div && o.div.parentNode) {
                        o.div.parentNode.removeChild(o.div);
                };
                
                o.titleBar = o.table = o.div = null;
                o = null;
        };
        o.create();
};

datePickerController = function() {
        var datePickers = {};
        var uniqueId    = 0;
        
        var addEvent = function(obj, type, fn) {
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        };
        var removeEvent = function(obj, type, fn) {
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        };
        var hideAll = function(exception) {
                var dp;
                for(dp in datePickers) {
                        if(!datePickers[dp].created || datePickers[dp].staticPos) continue;
                        if(exception && exception == datePickers[dp].id) { continue; };
                        if(document.getElementById(datePickers[dp].id))  { datePickers[dp].hide(); };
                };
        };
        var cleanUp = function() {
                var dp;
                for(dp in datePickers) {
                        if(!document.getElementById(datePickers[dp].id)) {
                                if(!datePickers[dp].created) continue;
                                datePickers[dp].destroy();
                                datePickers[dp] = null;
                                delete datePickers[dp];
                        };
                };
        };
        var destroy = function() {
                for(dp in datePickers) {
                        if(!datePickers[dp].created) continue;
                        datePickers[dp].destroy();
                        datePickers[dp] = null;
                        delete datePickers[dp];
                };
                datePickers = null;
                /*@cc_on
                @if(@_jscript_version <= 5.6)
                        if(document.getElementById("iePopUpHack")) {
                                document.body.removeChild(document.getElementById("iePopUpHack"));
                        };
                @end
                @*/
                datePicker.script = null;
                removeEvent(window, 'load', datePickerController.create);
                removeEvent(window, 'unload', datePickerController.destroy);
        };
        var dateFormat = function(dateIn, favourMDY) {
                var dateTest = [
                        { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                        { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                        { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/,    d:5, m:3, y:1 }   // ymd
                        ];

                var start;
                var cnt = 0;
                while(cnt < 3) {
                        start = (cnt + (favourMDY ? 4 : 3)) % 3;
                        if(dateIn.match(dateTest[start].regExp)) {
                                res = dateIn.match(dateTest[start].regExp);
                                y = res[dateTest[start].y];
                                m = res[dateTest[start].m];
                                d = res[dateTest[start].d];
                                if(m.length == 1) m = "0" + m;
                                if(d.length == 1) d = "0" + d;
                                if(y.length != 4) y = (parseInt(y) < 50) ? '20' + y : '19' + y;
                                return String(y)+m+d;
                        };
                        cnt++;
                };
                return 0;
        };
        var joinNodeLists = function() {
                if(!arguments.length) { return []; }
                var nodeList = [];
                for (var i = 0; i < arguments.length; i++) {
                        for (var j = 0, item; item = arguments[i][j]; j++) {
                                nodeList[nodeList.length] = item;
                        };
                };
                return nodeList;
        };
        var addDatePicker = function(inpId, options) {
                if(!(inpId in datePickers)) {
                        datePickers[inpId] = new datePicker(options);
                };
        };
        var getDatePicker = function(inpId) {
                if(!(inpId in datePickers)) { throw "No datePicker has been created for the form element with an id of '" + inpId.toString() + "'"; };
                return datePickers[inpId];
        };
        var grepRangeLimits = function(sel) {
                var range = [];
                for(var i = 0; i < sel.options.length; i++) {
                        if(sel.options[i].value.search(/^\d\d\d\d$/) == -1) { continue; };
                        if(!range[0] || Number(sel.options[i].value) < range[0]) { range[0] = Number(sel.options[i].value); };
                        if(!range[1] || Number(sel.options[i].value) > range[1]) { range[1] = Number(sel.options[i].value); };
                };
                return range;
        };
        var create = function(inp) {
                if(!(typeof document.createElement != "undefined" && typeof document.documentElement != "undefined" && typeof document.documentElement.offsetWidth == "number")) return;

                var inputs  = (inp && inp.tagName) ? [inp] : joinNodeLists(document.getElementsByTagName('input'), document.getElementsByTagName('select'));
                var regExp1 = /disable-days-([1-7]){1,6}/g;             // the days to disable
                var regExp2 = /no-transparency/g;                       // do not use transparency effects
                var regExp3 = /highlight-days-([1-7]){1,7}/g;           // the days to highlight in red
                var regExp4 = /range-low-(\d\d\d\d-\d\d-\d\d)/g;        // the lowest selectable date
                var regExp5 = /range-high-(\d\d\d\d-\d\d-\d\d)/g;       // the highest selectable date
                var regExp6 = /format-(d-m-y|m-d-y|y-m-d)/g;            // the input/output date format
                var regExp7 = /divider-(dot|slash|space|dash)/g;        // the character used to divide the date
                var regExp8 = /no-locale/g;                             // do not attempt to detect the browser language
                var regExp9 = /no-fade/g;                               // always show the datepicker
                var regExp10 = /hide-input/g;                           // hide the input
                
                for(var i=0, inp; inp = inputs[i]; i++) {
                        if(inp.className && (inp.className.search(regExp6) != -1 || inp.className.search(/split-date/) != -1) && ((inp.tagName.toLowerCase() == "input" && (inp.type == "text" || inp.type == "hidden")) || inp.tagName.toLowerCase() == "select")) {

														// if(inp.id && document.getElementById('fd-'+inp.id)) { continue; };
														// this could solve AJAX Call problem - CK : 	
															 if(inp.id && document.getElementById('fd-'+inp.id)) { if (inp.id in datePickers) { datePickerController.datePickers[inp.id].createButton(); } continue;};


																
                                if(!inp.id) { inp.id = "fdDatePicker-" + uniqueId++; };
                                
                                var options = {
                                        id:inp.id,
                                        low:"",
                                        high:"",
                                        divider:"/",
                                        format:"d-m-y",
                                        highlightDays:[0,0,0,0,0,1,1],
                                        disableDays:[0,0,0,0,0,0,0],
                                        locale:inp.className.search(regExp8) == -1,
                                        splitDate:0,
                                        noTransparency:inp.className.search(regExp2) != -1,
                                        staticPos:inp.className.search(regExp9) != -1,
                                        hideInput:inp.className.search(regExp10) != -1
                                };

                                if(!options.staticPos) {
                                        options.hideInput = false;
                                } else {
                                        options.noTransparency = true;
                                };
                                
                                // Split the date into three parts ?
                                if(inp.className.search(/split-date/) != -1) {
                                        if(document.getElementById(inp.id+'-dd') && document.getElementById(inp.id+'-mm') && document.getElementById(inp.id+'-dd').tagName.search(/input|select/i) != -1 && document.getElementById(inp.id+'-mm').tagName.search(/input|select/i) != -1) {
                                                options.splitDate = 1;
                                        };
                                };
                                
                                // Date format(variations of d-m-y)
                                if(inp.className.search(regExp6) != -1) {
                                        options.format = inp.className.match(regExp6)[0].replace('format-','');
                                };
                                
                                // What divider to use, a "/", "-", "." or " "
                                if(inp.className.search(regExp7) != -1) {
                                        var dividers = { dot:".", space:" ", dash:"-", slash:"/" };
                                        options.divider = (inp.className.search(regExp7) != -1 && inp.className.match(regExp7)[0].replace('divider-','') in dividers) ? dividers[inp.className.match(regExp7)[0].replace('divider-','')] : "/";
                                };

                                // The days to highlight
                                if(inp.className.search(regExp3) != -1) {
                                        var tmp = inp.className.match(regExp3)[0].replace(/highlight-days-/, '');
                                        options.highlightDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.highlightDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The days to disable
                                if(inp.className.search(regExp1) != -1) {
                                        var tmp = inp.className.match(regExp1)[0].replace(/disable-days-/, '');
                                        options.disableDays = [0,0,0,0,0,0,0];
                                        for(var j = 0; j < tmp.length; j++) {
                                                options.disableDays[tmp.charAt(j) - 1] = 1;
                                        };
                                };

                                // The lower limit
                                if(inp.className.search(/range-low-today/i) != -1) {
                                        options.low = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp4) != -1) {
                                        options.low = datePickerController.dateFormat(inp.className.match(regExp4)[0].replace(/range-low-/, ''), false);
                                        if(!options.low) {
                                                options.low = '';
                                        };
                                };

                                // The higher limit
                                if(inp.className.search(/range-high-today/i) != -1 && inp.className.search(/range-low-today/i) == -1) {
                                        options.high = datePickerController.dateFormat((new Date().getMonth() + 1) + "/" + new Date().getDate() + "/" + new Date().getFullYear(), true);
                                } else if(inp.className.search(regExp5) != -1) {
                                        options.high = datePickerController.dateFormat(inp.className.match(regExp5)[0].replace(/range-high-/, ''), false);
                                        if(!options.high) {
                                                options.high = '';
                                        };
                                };

                                // Always round lower & higher limits if a selectList involved
                                if(inp.tagName.search(/select/i) != -1) {
                                        var range = grepRangeLimits(inp);
                                        options.low  = options.low  ? range[0] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[0] + "/01/01");
                                        options.high = options.high ? range[1] + String(options.low).substr(4,4)  : datePickerController.dateFormat(range[1] + "/12/31");
                                };

                                addDatePicker(inp.id, options);
                        };
                };
      
				}
        
        return {
                addEvent:addEvent,
                removeEvent:removeEvent,
                create:create,
                destroy:destroy,
                cleanUp:cleanUp,
                addDatePicker:addDatePicker,
                getDatePicker:getDatePicker,
                dateFormat:dateFormat,
                datePickers:datePickers,
                hideAll:hideAll
        };
}();

})();

datePickerController.addEvent(window, 'load', datePickerController.create);
datePickerController.addEvent(window, 'unload', datePickerController.destroy);

//*************************************
///code/date-picker/datepicker.js END
//***********************************/





//*****************************
//PopImage.js
//****************************/

/*
See http://www.howtocreate.co.uk/perfectPopups.html and http://www.howtocreate.co.uk/jslibs/termsOfUse.html
for details and terms of use.
To call this script, use something like (the number is a delay before it closes or 0 for no timed closing -
the true/false says if the window should close when they switch to another window):
<script type="text/javascript"><!--
//you can style this, but don't try to text-align it to the right, it will break the resizing effect
//keep it narrow, if it is wider than the image, the window will wrap to this width
//the makeright class tells the script to automatically align it to the right
var extraHTML = '<br><a href="javascript:window.close()" style="text-decoration:none;color:#777;background-color:#bbb;font-weight:bold;border-left:2px solid #000;" class="makeright">Close<\/a>';
//--></script>
<a href="me.jpg" onclick="return popImageExtra(this.href,'Site author',true,3000,extraHTML);">link</a>
*/

//really not important (the first two should be small for Opera's sake)
PositionX = 10;
PositionY = 10;
defaultWidth  = 600;
defaultHeight = 400;

//don't touch (except to modify the window contents)
var extraHTML = '<br><a href="javascript:window.close()" style="text-decoration:none;color:#777;background-color:#bbb;font-weight:bold;border-left:2px solid #000;" class="makeright">Close<\/a>';

function popImageExtra(imageURL,imageTitle,AutoClose,oTimeClose,extraHTML){
	var imgWin = window.open('','_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
	if( !imgWin ) { return true; } //popup blockers should not cause errors
	imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
		'function getRefToDivMod( divID, oDoc ) {\n'+
			'if( !oDoc ) { oDoc = document; }\n'+
			'if( document.layers ) {\n'+
			'if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {\n'+
			'for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {\n'+
			'y = getRefToDivNest(divID,oDoc.layers[x].document); }\n'+
			'return y; } }\n'+
			'if( document.getElementById ) { return oDoc.getElementById(divID); }\n'+
			'if( document.all ) { return oDoc.all[divID]; }\n'+
			'return document[divID];\n'+
		'}\n'+
		'function resizeWinTo() {\n'+
			'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
			'if( !document.images[0].height || window.doneAlready ) { return; }\n'+ //in case images are disabled
			'var oH = getRefToDivMod( \'myID\' ); if( !oH ) { return false; }\n'+
			'var oW = oH.clip ? oH.clip.width : oH.offsetWidth;\n'+
			'var oH = oH.clip ? oH.clip.height : oH.offsetHeight; if( !oH ) { return false; }\n'+
			'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
			'window.doneAlready = true;\n'+ //for Safari and Opera
			'var mH = screen.availHeight-130, mW = screen.availWidth-40;\n'+
			'if( oH > mH || oW > mW ) {\n'+
			'var hDif = oH - document.images[0].height;\n'+
			'var wDif = oW - document.images[0].width;\n'+
			'mH = mH - hDif; mW = mW - wDif;\n'+
			'mH = mH \/ document.images[0].height;\n'+
			'mW = mW \/ document.images[0].width;\n'+
			'var zoomFactor = ( mH < mW ) ? mH : mW;\n'+
			'oH = Math.floor( document.images[0].height * zoomFactor );\n'+
			'oW = Math.floor( document.images[0].width * zoomFactor );\n'+
			'document.images[0].height = oH;\n'+
			'document.images[0].width = oW;\n'+
			'oH += hDif; oW += wDif;\n'+
			'}\n'+
			'if(document.getElementsByTagName) {\n'+
				'for( var l = document.getElementsByTagName(\'a\'), x = 0; l[x]; x++ ) {\n'+
					'if(l[x].className==\'makeright\'&&!l[x].style.position){\n'+
						'l[x].style.position=\'relative\';\n'+
						'l[x].style.left=(document.images[0].width-(l[x].offsetWidth+l[x].offsetLeft))+\'px\';\n'+
			'}}}\n'+
			'var mH = screen.availHeight-50, mW = screen.availWidth-40;\n'+
			'if( oH > mH ) { oH = mH; }\n'+
			'if( oW > mW ) { oW = mW; }\n'+
			'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
			'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
			'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
			'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
			'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
			'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
			'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
			'var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
			'var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
			'if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
			(oTimeClose?('window.setTimeout(\'window.close()\','+oTimeClose+');\n'):'')+
		'}\n'+
		'<\/script>'+
		'<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
		(document.layers?('<layer left="0" top="0" id="myID">'):('<div style="position:absolute;left:0px;top:0px;" id="myID">'))+
		'<img src="'+imageURL+'" alt="Loading image ..." title="" onload="resizeWinTo();">'+
		(extraHTML?extraHTML:'')+(document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
	imgWin.document.close();
	if( imgWin.focus ) { imgWin.focus(); }
	return false;
}

//*****************************
//PopImage.js --> end
//****************************/


//*****************************
//jsval.js
//****************************/

function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
	var strErrorMessage="";
	var objFirstError=null;
	if(nErrorThrowType==0){
		strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
	};
	var fields=_GenerateFormFields(form);
	for(var i=0;i<fields.length;++i){
		var field=fields[i];
		if(!field.IsValid(fields)){
			field.SetClass(strErrorClass);
			if(nErrorThrowType==1){
				_throwError(field);
				return false;
			}else{
				if(objFirstError==null){
					objFirstError=field;
				}
				strErrorMessage=_handleError(field,strErrorMessage);
				bError=true;
			}
		}else{
			field.ResetClass();
		}
	};
	if(objFirstError!=null){
		alert(strErrorMessage);
		objFirstError.element.focus();
		return false;
	};
	return true;
};

function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute('exclude');
this.err=element.err||element.getAttribute('err');
this.required=_parseBoolean(element.required||element.getAttribute('required'));
this.realname=element.realname||element.getAttribute('realname');
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute('minlength');
this.maxLength=element.maxlength||element.getAttribute('maxlength');
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute('minvalue');
this.maxValue=element.maxvalue||element.getAttribute('maxvalue');
this.equals=element.equals||element.getAttribute('equals');
this.callback=element.callback||element.getAttribute('callback');
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute('min');
this.max=element.max||element.getAttribute('max');
this.equals=element.equals||element.getAttribute('equals');
break;
case "checkbox":
this.min=element.min||element.getAttribute('min');
this.max=element.max||element.getAttribute('max');
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute('required'));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute('required'));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute('err');
};
if(!this.equals){
this.equals=element.getAttribute('equals');
};
if(!this.callback){
this.callback=element.getAttribute('callback');
};
if(!this.realname){
this.realname=element.getAttribute('realname');
};
if(!this.max){
this.max=element.getAttribute('max');
};
if(!this.min){
this.min=element.getAttribute('min');
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute('regexp')
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP")
&&!(regex=="JSVAL_RX_NUM"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"('"+nCurId+"', '"+nCurName+"', '"+this.value+"');");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":

/*return((/^[0-9a-zA-ZüöäßÄÖÜ]+([\.-]?[0-9a-zA-ZüöäßÄÖÜ]+)*@[0-9a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));*/
return((/^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_NUM":
return((/^\d*$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};

//*****************************
//jsval.js end
//****************************/


