var groupShowSrc;
var groupHideSrc;
var locationUrl;

function init(groupShow, groupHide)
{
	groupShowSrc = groupShow;
	groupHideSrc = groupHide;
	tempLocationUrl = location.href.substring(0, location.href.indexOf("?"));
	locationUrl = tempLocationUrl.substring(0, tempLocationUrl.lastIndexOf("/") + 1);
}

function getGroupShow()
{
	return groupShowSrc;
}

function showHide(target)
{
	if (target.style.display == 'none')
		target.style.display = '';
	else
		target.style.display = 'none';
}

function resetImage(src1, src2, hidden, sender)
{
	if (hidden)
		sender.src = src2;
	else
		sender.src = src1;
}

function resetCssClass(css1, css2, hidden, sender)
{
	if (hidden)
		sender.className = css2;
	else
		sender.className = css1;
}

function showHideImage(target, src1, src2, sender)
{
	showHide(target);
	resetImage(src1, src2, target.style.display == 'none', sender);
}

function changeCssClass(target, css1, css2, sender)
{
	showHide(target);
	resetCssClass(css1, css2, target.style.display == 'none', sender)
}

function showHideGroup(target, sender)
{
	showHideImage(target, groupHideSrc, groupShowSrc, sender);
}

function waitPageLoad()
{
	self.setTimeout("alertWaitPageLoad()", 2000);
}

function alertWaitPageLoad()
{
	var eWaitTable = document.createElement("table");

	eWaitTable.className = "wait-load-table";
	eWaitTable.width = 200;
	eWaitTable.border = 0;
	eWaitTable.cellspacing = 0;
	eWaitTable.cellpadding = 0;
	eWaitTable.style.zIndex = "1000";
	eWaitTable.style.position = "absolute";
	eWaitTable.id = "pleaseWaitSplash";

	eWaitTable.style.posLeft = window.document.body.offsetWidth / 2 - (eWaitTable.width / 2);
	eWaitTable.style.posTop = window.document.body.scrollTop + (window.document.body.offsetHeight / 2 - (40 / 2));

	eWaitTableTR = eWaitTable.insertRow();

	var eTDImg = eWaitTableTR.insertCell();
	var eTDText = eWaitTableTR.insertCell();

	var sImgText = "<img src='Image.aspx?image=please-wait.gif' width='40' height='40'>";
	eTDImg.appendChild(document.createElement(sImgText));
	eTDImg.align = "center";

	eTDText.align = "center";
	eTDText.className = "wait-load-text";
	eTDText.innerText = waitMessage;

	window.document.body.insertAdjacentElement("BeforeEnd", eWaitTable);
}

function showMessage(message)
{
	window.status = message;
}

function isTop()
{
	return top == self;
}

function isFramed()
{
	return top != self;
}

function setPageAtTop()
{
	top.document.location = self.document.location;
}

function autoRedirect(timeout, destination)
{
	self.setTimeout("jumpToFlow('" + destination + "')", timeout);
}

function autoFormPost(timeout, formId)
{
	self.setTimeout("autoFormPostExecute('" + formId + "')", timeout);
}

function autoFormPostExecute(formId)
{
	var form = document.getElementById(formId);
	var isSubmited = form.isSubmited;
	if ((isSubmited != null) && (isSubmited == "true"))
		isSubmited = true;
	else
		isSubmited = false;
	if (!isSubmited)
		form.submit();
}

function setActionQueryParams(queryParams)
{
	var queryParamsString = "";
	for (key in queryParams)
	{
		if (queryParamsString != "")
			queryParamsString += "&";
		queryParamsString += key + "=" + queryParams[key];
	}
	window.top.document.Form1.action = "Main.aspx";
	if (queryParamsString != "")
		window.top.document.Form1.action += "?" + queryParamsString;
}

function validateAndSubmit(queryParams)
{
	if (typeof (Page_ClientValidate) != 'function' || Page_ClientValidate())
	{
		if (queryParams != null)
			setActionQueryParams(queryParams);
		waitPageLoad();
		window.top.document.Form1.submit();
		if (window.top.document.getElementById("pleaseWaitSplash") != null)
			window.top.document.Form1.submit();
		return true;
	}
	return false;
}

