var rowStyle;

function jQuerySelectorEscape(expression) {
	return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
}

function select(elem) {
	//console.log("select");
	
	var node = $(elem);
	var parent = node.closest("table");
	// unmark all
	var root = node.parents("[class=proveoTree]");
	var chlds = root.find("table");

	chlds.each(function() {
		$(this).toggleClass("rf-tree-marked", false);
	});
	// mark
	parent.toggleClass("rf-tree-marked", true);
}

function mark(elem) {
	// console.log("mark");
	var node = $(elem);
	var checked = node.prop('checked') ? true : false;
	var id = node.parent().prop('id');
	var root = node.parents("[class=proveoTree]");
	var parent = root.find("table[id=" + jQuerySelectorEscape(id) + "_table]");

	//parent.toggleClass('rf-tree-marked', checked);
}

function checkParent(parentCheck, parentUncheck, elem) {
	// console.log("check parent");

	// get node
	var node = $(elem);
	var checked = node.prop('checked') ? true : false;
	var id = node.parent().prop('id');
	if (id == undefined || id == "")
		return;
	var root = node.parents("[class=proveoTree]");
	var parentId = id.substring(0, id.lastIndexOf(":"));
	if (parentId == undefined || parentId == "")
		return;
	var parent = root.find("div[id=" + jQuerySelectorEscape(parentId) + "]");
	parent = parent.children("input[type=checkbox]");

	if (parentCheck == "NONE" && checked == true || parentUncheck == "NONE"
			&& checked == false) {
		return;
	}

	if (parentCheck == "ALL" && checked == true || parentUncheck == "ALL"
			&& checked == false) {
		var skip = false;
		var chlds = root
				.find("div[id^=" + jQuerySelectorEscape(parentId) + "]");

		chlds.each(function() {
			var sub = $(this).children("input[type=checkbox]");
			var childChecked = sub.prop('checked') ? true : false;
			if (childChecked != checked && $(this).prop("id") != parentId) {
				skip = true;
			}
		});

		if (skip)
			return;
	}

	// check and go upwards
	parent.prop('checked', checked);
	// mark
	mark(parent[0]);
	checkParent(parentCheck, parentUncheck, parent[0]);
}

function checkChildren(childCheck, childUncheck, elem) {
	// console.log("check children");

	// get node
	var node = $(elem);
	var checked = node.prop('checked') ? true : false;
	// get parent and node id
	var id = node.parent().prop('id');

	// get root node
	var rootId = ":" + id.split(":")[1];
	var root = node.parents("[class=proveoTree]");

	if (childCheck == "NONE" && checked == true || childUncheck == "NONE"
			&& checked == false) {
		return;
	}

	// get all subnode-checkboxes and uncheck/check
	var chlds = root.find("div[id^=" + jQuerySelectorEscape(id) + "]");
	chlds.each(function() {
		var sub = $(this).children("input[type=checkbox]");
		sub.prop('checked', checked);
		mark(sub[0]);
	});
}

function switchRichFacesTab(tab1, tab2, tab3) {
	RichFaces.switchTab(tab1, tab2, tab3);
}

function isMobileDevice() {
	function Client() {
	}

	Client.prototype.mobileClients = [ "midp", "240x320", "blackberry",
			"netfront", "nokia", "panasonic", "portalmmm", "sharp", "sie-",
			"sonyericsson", "symbian", "windows ce", "benq", "mda", "mot-",
			"opera mini", "philips", "pocket pc", "sagem", "samsung", "sda",
			"sgh-", "vodafone", "xda", "iphone", "android", "ipad", "ipod" ];

	Client.prototype.isMobileClient = function(userAgent) {
		userAgent = userAgent.toLowerCase();
		for ( var i in this.mobileClients) {
			if (userAgent.indexOf(this.mobileClients[i]) != -1) {
				return true;
			}
		}
		return false;
	}

	var client = new Client();
	return client.isMobileClient(navigator.userAgent);
}

function getStartPage() {
	var mobileSite = '../pages/mobile/mobileStartPage.jsf';
	var desktopSite = '../pages/test/test.jsf';

	if (isMobileDevice()) {
		return mobileSite;
	} else {
		return desktopSite;
	}
}

function getLoginPage() {
	var mobileSite = 'mobileLogin.jsf';
	var desktopSite = 'standardLogin.jsf';
	if (isMobileDevice()) {
		return mobileSite;
	} else {
		return desktopSite;
	}
}

// highlight for DataTable
function hl(thisObj) {
	rowStyle = thisObj.className;
	thisObj.className = "rowHighlighted";

}
// removeHighlight for DataTable
function rhl(thisObj) {
	thisObj.className = rowStyle;
}

function showLoadingProgress() {
	document.getElementById('progressPanelContainer').style.display = '';
}

function showLoadingProgressMsg(progressText) {
	document.getElementById('progressPanelContainer').style.display = '';
	document.getElementById('progressPanelText').innerHTML = progressText;
}

