browser = navigator.userAgent.toLowerCase();
isMoz = browser.indexOf('mozilla')>=0;
EMPTYSTRING = ''; //????
if (typeof(PATH)!='undefined') {
	MFOLDER = '__miracle/';
	BKND_DIR = PATH + MFOLDER + 'bknd/';
	IFC_IMG_DIR = PATH + MFOLDER + 'ifc/img/';
	IFC_CSS_DIR = PATH + MFOLDER + 'ifc/css/';
	IFC_JS_DIR  = PATH + MFOLDER + 'ifc/js/';
	IFC_PHP_DIR = PATH + MFOLDER + 'ifc/php/';
	IFC_LIB_DIR = PATH + MFOLDER + 'lib/';
};

if (typeof(JSERR)=='undefined') JSERR='DEFAULT';



window.DOMContentLoaded_eventFired = false;
window.DOMContentLoaded_events = [];
window.DOMContentLoaded_evt = function(e)
{
	var a, len;
	if (DOMContentLoaded_eventFired || !window.DOMContentLoaded_events) return;
	DOMContentLoaded_eventFired = true;
	
	len = window.DOMContentLoaded_events.length;
	 
	for (a = 0; a < len; a++)
	{
		DOMContentLoaded_events[a]();
	}
	window.DOMContentLoaded_events = [];	
};

function addDOMLoadEvent(listener)
{
	if (DOMContentLoaded_eventFired)
		listener();
	
	if (!window.DOMContentLoaded_events)
		window.DOMContentLoaded_events = [];
		
	window.DOMContentLoaded_events.push(listener);
}

if (window.addEventListener) 
{
	window.addEventListener('DOMContentLoaded', window.DOMContentLoaded_evt, false);
	window.addEventListener('load', window.DOMContentLoaded_evt, false);
}
else if (window.attachEvent)
{
	window.attachEvent('onload', window.DOMContentLoaded_evt);
}

//Conditional Compilation http://msdn2.microsoft.com/en-us/library/2z6exc9e(VS.80).aspx
/*@cc_on
(function(){ // Stolen from jquery
	if (window.DOMContentLoaded_eventFired) return;
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch (error) {
		setTimeout( arguments.callee, 4);
		return;
	}
	
	window.DOMContentLoaded_evt();
})();
@*/

function firebugLogReplacement()
{
	var a;
	var s = '';
	var len = arguments.length;
	
	for (a = 0;a < len; a++)
	{
		s += (arguments[a] + "\n");
	}
	alert(s);
} 

if (!window.console) // firebug, allows use of console.log and others, no error if firebug is not installed
{
	window.console = {
		rm_replaced: true, //use this to test if firebug is present
		init: function(){},
		notifyFirebug: function(){},
		getFirebugElement: function(){},
		firebug: function(){},
		evaluate: function(){},
		log: firebugLogReplacement,
		debug: function(){},
		info: firebugLogReplacement,
		warn: firebugLogReplacement,
		error: firebugLogReplacement,
		assert: function(){},
		dir: function(){},
		dirxml: function(){},
		trace: function(){},
		group: function(){},
		groupEnd: function(){},
		groupCollapsed: function(){},
		time: function(){},
		timeEnd: function(){},
		profile: function(){},
		profileEnd: function(){},
		count: function(){}
	};
}
window.rm_callbacks = {};
function callback(identifier, fn)
{	
	if (!rm_callbacks[identifier])
		rm_callbacks[identifier] = [];
	
	rm_callbacks[identifier].push(fn);
}

function docallback(identifier/*, args*/)
{
	var a, len; 
	
	if (!rm_callbacks[identifier])
		return;
		
	len = rm_callbacks[identifier].length;
	for (a = 0; a < len; a++)
	{
		rm_callbacks[identifier][a].apply(this, arguments);
	}
}

function jsErrTrap (msg,url,line) {

	// error trapping routine of window.onerror event
	// covers all errors except errors within element event handlers and dependent functions

	var ret = true;
	switch (JSERR) {
	case 'DEFAULT':
		ret = false;
		break;
	case 'CLIENT':	
		console.error(msg+'\n'+url+'\n'+line);
		break;
	case 'SERVER':
		writeJsErr(msg,url,line);	
		ret = true;
		break;
	case 'REPRESS':
		ret = true;
		break;
	}		
	return ret;

};

window.onerror = jsErrTrap;