function jumpToFlow(flow)
{
	nextFlowSubmit(flow);
}

function nextFlowSubmitWithArgument(flow, argKey, argValue)
{
	var queryParams = new Array();
	queryParams["flow"] = flow;
	queryParams[argKey] = argValue;
	return validateAndSubmit(queryParams);
}

function nextFlowSubmit(flow, confirmation)
{
	var queryParams = new Array();
	queryParams["flow"] = flow;
	setActionQueryParams(queryParams);
	if (confirmation)
		MessageBox.show("Do you want to continue?", "mBPM Confirmation", new Array("Yes", "No"), new Array(nextFlowSubmitConfirmed, MessageBox.hide));
	else
		nextFlowSubmitConfirmed();
}

function nextFlowSubmitConfirmed()
{
	return validateAndSubmit(null);
}

function callFlow()
{
	var queryParams = new Array();
	queryParams["call"] = "true";
	return validateAndSubmit(queryParams);
}

function onTimeCtrl_Changed(microsoftGeneratedName, ctrlid)
{
	document.getElementById(microsoftGeneratedName + ctrlid).value = document.getElementById(microsoftGeneratedName + 'hour' + ctrlid).value + ':' + document.getElementById(microsoftGeneratedName + 'minute' + ctrlid).value + ':' + document.getElementById(microsoftGeneratedName + 'second' + ctrlid).value
	if (document.getElementById(microsoftGeneratedName + ctrlid).value == '::')
		document.getElementById(microsoftGeneratedName + ctrlid).value = '';

}

function onSelectDatagridRow(nextflow)
{
	window.parent.location = window.parent.location.href.substring(window.parent.location.href.lastIndexOf("/") + 1, window.parent.location.href.lastIndexOf("?") + 1) + "?flow=" + nextflow
	window.parent.document.Form1.submit();
}

function addEntryToUrl(url, key, value)
{
	var index = url.indexOf(key + "=");
	if (index > 0)
	{
		var head = url.substring(0, index) + key + "=" + value;
		var tail = url.substring(index, url.length);
		if (tail.indexOf("&") > 0)
			tail = tail.substring(tail.indexOf("&"), tail.length);
		else
			tail = "";

		if (tail.length > 0)
			url = head + "&" + tail;
		else
			url = head;
	}
	else
		url = url + "&" + key + "=" + value;
	return url;
}

function confirmOperation(flow, text)
{
	var name = confirm(text)
	waitPageLoad();
	if (name == true)
		location = location.href.substring(location.href.lastIndexOf("/") + 1, location.href.lastIndexOf("?") + 1) + "call=true&confirm=1";
	else
		location = location.href.substring(location.href.lastIndexOf("/") + 1, location.href.lastIndexOf("?") + 1) + "call=true&confirm=0";
}

function maxtext(text, max)
{
	tempstr = text.value;
	if (tempstr.length > max)
		text.value = tempstr.substring(0, max);
}

function reposition(targetID)
{
	target = document.getElementById(targetID);
	winY = window.top.document.body.scrollTop;

	targetTop = target.style.pixelTop;

	if (winY != targetTop && (target.clientHeight + 150 < document.body.clientHeight))
	{
		delta = (winY - targetTop) * 0.75;
		if (delta >= 0)
		{
			if (delta < 3)
				delta = 3;
		}
		else
			if (delta > -3)
			delta = -3;

		targetTop += delta;

		if ((targetTop > winY) && (delta > 0))
			targetTop = winY;
		if ((targetTop < 0) && (delta < 0))
			targetTop = 0;

		target.style.pixelTop = targetTop;
		self.setTimeout("reposition('" + targetID + "')", 20);
	}
	else
		self.setTimeout("reposition('" + targetID + "')", 150);
}

function trim(str)
{
	return ltrim(rtrim(str));
}

function ltrim(str)
{
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1)
	{
		var i = 0;

		// Iterate from the beggining of string until we
		// don't have any more whitespace...
		while (i < s.length && whitespace.indexOf(s.charAt(i)) != -1)
			i++;

		// Get the substring from the front of the string to
		// where the last non-whitespace character is...
		s = s.substring(i);
	}
	return s;
}