function closeLoadingProgress() {
	document.getElementById('progressPanelContainer').style.display = 'none';
}

function toggleDisplay(id) {
	var s = document.getElementById(id).style;
	if (s.display == 'none') {
		s.display = 'inline';
		var pxl = document.getElementById(id).offsetHeight;
		scrollDown(pxl);
	} else
		s.display = 'none';
}

// Some functions for cookie handling

// Set cookie value
//
// param1: name
// param2: value
// param3: expiration in days
// param4: path
// param5: domain
// param6: secure

function setCookie(name, value) {
	// Prepare arguments
	var args = setCookie.arguments;
	var num_args = setCookie.arguments.length;
	var expires = (num_args > 2) ? args[2] : null;
	var path = (num_args > 3) ? args[3] : null;
	var domain = (num_args > 4) ? args[4] : null;
	var secure = (num_args > 5) ? args[5] : false;

	// Calculate expiration date
	var today = new Date();
	if (expires)
		expires = expires * 1000 * 60 * 60 * 24;
	var expirationDate = new Date(today.getTime() + (expires));

	// Set cookie
	document.cookie = name
			+ "="
			+ encodeURIComponent(value)
			+ ((expires == null) ? "" : (";expires=" + expirationDate
					.toGMTString()))
			+ ((path == null) ? ";path=/" : (";path=" + path))
			+ ((domain == null) ? "" : (";domain=" + domain))
			+ ((secure == true) ? ";secure" : "");
}

// Get cookie value
//
// param1: name of cookie to retrieve
// returns: value of cookie, null on error
function getCookie(name) {
	var test = document.cookie;
	var start = document.cookie.indexOf(name + "=");
	if ((!start) && (name != document.cookie.substring(0, name.length)))
		return null;
	if (start == -1)
		return null;
	var len = start + name.length + 1;
	var end = document.cookie.indexOf(";", len);
	if (end == -1)
		end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

// Delete cookie
//
// param1: cookie name
function deleteCookie(name, path, domain) {
	if (getCookie(name))
		document.cookie = name + "=" + ((path) ? ";path=" + location.path : "")
				+ ((domain) ? ";domain=" + location.hostname : "")
				+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Check for browser cookie support
//
// returns: true, when successful
function checkCookieSupport() {
	setCookie("test", "none", "", location.pathname + "/testpath",
			location.hostname);
	if (getCookie("test"))
		return true;
	else
		return false;
}

function setDisabled(isDisabled, disableId) {
	if (disableId != null)
		document.getElementById(disableId).disabled = isDisabled;
}

function confirmWithLoading(confirmText) {
	if (confirm(confirmText)) {
		showLoadingProgress();
		return true;
	}
	return false;
}

function confirmWithLoadingProgressText(confirmText, progressText) {
	if (confirm(confirmText)) {
		showLoadingProgressMsg(progressText);
		return true;
	}
	return false;
}

function scrollToBottom() {
	window.scrollBy(0, document.body.scrollHeight);
}

function scrollDown(pxl) {
	window.scrollBy(0, pxl);
}

function sortSelect(selElem) {
	var tmpAry = new Array();
	for ( var i = 0; i < selElem.options.length; i++) {
		tmpAry[i] = new Array();
		tmpAry[i][0] = selElem.options[i].text;
		tmpAry[i][1] = selElem.options[i].value;
	}
	tmpAry.sort();
	while (selElem.options.length > 0) {
		selElem.options[0] = null;
	}
	for ( var i = 0; i < tmpAry.length; i++) {
		var op = new Option(tmpAry[i][0], tmpAry[i][1]);
		selElem.options[i] = op;
	}
	return;
}

function showAI() {
	var e = document.getElementById('ajaxIndicator').style;
	e.top = (document.documentElement.scrollTop + 10) + "px";
	e.left = (document.documentElement.clientWidth - 75) + "px";
	e.display = 'block';
}
function hideAI() {
	document.getElementById('ajaxIndicator').style.display = 'none';
}
function showAjaxProgress() {
	var e = document.getElementById('ajaxProgress').style;
	e.top = (document.documentElement.scrollTop + 10) + "px";
	e.left = (document.documentElement.clientWidth - 75) + "px";
	e.display = 'block';
}
function hideAjaxProgress() {
	document.getElementById('ajaxProgress').style.display = 'none';
}

function ajaxFocus(event) {
	var comp = event.source;
	var id = comp.id;
	var elem = document.getElementById(id);
	// elem.focus();
	var control = elem;
	if (control.createTextRange) {
		var range = control.createTextRange();
		range.collapse(false);
		range.select();
	} else if (control.setSelectionRange) {
		control.focus();
		var length = control.value.length;
		control.setSelectionRange(length, length);
	}
	control.selectionStart = control.selectionEnd = control.value.length;
}

function ajaxScrollTop() {
	window.scrollTo(0, 0);
}