function classAppend (elm, className) //Can use multiple class names here, however duplicate class names are not checked
{
	if (!classCheck(elm, className))
	{
		var tmpclassNames = (elm.hasAttribute('class') ? elm.getAttribute('class') : '') + ' ' + className;
		elm.setAttribute('class', tmpclassNames.replace (/\s+/g,' ').replace (/(^\s+)|(\s+$)/g,''));
	}
}

function classRemove (elm, className)
{
	var tmpRegex = new RegExp('\\b(' + className + ')\\b', 'gi');
	var tmpclassName = (elm.hasAttribute('class') ? elm.getAttribute('class') : '').replace (tmpRegex,' ');
	elm.className = tmpclassName.replace (/\s+/g,' ').replace (/(^\s+)|(\s+$)/g,'');
}

function classCheck (elm, className)
{
	var tmpclassName = ' ' + (elm.hasAttribute('class') ? elm.getAttribute('class') : '') + ' ';
	return (tmpclassName.indexOf(' ' + className + ' ') > -1);
}

function eCatchErr() {

	// Error catch wrapper around function that needs errors caught
	// Syntax: eTrap([function name], [parameter 1], [parameter2], ...)
	// unlimited parameters supported
	// (function name without quotes)
	// This can be used to trap errors generated by event listener functions

	var fu = eCatchErr.arguments[0];
	var args = Array.prototype.slice.call(eCatchErr.arguments, 1); //remove index 0

	if (JSERR=='DEFAULT') {
		fu.apply(this, args);  
	} else {                
		try { 
			fu.apply(this, args);     
		} catch (e) {
			if (JSERR!='REPRESS') {
				var msg = e.message;
				var url = e.fileName;
				var line = e.lineNumber;
				if (JSERR=='CLIENT') {
					console.error(msg+'\n'+url+'\n'+'line:'+line);
				} else {
					writeJsErr(msg,url,line);       
				}
			}       
		}
	}

};


function npath(loc) {
	setCookie('navpath',loc.id);
};

function submitOnEnter(e,frm,typ) {
	var keynum;
	if(window.event) { // IE
		keynum = e.keyCode;
	} else if(e.which) { // Netscape/Firefox/Opera
		keynum = e.which
	}
	if (keynum==13) {
		frmSubmit(frm,typ);
	}
};

function frmSubmit(frm,typ) {
	switch (typ) {
	case 'SRH':
		if (frm.srh_txt.value!='') {
			frm.submit();
		}
		break;
	}
	return true;	
};

function usrLogout(frm) {
	frm.log_out.value = '1';
	frm.submit();
};

function searchPaging (frm, offset) {
	frm.srh_ofs.value = offset;
	frm.submit();
};

function decLevel(lvl) {
	lvl = lvl.toString();
	var lstr = 'rien,une,deux,trois,quatre,cinque,six,sept,huit,neuf,dix';
	var lvls = lstr.split(',');
	str = '';
	for (var i=0;i<lvl.length;i++) {
		var s = lvl.substr(i,1);
		var n = parseInt(s.charCodeAt());
		n+= i*3;
		var c = String.fromCharCode(n);
		str+= c;
	}
	num = -1;
	for (var i=0;i<lvls.length;i++) {
		if (lvls[i]==str) {
			num = i;
			break;
		}	
	}
	return parseInt(num);
};
function getDir(url) {
	var a = url.split('/');
	var d = '';
	for (var i=0;i<a.length-1;i++) {
		d+=a[i]+'/';
	}
	return d;
}

