// check browser 
var ie = (document.all);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var nn4 = (document.layers);
var nn6 = (document.getElementById && !ie);
var mz = (document.getElementById && !ie);
var bVersion = parseInt(navigator.appVersion);
//alert('Navigator\nappName = '+navigator.appName+'\nappCodeName = '+navigator.appCodeName+'\nappVersion = '+navigator.appVersion+'\nuserAgent = '+navigator.userAgent + '\nbVersion = ' + bVersion); // TEST 
/*
var $BROWSER = navigator.userAgent.split("/");
$BROWSER = $BROWSER[3].split(" ");
var $browserType = $BROWSER[1];
var $browserVersion = $BROWSER[0];
alert('browserType = ' + $browserType + '\nbrowserVersion = ' + $browserVersion); // TEST 
*/
/*
// TEST BROWSER 
var $displayBrowser = '';
if(ie) $displayBrowser += 'IE '; else $displayBrowser += '';
if(ie4) $displayBrowser += 'IE4 '; else $displayBrowser += '';
if(ie5) $displayBrowser += 'IE5 '; else $displayBrowser += '';
if(nn4) $displayBrowser += 'NN4 '; else $displayBrowser += '';
if(nn6) $displayBrowser += 'NN6 '; else $displayBrowser += '';
if(mz) $displayBrowser += 'MZ '; else $displayBrowser += '';
alert($displayBrowser);
*/

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();
//window.alert(BrowserDetect.browser + ' * ' + BrowserDetect.version + ' * ' + BrowserDetect.OS); // TEST 



// **********************************************************************************
// ====================== PROJECT SPEC. FUNCTIONS ===============================
// **********************************************************************************

//	EXPORT BOOK to EXCEL 
function exportBooks($part) {
	var $target = 'excel';
	var $url = PROJECTPATH + 'books_to_excel.php?part=' + $part;
	window.open($url, $target, 'left='+ $windowFromLeft +',top='+ $windowFromTop +',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes');
}

//	PRINT BOOK 
function printBooks($part) {
	var $target = 'print';
	var $url = PROJECTPATH + 'print_books.php?part=' + $part;
	window.open($url, $target, 'left='+ $windowFromLeft +',top='+ $windowFromTop +',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes');
}

//	Open / Close Book Comment Editor 
function openCloseEditBookComment($buttonId, $messageToDisplay, $messageToNone) {
	//alert(document.getElementById('editBookCommentArea').style.display);
	if(document.getElementById('editBookCommentArea').style.display == 'none' || document.getElementById('editBookCommentArea').style.display == '') {
		document.getElementById('editBookCommentArea').style.display = 'block';
		//document.getElementById($buttonId).className = 'transitRound bgGray';
		//document.getElementById($buttonId).childNodes[1].firstChild.nodeValue = $messageToNone;
	} else {
		document.getElementById('editBookCommentArea').style.display = 'none';
		//document.getElementById($buttonId).className = 'transitRound bgOrange';
		//document.getElementById($buttonId).childNodes[1].firstChild.nodeValue = $messageToDisplay;
	}
	//alert(document.getElementById('editBookCommentArea').style.display);
}

//	Edit Book Comment  
function editBookComment($thisId) {
	sendPostData($FULLREQUESTURI, {actio: 'editBookComment', thisId: $thisId});
}
//	Update Book Comment  
function updateBookComment($thisId) {
	sendPostData($FULLREQUESTURI, {actio: 'editBookComment', thisId: $thisId});
}
//	Delete Book Comment  
function deleteBookComment($thisId) {
	if (window.confirm(LNG_DO_YOU_WANT_DELETE_THIS_COMMENT + "\n" + LNG_FOREVER))	{
		sendPostData($FULLREQUESTURI, {actio: 'deleteBookComment', thisId: $thisId});
	}
}

// ************************  CUSTOMER SITE  ********************************************

// Log In 
function sendLogin()	{
	var $al = "";
	var $al2 = "";
	if (!gid('userLogin').value) { $al += LNG_USER_NAME +"\n"; }
	if (!gid('userPassword').value) { $al += LNG_PASSWORD +"\n"; }
	if ($al) { $al = LNG_FILL_UP_OR_CHOOSE +": \n=================\n" + $al + "\n\n"; }
	if ($al || $al2) {
		window.alert ($al + $al2);
		return false;
	}
	gid('auth_str').value = MD5(gid('u_key').value + gid('userPassword').value);
	gid('u_key').value = '';
	gid('userPassword').value = '';
	return true;
}

// Log Out 
function logOut() {
	location.replace(PROJECTPATH + 'users/log_off.php');
}

// user settings - book settings 
function userSettings($field, $actio, $bookId) {
	sendPostData($FULLREQUESTURI, {field: $field, actio: $actio, bookId: $bookId});
}

// change Currency 
function changeCurrency() {
	location.href = splitUrl($FULLREQUESTURI, 'currency', '&', 'currency=' + document.getElementById('changeCurrency').options[document.getElementById('changeCurrency').options.selectedIndex].value);
}

// change Products On Page 
function changeProductsOnPage($id) {
	location.href = splitUrl($FULLREQUESTURI, 'onPage', '&', 'onPage=' + document.getElementById($id).options[document.getElementById($id).options.selectedIndex].value);
}

// change Clients Product Settings 
function changeClientsProductSettings($id, $settings) {
	location.href = splitUrl($FULLREQUESTURI, $settings, '&', $settings + '=' + document.getElementById($id).options[document.getElementById($id).options.selectedIndex].value);
}

// empty ShoppingBag 
function emptyShoppingBag() {
	alert(LNG_SHOPPING_BAG_IS_EMPTY + "\n" + LNG_CHOOSE_SOME_ARTICLE);
}

// Remove from ShoppingBag and WishList 
function removeShopAndWish($iframeId, $bag_id, $what, $location) {
	$frameSrc = PROJECTPATH + "iframe_shoppingbag.php?lng=" + $lng + "&actio=" + $what + "&bag_id=" + $bag_id;
	//alert($frameSrc); // TEST 
	document.getElementById($iframeId).src = $frameSrc;
	if($location) {
		$setLink = PROJECTPATH + "" + $location + "/";
		window.setTimeout('location.href = \''+$setLink+'\'', 400);
	}
}
// Copy from ShoppingBag to WishList 
function copyFromBagToWish($iframeId, $bag_id) {
	$frameSrc = PROJECTPATH + "iframe_shoppingbag.php?lng=" +$lng + "&actio=copyFromBagToWish&bag_id=" + $bag_id;
	//alert($frameSrc); // TEST 
	document.getElementById($iframeId).src = $frameSrc;
}
// Copy from WishList to ShoppingBag 
function copyFromWishToBag($iframeId, $bag_id) {
	$frameSrc = PROJECTPATH + "iframe_shoppingbag.php?lng=" +$lng + "&actio=copyFromWishToBag&bag_id=" + $bag_id;
	//alert($frameSrc); // TEST 
	document.getElementById($iframeId).src = $frameSrc;
}
// UPDATE || DELETE QUANTITY 
function updateQuantity($bagId, $prdQuantity) {
	location.href = $CLEARPATH + "?actio=updateQuantity&bagId=" + $bagId + "&prdQuantity=" + $prdQuantity;
}
// DELETE from ShoppingBag 
function deleteFromBag($bagId) {
	var $iframeId = 'wishListFrame';
	$frameSrc = PROJECTPATH + "iframe_shoppingbag.php?lng=" +$lng + "&actio=bagRemove&bagId=" + $bagId;
	//alert($frameSrc); // TEST 
	document.getElementById($iframeId).src = $frameSrc;
	$setLink = PROJECTPATH + "shoppingbag/";
	window.setTimeout('location.href = \''+$setLink+'\'', 400);
}
// DELETE from Wish List 
function deleteFromWish($bagId) {
	var $iframeId = 'wishListFrame';
	$frameSrc = PROJECTPATH + "iframe_shoppingbag.php?lng=" +$lng + "&actio=wishRemove&bagId=" + $bagId;
	//alert($frameSrc); // TEST 
	document.getElementById($iframeId).src = $frameSrc;
	$setLink = PROJECTPATH + "wishlist/";
	window.setTimeout('location.href = \''+$setLink+'\'', 400);
}
// change Postage Type 
function changePostageType($value) {
	location.href = $CLEARPATH + "?postageType=" + $value;
}
// change Postage Payment 
function changePostagePayment($value) {
	location.href = $CLEARPATH + "?postagePayment=" + $value;
}
// switch Payment Type (invoice, bankDeposit)  
function switchPaymentType($type) {
	if($type == 'invoice') {
		document.getElementById('divBankDeposit').style.display = 'none';
		document.getElementById('payment_invoice').checked = true;
	}
	if($type == 'bankDeposit') {
		document.getElementById('divBankDeposit').style.display = 'block';
		document.getElementById('payment_bank_deposit').checked = true;
	}
}

// change SELECT with colors (files, sleeves, stones) 
function clickColor($mysqlName, $colorId, $selectId) {
	$options = document.getElementById($selectId).options;
	for($i=0; $i<$options.length; $i++) {
		if($options[$i].value == $mysqlName + '##' + $colorId) {
			$options[$i].selected = true;
		}
	}
}

// Shop - Product - Choose by Us | You 
function showHideParameters() {
	var $chooseByUs = document.getElementById('chooseByUs'); // div 
	var $checkChoose = document.getElementById('choose_by_us'); // checkbox 
	var $paramToChoose = document.getElementById('allParametersToChoose'); // div with all parameters to choose 
	if ($checkChoose.checked == false) {
		$checkChoose.checked = true;
		$paramToChoose.style.display = 'none';
	} else {
		$checkChoose.checked = false;
		$paramToChoose.style.display = 'block';
	}
}

// Forms - HELP BOX show and hide 
function showHideHelp($elementId) {
	var $display = document.getElementById($elementId);
	if($display.style.display == 'none' || !$display.style.display) $display.style.display = 'block'; else $display.style.display = 'none';
}


// ************************  ADMINISTRATION  ********************************************

// ADMIN change language (navigation) 
function changeLng() {
	$adminLng = document.getElementById("adminLng");
	for ($g=0; $g<$LNG_TO_SEE.length; $g++) {
		if ($adminLng.options[$g].selected == true) { location.href = splitUrl($FULLFILE, 'lng=', '&', 'lng=' + $LNG_TO_SEE[$g]); break; }
	}
}

// COMPARE register WITH clients 
function compare($clientId) {
	location.href = $FILE + '?compare=yes&section=compare&cln_id=' + $clientId;
}

// SEND POST DATA ($namesAndValues in form {user:'someone',password:'something'}) 
function sendPostData($action, $namesAndValues) {
  // creates FORM element 
	var $sendPostDataForm = document.createElement("form");
  $sendPostDataForm.method = "post";
  $sendPostDataForm.action = $action;
  for(var $i in $namesAndValues) {
    var $newInput = document.createElement("input") ;
    $newInput.setAttribute("type", "hidden");
    $newInput.setAttribute("name", $i);
    $newInput.setAttribute("value", $namesAndValues[$i]);
    $sendPostDataForm.appendChild($newInput) ;
  }
	var $body = document.getElementsByTagName("body")[0];
  $body.appendChild($sendPostDataForm);
  $sendPostDataForm.submit() ;
}

// show Language Box 
function showLangBox($lng) {
	for($g=0; $g<$LNG_TO_SEE.length; $g++) {
		document.getElementById($LNG_TO_SEE[$g] + 'Flag').style.background = '#FFF';
		document.getElementById($LNG_TO_SEE[$g] + 'Table').style.display = 'none';
	}
	document.getElementById($lng + 'Flag').style.background = '#999';
	document.getElementById($lng + 'Table').style.display = 'block';
}

// test WebName 
function testWebName($elementId) {
	$textDiv = document.getElementById($elementId);
	if (!/^[0-9a-z_-]*$/.test($textDiv.firstChild.nodeValue)) {
		$textDiv.style.fontWeight = 'bold';
		$textDiv.style.color = '#F00';
		alert(LNG_PLEASE_CHECK_THIS_STRING + "\n\n" + $textDiv.firstChild.nodeValue + "\n\n" + LNG_SOME_CHARACTERS_ARE_NOT_CORRECT_TRANSFORMED + "\n" + LNG_PLEASE_CHECK_TRANSLATION_FOR_LOCAL_CHARACTERS);
	}
}