function rtrim(str)
{
	var whitespace = new String(" \t\n\r");
	var s = new String(str);

	if (whitespace.indexOf(s.charAt(s.length - 1)) != -1)
	{
		var i = s.length - 1;       // Get length of string

		// Iterate from the far right of string until we
		// don't have any more whitespace...
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;

		// Get the substring from the front of the string to
		// where the last non-whitespace character is...
		s = s.substring(0, i + 1);
	}
	return s;
}

// Existe uma função em JavaScript que faz o mesmo que esta, o nome é 'escape'
function htmlSafe(htmlText)
{
	htmlText = htmlText.replace(/\%/g, "%25");
	htmlText = htmlText.replace(/\&/g, "%26"); // To replace all
	htmlText = htmlText.replace(/\'/g, "%27");
	htmlText = htmlText.replace(/\#/g, "%23");
	htmlText = htmlText.replace(/\</g, "%3C");
	htmlText = htmlText.replace(/\>/g, "%3E");
	htmlText = htmlText.replace(/\;/g, "%3B");
	htmlText = htmlText.replace(/\//g, "%2F");
	htmlText = htmlText.replace(/\?/g, "%3F");
	htmlText = htmlText.replace(/\:/g, "%3A");
	htmlText = htmlText.replace(/\@/g, "%40");
	htmlText = htmlText.replace(/\&/g, "%26");
	htmlText = htmlText.replace(/\=/g, "%3D");
	htmlText = htmlText.replace(/\+/g, "%2B");
	htmlText = htmlText.replace(/\$/g, "%24");
	htmlText = htmlText.replace(/\,/g, "%2C");
	htmlText = htmlText.replace(/\{/g, "%7B");
	htmlText = htmlText.replace(/\}/g, "%7D");
	htmlText = htmlText.replace(/\|/g, "%7C");
	htmlText = htmlText.replace(/\\/g, "%5C");
	htmlText = htmlText.replace(/\^/g, "%5E");
	htmlText = htmlText.replace(/\[/g, "%5B");
	htmlText = htmlText.replace(/\]/g, "%5D");
	htmlText = htmlText.replace(/\`/g, "%60");
	htmlText = htmlText.replace(/\ /g, "%20");
	htmlText = htmlText.replace(/\n/g, "%0D");
	htmlText = htmlText.replace(/\r/g, "%0A");
	htmlText = encodeURI(htmlText)
	return htmlText;
}

function HtmlEditorWindow(strURLIN, strTarget, controlId, session)
{
	var w;
	if (strTarget == "new")
	{
		var htmlText = window.document.getElementById(controlId).value;

		var myObject = new Object();
		myObject.content = htmlText;
		myObject.session = session;
		w = window.showModalDialog(strURLIN, myObject, "center:yes; dialogWidth:600px; dialogHeight:490px; status:no; scroll:no;");
		if (w != null)
			window.document.getElementById(controlId).value = w;
	}
	else
	{
		window.location.href = strURLIN + "?content=" + window.document.getElementById(controlId).value;
	}
}

function EmulatorWindow(strURLIN, widthField, heightField, imgwidthField, imgheightField, contentField)
{
	var width = window.document.getElementById(widthField).value;
	var height = window.document.getElementById(heightField).value;
	var imgwidth = window.document.getElementById(imgwidthField).value;
	var imgheight = window.document.getElementById(imgheightField).value;
	var content = window.document.getElementById(contentField).value;
	var dialogWidth = parseInt(imgwidth) + 6;
	var dialogHeight = parseInt(imgheight) + 28;
	if ((width != null) && (height != null) && (content != null))
		window.showModalDialog(strURLIN + "?content=" + content + "&width=" + width + "&height=" + height, "", "center:yes; dialogWidth:" + dialogWidth + "px; dialogHeight:" + dialogHeight + "px; status:no; scroll:no;");
}

function printwindow(flow)
{
	window.open('Print.aspx?flow=' + flow, 'Print');
}

function parseAutoCurrency(e)
{
	var evt = W3C.getEvent(e);
	var target = W3C.Event.getTarget(evt);

	if (target == null) return; // If there is nothing in the box keep it that way

	var sValue = target.value;
	if (sValue.length == 0) return; // If there is nothing in the box keep it that way

	sValue = sValue.replace(",", "").replace(".", "");
	var iValue = (sValue * 1) / 100;
	sValue = "" + iValue;
	var finalResult = sValue.replace(".", ",");

	// If the number is divisible by 100 with rest 0 the sValue will contain no "."
	// Adds the decimal digits to compensate
	if (finalResult.length > 0 && finalResult.indexOf(",") == -1 && finalResult != "0")
	{
		finalResult += ",00";
	}

	// Adds a leading zero if necessary
	var afterSeparatorLength = finalResult.substring(finalResult.indexOf(",") + 1).length;
	if (afterSeparatorLength != 0)
	{
		if (afterSeparatorLength == 1 && finalResult != "0" && finalResult.length > 0)
			finalResult = finalResult + "0";
	}
	target.value = finalResult;
}

function validateNumber(e)
{
	var evt = W3C.getEvent(e);
	if ((W3C.Event.UIEvent.KeyboardEvent.getKeyCode(evt) < Utils.KeyIdentifiers.ZERO) || (W3C.Event.UIEvent.KeyboardEvent.getKeyCode(evt) > Utils.KeyIdentifiers.NINE))
	{
		W3C.Event.stopPropagation(evt);
		W3C.Event.preventDefault(evt);
	}
}

function validateRequiredField(idField)
{
	var carCode = event.keyCode;
	if ((carCode == 13) || (carCode == 9))
	{
		event.returnValue = false;
		if (document.Form1.elements[idField].value == "")
		{
			alert("Campo Obrigatório");
			return;
		}
		else
			event.returnValue = true;
	}
}

function validateFloatNumber(idField)
{
	var carCode = event.keyCode;
	if ((carCode == 13) || (carCode == 9))
	{
		event.returnValue = false;
		if (isNaN(document.Form1.elements[idField].value))
		{
			alert("Por favor introduza um número válido");
			return;
		}
		else
			event.returnValue = true;
	}
}


// Login
var appWindow;
function openInNewWindow(src, windowName, isCloseWindow)
{
	var width = screen.availWidth - 64;
	var height = screen.availHeight - 96;
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2 - 32;
	appWindow = window.open(src, windowName,
		'width=' + width + ',' +
		'height=' + height + ',' +
		'left=' + left + ',' +
		'top=' + top + ',' +
		'screenX=' + left + ',' +
		'screenY=' + top + ',' +
		'resizable=yes,scrollbars=yes,status=yes');
	appWindow.focus();
	if (isCloseWindow)
		window.close();
}

function openWindow(src, windowName, width, height)
{
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2 - 32;
	window.open(src, windowName,
		'width=' + width + ',' +
		'height=' + height + ',' +
		'left=' + left + ',' +
		'top=' + top + ',' +
		'screenX=' + left + ',' +
		'screenY=' + top + ',' +
		'resizable=yes,scrollbars=yes');
}

//Logout
function exit(message, successTarget, id)
{
	MessageBox.show(message, "MORE", new Array("Ok", "Cancel"), new Array(function() { top.location.href = successTarget; }, function() { MessageBox.hide(); }));
	/*var res;
	if (message != null)
	res = confirm(message);
	else
	res = true;
	if (res)
	{
	window.document.getElementById(id).disabled = true;
	top.location.href = successTarget;
	}
	else
	{
	}
	return res;*/
}

function logout(isCloseWindow)
{
	fireChildEvent("logout", null);
	if (isCloseWindow)
		window.close();
}

function fireCloseEvent(isCloseWindow)
{
	if (self.screenTop < 9000)	// Just page change
		return;
	if (self.opener != null && !self.opener.closed)
		self.location.href = "Logout.aspx";
	fireChildEvent("logout", null);
}

// Recover Password
function setUpRecoverPwdDialog(dialogCtrlId, fieldsCtrlId, userCtrlId, emailCtrlId, messageCtrlId)
{
    $(function()
    {
        $("#" + messageCtrlId).hide();
        $("#" + fieldsCtrlId).show();
        $("#" + userCtrlId).val("");
        $("#" + emailCtrlId).val("");
        $("#" + dialogCtrlId).dialog({
            autoOpen: false,
            height: 155,
            width: 350,
            resizable: false,
            show: 'blind',
            modal: true,
            buttons: {
                'Ok': function()
                {
                    $.ajax({
                        url: 'Login.aspx?call=true&caller=recoverpwd&user=' + $("#" + userCtrlId).val() + '&email=' + $("#" + emailCtrlId).val(),
                        success: function()
                        {
                            $("#" + fieldsCtrlId).fadeOut('slow');
                            $("#" + messageCtrlId).fadeIn('slow');
                            $("#" + dialogCtrlId).dialog("option", "buttons", { "Ok": function() { $(this).dialog("close"); } });
                        }
                    });
                },
                Cancel: function()
                {
                    $(this).dialog('close');
                }
            },
            close: function()
            {
                $(this).dialog("destroy")
                setUpRecoverPwdDialog(dialogCtrlId, fieldsCtrlId, userCtrlId, emailCtrlId, messageCtrlId);
            }
        });
    });
}

function recoverPassword(ctrlId)
{
    $('#' + ctrlId).dialog('open');
    $('#' + ctrlId).dialog('open');
}

// Messaging
var locationUrl = location.href.substring(0, location.href.lastIndexOf("/") + 1);

function messaging_checkTimer(flowCode, arguments, targetWindow, targetUrl, refreshPeriod, alertType, alertMessage)
{
	var args = "?action=execFlow";
	args += "&flow=" + flowCode;
	args += "&arguments=" + arguments;
	
	var request = new DataRequest();
	request.setUrl("Alert.aspx" + args);
	var func = new DelayedFunction();
	func.setFunctionString("messaging_checkCallBack($#arg0#, $#arg1#, $#arg2#, $#arg3#, $#arg4#, $#arg5#, $#arg6#, $#arg7#);");
	func.bindArgument(request);
	func.bindArgument(flowCode);
	func.bindArgument(arguments);
	func.bindArgument(targetWindow);
	func.bindArgument(targetUrl);
	func.bindArgument(refreshPeriod);
	func.bindArgument(alertType);
	func.bindArgument(alertMessage);
	func.setCaller(this);
	request.setOnDoneFunction(func);
	request.setOnErrorFunction(func);
	DataRequester.execute(request);
}

function messaging_checkCallBack(request, flowCode, arguments, targetWindow, targetUrl, refreshPeriod, alertType, alertMessage)
{
	if (request.getResult()==null) //if there is an error
	{
		window.status = "Error: Executing flow.";
		alert("Error: Executing flow."); //Add code to handle specific error codes here
	}
	else //if there was no error
	{
		var result = Utils.Node.getChildById(request.getResult(), "alertResult")
		if (result.innerHTML == "REFRESH")
		{
			if (alertType == '2')
			{
				document.getElementById('sound_alert').src = targetUrl;
				alert(alertMessage);
				document.getElementById('sound_alert').src = null;
			}
			else
				window.open(targetUrl, targetWindow, 'width=480,height=300,left=0,top=0,screenX=0,screenY=0,resizable=yes,scrollbars=yes,status=yes').focus();
		}
		self.setTimeout("messaging_checkTimer('" + flowCode + "','" + arguments + "','" + targetWindow + "','" + targetUrl + "'," + refreshPeriod + ",'" + alertType + "','" + alertMessage + "')", refreshPeriod);
	}
}

// Timer
var timer_map = new Object();

function Timer(id)
{
	this.id = "timerid_" + id;
	this.Interval = 1000;
	this.Enabled = false;
	this.Tick = null;
	this.enable = timer_enable;
	this.disable = timer_disable;
	this.setTimeout = timer_set;
	timer_map[this.id] = this;
}

/*=======Private methods for internal use only========*/
function timer_set()
{
	window.setTimeout("timer_callBack('" + this.id + "')", this.Interval);
}

function timer_enable()
{
	if (!this.Enabled)
	{
		this.Enabled = true;
		this.setTimeout();
	}
}

function timer_disable()
{
	this.Enabled = false;
}

function timer_callBack(id)
{
	timer = timer_map[id];
	if (timer.Enabled && timer.Tick != null && typeof (timer.Tick) == 'function')
	{
		timer.Tick();
		timer.setTimeout();
	}
}