function getFile(url)
{
	var i, i2;
	
	i = url.lastIndexOf('/');
	i2 = url.lastIndexOf('\\');
	
	i = i > i2 ? i : i2;
	
	if (i < 0) return url;
	
	return url.substr(i+1);
}
function windowWidth(){
    if (window.innerWidth){
        if (document.body.offsetWidth){
            if (window.innerWidth!=document.body.offsetWidth)
                return document.body.offsetWidth;
            }
        return (window.innerWidth);                     // Mozilla
    }
    if (document.documentElement.clientWidth)
        return document.documentElement.clientWidth;    // IE6
    if (document.body.clientWidth)
        return document.body.clientWidth;               // IE DHTML-compliant any other
    return 800;
};
function windowHeight(){
    if (window.innerHeight){
        if (document.body.offsetHeight){
            if (window.innerHeight!=document.body.offsetHeight)
                return document.body.offsetHeight;
            }
        return (window.innerHeight);                     // Mozilla
    }
    if (document.documentElement.clientHeight)
        return document.documentElement.clientHeight;    // IE6
    if (document.body.clientHeight)
        return document.body.clientHeight;               // IE DHTML-compliant any other
    return 600;
};
function showRndImg(dir,elmId,rNum) {
	if (document.getElementById) {
		rNum = parseInt(rNum);
		var imgs = rndImgs[rNum];
		var num = Math.floor(Math.random() * imgs.length);
		var img = document.getElementById('img_' + elmId);
		var elm = document.getElementById('elm_' + elmId);
		img.src =  dir + imgs[num]['src'];
		img.alt = imgs[num]['alt'];
		img.title = imgs[num]['alt'];
		img.width = imgs[num]['w'];
		img.height = imgs[num]['h'];
		elm.style.width = imgs[num]['w'];
		elm.style.height = imgs[num]['h'];
		elm.style.marginLeft = imgs[num]['x'];
		elm.style.marginTop = imgs[num]['y'];
		setTimeout("showRndImg('"+dir+"','"+elmId+"',"+rNum+")",imgs[num]['wait']);
	}	
};
function ieReposFixed(id,algn,base,x,y,w,h) {
	var hAdj = 0;
	var wH = document.body.clientHeight;
	var wY = document.body.scrollTop;
	var elm = document.getElementById(id);
	if (base=='B') {
		elm.style.top = (document.body.clientHeight + document.body.scrollTop - hAdj - h - y)+'px';
	} else {
		elm.style.top = (document.body.scrollTop + y)+'px';
	}	
};
function showStat(s) {
	window.status=s;
	return true;
};
function setOpacity(elm,o) {
	var browser=elm.filters?'ie':typeof elm.style.MozOpacity=='string'?'moz':'';
	switch (browser) {
	case 'ie':
   		elm.style.filter='alpha(opacity='+(100*o)+')';
		break;
	case 'moz':
		elm.style.MozOpacity=o;
		break;
	default:
	}		
};
function swapImg(id,img) {
	document.getElementById(id).src = img;
};
function setStyle(elm,style) {
	elm.className=style;
};
function inArray(s,a) {
	var s1 = a.join('|');
	return (s1.indexOf(s)>-1);
};
function arraySearch(s,a) {
	var ret = false;
	for (var i=0;i<a.length;i++) {
		if (a[i]==s) {
			ret = i;
			break;
		}
	}		
	return (ret);
};
function strRepeat(s,num) {
	var rS='';
	for (var i=0;i<=num;i++) {
		rS+=s;
	}
	return rS;
};
function fldSizeToPx (s,pxFont) {
	if (!pxFont) pxFont=11;
	return s*pxFont;
};
function formSubmit(frm,txtReq,txtInvalid) {
	var req = [];
	var inval = [];
	
	for (var i=0; i<contFlds.length; i++) {
		if (contFlds[i]['req']=='Y') {
			if (frm[contFlds[i]['fld']].value=='') {
				req.length++;
				req[req.length-1] = contFlds[i]['name'];
			} else if (contFlds[i]['type']=='EMAIL') {
				if (!emailOK(frm[contFlds[i]['fld']].value)) {
					inval.length++;
					inval[inval.length-1] =contFlds[i]['name'];
				}
			}
		}
	}	
	var msgReq = '';			
	var msgInv = '';
	if (req.length>0) msgReq = txtReq + ':\n' + req.join(',') + '\n';			
	if (inval.length>0) msgInv = txtInvalid + ':\n' + inval.join(',');			
	if (msgReq!='' || msgInv!='') {
		console.log(msgReq+msgInv);
	} else {		
		frm.submit();
	}	
};

function capitalize (s) {

	if (s.length>0) {
		var s1 = s.substr(0,1).toUpperCase();
		if (s.length>1) {
			s1 += s.substr(1,s.length-1);
		}
	} else {
		s1 = s;
	}
	return s1;			
};

function isInteger (s) {   

	var ret = false;
	if (s.length>0) {
		ret = true;
		for (var i=0;i<s.length;i++) {   
			var c = s.charAt(i);
			if (!isDigit(c)) {
				ret = false;
				break;
			}	
		}
	}
    return ret;
};
function isDigit (c) {   
	return ((c >= "0") && (c <= "9"));
};
function emailOK (s) {   

	// Email address must be of form a@b.c -- in other words:
	// * there must be at least one character before the @
	// * there must be at least one character before and after the .
	// * the characters @ and . are both required
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;
	if (sLength<=3) return false;
    // look for @
    while ((i < sLength) && (s.charAt(i) != "@")) {
		i++;
    }
    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;
    // look for .
    while ((i < sLength) && (s.charAt(i) != ".")) {
		i++;
    }
    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
};