// Round Button Over/Out 
function buttonTransitOverColor($buttonId, $actio, $setColor) {
	$oldClass = document.getElementById($buttonId).className.split(" "); // array 
	if($setColor) $setColorTo = ' ' + $setColor; else $setColorTo = '';
	if($actio) {
		document.getElementById($buttonId).className = $oldClass[0] + $setColorTo;
	} else {
		document.getElementById($buttonId).className = $oldClass[0] +  $setColorTo;
	}
}
// onclick Settings Button 
function onclickSettingsButton($buttonId) {
	if(document.getElementById($buttonId + 'Div').style.display == 'none') {
		document.getElementById($buttonId).className = 'transitRound bgOrange';
		document.getElementById($buttonId + 'Div').style.display = 'block';
		document.getElementById($buttonId).childNodes[1].firstChild.nodeValue = LNG_CLOSE_SETTINGS;
	} else {
		document.getElementById($buttonId).className = 'transitRound bgGray';
		document.getElementById($buttonId + 'Div').style.display = 'none';
		document.getElementById($buttonId).childNodes[1].firstChild.nodeValue = LNG_SETTINGS;
	}
}
// onclick Show Button 
function onclickShowButton($buttonId, $elementToShowId, $display, $transitColor) {
	if(document.getElementById($elementToShowId).style.display == 'none') {
		document.getElementById($buttonId).className = 'transitRound bgOrange';
		document.getElementById($elementToShowId).style.display = $display;
		document.getElementById($buttonId).childNodes[1].firstChild.nodeValue = LNG_CLOSE;
	} else {
		document.getElementById($buttonId).className = 'transitRound ' + $transitColor;
		document.getElementById($elementToShowId).style.display = 'none';
		document.getElementById($buttonId).childNodes[1].firstChild.nodeValue = LNG_NEW_EVENT;
	}
}

// COLOR BUTTON BackGround 
function colorButtonBg($id) { document.getElementById($id).style.background = '#FF3'; }
function colorOutButtonBg($id, $bgColor) { if($bgColor) document.getElementById($id).style.background = $bgColor; else  document.getElementById($id).style.background = '#FFF'; }

// Active / Inactive Section and Languages 
function changeActiveSection($active) {
	if($active=='0' || $active=='1') {
		document.getElementById('checkLngActive_all').checked = false;
	}
	if($active=='2') {
		document.getElementById('checkLngActive_all').checked = true;
	}
	if($active=='0' || $active=='1' || $active=='2') {
		colorActive($active);
	}
	if($active=='all') {
		if(document.getElementById('checkLngActive_all').checked == false) { // main ACTIVE is unchecked 
			document.getElementById('checkLngActive_all').checked = true;
			colorActive('2');
		} else {
			document.getElementById('checkLngActive_all').checked = false;
			colorActive('1');
		}
	}
	for($g=0; $g<$LNG.length; $g++) { colorLngActive($LNG[$g]); }
}
// Active / Inactive Section and Languages 
function changeLngActive($thisLng) {
	if(document.getElementById('checkLngActive_all').checked == true) { // main ACTIVE is checked 
		if(document.getElementById('checkLngActive_' + $thisLng).checked == false) { // is unchecked 
			document.getElementById('checkLngActive_' + $thisLng).checked = true;
		} else {
			document.getElementById('checkLngActive_' + $thisLng).checked = false;
		}
	}
	colorLngActive($thisLng);
}
// Color Active  
function colorActive($active) {
	if($active=='0') {
		document.getElementById('eyeLngActive_all').src = '../img/ik_eye_green.gif';
		document.getElementById('divLngActive_all').style.background = '#CCC'; // gray bg 
		document.getElementById('spanLngActive_all').firstChild.nodeValue = LNG_DELETED;
	}
	if($active=='1') {
		document.getElementById('eyeLngActive_all').src = '../img/ik_eye_gray.gif';
		document.getElementById('divLngActive_all').style.background = '#FFF'; // white bg 
		document.getElementById('spanLngActive_all').firstChild.nodeValue = LNG_INACTIVE;
	}
	if($active=='2') {
		document.getElementById('eyeLngActive_all').src = '../img/ik_eye_blue.gif';
		document.getElementById('divLngActive_all').style.background = '#FF9'; // yellow bg 
		document.getElementById('spanLngActive_all').firstChild.nodeValue = LNG_ACTIVE;
	}
}
// Color Languages 
function colorLngActive($thisLng) {
	if(document.getElementById('checkLngActive_all').checked == true) { // main ACTIVE is checked 
		if(document.getElementById('checkLngActive_' + $thisLng).checked == true) { // is checked 
			document.getElementById('eyeLngActive_' + $thisLng).src = '../img/ik_eye_blue.gif';
			document.getElementById('divLngActive_' + $thisLng).style.background = '#FF9'; // yellow bg 
		} else {
			document.getElementById('eyeLngActive_' + $thisLng).src = '../img/ik_eye_gray.gif';
			document.getElementById('divLngActive_' + $thisLng).style.background = '#FFF'; // white bg 
		}
	} else {
		document.getElementById('divLngActive_' + $thisLng).style.background = '#CCC'; // gray bg 
		if(document.getElementById('checkLngActive_' + $thisLng).checked == true) { // is checked 
			document.getElementById('eyeLngActive_' + $thisLng).src = '../img/ik_eye_blue.gif';
		} else {
			document.getElementById('eyeLngActive_' + $thisLng).src = '../img/ik_eye_gray.gif';
		}
	}
}

// SWITCH BETWEEN PICTURES PREVIEW (used in 'adm_shop_products') 
function switchToPic($nr, $max) {
	for($i=1; $i<=$max; $i++) {
		if($i==$nr) {
			document.getElementById('picturePreview' + $i).style.display = 'block';
		} else {
			document.getElementById('picturePreview' + $i).style.display = 'none';
		}
	}
}

// ****************************************************** 
// ************** PAGE navigation -> change page ************* 
// ****************************************************** 

function focusPage() {
	$nr = document.getElementById('nrPage');
	$nr.select();
}

function goToPage(e) {
  // get the event
  e = (!e) ? window.event : e;
  // get the character code of the pressed button
  code = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0));
  // check to see if the event was keyup
	//alert(e.type);
  if (e.type == "keydown") {
    if (code == 9 || code == 13) { // tab or enter 
			$nr = document.getElementById('nrPage');
			$nrValue = $nr.value;
			if(!/^[0-9]+$/.test($nrValue) || $nrValue == "0" || $nrValue == false || $nrValue > $lastPage) {
				window.alert (LNG_FIELD_INPUT_PAGE_DEFINITION);
				$nr.value = $oldValue;
				$nr.select();
			} else {
				$href = splitUrl($FULLFILE, 'page', '&', 'page=' + $nrValue);
				//alert($href); // TEST 
				location.href = $href;
			}
		}
		//else if (code >= 48 || code <= 57) { }// number 0-9 
	}
}


// **********************************************************************************
// ====================== UNIVERSAL FUNCTIONS ==================================
// **********************************************************************************

var $mainDivWidth = 1000; // ******* change main DIV width 

// ALL MEASURES OF SCREEN, WINDOW, FRAME etc. 
var frameWidth = 0;
var frameHeight = 0;
var $innerW = 0;
var $innerH = 0;
var screenWidth = 0;
var screenHeight = 0;
var $mainDivLeft = 0;
var $mainDivTop = 0;

function allMeasures() {
	if (mz) { // MZ... 
		frameWidth = window.innerWidth;
		frameHeight = window.innerHeight;
		$innerW = window.innerWidth;
		$innerH = window.innerHeight;
	} else if (self.innerWidth) { // all except IE = FireFox, MZ, NN... 
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
		$innerW = self.innerWidth;
		$innerH = self.innerHeight;
	} else if (document.documentElement && document.documentElement.offsetWidth) { // IE 6 
		frameWidth = document.documentElement.offsetWidth;
		frameHeight = document.documentElement.offsetHeight;
		$innerW = document.documentElement.offsetWidth;
		$innerH = document.documentElement.offsetHeight;
	} else if (document.body) { // other IE 
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
		$innerW = document.body.clientWidth;
		$innerH = document.body.clientHeight;
	}
	if (self.screen) {
		screenWidth = screen.width;
		screenHeight = screen.height;
	}
	$mainDivLeft = $innerW > $mainDivWidth ? Math.ceil(($innerW - $mainDivWidth) / 2) : 0;
	$mainDivTop = 0;
	//alert(screenWidth + ' * ' + screenHeight + ' | ' + frameWidth + ' * ' + frameHeight);
	//setStatusOuter();
}
window.onresize = allMeasures;
allMeasures();

function setStatValues()	{
	document.cookie = "cnt_monitor="+ screenWidth +"x"+ screenHeight;
//	document.cookie="cnt_window="+ frameWidth +"x"+ frameHeight;
	document.cookie="cnt_color="+ (screen.pixelDepth ? screen.pixelDepth : screen.colorDepth);
}

// FOR TESTS... 
// show outer width and height in status 
function setStatusOuter() {
	$measuresMessage = '';
	//$measuresMessage += 'window outer width and height = ' + window.outerWidth + ' * ' + window.outerHeight;
	$measuresMessage += 'window inner width and height = ' + window.innerWidth + ' * ' + window.innerHeight;
	//$measuresMessage += ' :: screen width & height = ' + window.screen.availWidth + ' * ' + window.screen.availHeight;
	$measuresMessage += ' :: window from top and left = ' + window.screenY + ' * ' + window.screenX;
	$measuresMessage += ' :: main div from top and left = ' + $mainDivTop + ' * ' + $mainDivLeft;
	//window.status = $measuresMessage;
	//alert($measuresMessage);
}

var $windowFromTop = window.screenY;
var $windowFromLeft = window.screenX;

// shortcut for "getElementById" (only for mz) 
function gid(what)	{
	if (document.getElementById(what)) return document.getElementById(what);
	else if (eval(what)) return eval(what);
	else return false;
}

// shortcut for "getElementById" or for ie4 or for nn4 
function elem(what)	{
	if(mz || ie5) {
		if (document.getElementById(what)) return document.getElementById(what);
		else if (eval(what)) return eval(what);
		else return false;
	}
	if(ie4) {
		if (document.all.what) return document.all.what;
		else if (eval(what)) return eval(what);
		else return false;
	}
	if(nn4) {
		if (document.layers[what]) return document.layers[what];
		else if (eval(what)) return eval(what);
		else return false;
	}
}

// FUNCTION NOT ACTIVE 
function functionNotActive() {
	alert(LNG_WE_ARE_SORRY + "\n" +LNG_THIS_FUNCTION_IS_NOT_AVAILABLE_AT_THIS_TIME);
}

// NO USER RIGHTS 
function noRights() {
	alert(LNG_WE_ARE_SORRY + "\n" + LNG_USER_RIGHTS_DISALOW_THIS_ACTION + "\n" + LNG_CONTACT_ADMINISTRATOR);
}

// **** LOGIN  **** //
function checkLogin()	{
	var $al = "";
	var $al2 = "";
	if (!document.getElementById('login').value || document.getElementById('login').value == '(' + LNG_YOUR_EMAIL + ')') { $al += LNG_YOUR_LOGIN + "\n"; }
	if (!document.getElementById('pwd').value) { $al += LNG_PASSWORD + "\n"; }
	if ($al) { $al = LNG_FILL_UP_OR_CHOOSE + ":\n=================\n" + $al + "\n\n"; }
	if (document.getElementById('login').value && document.getElementById('login').value != '(' + LNG_YOUR_EMAIL + ')' && !checkMail(document.getElementById('login').value)) { $al2 += LNG_EMAIL_WRONG_FORMAT + "\n"; }
	if ($al2) { $al2 += "===============================\n" + LNG_PLEASE_CHECK_IT_AND_CORRECT_IT + "\n\n\n"; }
	if ($al || $al2) {
		window.alert ($al + $al2);
		return false;
	}
	document.getElementById('auth_str').value = MD5(document.getElementById('u_key').value + document.getElementById('pwd').value);
	document.getElementById('u_key').value = '';
	document.getElementById('pwd').value = '';
	return true;
}


// **** POPUPS  **** //

var $axisX = 0;
var $axisY = 0;

function getMouseXY(e) {
	if (ie)	{
		$axisX = event.clientX + document.body.scrollLeft;
		$axisY = event.clientY + document.body.scrollTop;
	} else {
		$axisX = e.pageX;
		$axisY = e.pageY;
	}  
	if ($axisX < 0) { axisX = 0; }
	if ($axisY < 0) { axisY = 0; }
	//window.status = 'mouse x * y = ' + axisX + ' * ' + axisY;
	return $axisX;
	return $axisY;
}

// INIT 
document.onmousemove = getMouseXY;
if (nn4 || mz) document.captureEvents(Event.CLICK | Event.MOUSEMOVE)

/*
// FOR TEST MOUSE X & Y 
var mX = 0;
var mY = 0;
//if (!ie) document.captureEvents(Event.MOUSEMOVE);
function mouseXY(e) {
	if (ie) { // if browser is IE 
		mX = event.clientX + document.body.scrollLeft;
		mY = event.clientY + document.body.scrollTop;
	} else {  // if browser is other as IE 
		mX = e.pageX;
		mY = e.pageY;
	}
	if (mX < 0) { mX = 0; }
	if (mY < 0) { mY = 0; }
	window.status = 'mouse x * y = ' + mX + ' * ' + mY;
	return true;
}
// show mouse coordinate in status 
//document.onmousemove = mouseXY;
*/
/* // ORIG
function show(str)	{
	if (ie5 || nn6) {
		document.getElementById(str).style.left = axisX;
		document.getElementById(str).style.top = axisY;
	}
	if (ie4) {
		document.all.str.style.left = axisX;
		document.all.str.style.top = axisY;
	}
	if (nn4) {
		document.layers[str].style.left = axisX;
		document.layers[str].style.top = axisY;
	}
	if (ie5 || nn6)	{	document.getElementById(str).style.display = "block";	}
	if (ie4)	{	document.all.str.style.display = "block";	}
	if (nn4)	{	document.layers[str].style.display = "block";	}
}
*/

// NEW DX 
// elementId, slide in x, slide in y, abs. pos. elem. from left, abs. pos. elem. from top, elem. width, elem.height 
function show($elemId, $x, $y, $absX, $absY, $elemW, $elemH) {
	if (mz) {
		// coord of mouse x|y + abs. pos. elem. from left|top + slide x|y + element W|H + 15 scroll 
		if($axisX + $x + $elemW + 25 > $innerW) {
			$totalX = $axisX - $absX - $x - $elemW;
		} else {
			$totalX = $axisX - $absX + $x;
		}
		elem($elemId).style.left = $totalX + 'px';
		if($axisY + $y + $elemH + 25 > $innerH) {
			$totalY = $axisY - $absY + $y - $elemH;
			//elem($str).style.bottom = $totalY;
			elem($elemId).style.top = $totalY + 'px';
		} else {
			$totalY = $axisY - $absY + $y;
			elem($elemId).style.top = $totalY + 'px';
		}
		elem($elemId).style.display = "block";
		// status bar 
		/*
		window.status = ''
			+ 'outer W|H = ' + $outerW + '|' + $outerH 
			+ ' :: inner W|H = ' + $innerW + '|' + $innerH 
			+ ' :: $axisX + $x = ' + $axisX + ' + ' + $x + ' = ' + ($axisX + $x) + ' :: $axisY + $y = ' + $axisY + ' + ' + $y + ' = ' + ($axisY + $y) 
			+ ' :: element W|H = ' + $elemW + '|' + $elemH
			+ ' :: $axisX - $absX + $x + $elemW = ' + ($axisX - $absX + $x + $elemW);
			*/
	}
}

// SHOW on CLIENT WEB 
function showNoOrderMessage($elemId)	{
	elem($elemId).style.left = '86px';
	elem($elemId).style.top = '30px';
	elem($elemId).style.display = "block";
}
function showChangeTerminMessage($elemId, $x, $y, $elemW, $elemH)	{
	$totalX = $axisX - $mainDivLeft;
	$totalY = $axisY - $mainDivTop;
	//alert('total X|Y = ' +$totalX + '|' +$totalY); // TEST 
	// coord of mouse x|y + abs. pos. elem. from left|top + slide x|y + element W|H + 20 scroll 
	if($axisX + $x + $elemW + 20 > $innerW - 20) {
		$totalX = $totalX - ($x +20 + $elemW);
	} else {
		$totalX = $totalX + $x + 20;
	}
	if($axisY + $y + $elemH + 20 > $innerH - 20) {
		$totalY = $totalY - ($y + 20 + $elemH);
	} else {
		$totalY = $totalY + $y;
	}
	elem($elemId).style.left = $totalX;
	elem($elemId).style.top = $totalY;
	elem($elemId).style.display = "block";
	$testMessage = ''
		+ ' :: inner W|H = ' + $innerW + '|' + $innerH 
		+ ' :: $axisX + $x = ' + $axisX + ' + ' + $x + ' = ' + ($axisX + $x) + ' :: $axisY + $y = ' + $axisY + ' + ' + $y + ' = ' + ($axisY + $y) 
		+ ' :: element W|H = ' + $elemW + '|' + $elemH
		+ ' :: total X|Y = ' + $totalX + '|' + $totalY;
	//window.status = $testMessage;
	//alert($testMessage); // TEST 
}

function hide($elemId)	{
	elem($elemId).style.display = "none";
}
// **** end POPUPS  **** //


// ADMIN - sections / rubrics 
function switchRows($trId, $last) {
	var $rowElement = document.getElementById("tr" + $trId);
	var $path = "../img/";
	if ($rowElement.style.display != "none") {
		$rowElement.style.display = "none";
		document.getElementById("img" + $trId).src = $path + "ik_tree_p" + $last + ".gif";
	} else {
		$rowElement.style.display = "block";
		document.getElementById("img" + $trId).src = $path + "ik_tree_m" + $last + ".gif";
	}
}

// ADMIN - sections / categories - show and hide 
function showAndHideRows($rowId) {
	var $rowElement = document.getElementById("row_" + $rowId);
	var $source = document.getElementById("img" + $rowId).src;
	var $image = $source.substring($source.indexOf('ik_tree'));
	//alert($source + ' * ' + $image); // TEST 
	if ($rowElement.style.display != "none") {
		$rowElement.style.display = "none";
		if($image == "ik_tree_m.gif") {
			document.getElementById("img" + $rowId).src = "../img/ik_tree_p.gif";
		} else if($image == "ik_tree_me.gif") {
			document.getElementById("img" + $rowId).src = "../img/ik_tree_pe.gif";
		}
	} else {
		$rowElement.style.display = "block";
		if($image == "ik_tree_p.gif") {
			document.getElementById("img" + $rowId).src = "../img/ik_tree_m.gif";
		} else if($image == "ik_tree_pe.gif") {
			document.getElementById("img" + $rowId).src = "../img/ik_tree_me.gif";
		}
	}
}


// function that escapes a string  ******************************************************** FCE encode URI ******
function encode(uri) {
	if (encodeURIComponent) {
		return encodeURIComponent(uri);
	}
	if (escape) {
		return escape(uri);
	}
}

// CLOSE POPUP WINDOW 
function closeWin($time) {
	if($time && $time > 0) {
		window.setTimeout('window.close()', $time);
	} else {
		window.close();
	}
}

// PRINT WINDOW 
function printWin()	{
	window.print();
}


// CONFIRM user changes  
var $confirm = false; // global variable -> set confirm 

// POPUP WINDOWS STAY ALL THE TIME IN FRONT 
// break refresh window on top -> show alert -> restore window on top 
var $popupOn = false; // global variable -> set confirm 

function popupAlert($what) {
	if($popupOn == true) { stayBack(); }
	window.alert($what);
	if($popupOn == true) { stayOnTop(); }
}

var $stayTop = false;
var $timer = '';
// Brings the current window on top of others 
function stayOnTop() {
	if(!ie) {
		$timer = window.setTimeout("stayOnTop()", 200);
		$stayTop = true;
		window.focus();
	}
}

// Cancel bringing the current window on top of others 
function stayBack() {
	if($stayTop) {
		window.clearTimeout($timer);
		$stayTop = false;
	}
}



// **********************************************************************************
// =========================== STRING & NUMBER ================================
// **********************************************************************************


// Check E-Mail 
function checkMail($mail) {
	if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test($mail)) return 1;
	else return 0;
}

// SUBSTRING2 (from, length) 
function substring2($string, $start, $length) {
	if($string) {
		return $string.substring($start, $start + $length);
	} else { return ''; }
}

// SPRINTF = like at PHP, just limited to max. 5 parts 
function sprintf($string, $part0, $part1, $part2, $part3, $part4) {
	$splitedString = $string.split("%s"); // array 
	$returnedText = $splitedString[0];
	for($i=0; $i<$splitedString.length; $i++) {
		if($i==1) { $returnedText += $part0 + $splitedString[$i]; }
		if($i==2) { $returnedText += $part1 + $splitedString[$i]; }
		if($i==3) { $returnedText += $part2 + $splitedString[$i]; }
		if($i==4) { $returnedText += $part3 + $splitedString[$i]; }
		if($i==5) { $returnedText += $part4 + $splitedString[$i]; }
	}
	return $returnedText;
}

// COUNT CHARACTER in fieldId, maxLength   
function countChar($fieldToCount, $maxLimit) {
	$alertText = sprintf(LNG_FIELD_CAN_CONTAIN_MAX_X_CHARACTER, $maxLimit);
	//alert($fieldToCount+' * '+$maxLimit);
	//$fieldToCount = document.getElementById($fieldToCount);
	if(!$fieldToCount) $fieldValue = ''; else $fieldValue = $fieldToCount.value;
	//alert($fieldValue);
	if ($fieldValue.length > $maxLimit) {
		window.alert($alertText);
		$fieldToCount.value = $fieldValue.substring(0, $maxLimit);
	}
}

// split and replace part of string or url  
function splitUrl($string, $p1, $p2, $replace) {
	if(parseInt($string.indexOf('?')) == -1) $join = '?'; else $join = '&';
	$pos1 = parseInt($string.indexOf($p1));
	$pos2 = parseInt($string.indexOf($p2, ($pos1+1)));
	//alert($pos1 + ' * ' + $pos2);
	//alert($pos1 + ' * ' + parseInt($pos1) + ' * ' + ($pos1+1) + ' * ' + $pos2);
	if($pos1==-1) {
		if($replace=='') {
			$url = $string;
		} else {
			$url = $string + $join + $replace;
		}
	} else if($pos1 && $pos2==-1) {
		if($replace=='') {
			$url = $string.substring(0, ($pos1-1)) + $replace;
		} else {
			$url = $string.substring(0, $pos1) + $replace;
		}
	} else {
		if($replace=='') {
			$url = $string.substring(0, ($pos1-1)) + $replace + $string.substring($pos2);
		} else {
			$url = $string.substring(0, $pos1) + $replace + $string.substring($pos2);
		}
	}
	//alert($url);
	return $url;
}

// check input file type 
function returnFileInputType($inputId) {
	$input = document.getElementById($inputId).value;
	$lastDotPosition = parseInt($input.lastIndexOf('.'));
	if($lastDotPosition == -1) {
		return '';
	} else {
		$checkedType = $input.substring($lastDotPosition+1);
		return $checkedType.toLowerCase();
		//alert('checkedType = ' + $checkedType.toLowerCase()); // TEST 
	}
}

// check input file type 
function checkFileInputType($inputId, $docType) {
	$input = document.getElementById($inputId).value;
	$lastDotPosition = parseInt($input.lastIndexOf('.'));
	if($lastDotPosition == -1) {
		return false;
	} else {
		$checkedType = returnFileInputType($inputId);
		//alert('checkedType * docType = ' + $checkedType.toLowerCase() + ' * ' + $docType.toLowerCase()); // TEST 
		if($checkedType.toLowerCase() != $docType.toLowerCase()) {
			return false;
		} else {
			return true;
		}
	}
}


// is Number ?? 
function isNum($number) {
	if (/^[0-9]+$/.test($number)) return true; else return false;
}

// check Number ?? 
function checkNum($number) {
	if (/^[0-9]+$/.test($number)) return $number; else return '';
}

// check Barcode 
function checkBarcode($code, $fieldId) {
	if (!/^[0-9]+$/.test($code)) {
		document.getElementById($fieldId).select();
		myAlert (sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_BARCODE+"'"));
		document.getElementById($fieldId).focus();
	}
}

// if the number is smaller than 10, add in front of it "0"	[+ parameter how should be display zero "0" (e.g. "00")]
function toTen($number, $oo) {
	if (!$oo) $oo = '00';
	if ($number==0) { return $oo; }
	else if ($number>0 && $number<10) { return '0' + $number; }
	else { return $number; }
}

// return just number from number, what has '0' in front of it 
function toOne($number) {
	if ($number) {
		return parseInt($number, 10);
	} else {
		return 0;
	}
}

// is Price ?? 
function isPrice($number) {
	if (/^[0-9\.,]+$/.test($number)) return true; else return false;
}

// Clear Price => suppose price with 2 decimal numbers 
function clearPrice($value, $newDecimalPoint) {
	if(!$newDecimalPoint) $newDecimalPoint = ".";
	if($value) {
		$integralNumber = $value.substring(0, ($value.length - 3));
		$decimalNumber = $value.substring(($value.length - 2), $value.length);
		
		$integralNumber = str_replace(['.', ','], '', $integralNumber); // $integralNumber.preg_replace(/,*|\.*/, "");
		return $integralNumber + $newDecimalPoint + $decimalNumber;
	} else {
		return "0" + $newDecimalPoint + "00";
	}
}