function stopPropagationEvent(e)
{
	e.stopPropagation();
}


function makeUrlName (name) 
{	
	name = name.toLowerCase();
	name = urlencode(name);
	name = name.replace('+', '_', 'g');
	return name;
	
};

function stripInvalidChars (s) {

	s = s.replace(/'/g,'');
	s = s.replace(/"/g,'');
	s = s.replace(/\)/g,'');
	s = s.replace(/\(/g,'');
	s = s.replace(/,/g,'');
	s = s.replace(/\./g,'');
	s = s.replace(/:/g,'');
	s = s.replace(/;/g,'');
	s = s.replace(/\[/g,'');
	s = s.replace(/\]/g,'');
	s = s.replace(/\</g,'');
	s = s.replace(/\>/g,'');
	s = s.replace(/\|/g,'');
	s = s.replace(/\*/g,'');
	s = s.replace(/\$/g,'');
	s = s.replace(/\%/g,'');
	s = s.replace(/\^/g,'');
	s = s.replace(/\&/g,'');
	s = s.replace(/\#/g,'');
	s = s.replace(/\@/g,'');
	s = s.replace(/!/g,'');
	s = s.replace(/\?/g,'');
	s = s.replace(/\//g,'');
	s = s.replace(/\+/g,'');
	s = s.replace(/\-/g,'');
	s = s.replace(/\=/g,'');
	
	return s;

};

function urlencode (clearString) 
{
	if (clearString === null) return null;
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
	var match = regex.exec(clearString.substr(x));
	if (match != null && match.length > 1 && match[1] != '') 
	{
		output += match[1];
		x += match[1].length;
	}
	else 
	{
		if (clearString[x] == ' ')
			output += '+';
		else 
		{
			var charCode = clearString.charCodeAt(x);
			var hexVal = charCode.toString(16);
			output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
		}
		x++;
	}
	}
	return output;
}

function urldecode (encodedString) 
{
	if (encodedString === null) return null;
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	
	while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') 
	{
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
	return output;
}


function addslashes( str ) {
	//This is a Javascript version of the PHP function: addslashes.
	// 
	// +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_addslashes/
	// +       version: 809.522
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Ates Goral (http://magnetiq.com)
	// +   improved by: marrtins
	// +   improved by: Nate
	// +   improved by: Onno Marsman
	// *     example 1: addslashes("kevin's birthday");
	// *     returns 1: 'kevin\'s birthday'
	if (str === null) return null;
	return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");   
}

function stripslashes( str ) {
	//This is a Javascript version of the PHP function: stripslashes
	
	// 
	// +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_stripslashes/
	// +       version: 809.522
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Ates Goral (http://magnetiq.com)
	// +      fixed by: Mick@el
	// +   improved by: marrtins
	// *     example 1: stripslashes('Kevin\'s code');
	// *     returns 1: "Kevin's code"
	if (str === null) return null;
	return str.replace('/\0/g', '0').replace('/\(.)/g', '$1');
}



function phpUnescape(s) {
	s = s.replace(/_Q/g,' ');
	s = s.replace(/_A/g,'&');
	s = s.replace(/_I/g,'=');
	return urldecode(s);
}

function fitDimension(width, height, maxWidth, maxHeight)
{
	var ratio;
	var newWidthBasedOnHeight;
	var newHeightBasedOnWidth;
	
	if (width < maxWidth && height < maxHeight)
	{	//Image is smaller then the desired dimensions
		return {w:width, h:height, resizeFactor: 1.0};
	}
	else
	{
		ratio = width / height;
		newWidthBasedOnHeight = parseInt(maxHeight * ratio);
		newHeightBasedOnWidth = parseInt(maxWidth / ratio);
		
		if (newWidthBasedOnHeight <= maxWidth) // Resizing by decreasing the height fits?
		{
			return {w:newWidthBasedOnHeight, h:maxHeight,resizeFactor:maxHeight / height};
		}
		else //if (newHeightBasedOnWidth <= maxHeight) // Resizing by decreasing the width fits?
		{
			return {w:maxWidth, h:newHeightBasedOnWidth, resizeFactor: maxWidth / width};
		} 
	} 
}