// convert / make price 
function makePrice($value, $oldThousandSeparator, $oldDecimalPoint, $newThousandSeparator, $newDecimalPoint) {
	if(!$oldThousandSeparator) $oldThousandSeparator = "";
	if(!$oldDecimalPoint) $oldDecimalPoint = ",";
	if(!$newThousandSeparator) $newThousandSeparator = "";
	if(!$newDecimalPoint) $newDecimalPoint = ".";
	if($value || $value > 0) {
		if($oldDecimalPoint && $value.substring($value.length - 2, $value.length - 3) == $oldDecimalPoint) {
			var $numArray = $value.split($oldDecimalPoint);
			$integralNumber = $numArray[0];
			$decimalNumber = $numArray[1];
		} else {
			$integralNumber = $value;
			$decimalNumber = '00';
		}
		if($oldThousandSeparator) {
			$integralNumber = str_replace($oldThousandSeparator, "", $integralNumber);
		}
		if($newThousandSeparator) {
			$length = $integralNumber.length;
			$parts = Math.ceil($length / 3);
			$rest = $length % 3 == 0 ? 3 : $length % 3;
			//alert($length +'*'+ $parts +'*'+ $rest);
			$array = new Array();
			for($i=0; $i<$parts; $i++) {
				if($i == 0) {
					$array[0] = substring2($integralNumber, 0, $rest);
				} else {
					$array[$i] = substring2($integralNumber, $rest + ($i-1) * 3, 3);
				}
			}
			if($integralNumber > 0 || $decimalNumber > 0 || $decimalNumber != '00') {
				return $array.join($newThousandSeparator) + $newDecimalPoint + $decimalNumber;
			} else { return ''; }
		} else {
			if($integralNumber > 0 || $decimalNumber > 0 || $decimalNumber != '00') {
				return $integralNumber + $newDecimalPoint + $decimalNumber;
			} else { return ''; }
		}
	} else { return ''; }
}



// **********************************************************************************
// ============================ DATE & TIME ===================================
// **********************************************************************************


// check DATE (Year=YYYY, Year From, Year To) 
function checkYear($YYYY, $yearFrom, $yearTo) {
	if(!$yearFrom) $yearFrom = 1900;
	if(!$yearTo) $yearTo = 2100;
	//alert($YYYY+' '+$yearFrom+' '+$yearTo);
	var $al = '';
	
	if ($YYYY && (!/^[0-9]{1,4}$/.test($YYYY))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_YEAR+"'") +"\n"; }
	
	if (!($YYYY >= $yearFrom && $YYYY <= $yearTo)) {
		$al += sprintf(LNG_FILL_YEAR_BETWEEN, $yearFrom, $yearTo) +"\n"; }
	
	return $al;
}

// check DATE (Year=YYYY, Month=MM, Day=DD, Year From, Year To) 
function checkDate($YYYY, $MM, $DD, $yearFrom, $yearTo) {
	//alert($YYYY+' '+$MM+' '+$DD);
	if(!$yearFrom) $yearFrom = 1900;
	if(!$yearTo) $yearTo = 2100;
	var $al = '';
	
	if ($DD && (!/^[0-9]{1,2}$/.test($DD))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_DAY+"'") +"\n"; }
	if ($MM && (!/^[0-9]{1,2}$/.test($MM))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_MONTH+"'") +"\n"; }
	if ($YYYY && (!/^[0-9]{1,4}$/.test($YYYY))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_YEAR+"'") +"\n"; }
	
	if ($DD < 1) { $al += sprintf(LNG_FILL_UP_X, "'"+LNG_DAY+"'") +"\n"; }
	if (!($MM>=1 && $MM <= 12)) {
		$al += LNG_FILL_MONTH_BETWEEN +"\n"; }
	if (!($YYYY >= $yearFrom && $YYYY <= $yearTo)) {
		$al += sprintf(LNG_FILL_YEAR_BETWEEN, $yearFrom, $yearTo) +"\n"; }
	if ($YYYY%4 != 0 && $MM == 2 && $DD > 28) {
 		$al += LNG_FEBRUARY_28_DAYS +"\n"; }
	if ($YYYY%4 == 0 && $MM == 2 && $DD > 29) {
		$al += LNG_FEBRUARY_29_DAYS +"\n"; }
	if (($MM == 1 || $MM == 3 || $MM == 5 || $MM == 7 || $MM == 8 || $MM == 10 || $MM == 12) && ($DD > 31)) {	// in months = 1,3,5,7,8,10,12 = 31 days
		$al += LNG_MONTH_MAX_31_DAYS +"\n"; }
	if (($MM == 4 || $MM == 6 || $MM == 9 || $MM == 11) && ($DD > 30)) {	// in months = 4,6,9,11 = 30 days
		$al += LNG_MONTH_MAX_30_DAYS +"\n"; }
	
	return $al;
}

// check TIME (Hour=HH, Minute=ii, Second=ss) 
function checkTime($HH, $ii, $ss) {
	//alert($HH+' '+$ii+' '+$ss);
	var $al = '';
	
	if ($HH && (!/^[0-9]{1,2}$/.test($HH))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_HOURS+"'") +"\n"; }
	if ($ii && (!/^[0-9]{1,2}$/.test($ii))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_MINUTES+"'") +"\n"; }
	if ($ss && (!/^[0-9]{1,2}$/.test($ss))) { $al += sprintf(LNG_IN_FIELD_ONLY_NUMBERS, "'"+LNG_SECONDS+"'") +"\n"; }
	
	if (!(toOne($HH) >= 0 && toOne($HH) <= 23)) {
		$al += LNG_FILL_HOURS_BETWEEN +"\n"; }
	if (!(toOne($ii) >= 0 && toOne($ii) <= 59)) {
		$al += LNG_FILL_MINUTES_BETWEEN +"\n"; }
	if (!(toOne($ss) >= 0 && toOne($ss) <= 59)) {
		$al += LNG_FILL_SECONDS_BETWEEN +"\n"; }
	
	return $al;
}


// check ALL DATES form like EU with dots "28.05.2006" or "28.05.06", EU without dots "28052006" or "280506" and SQL "2006-05-28" 
function checkAllDates($value, $type) {
	
	var $yearTwoDigits = 29;  // yers with 2 digits => 1930 - 2029 
	
	if(!$type ||$type == 'value') { $date = $value; }
	if($type == 'input') { $date = document.getElementById($value).value; }
	if($type == 'tag') { $date = document.getElementById($value).firstChild.nodeValue; }
	//alert($date+' '+$type); // TEST 

	if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$/.test($date)) {
		// for EU date with dots like "28.5.2006" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2}$/.test($date)) {
		// for EU date with dots like "28.5.06" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YY = $array[2];
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;

	} else if (/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/.test($date)) {
		// for EU date with dash like "28-5-2006" 
		var $array = $date.split("-");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];

	} else if (/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/.test($date)) {
		// for EU date with slash like "28/5/2006" 
		var $array = $date.split("/");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/.test($date)) {
		// for date from "2006-5-28" 
		var $array = $date.split("-");
		var $DD = $array[2];
		var $MM = $array[1];
		var $YYYY = $array[0];
		
	} else if (/^[0-9]{8}$/.test($date)) {
		// for EU date without dots like "28052006" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YYYY = $date.substring(4,8);
		
	} else if (/^[0-9]{6}$/.test($date)) {
		// for EU date without dots like "280506" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YY = $date.substring(4,6);
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;
		
	} else if (/^[0-9]{4}$/.test($date)) {
		// for EU date without dots and year is actual -> like "2805" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $thisDay = new Date();
		var $YYYY = $thisDay.getFullYear();
	}
	//alert('Date: ' + $date + ' | Day: ' + $DD + ' * ' + toOne($DD) + ' * ' + toTen(toOne($DD)) + ' | Month: ' + $MM + ' * ' + toOne($MM) + ' * ' + toTen(toOne($MM)) + ' | Year: ' + $YY + ' * ' + toOne($YY) + ' * ' + $YYYY);
	
	return checkDate($YYYY, toTen(toOne($MM)), toTen(toOne($DD)));
}

function checkAllDates3Fields($obj1, $obj2, $obj3) {
	//alert($obj1 + ' ' + $obj2 + ' ' + $obj3);
	var $DD = document.getElementById($obj1).value;
	var $MM = document.getElementById($obj2).value;
	var $YYYY = document.getElementById($obj3).value;
	//alert($DD + ' * ' + $MM + ' * ' + $YYYY);
	
	return checkAllDates($YYYY, toTen(toOne($MM)), toTen(toOne($DD)));
}

// change ALL DATES form like EU with dots "28.05.2006" or "28.05.06", EU without dots "28052006" or "280506" and SQL "2006-05-28" 
// to SQL 
function changeAllDatesToSqlDate($date) {
	
	var $yearTwoDigits = 29;  // yeras with 2 digits => 1930 - 2029 
	
	if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$/.test($date)) {
		// for EU date with dots like "28.5.2006" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2}$/.test($date)) {
		// for EU date with dots like "28.5.06" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YY = $array[2];
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;

	} else if (/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/.test($date)) {
		// for EU date with dash like "28-5-2006" 
		var $array = $date.split("-");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];

	} else if (/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/.test($date)) {
		// for EU date with slash like "28/5/2006" 
		var $array = $date.split("/");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/.test($date)) {
		// for date from "2006-5-28" 
		var $array = $date.split("-");
		var $DD = $array[2];
		var $MM = $array[1];
		var $YYYY = $array[0];
		
	} else if (/^[0-9]{8}$/.test($date)) {
		// for EU date without dots like "28052006" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YYYY = $date.substring(4,8);
		
	} else if (/^[0-9]{6}$/.test($date)) {
		// for EU date without dots like "280506" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YY = $date.substring(4,6);
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;
		
	} else if (/^[0-9]{4}$/.test($date)) {
		// for EU date without dots and year is actual -> like "2805" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $thisDay = new Date();
		var $YYYY = $thisDay.getFullYear();
	}
	
	var $newDate = $YYYY + '-' + toTen(toOne($MM)) + '-' + toTen(toOne($DD));
	//alert('Date: ' + $date + ' | Day: ' + $DD + ' * ' + toOne($DD) + ' * ' + toTen(toOne($DD)) + ' | Month: ' + $MM + ' * ' + toOne($MM) + ' * ' + toTen(toOne($MM)) + ' | Year: ' + $YY + ' * ' + toOne($YY) + ' * ' + $YYYY + ' * ' + $newDate);
	if($date && $DD && $DD != '00' && $MM && $MM != '00' && $YYYY && $YYYY != '0000') {
		return $newDate;
	} else {
		return '';
	}
}


// change ALL DATES form like EU with dots "28.05.2006" or "28.05.06", EU without dots "28052006" or "280506" and SQL "2006-05-28" 
// to EU with dots
function changeAllDatesToEuDateWithDots($date, $halfYear) {
	
	var $yearTwoDigits = 29;  // years with 2 digits => 1930 - 2029 
	
	if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$/.test($date)) {
		// for EU date with dots like "28.5.2006" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2}$/.test($date)) {
		// for EU date with dots like "28.5.06" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YY = $array[2];
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;

	} else if (/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/.test($date)) {
		// for EU date with dash like "28-5-2006" 
		var $array = $date.split("-");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];

	} else if (/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/.test($date)) {
		// for EU date with slash like "28/5/2006" 
		var $array = $date.split("/");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/.test($date)) {
		// for date from "2006-5-28" 
		var $array = $date.split("-");
		var $DD = $array[2];
		var $MM = $array[1];
		var $YYYY = $array[0];
		
	} else if (/^[0-9]{8}$/.test($date)) {
		// for EU date without dots like "28052006" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YYYY = $date.substring(4,8);
		
	} else if (/^[0-9]{6}$/.test($date)) {
		// for EU date without dots like "280506" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YY = $date.substring(4,6);
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;
		
	} else if (/^[0-9]{4}$/.test($date)) {
		// for EU date without dots and year is actual -> like "2805" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $thisDay = new Date();
		var $YYYY = $thisDay.getFullYear();
	}
	
	if($halfYear) {
		var $newDate = toTen(toOne($DD)) + '.' + toTen(toOne($MM)) + '.' + $YYYY.substring(2,4);
	} else {
		var $newDate = toTen(toOne($DD)) + '.' + toTen(toOne($MM)) + '.' + $YYYY;
	}
	//alert('Date: ' + $date + ' | Day: ' + $DD + ' * ' + toOne($DD) + ' * ' + toTen(toOne($DD)) + ' | Month: ' + $MM + ' * ' + toOne($MM) + ' * ' + toTen(toOne($MM)) + ' | Year: ' + $YY + ' * ' + toOne($YY) + ' * ' + $YYYY + ' * ' + $newDate);
	if($date && $DD && $DD != '00' && $MM && $MM != '00' && $YYYY && $YYYY != '0000') {
		return $newDate;
	} else {
		return '';
	}
}



// change ALL DATES form like EU with dots "28.05.2006" or "28.05.06", EU without dots "28052006" or "280506" and SQL "2006-05-28" 
// to EU without dots
function changeAllDatesToEuDateWithoutDots($date, $halfYear) {
	
	var $yearTwoDigits = 29;  // yeras with 2 digits => 1930 - 2029 
	
	if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$/.test($date)) {
		// for EU date with dots like "28.5.2006" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2}$/.test($date)) {
		// for EU date with dots like "28.5.06" 
		var $array = $date.split(".");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YY = $array[2];
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;

	} else if (/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/.test($date)) {
		// for EU date with dash like "28-5-2006" 
		var $array = $date.split("-");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];

	} else if (/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/.test($date)) {
		// for EU date with slash like "28/5/2006" 
		var $array = $date.split("/");
		var $DD = $array[0];
		var $MM = $array[1];
		var $YYYY = $array[2];
		
	} else if (/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/.test($date)) {
		// for date from "2006-5-28" 
		var $array = $date.split("-");
		var $DD = $array[2];
		var $MM = $array[1];
		var $YYYY = $array[0];
		
	} else if (/^[0-9]{8}$/.test($date)) {
		// for EU date without dots like "28052006" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YYYY = $date.substring(4,8);
		
	} else if (/^[0-9]{6}$/.test($date)) {
		// for EU date without dots like "280506" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $YY = $date.substring(4,6);
		if(toOne($YY) <= $yearTwoDigits) $YYYY = '20'+$YY; else $YYYY = '19'+$YY;
		
	} else if (/^[0-9]{4}$/.test($date)) {
		// for EU date without dots and year is actual -> like "2805" 
		var $DD = $date.substring(0,2);
		var $MM = $date.substring(2,4);
		var $thisDay = new Date();
		var $YYYY = $thisDay.getFullYear();
	}
	
	if($halfYear) {
		var $newDate = toTen(toOne($DD)) + toTen(toOne($MM)) + $YYYY.substring(2,4);
	} else {
		var $newDate = toTen(toOne($DD)) + toTen(toOne($MM)) + $YYYY;
	}
	//alert('Date: ' + $date + ' | Day: ' + $DD + ' * ' + toOne($DD) + ' * ' + toTen(toOne($DD)) + ' | Month: ' + $MM + ' * ' + toOne($MM) + ' * ' + toTen(toOne($MM)) + ' | Year: ' + $YY + ' * ' + toOne($YY) + ' * ' + $YYYY + ' * ' + $newDate);
	if($date && $DD && $DD != '00' && $MM && $MM != '00' && $YYYY && $YYYY != '0000') {
		return $newDate;
	} else {
		return '';
	}
}

// from date '27.05.2007' returns year '2007' 
function changeEuDateWithDotsToYear($date) {
	if($date && $date.length == 10) {
		var $YYYY = $date.substring(6,10);
		return $YYYY;
	} else { return ''; }
}

// fieldId1 = date '27.05.2007' change fieldId2 to year '2007' 
function setDateToYear($fieldId1, $fieldId2) {
	$fieldId1 = changeAllDatesToEuDateWithDots(document.getElementById($fieldId1).value);
	document.getElementById($fieldId2).value = changeEuDateWithDotsToYear($fieldId1);
	document.getElementById($fieldId2).focus();
	document.getElementById($fieldId2).select();
}

// return Year or nothing 
function returnYear($fieldId) {
	if($fieldId && $fieldId != '0000' && /^[0-9]+$/.test($fieldId) && $fieldId >= 1900 && $fieldId <= 2100) {
		return $fieldId;
	} else { return ''; }
}

// check Year  
function isYear($value, $yearFrom, $yearTo) {
	if(!$yearFrom) $yearFrom = 1900;
	if(!$yearTo) $yearTo = 2100;
	if($value && /^[0-9]{4}$/.test($value) && $value >= $yearFrom && $value <= $yearTo) {
		return true;
	} else { return false; }
}

// change ALL TIMES form with colon "x0:x0:x0" or "x0:x0", with dash "x0-x0-x0" or "x0-x0", without dots "000000" or "0000" 
// to TIME with $newChar and length... 
function changeAllTimes($time, $newChar, $withSeconds, $showNull) {
	if(!$withSeconds) $withSeconds = 0;
	if(!$showNull) $showNull = 0;
	
	var $HH = '00';
	var $ii = '00';
	var $ss = '00';
	
	if (/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$/.test($time)) {
		// time with colon like "x0:x0:x0" 
		var $array = $time.split(":");
		var $HH = $array[0];
		var $ii = $array[1];
		var $ss = $array[2];
		
	} else if (/^[0-9]{1,2}:[0-9]{1,2}$/.test($time)) {
		// time with colon like "x0:x0" 
		var $array = $time.split(":");
		var $HH = $array[0];
		var $ii = $array[1];
		
	} else if (/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{1,2}$/.test($time)) {
		// time with dash like "x0-x0-x0" 
		var $array = $time.split("-");
		var $HH = $array[0];
		var $ii = $array[1];
		var $ss = $array[2];
		
	} else if (/^[0-9]{1,2}-[0-9]{1,2}$/.test($time)) {
		// time with dash like "x0-x0" 
		var $array = $time.split("-");
		var $HH = $array[0];
		var $ii = $array[1];
		
	} else if (/^[0-9]{6}$/.test($time)) {
		// time without colon like "000000" 
		var $HH = $time.substring(0,2);
		var $ii = $time.substring(2,4);
		var $ss = $time.substring(4,6);
		
	} else if (/^[0-9]{4}$/.test($time)) {
		// time without colon like "0000" 
		var $HH = $time.substring(0,2);
		var $ii = $time.substring(2,4);
	
	}
	if($withSeconds) {
		var $newTime = toTen(toOne($HH)) + $newChar + toTen(toOne($ii)) + $newChar + toTen(toOne($ss));
	} else {
		var $newTime = toTen(toOne($HH)) + $newChar + toTen(toOne($ii));
	}
	//document.getElementById('showAjax').innerHTML += '<br />Time: ' + $time + ' | Hour: ' + $HH + ' * ' + toOne($HH) + ' * ' + toTen(toOne($HH)) + ' | Minutes: ' + $ii + ' * ' + toOne($ii) + ' * ' + toTen(toOne($ii)) + ' | Seconds: ' + $ss + ' * ' + toOne($ss) + ' * ' + $ss + ' * ' + $newTime; // TEST 
	//alert('Time: ' + $time + ' | Hour: ' + $HH + ' * ' + toOne($HH) + ' * ' + toTen(toOne($HH)) + ' | Minutes: ' + $ii + ' * ' + toOne($ii) + ' * ' + toTen(toOne($ii)) + ' | Seconds: ' + $ss + ' * ' + toOne($ss) + ' * ' + $ss + ' * ' + $newTime);
	if($HH+$ii+$ss != '000000' || ($showNull && $HH+$ii+$ss == '000000')) {
		return $newTime;
	} else {
		return '';
	}
}

// check ALL TIMES form with colon "x0:x0:x0" or "x0:x0", with dash "x0-x0-x0" or "x0-x0", without dots "000000" or "0000" 
function checkAllTimes($time, $type) {
	
	//alert($time + ' ' + $type); // TEST 
	if(!$type || $type == 'value') { $time = $time; }
	if($type == 'input') { $time = document.getElementById($time).value; }
	if($type == 'tag') { $time = document.getElementById($time).firstChild.nodeValue; }
	//alert($time + ' ' + $type); // TEST 
	
	if (/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$/.test($time)) {
		// time with colon like "x0:x0:x0" 
		var $array = $time.split(":");
		var $HH = $array[0];
		var $ii = $array[1];
		var $ss = $array[2];
		
	} else if (/^[0-9]{1,2}:[0-9]{1,2}$/.test($time)) {
		// time with colon like "x0:x0" 
		var $array = $time.split(":");
		var $HH = $array[0];
		var $ii = $array[1];
		var $ss = '00';
		
	} else if (/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{1,2}$/.test($time)) {
		// time with dash like "x0-x0-x0" 
		var $array = $time.split("-");
		var $HH = $array[0];
		var $ii = $array[1];
		var $ss = $array[2];
		
	} else if (/^[0-9]{1,2}-[0-9]{1,2}$/.test($time)) {
		// time with dash like "x0-x0" 
		var $array = $time.split("-");
		var $HH = $array[0];
		var $ii = $array[1];
		var $ss = '00';
		
	} else if (/^[0-9]{6}$/.test($time)) {
		// time without colon like "000000" 
		var $HH = $time.substring(0,2);
		var $ii = $time.substring(2,4);
		var $ss = $time.substring(4,6);
		
	} else if (/^[0-9]{4}$/.test($time)) {
		// time without colon like "0000" 
		var $HH = $time.substring(0,2);
		var $ii = $time.substring(2,4);
		var $ss = '00';
	
	}
	return checkTime($HH, $ii, $ss);
}




// **********************************************************************************
// ====================== PROJECT SPEC. FUNCTIONS ===============================
// **********************************************************************************


// CONFIRM user changes  
var $confirm = false; // global variable -> set confirm 

// POPUP WINDOWS STAY ALL THE TIME IN FRONT 
// break refresh window on top -> show alert -> restore window on top 
var $popupOn = false; // global variable -> set confirm 

function myAlert($what) {
	if($popupOn == true) { stayBack(); }
	window.alert($what);
	if($popupOn == true) { stayOnTop(); }
}

var $stayTop = false;
var $timer = '';
// Brings the current window on top of others 
function stayOnTop() {
	$timer = window.setTimeout("stayOnTop()", 200);
	$stayTop = true;
	window.focus();
}

// Cancel bringing the current window on top of others 
function stayBack() {
	if($stayTop) {
		window.clearTimeout($timer);
		$stayTop = false;
	}
}


// UNIVERSAL IMAGES POPUP 
var $imageWindow = null; // global variable
function imagePopup($path, $alt, $popupOn) {
	if($path) {
		if($imageWindow == null || $imageWindow.closed) {
			if($popupOn == true) { stayBack(); }
			$imageWindow = window.open(PROJECTPATH + 'www/image_popup.php?path=' + $path + '&alt=' + $alt, 'imagePopup', 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=1000,height=600,toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=yes,scrollbars=yes');
		} else {
	    $imageWindow.focus();
			if($popupOn == true) { stayBack(); }
		}
	}
}

// ADMIN VeselePoutnice BOOKS COMMENTS - TEXT popUp 
var $commentsWindow = null; // global variable
var $commentsTimer = ''; // global variable
function popComments($url, $target) {
	if($commentsWindow == null || $commentsWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$commentsWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=620,height=550,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
		//$commentsTimer = window.setTimeout('popComments("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $commentsWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$commentsTimer = window.setTimeout('popComments("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}


// ADMIN VeselePoutnice BOOKS TO CHOOSE popUp 
var $booksWindow = null; // global variable
var $booksTimer = ''; // global variable
function popBooks($url, $target) {
	if($booksWindow == null || $booksWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$booksWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=570,height=550,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
		//$booksTimer = window.setTimeout('popBooks("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $booksWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$booksTimer = window.setTimeout('popBooks("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}


// ADMIN VeselePoutnice USERS TO CHOOSE popUp 
var $usersWindow = null; // global variable
var $usersTimer = ''; // global variable
function popUsers($url, $target) {
	if($usersWindow == null || $usersWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$usersWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=570,height=550,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
		//$usersTimer = window.setTimeout('popUsers("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $usersWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$usersTimer = window.setTimeout('popUsers("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}


// USER INFO popUp 
var $userInfoWindow = null; // global variable
var $userInfoTimer = ''; // global variable
function popUserInfo($url, $target) {
	if($userInfoWindow == null || $userInfoWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$userInfoWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=800,height=650,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
		//$userInfoTimer = window.setTimeout('popUserInfo("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $userInfoWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$userInfoTimer = window.setTimeout('popUserInfo("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// PARAMETERS popUp (color sleeves, nailfiles etc.)
var $parametersWindow = null; // global variable
var $parametersTimer = ''; // global variable
function popParameters($url, $target, $value, $id) {
	if($parametersWindow == null || $parametersWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$parametersWindow = window.open($url + $value + '&fieldId='+$id, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=620,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
		//$parametersTimer = window.setTimeout('popParameters("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $parametersWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$parametersTimer = window.setTimeout('popParameters("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// PASSWORD popUp 
var $passwordWindow = null; // global variable
var $passwordTimer = ''; // global variable
function popPassword($url, $target) {
	if($passwordWindow == null || $passwordWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$passwordWindow = window.open($url, $target, 'left='+ ($windowFromLeft+200) +',top='+ ($windowFromTop+200) +',width=460,height=200,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=no');
		//$passwordTimer = window.setTimeout('popPassword("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $passwordWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$passwordTimer = window.setTimeout('popPassword("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// RECOMMEND popUp 
var $recommendWindow = null; // global variable
var $recommendTimer = ''; // global variable
function popRecommend($url, $target) {
	if($recommendWindow == null || $recommendWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$recommendWindow = window.open($url, $target, 'left='+ ($windowFromLeft+200) +',top='+ ($windowFromTop+200) +',width=500,height=440,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=no');
		//$recommendTimer = window.setTimeout('popRecommend("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $recommendWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$recommendTimer = window.setTimeout('popRecommend("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// SEND WISH popUp 
var $sendWishWindow = null; // global variable
var $sendWishTimer = ''; // global variable
function popSendWish($url, $target) {
	if($sendWishWindow == null || $sendWishWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$sendWishWindow = window.open($url, $target, 'left='+ ($windowFromLeft+200) +',top='+ ($windowFromTop+200) +',width=500,height=460,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=no');
		//$sendWishTimer = window.setTimeout('popSendWish("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $sendWishWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$sendWishTimer = window.setTimeout('popSendWish("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// ADMIN ORDER popUp 
var $adminOrderWindow = null; // global variable
var $adminOrderTimer = ''; // global variable
function popAdminOrder($url, $target) {
	if($adminOrderWindow == null || $adminOrderWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$adminOrderWindow = window.open($url, $target, 'left='+ ($windowFromLeft+100) +',top='+ ($windowFromTop+100) +',width=800,height=700,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=no');
		//$adminOrderTimer = window.setTimeout('popAdminOrder("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $adminOrderWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$adminOrderTimer = window.setTimeout('popAdminOrder("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// ADMIN ORDER -> ADD PRODUCT popUp 
var $adminOrderAddProductWindow = null; // global variable
var $adminOrderAddProductTimer = ''; // global variable
function popAdminOrderAddProduct($url, $target) {
	if($adminOrderAddProductWindow == null || $adminOrderAddProductWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$adminOrderAddProductWindow = window.open($url, $target, 'left='+ ($windowFromLeft+100) +',top='+ ($windowFromTop+100) +',width=850,height=720,toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=yes,scrollbars=yes');
		//$adminOrderAddProductTimer = window.setTimeout('popAdminOrderAddProduct("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $adminOrderAddProductWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$adminOrderAddProductTimer = window.setTimeout('popAdminOrderAddProduct("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// CONTACT popUp 
var $contactWindow = null; // global variable
function popContact($url, $target) {
	if($contactWindow == null || $contactWindow.closed) {
	  $contactWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=660,height=520,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=no');
	} else {
		$contactWindow.focus();
	}
}
// CONTACT from Movie 
var $fieldContactName = '';
var $fieldContactId = '';
function popContactfromMovie($url, $target, $form, $field, $id) {
	//document.getElementById('showAjax').innerHTML += 'fce(popContact) -> url * target * form * field * id = ' + $url +' * '+ $target +' * '+ $form +' * '+ $field +' * '+ $id + '<br>'; // TEST 
	if($contactWindow == null || $contactWindow.closed) {
	  $contactWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=660,height=520,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=no');
	} else {
		$contactWindow.focus();
	}
	//$fieldContactName = eval("document." + $form + "." + $field);
	//$fieldContactId = eval("document." + $form + "." + $id);
	$fieldContactName = eval("document.getElementById('" + $field + "')");
	$fieldContactId = eval("document.getElementById('" + $id + "')");
	//document.getElementById('showAjax').innerHTML += 'fce(popContact) -> $fieldHistoryName.value = ' + $fieldContactName.value + '<br>'; // TEST 
}

// SELECTION popUp 
var $selectWindow = null; // global variable
var $selectTimer = ''; // global variable
function popSelect($url, $target, $popupOn) {
	if($selectWindow == null || $selectWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$selectWindow = window.open($url, $target, 'left='+ $windowFromLeft +',top='+ ($windowFromTop+50) +',width=1020,height=650,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=yes');
		//$selectTimer = window.setTimeout('popSelect("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $selectWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$selectTimer = window.setTimeout('popSelect("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// PRINT popUp 
var $printWindow = null; // global variable 
var $printTimer = ''; // global variable
function popPrint($url, $target, $popupOn) {
	if($printWindow == null || $printWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$printWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=870,height=650,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=yes');
		//$printTimer = window.setTimeout('popPrint("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $printWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$printTimer = window.setTimeout('popPrint("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// PICTURES modul popUp 
var $picWindow = null; // global variable
function popPictures($url, $target, $popupOn) {
	if($picWindow == null || $picWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$picWindow = window.open($url, $target, 'left='+ ($windowFromLeft+50) +',top='+ ($windowFromTop+50) +',width=1000,height=750,toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=no,scrollbars=yes');
	} else {
    $picWindow.focus();
		if($popupOn == true) { stayBack(); }
	}
}

// PICTURE ORIGINAL SIZE popUp 
var $picOrigWindow = null; // global variable
var $picOrigTimer = ''; // global variable
function popOrigPicture($url, $target, $popupOn) {
	if($picOrigWindow == null || $picOrigWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$picOrigWindow = window.open($url, $target, 'left='+ $windowFromLeft +',top='+ $windowFromTop +',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes');
		//$picOrigTimer = window.setTimeout('popOrigPicture("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $picOrigWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$picOrigTimer = window.setTimeout('popOrigPicture("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// PICTURE MIDDLE SIZE popUp 
var $picMiddleWindow = null; // global variable $popupPicture 
function popMiddlePicture($url, $target, $features, $popupOn) {
	//alert($url+' :: '+$target+' :: '+$features+' :: '+$popupOn);
	if($picMiddleWindow == null || $picMiddleWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$picMiddleWindow = window.open($url, $target, $features);
	} else {
    $picMiddleWindow.focus();
		if($popupOn == true) { stayBack(); }
	}
}

// MOVIE popUp 
var $movieWindow = null; // global variable
var $movieTimer = ''; // global variable
function popMovie($url, $target, $popupOn) {
	if($movieWindow == null || $movieWindow.closed) {
		if($popupOn == true) { stayBack(); }
		$movieWindow = window.open($url, $target, 'left='+ $windowFromLeft +',top='+ ($windowFromTop+30) +',width=1020,height=670,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=yes');
		//$movieTimer = window.setTimeout('popMovie("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	} else {
    $movieWindow.focus();
		if($popupOn == true) { stayBack(); }
		//$movieTimer = window.setTimeout('popMovie("'+$url+'", "'+$target+'", "'+$popupOn+'");', 200);
	}
}

// PRICE popUp 
function popPrice($url, $target) {
  window.open($url, $target, 'left='+ ($windowFromLeft+100) +',top='+ ($windowFromTop+150) +',width=300,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=yes');
}
var $popupPrice = null; // global variable $popupPrice 
function popPriceFirst($url, $target) {
	if($popupPrice == null || $popupPrice.closed) {
		$popupPrice = window.open($url, $target, 'left='+ ($windowFromLeft+100) +',top='+ ($windowFromTop+150) +',width=290,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,scrollbars=yes');
		//window.setTimeout('popPrice("'+$url+'", "'+$target+'");', 100);
	} else {
    $popupPrice.focus();
		//window.setTimeout('popPrice("'+$url+'", "'+$target+'");', 100);
	}
}


// function onKeyPress event (Ctrl + Num) - for global keyboard shortcuts 
function keyboardCtrlEvent(e, $file) {
	//alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + "CTRL key pressed: " + e.ctrlKey + "\n");
	//document.getElementById('showAjax').innerHTML += 'CTRL + keypress code = ' + String.fromCharCode(e.charCode) + '<br>'; // for TEST 
	if(e.ctrlKey == true && e.charCode == 48) { // Ctrl + 0 
	} else if(e.ctrlKey == true && e.charCode == 49) { // Ctrl + 1 !!! window - used by SeaMonkey !!!
	} else if(e.ctrlKey == true && e.charCode == 50) { // Ctrl + 2
		var $url = 'search.php';
		location.replace($url);
	} else if(e.ctrlKey == true && e.charCode == 51) { // Ctrl + 3 
		if($file == 'search.php') { return checkSearch(); }
	} else if(e.ctrlKey == true && e.charCode == 52) { // Ctrl + 4  !!! editor - used by SeaMonkey !!!
	} else if(e.ctrlKey == true && e.charCode == 53) { // Ctrl + 5 
	} else if(e.ctrlKey == true && e.charCode == 54) { // Ctrl + 6 
	} else if(e.ctrlKey == true && e.charCode == 55) { // Ctrl + 7 
	} else if(e.ctrlKey == true && e.charCode == 56) { // Ctrl + 8 
	} else if(e.ctrlKey == true && e.charCode == 57) { // Ctrl + 9 
	}
}

// function onKeyPress event (Ctrl + Alt + F) - for global keyboard shortcuts 
function keyboardCtrlAltEvent(e, $file) {
	//alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + "CTRL key pressed: " + e.ctrlKey + "\n" + "ALT key pressed: " + e.altKey + "\n");
	//document.getElementById('showAjax').innerHTML += 'CTRL + ALT + keypress code = ' + String.fromCharCode(e.charCode) + '<br>'; // for TEST 
	//document.getElementById('showAjax').innerHTML += 'CTRL + ALT + keypress code = ' + e.keyCode + '<br>'; // for TEST 
	if(e.ctrlKey == true && e.altKey == true && e.keyCode == 112) { // Ctrl + Alt + F1 
		if($file == 'index.php' || $file == 'search.php' || $file == 'selects.php' || $file == 'movies.php' || $file == 'movies_list.php' || $file == 'adm_users.php') {
			var $url = 'search.php';
			location.replace($url);
		} else if($file == 'movie.php') {
			var $url = 'search.php';
			window.opener.location.replace($url);
			window.close();
		}
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 113) { // Ctrl + Alt + F2 == SEARCH 
		if($file == 'search.php') { return checkSearch(); }
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 114) { // Ctrl + Alt + F3 == NEW MOVIE 
		if($file == 'index.php' || $file == 'search.php' || $file == 'selects.php' || $file == 'movies.php' || $file == 'movies_list.php' || $file == 'adm_users.php') {
			var $url = 'movie.php?page=1&orderBy=mov_id&sort=asc&movie=new';
			popMovie($url, 'movie');
		}
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 115) { // Ctrl + Alt + F4 
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 116) { // Ctrl + Alt + F5 
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 117) { // Ctrl + Alt + F6 
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 118) { // Ctrl + Alt + F7 
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 119) { // Ctrl + Alt + F8 
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 120) { // Ctrl + Alt + F9 
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 121) { // Ctrl + Alt + F10 == SAVE INTO THE SELECTION 
		if($file == 'movies.php' || $file == 'movie.php' || $file == 'movies_list.php') {
			return saveIntoSelection();
		}
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 122) { // Ctrl + Alt + F11 
		if($file == 'movies.php' || $file == 'movie.php' || $file == 'movies_list.php') {
			return saveAllIntoSelection();
		}
	} else if(e.ctrlKey == true && e.altKey == true && e.keyCode == 123) { // Ctrl + Alt + F12 
	}
}

// **********************************************************************************
// ============================ COLOR rows ===================================
// **********************************************************************************

// split Class old and change second class 
function splitClass($oldClass) {
	$firstClass = $oldClass.split(' ');
	if($firstClass[1]=='bgActive') { return $firstClass[0]+' bgActiveOver';
	} else if($firstClass[1]=='bgActiveOver') { return $firstClass[0]+' bgActive';
	} else if($firstClass[1]=='bgNormalOver') { return $firstClass[0]+' bgNormal';
	} else if($firstClass[1]=='bgNormal') { return $firstClass[0]+' bgNormalOver';
	}
}
// split Class old and return second class 
function returnNewClass($oldClass) {
	if($oldClass=='bgActive') { return 'bgActiveOver';
	} else if($oldClass=='bgActiveOver') { return 'bgActive';
	} else if($oldClass=='bgNormalOver') { return 'bgNormal';
	} else if($oldClass=='bgNormal') { return 'bgNormalOver';
	}
}
// split Class old and return first (old) class 
function returnOldClassFirstPart($oldClass) {
	$firstClass = $oldClass.split(' ');
	return $firstClass[0];
}
// split Class old and return first (old) class 
function returnOldClassSecondPart($oldClass) {
	$firstClass = $oldClass.split(' ');
	return $firstClass[1];
}
// deactivate row 
function deactRow($oldClass) {
	$firstClass = $oldClass.split(' ');
	return $firstClass[0]+' bgNormal';
}
// activate row 
function activeRow($oldClass) {
	$firstClass = $oldClass.split(' ');
	return $firstClass[0]+' bgActiveOver';
}


// change Simple class onMouseOver 
function colorSimpleRowOver($rowId) {
	$firstOldPart = returnOldClassFirstPart(document.getElementById('row__'+$rowId).className) + ' ';
	$secondOldPart = returnOldClassSecondPart(document.getElementById('row__'+$rowId).className);
	if($secondOldPart=='bgInActive') { $secondNewPart = 'bgInActiveOver'; }
	else if($secondOldPart=='bgNormal') { $secondNewPart = 'bgNormalOver'; }
	document.getElementById('row__'+$rowId).className = $firstOldPart + $secondNewPart;
	//document.getElementById('showTest').firstChild.nodeValue +=  document.getElementById('row__'+$rowId).className; // TEST 
}
// change Simple class onMouseOut 
function colorSimpleRowOut($rowId) {
	$firstOldPart = returnOldClassFirstPart(document.getElementById('row__'+$rowId).className) + ' ';
	$secondOldPart = returnOldClassSecondPart(document.getElementById('row__'+$rowId).className);
	if($secondOldPart=='bgInActiveOver') { $secondNewPart = 'bgInActive'; }
	else if($secondOldPart=='bgNormalOver') { $secondNewPart = 'bgNormal'; }
	document.getElementById('row__'+$rowId).className = $firstOldPart + $secondNewPart;
}
// change class onMouseOver 
function colorRowOver($rowId) {
	$firstOldPart = returnOldClassFirstPart(document.getElementById('row__'+$rowId).className) + ' ';
	$secondOldPart = returnOldClassSecondPart(document.getElementById('row__'+$rowId).className);
	if($secondOldPart=='bgActive') { $secondNewPart = 'bgActiveOver'; }
	else if($secondOldPart=='bgNormal') { $secondNewPart = 'bgNormalOver'; }
	document.getElementById('row__'+$rowId).className = $firstOldPart + $secondNewPart;
	//document.getElementById('showTest').firstChild.nodeValue +=  document.getElementById('row__'+$rowId).className; // TEST 
	for($i=0; $i<$columns.length; $i++) {
		$colObject = document.getElementById($columns[$i]+'_'+$rowId);
		$firstOldPart = returnOldClassFirstPart($colObject.className) + ' ';
		if($colObject.getAttribute('type')=='text' || $colObject.getAttribute('type')=='checkbox' || $colObject.getAttribute('type')=='radio' || $colObject.tagName=='SELECT' || $colObject.tagName=='DIV' || $colObject.tagName=='TEXTAREA') {
			$colObject.className = $firstOldPart + $secondNewPart;
		}
		//document.getElementById('showTest').firstChild.nodeValue +=  "\n" + $firstOldPart + " * " + $secondOldPart + " * " + $secondNewPart + " * " + $colObject.getAttribute("type") + " * " + $colObject.tagName; // TEST 
	}
}
// change class onMouseOut 
function colorRowOut($rowId, $class) {
	$firstOldPart = returnOldClassFirstPart(document.getElementById('row__'+$rowId).className) + ' ';
	$secondOldPart = returnOldClassSecondPart(document.getElementById('row__'+$rowId).className);
	if($secondOldPart=='bgActiveOver') { $secondNewPart = 'bgActive'; }
	else if($secondOldPart=='bgNormalOver') { $secondNewPart = 'bgNormal'; }
	document.getElementById('row__'+$rowId).className = $firstOldPart + $secondNewPart;
	for($i=0; $i<$columns.length; $i++) {
		$colObject = document.getElementById($columns[$i]+'_'+$rowId);
		$firstOldPart = returnOldClassFirstPart($colObject.className) + ' ';
		if($colObject.getAttribute('type')=='text' || $colObject.getAttribute('type')=='checkbox' || $colObject.getAttribute('type')=='radio'|| $colObject.tagName=='SELECT' || $colObject.tagName=='DIV' || $colObject.tagName=='TEXTAREA') {
			$colObject.className = $firstOldPart + $secondNewPart;
		}
		//document.getElementById('showTest').firstChild.nodeValue += $firstOldPart + $secondNewPart + ' * ' + $colObject.getAttribute('type') + ' * ' + $colObject.tagName; // TEST 
	}
}
// change class onClick  
function colorRowClick($rowId) {
	$activeRowId = document.getElementById('inputActive').value;
	document.getElementById('inputActive').value = $rowId;
	if($activeRowId) document.getElementById('row__'+$activeRowId).className = deactRow(document.getElementById('row__'+$activeRowId).className);
	document.getElementById('row__'+$rowId).className = activeRow(document.getElementById('row__'+$rowId).className);
	for($i=0; $i<$columns.length; $i++) {
		if($activeRowId) {
			$colObjectActive = document.getElementById($columns[$i]+'_'+$activeRowId);
			if($colObjectActive.getAttribute('type')=='text' || $colObjectActive.getAttribute('type')=='checkbox' || $colObjectActive.getAttribute('type')=='radio'|| $colObjectActive.tagName=='SELECT' || $colObjectActive.tagName=='DIV' || $colObjectActive.tagName=='TEXTAREA') {
				$colObjectActive.className = deactRow($colObjectActive.className);
			}
		}
		$colObject = document.getElementById($columns[$i]+'_'+$rowId);
		if($colObject.getAttribute('type')=='text' || $colObject.getAttribute('type')=='checkbox' || $colObject.getAttribute('type')=='radio'|| $colObject.tagName=='SELECT' || $colObject.tagName=='DIV' || $colObject.tagName=='TEXTAREA') {
			$colObject.className = activeRow($colObject.className);
		}
	}
}
// *********** end COLOR rows ****************



// **********************************************************************************
// ==================== AJAX UNIVERSAL FUNCTIONS ================================
// **********************************************************************************


// creates an XMLHttpRequest instance  **************
function createXmlHttpRequestObject()	{
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try {
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch(e) {
		// assume IE - older or newer 
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.9.0", "MSXML2.XMLHTTP.8.0", "MSXML2.XMLHTTP.7.0", "MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
		// try every prog id until one works
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
			try { 
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} 
			catch (e) {}
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
		alert("Error creating the XMLHttpRequest object.");
	else 
		return xmlHttp;
}

// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();

/* the keyword for which an HTTP request has been initiated */
var httpRequestKeyword = "";
/* the last keyword for which suggests have been requested */
var userKeyword = "";
/* number of suggestions received as results for the keyword */
var suggestions = 0;
/* the maximum number of characters to be displayed for a suggestion */
var suggestionMaxLength = 38;
/* flag that indicates if the up or down arrow keys were pressed
	 the last time a keyup event occurred	*/
var isKeyUpDownPressed = false;
/* the last suggestion that has been used for autocompleting the keyword */
var autocompletedKeyword = "";
/* start search after is writen characters */
var $searchAfterChar = 0;
/* flag that indicates if there are results for the current requested keyword */
var hasResults = false;
/* the identifier used to cancel the evaluation with the clearTimeout method. */
var timeoutId = -1;
/* the currently selected suggestion (by arrow keys or mouse)*/
var position = -1;
/* the minimum and maximum position of the visible suggestions */
var minVisiblePosition = 0;
var maxVisiblePosition = 4;
// when set to true, display detailed error messages
var debugMode = true;
/* the XMLHttp object for communicating with the server */
var xmlHttpGetSuggestions = createXmlHttpRequestObject();
/* the onload event is handled by our init function */
window.onload = init;

// all FIELDS to SEARCH 
var $fieldsForSearch = new Array();
var $fieldsForSearchId = new Array();

// function that initializes the page ******************************************************** FCE init ******
function init() {
	// prevent browser from starting the autofill function
	for($i=0; $i<$fieldsForSearch.length; $i++) { document.getElementById($fieldsForSearch[$i]).setAttribute("autocomplete", "off"); }
	for($i=0; $i<$fieldsForSearchId.length; $i++) { document.getElementById($fieldsForSearchId[$i] + '_search').setAttribute("autocomplete", "off"); }
}

// for AJAX - onFocus - clear input value to edit 
function clearField($fieldId, $type) {
	$inputSelect = document.getElementById('inputSelect').value;
	//document.getElementById('showAjax').innerHTML += '$inputSelect (fce clearField) = ' + $inputSelect + '<br/>'; // TEST 
	if(!$inputSelect) {
		if($type=='select') {
		} else {
			var $input = document.getElementById($fieldId);
			var $value = $input.value;
			if($type == 'date') { if($value) $input.value = changeAllDatesToEuDateWithoutDots($value); }
			if($type == 'time') { if($value) $input.value = changeAllTimes($value, ""); }
			if($type == 'price') { if($value) $input.value = clearPrice($value, ","); }
			$input.select();
		}
	} else {
		document.getElementById($inputSelect).focus(); // return to $fieldId 
		document.getElementById($inputSelect).select();
		document.getElementById('inputSelect').value = ''; // clear inputSelect value 
	}
}

//-----------------------------------------           AJAX USER VARIABLEs 	          -----------------------------------------------------------------------
//******************************************************************************************************************
var $forAjaxRowId = "";
var $forAjaxFieldId = "";
var $forAjaxFieldName = "";
var $forAjaxFieldType = "";
var $forAjaxFieldOldId = "";

var $forAjaxFieldSearchId = "";
var $forAjaxContactType = "";
var $forAjaxFieldSearchOldId = "";


// function set hidden fields, that we need to read 
function setHiddenFields($fieldType, $fieldName, $fieldId) {
	$forAjaxFieldType = $fieldType;
	$forAjaxFieldName = $fieldName;
	if($fieldId) $forAjaxFieldId = $fieldId; else $forAjaxFieldId = $fieldName;
	if($fieldId) $forAjaxFieldSearchId = $fieldId; else $forAjaxFieldId = $fieldName;
	if($fieldId) $forAjaxFieldOldId = $fieldId + "_old"; else $forAjaxFieldOldId = $fieldName + "_old";
	//document.getElementById('showAjax').innerHTML += '<br />forAjaxRowId = ' + $forAjaxRowId + ' | forAjaxFieldId = ' + $forAjaxFieldId + ' | forAjaxFieldName = ' + $forAjaxFieldName+ '<br>'; // TEST
}

// set hidden fields, that we need to read 
function setHiddenFieldsRow($fieldType, $fieldName, $fieldId, $rowId) {
	$forAjaxFieldType = $fieldType;
	$forAjaxRowId = $rowId;
	$forAjaxFieldName = $fieldName;
	if($fieldId) $forAjaxFieldId = $fieldId; else $forAjaxFieldId = $fieldName;
	if($fieldId) $forAjaxFieldSearchId = $fieldId; else $forAjaxFieldId = $fieldName;
	if($fieldId) $forAjaxFieldOldId = $fieldId + "_old"; else $forAjaxFieldOldId = $fieldName + "_old";
	//document.getElementById('showAjax').innerHTML += '<br />forAjaxRowId = ' + $forAjaxRowId + ' | forAjaxFieldId = ' + $forAjaxFieldId + ' | forAjaxFieldName = ' + $forAjaxFieldName + ' | forAjaxFieldOldId = ' + $forAjaxFieldOldId; // TEST
}


//-----------------------------------------   SAVE OPENED UNIVERSAL  (sections, categories...) - ADMIN 	----------------------------------------------
//******************************************************************************************************************
function saveShowAndHideRows($field, $rowId) {
	// only continue if xmlHttp isn't void and isn't busy 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		var $rowElement = document.getElementById("row_" + $rowId);
		if ($rowElement.style.display != "none") {
			$actio = '0';
		} else {
			$actio = '1';
		}
		//document.getElementById('showAjax').innerHTML += '<br/>$rowId = ' + $rowId; // TEST
		// try to connect to the server
		try {
			$path = "../config/ajax_save_opened_universal.php?field=" + $field + "&id=" + $rowId + "&actio=" + $actio;
			xmlHttp.open("GET", $path, true);
  	  xmlHttp.onreadystatechange = handleServerResponseOpenedUniversal;
    	xmlHttp.send(null);
			//document.getElementById('showAjax').innerHTML += '<br/>$path = ' + $path; // TEST
		}
		catch (e) {
			// display the error in case of failure
			alert("Can't connect to server:\n" + e.toString());
		}
	} else {
		//alert(xmlHttp.readyState +' * '+$field+' * '+$rowId); // TEST 
		setTimeout('saveShowAndHideRows('+$field+', '+$rowId+')', 1000);
	}
}

function handleServerResponseOpenedUniversal() {
	// do nothing 
}


// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------      HISTORY (ID)    -------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//-----------------------------------------   SHOW LAST MYSQL CHANGES (HISTORY) 	----------------------------------------------------------------
function showLastMysqlChanges($rowId, $field, $userId) {
	if(xmlHttp) { 
		try {
			// if the XMLHttpRequest object isn't busy with a previous request... 
			if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
				
				// ======================================================================================================================
				// !-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!   GET PATH   !-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!-!
				$urlFile = 'ajax_show_mysql.php';
				$getUrl = '../config/' + $urlFile + '?inTable=' + $inTable + '&inID=' + $inID + '&rowId=' + $forAjaxRowId + '&fieldType=' + $forAjaxFieldType + '&fieldName=' + $forAjaxFieldName;
				//document.getElementById('showAjax').innerHTML += '<br />$getUrl = ' +  $getUrl; // for TEST 
				xmlHttp.open("GET", $getUrl, true);
				xmlHttp.onreadystatechange = handleGettingSuggestionsHistory;
				xmlHttp.send(null);
			}
			// if the XMLHttpRequest object is busy...
			else {
				// clear any previous timeouts already set
				if(timeoutId != -1)
					clearTimeout(timeoutId);					
				// try again in 0.2 seconds 
				timeoutId = setTimeout("showLastMysqlChanges($rowId, $field, $userId);", 200);
			}
		}
		catch(e) {
			displayError("Can't connect to server:\n" + e.toString());
		}
	}
}

//-----------------------------------------   HIDE LAST MYSQL CHANGES (HISTORY) 	----------------------------------------------------------------
function hideLastMysqlChanges($rowId, $field) {
	var $historyList = document.getElementById("historyList_" + $field + "_" + $rowId);
	$historyList.innerHTML = '&nbsp;';
	var $history = document.getElementById("history_" + $field + "_" + $rowId);
	$history.style.display = "none";
}

// handles the server's response containing the suggestions for the requested keyword ******************************************************** FCE handleGettingSuggestionsHistory ******
function handleGettingSuggestionsHistory() {
	//document.getElementById('showAjax').innerHTML += '<br /> readyState ' + xmlHttp.readyState; // for TEST 
	if (xmlHttp.readyState == 4) {
		//document.getElementById('showAjax').innerHTML += '<br /> status ' + xmlHttp.status; // for TEST 
		if (xmlHttp.status == 200) {
			try {
				
				xmlResponse = xmlHttp.responseXML;
				// validation XML structure - IE and Opera 
				if(!xmlResponse || !xmlResponse.documentElement)
					throw("Invalid XML structure:\n" + xmlHttp.responseText);
				// validation XML structure - FF 
				var rootNodeName = xmlResponse.documentElement.nodeName;
				if(rootNodeName == "parsererror")
					throw("Invalid XML structure:\n" + xmlHttp.responseText);
				xmlRoot = xmlResponse.documentElement;
				
				// initialize the new array of functions' names
				arrayId = new Array();
				arrayDate = new Array();
				arrayValue = new Array();
				arrayUser = new Array();
				if(xmlResponse.childNodes.length) {
					// we retrieve the new functions' names from the document element as an array 
					arrayId = xmlToArray(xmlResponse.getElementsByTagName("id"));
					arrayDate = xmlToArray(xmlResponse.getElementsByTagName("date"));
					arrayValue = xmlToArray(xmlResponse.getElementsByTagName("value"));
					arrayUser = xmlToArray(xmlResponse.getElementsByTagName("user"));
				}
				// display the results array
				displayResultsHistory(arrayId, arrayDate, arrayValue, arrayUser);
				
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		}
		else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

// populates the list with the current suggestions ******************************************************** FCE displayResultsHistory ******
function displayResultsHistory(arrayId, arrayDate, arrayValue, arrayUser) {
	
	// if the array of results is empty display a message
	if(arrayId.length == 0) {
		// set the flag indicating that no results have been found and reset the counter for results
		hasResults = false;
		suggestions = 0;
		hideSuggestions();
	
	// display the results
	} else {
		// start building the HTML table containing the results	
		var div = '<table id="historyTable" cellpadding="0" cellspacing="0" border="1">';
		div += '<tr><th colspan="3">' + LNG_LAST_CHANGES + '</th></tr>';
		// resets the index of the currently selected suggestion
		position = -1;
		// sets the flag indicating that there are results for the searched for keyword 
		hasResults = true;
		// loop through all the results and generate the HTML list of results
		for (var i=0; i<arrayId.length; i++) {	
			// start building the HTML row that contains the link to the PHP help page of the current function
			//document.getElementById('showAjax').innerHTML += '<br />i = ' +  i + ' * encode(results_array[i]) = ' +  encode(results_array[i]) + ' * results_array_id[i] = ' +  results_array_id[i]; // for TEST 
			div += '<tr id="tr' + i + '" onclick="handleOnMouseClickHistory(\'' + addslashes(arrayValue[i]) + '\', \''+ arrayId[i] +'\');">'; //  onmouseover="handleOnMouseOver(this);" onmouseout="handleOnMouseOut(this);"
			div += '<td style="width:50px;">' + changeAllDatesToEuDateWithDots(arrayDate[i].substring(0, 10), 1) + '</td>';
			if($forAjaxFieldType == 'price') {
				div += '<th style="text-align:right;">' + arrayValue[i] + '</th>';
			} else {
				div += '<th style="text-align:left;">' + arrayValue[i] + '</th>';
			}
			div += '<td>' + arrayUser[i] + '</td>';
			//div += '<td align="left" title="' + arrayId[i] + '"><span title="' + results_array[i] + '" id="a' + i + '">' + results_array[i] + '</span></td>';
			div += '</tr>';
		}
		// end building the HTML table
		div += '</table>';
		//document.getElementById('showAjax').innerHTML += '<br />DIV = ' +  div; // for TEST 
		
		var $historyList = document.getElementById("historyList_" + $forAjaxFieldName + "_" + $forAjaxRowId);
		$historyList.innerHTML = div;
		var $history = document.getElementById("history_" + $forAjaxFieldName + "_" + $forAjaxRowId);
		$history.style.display = "block";
	}
}

// function that handles the mouse click on a suggestion's area event  ********************************************* FCE handleOnMouseClickHistory ******
function handleOnMouseClickHistory($value, $id) {
	document.getElementById($forAjaxFieldSearchId).value = decodeURIComponent($value);
	document.getElementById($forAjaxFieldId).value = $id;
	//document.getElementById('showAjax').innerHTML += '<br />$forAjaxFieldSearchId = ' + $value; // for TEST 
	//document.getElementById('showAjax').innerHTML += '<br />$forAjaxFieldId = ' + $id; // for TEST 
	if($forAjaxContactGray) {
		$forAjaxContactGray.style.display = 'none';
		$forAjaxContactHref.style.display = 'inline';
		$forAjaxContactHref.href = splitUrl($forAjaxContactHref.href, 'cnt_id=', '&amp;', 'cnt_id=' + $id);
		setHiddenContactSymbolFields(0);
	}
	document.getElementById($forAjaxFieldSearchId).focus();
	hideSuggestions();
}



// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------    for ALL    ---------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


// transforms all the children of an xml node into an array ******************************************************** FCE xmlToArray ******
function xmlToArray(resultsXml) {
	// initiate the resultsArray
	var resultsArray= new Array();	
	// loop through all the xml nodes retrieving the content	
	for(i=0;i<resultsXml.length;i++)
		if(resultsXml.item(i).hasChildNodes()) {
			resultsArray[i] = str_ireplace('&amp;', '&', resultsXml.item(i).firstChild.data);
		} else {
			resultsArray[i] = '';
		}
	// return the node's content as an array
	return resultsArray;
}


// function that handles the mouse click on a suggestion's area event  ******************************************************** FCE handleOnMouseClick ******
function handleOnMouseClick($value) {
	document.getElementById($forAjaxFieldSearchId).value = decodeURIComponent($value);
	hideSuggestions();
}

// function that handles the keys that are pressed  ******************************************************** FCE handleKeyDown ******
function handleKeyDown(e) {
	// get the event
	e = (!e) ? window.event : e;
	// get the event's target
	target = (!e.target) ? e.srcElement : e.target;
	if (target.nodeType == 3) target = target.parentNode;
	// get the character code of the pressed button
	code = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0));
	// check to see if the event was keyup
	if (e.type == "keydown") {
		//document.getElementById('showAjax').innerHTML += '<br />code = ' + code; // for TEST 
		if(code == 9) {
			//document.getElementById($forAjaxFieldSearchId).value = 'title span aX = ' + document.getElementById("a" + position).title;
			hideSuggestions();
		}
	}
}

// function that hides the layer containing the suggestions  ******************************************************** FCE hideSuggestions ******
function hideSuggestions() {
	if(suggestions > 0) {
		var $table = document.getElementById('resultTable');
		var $parent = $table.parentNode;
		$parent.removeChild($table);
	}
	//document.getElementById('showAjax').innerHTML += '<br />suggestions = ' +  suggestions; // for TEST 
	httpRequestKeyword = "";
	userKeyword = "";
	suggestions = 0;
	isKeyUpDownPressed = false;
	autocompletedKeyword = "";
	hasResults = false;
	timeoutId = -1;
	position = -1;
	minVisiblePosition = 0;
	maxVisiblePosition = 4;
	for($i=0; $i<$fieldsForSearch.length; $i++) {
		document.getElementById($fieldsForSearch[$i] + "_scroll").style.display = "none";
		//document.getElementById('showAjax').innerHTML += '<br />filed name = ' +  document.getElementById($fieldsForSearch[$i] + "_scroll").id; // for TEST 
	}
	for($i=0; $i<$fieldsForSearchId.length; $i++) {
		document.getElementById($fieldsForSearchId[$i] + "_search_scroll").style.display = "none";
		//document.getElementById('showAjax').innerHTML += '<br />filed name = ' +  document.getElementById($fieldsForSearchId[$i] + "_search_scroll").id; // for TEST 
	}
}

// function that updates the keyword value with the value of the currently selected suggestion  ******************************************************** FCE updateKeywordValue ******
function updateKeywordValue(oTr) {
	//document.getElementById('showAjax').innerHTML += '<br />forAjaxFieldSearchId = ' +  $forAjaxFieldSearchId; // for TEST 
	// retrieve the keyword object
	var oKeyword = document.getElementById($forAjaxFieldSearchId);
	// retrieve the link for the current function
	var crtLink = decodeURIComponent(document.getElementById("a" + oTr.id.substring(2,oTr.id.length)).title);
	//document.getElementById('showAjax').innerHTML += '<br />selected span title = ' +  crtLink; // for TEST 
	// update the keyword's value
	oKeyword.value = crtLink;
}

// function that removes the style from all suggestions  ******************************************************** FCE deselectAll ******
function deselectAll() {
	for(i=0; i<suggestions; i++) {
		var oCrtTr = document.getElementById("tr" + i);
		oCrtTr.className = "";		
	}
}

// function that handles the mouse entering over a suggestion's area event  ******************************************************** FCE handleOnMouseOver ******
function handleOnMouseOver(oTr) {
	deselectAll();
	oTr.className = "highlightrow";
	position = oTr.id.substring(2, oTr.id.length);
}

// function that handles the mouse exiting a suggestion's area event  ******************************************************** FCE handleOnMouseOut ******
function handleOnMouseOut(oTr) {
	oTr.className = "";	 
	position = -1;
}

// function that escapes a string  ******************************************************** FCE encode ******
function encode(uri) {
	if (encodeURIComponent) {
		return encodeURIComponent(uri);
	}
	if (escape) {
		return escape(uri);
	}
	else {
		return uri;
	}
}

// function that selects a range in the text object passed as parameter  ******************************************************** FCE selectRange ******
function selectRange(oText, start, length) {
	// check to see if in IE or FF 
	if (oText.createTextRange) {
		//IE 
		var oRange = oText.createTextRange(); 
		oRange.moveStart("character", start); 
		oRange.moveEnd("character", length - oText.value.length); 
		oRange.select();
	}
	else 
		// FF 
		if (oText.setSelectionRange) {
			oText.setSelectionRange(start, length);
		} 
	oText.focus(); 
}

// function that autocompletes the typed keyword  ******************************************************** FCE autocompleteKeyword ******
function autocompleteKeyword() {
	//retrieve the keyword object
	var oKeyword = document.getElementById($forAjaxFieldSearchId);
	// reset the position of the selected suggestion
	position=0;
	// deselect all suggestions
	deselectAll();
	// highlight the selected suggestion 
	document.getElementById("tr0").className = "highlightrow";
	// update the keyword's value with the suggestion
	updateKeywordValue(document.getElementById("tr0"));
	// apply the type-ahead style
	selectRange(oKeyword, httpRequestKeyword.length, oKeyword.value.length);	
	// set the autocompleted word to the keyword's value
	autocompletedKeyword = oKeyword.value;
}

// function that displays an error message  ******************************************************** FCE displayError ******
function displayError(message) {
	// display error message, with more technical details if debugMode is true
	alert("Error accessing the server! "+ (debugMode ? "\n" + message : ""));
}




// **********************************************************************************
// ==================== CZECH SPECIFI CFUNCTIONS ================================
// **********************************************************************************

// BIRTHNUMBER TO BIRTHDATE  
function rcToBirthdate($inputId, $dayId, $monthId, $yearId, $sexId) {
	var $rc = document.getElementById($inputId).value;
	if($rc && $rc.length>=6) {
		$DD = $rc.substring(4,6);
		$MM = $rc.substring(2,4);
		$YY = $rc.substring(0,2);
		if(document.getElementById($sexId).checked==true) $MM = $MM-50;
		if($YY >= 0 && $YY <= 10) $YY = '20'+$YY; else $YY = '19'+$YY;
		//alert($DD+$MM+$YY);
		document.getElementById($dayId).value = $DD;
		document.getElementById($monthId).value = $MM;
		document.getElementById($yearId).value = $YY;
	}
}

// set DIC from ICO  
function setIcoToDic($idIco, $idDic) {
	if(document.getElementById($idIco).value) {
		document.getElementById($idDic).value = 'CZ' + document.getElementById($idIco).value;
		document.getElementById($idDic).focus();
	}
}


