﻿var Page_IsDirty = false;
var Page_CheckDirty = false;
var Page_CheckDirtyForTabChange = false;
var Page_IsSubmitted = false;
var Page_SkipIsDirtyCheckOnce = false;
var Page_ControlGroups = {};
var Page_DirtyFlags = {};
var Page_Controls = {};
var Page_ForceLogOut = false;

var Page_DefaultGroup = "default";

var Page_GroupToValidate = Page_DefaultGroup;

var Page_AutoLogout = false;

var Page_DisplayLoadingMessage = false;

var ControlIDIndex = 0;
var ControlParentIndex = 1;
var ControlGroupIndex = 2;
var ControlCausesValidationIndex = 3;
var ControlChecksForDirtyIndex = 4;


window.onbeforeunload = Page_BeforeUnload;
window.onunload = Page_OnUnload;

// Fix for href="javascript:blah blah;" kind of stuff
// If there is a mouseclick event that means user clicked on a link. 
//document.attachEvent('onmouseup', GlobalEventHandlerForDirtyCheck)
/*
document.attachEvent('onmouseup', GlobalEventHandlerForDirtyCheck)
function GlobalEventHandlerForDirtyCheck()
{
	Page_SkipIsDirtyCheckOnce = true;
	setTimeout("Page_SkipIsDirtyCheckOnce = false;", 1000);
	return true;
}
*/

// save a reference to the original __doPostBack
var __oldDoPostBack;

if (typeof(__doPostBack) == 'function') 
{
	__oldDoPostBack = __doPostBack ;
	// replace __doPostBack with another function
	__doPostBack = AlwaysFireBeforeFormSubmit;
}

function AlwaysFireBeforeFormSubmit(eventTarget, eventArgument) 
{
	if (typeof(DoBeforeFormSubmit) == 'function')
	{
		if (DoBeforeFormSubmit() == false)
			return;
	}
	Page_IsSubmitted = true;

    if (Page_DisplayLoadingMessage)	
	    DisplayLoadingMessage();
	    
	return __oldDoPostBack (eventTarget, eventArgument);
}


function ForceLogOut()
{
	// Obsolete
}	


function Page_OnUnload()
{
    if (Page_DisplayLoadingMessage)
	    DisplayLoadingMessage();
	    
	if (Page_ForceLogOut || (Page_AutoLogout && IsUserClosingTheWindow()))
	{
		LogOut();
	}
}


/* Display the logout window */
function LogOut()
{
	var woLogOut = new WindowOpener("LogOut", "LogOut.aspx?NewWindow=true", "400px", "200px");
	woLogOut.open();
}


/* Close the main window and display the logout window */
function CloseAndLogOut()
{
	Page_ForceLogOut = true;
	parent.window.close();
}


/* This is a little hack. Its proper working depends on the fact that when the user closes the application
window by clicking the 'x' mouse X and Y coordinates both show a negative value. */
function IsUserClosingTheWindow()
{
		var posx = 0;
		var posy = 0;
		var e = window.event;
		if (e.pageX || e.pageY)
		{
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY)
		{
			posx = e.clientX + document.body.scrollLeft;
			posy = e.clientY + document.body.scrollTop;
		}

		return (posx < 0 && posy < 0);
}


function IsDirty()
{
	return (!Page_SkipIsDirtyCheckOnce && (Page_IsDirty && Page_CheckDirty && !Page_IsSubmitted))
}


function Page_BeforeUnload()
{
    if (Page_DisplayLoadingMessage)
    	DisplayLoadingMessage();
    	
	if (Page_SkipIsDirtyCheckOnce)
		Page_SkipIsDirtyCheckOnce = false;
	else
	{
		if (Page_IsDirty && Page_CheckDirty && !Page_IsSubmitted)
			return "You will lose all the unsaved changes.";
	}
}

function DisplayIsDirtyWarning()
{
	if (!Page_CheckDirty)		/* fixed by ilkay */  // we need to check this global flag.
		return true;
	if (Page_IsDirty)
		return confirm("Are you sure you want to navigate away from this page?\n\nYou will lose all the unsaved changes.\n\nPress OK to continue, or Cancel to stay on the current page.");
	else
		return true;
}


// Sets the dirty flag on the group associated with this control
function SetDirty(id)
{
	var controlGroup = Page_Controls[id][ControlGroupIndex];
    Page_DirtyFlags[controlGroup] = 1;
    Page_IsDirty = true;
}

// Set group dirty
function SetGroupDirty(controlGroup)
{
    Page_DirtyFlags[controlGroup] = 1;
    Page_IsDirty = true;
}

function SetPageDirty(isDirty)
{
	Page_IsDirty = isDirty;
}


/* End */


/*
Modified by NetsoftUSA

function ValidatorUpdateDisplay(val) {
    if (typeof(val.display) == "string") {
        if (val.display == "None") {
            return;
        }
        if (val.display == "Dynamic") {
            val.style.display = val.isvalid ? "none" : "inline";
            return;
        }
    }
    if ((navigator.userAgent.indexOf("Mac") > -1) &&
        (navigator.userAgent.indexOf("MSIE") > -1)) {
        val.style.display = "inline";
    }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
}
*/

function Netsoft_ValidatorUpdateDisplay(val) {

    var control;
    control = document.getElementById(val.controltovalidate);
    
    if (!control) return;
   
    if (typeof(val.display) == "string") {    
        if (val.display == "None") {
            return;
        }
        if (val.display == "Dynamic") 
        {
            if (typeof(ig_UpdateDisplay) != "function" || !ig_UpdateDisplay(control.id, val.ControlType))
    			val.style.display = val.isvalid ? "none" : "inline";
			return;
        }
    }
    if ((navigator.userAgent.indexOf("Mac") > -1) &&
        (navigator.userAgent.indexOf("MSIE") > -1)) {
         if (!ig_UpdateDisplay(control.id, val.ControlType))
            val.style.display = "inline";
    }    
    if (typeof(ig_UpdateDisplay) != "function" || !ig_UpdateDisplay(control.id, val.ControlType))
		val.style.visibility = val.isvalid ? "hidden" : "visible";
}



/* End */




function ValidatorGetComboValue(oWebCombo)
{
	var value = "";

	if (oWebCombo.getSelectedIndex() >= 0)
	{
		var oRow = oWebCombo.getGrid().getActiveRow();
		if (oRow && oWebCombo.DataValueField) 
			value = "" + oRow.getCellFromKey(oWebCombo.DataValueField).getValue();
	}
	else if (oWebCombo.Editable == true && oWebCombo.FreeTextAllowed == true)
		value = "" + oWebCombo.getDisplayValue();

	return value;
}

/*

function ValidatorGetValue(id) {
    var control;
    control = document.getElementById(id);
    if (typeof(control.value) == "string") {
        return control.value;
    }
    return ValidatorGetValueRecursive(control);
}

*/

function Netsoft_ValidatorGetValue(id) {
    var control;
    control = document.getElementById(id);
    
    if (typeof(control.value) == "string") 
    {
		if (typeof(igcmbo_getComboById) == "function") // Netsoft
		{
			var oWebCombo1 = igcmbo_getComboById(id);
			if (typeof(oWebCombo1) == "object"){return ValidatorGetComboValue(oWebCombo1)};
		}
		return control.value;
    }
    return ValidatorGetValueRecursive(control);
}


/*
function Page_ClientValidate(validationGroup) {
    Page_InvalidControlToBeFocused = null;
    if (typeof(Page_Validators) == "undefined") {
        return true;
    }
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(Page_Validators[i], validationGroup, null);
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit(validationGroup);
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
}
*/


function Netsoft_Page_ClientValidate(validationGroup, override) {
    Page_InvalidControlToBeFocused = null;
    if (typeof(Page_Validators) == "undefined") {
        return true;
    }
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(Page_Validators[i], validationGroup, null, override);
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit(validationGroup);
    Page_BlockSubmit = !Page_IsValid;
    Page_GroupToValidate = Page_DefaultGroup  // Netsoft
    
    SimulatePageScroll();
    
    return Page_IsValid;
}



/*
function ValidatorCommonOnSubmit() {
    Page_InvalidControlToBeFocused = null;
    var result = !Page_BlockSubmit;
    if ((typeof(window.event) != "undefined") && (window.event != null)) {
        window.event.returnValue = result;
    }
    Page_BlockSubmit = false;
    return result;
}
*/


function Netsoft_ValidatorCommonOnSubmit() {
    Page_InvalidControlToBeFocused = null;
    var result = !Page_BlockSubmit;
    if ((typeof(window.event) != "undefined") && (window.event != null)) {
        window.event.returnValue = result;
    }
    Page_BlockSubmit = false; 
    Page_IsSubmitted = true; // Netsoft
    return result;
}




function Netsoft_ValidatorValidateIndividual(id)
{
	if (typeof(Page_Validators) == "undefined") return;
	
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        if (Page_Validators[i].controltovalidate == id)
	    {
	        ValidatorValidate(Page_Validators[i], null, null, null, true);
	    }
    }
    ValidatorUpdateIsValid();    
}



/*
Modified by NetsoftUSA

function ValidatorValidate(val, validationGroup, event) {
    val.isvalid = true;
    if ((typeof(val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, validationGroup)) {
        if (typeof(val.evaluationfunction) == "function") {
            val.isvalid = val.evaluationfunction(val);
            if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
                typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                ValidatorSetFocus(val, event);
            }
        }
    }
    ValidatorUpdateDisplay(val);
}
*/

function Netsoft_ValidatorValidate(val, validationGroup, event, override, forceNeed) {
    val.isvalid = true;
    /*return;*/
    if ((typeof(val.enabled) == "undefined" || val.enabled != false) && /*IsValidationGroupMatch(val, validationGroup) && */ (forceNeed || NeedsToBeValidated(val))) { // Netsoft
        if (typeof(val.evaluationfunction) == "function") {
            val.isvalid = (override == true) || val.evaluationfunction(val); // if override requested just assume everything is valid
            if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
                typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                ValidatorSetFocus(val, event);
            }
        }
    }
    ValidatorUpdateDisplay(val);
}



/* End */



/*
Added by NetsoftUSA
*/
function NeedsToBeValidated(val)
{
    var controlGroup = "";
    var control = val.controltovalidate;
    
	if (typeof(control) == "undefined" || control == "") return false;	
    
    var ctrl = document.getElementById(control)
    if (ctrl)
        controlGroup = ctrl.ControlGroup
        
    if (typeof(controlGroup) == "undefined") 
    {
        if (typeof(Page_Controls[control]) == "undefined" ) return true;
        controlGroup = Page_Controls[control][ControlGroupIndex];
    }
    
    return IsInGroup(controlGroup);
}


function IsInGroup(controlGroup)
{
    var subGroups = Page_ControlGroups[Page_GroupToValidate]; 

    if (typeof(subGroups) == "undefined")
    {
        return (controlGroup == Page_GroupToValidate);
    }

	// If the group name start with tilde (~) and we're not directly validating this group, just skip it
	if (controlGroup != null && controlGroup.charAt(0) == '~' && controlGroup != Page_GroupToValidate)
		return false;
    
    for (i = 0; i < subGroups.length; i++)
    {
        if (controlGroup == subGroups[i])
        {
				return true;
        }
    }
    
    return false;
}

/* End */


/*
function RequiredFieldValidatorEvaluateIsValid(val) {
    return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != ValidatorTrim(val.initialvalue))
}
*/

function Netsoft_RequiredFieldValidatorEvaluateIsValid(val) {

	var result;

	if (typeof(val.ConditionScript) != "undefined")
	{
		eval("result = " + val.ConditionScript + ";")
		if (result != true)
		{ 
			return true;
		}
	}
	
	var ctlvalue = "";
	if (val.ControlType == "WebMaskEdit")
	{
		// For mask edit, we don't want formatting literals when checking for required.
		if (typeof(igedit_getById) == "function")
		{
			var oWebMask1 = igedit_getById(val.controltovalidate);
			if (typeof(oWebMask1) == "object")
			{
				ctlvalue = oWebMask1.getValue();
				ctlvalue = RemoveCharactersForRequiredCheck(ctlvalue, val.ReqCheckRemv);
			}
		}
	}
	else
	{
		ctlvalue = ValidatorGetValue(val.controltovalidate);
	}
	
	return (ValidatorTrim(ctlvalue) != ValidatorTrim(val.initialvalue))
}


function ControlReHookupValidators(control, forceEnabled) 
{
    if (typeof(Page_Validators) == "undefined")
        return;
    var i, val;
    for (i = 0; i < Page_Validators.length; i++) 
    {
        val = Page_Validators[i];

        if (typeof(val.controltovalidate) == "string" && val.controltovalidate == control.id) 
        {
            ValidatorHookupControlID(val.controltovalidate, val);
            
            val.enabled = forceEnabled || (val.enabled != "False");

            if (typeof(val.controlhookup) == "string") 
            {
                ValidatorHookupControlID(val.controlhookup, val);
            }
        }
    }
}



function RemoveCharactersForRequiredCheck(s, ReqCheckRemv)
{
	if (ReqCheckRemv == null)
		return s;
	if (s == null)
		return "";
	else
	{
		var snew = "";
		for (i = 0; i < s.length; i++)
		{
			var c = s.substring(i,i+1);
			if (ReqCheckRemv.indexOf(c) < 0)
				snew += c;
		}
		return snew;
	}
}

/*

Modified by NetsoftUSA

function ValidationSummaryOnSubmit(validationGroup) {
    if (typeof(Page_ValidationSummaries) == "undefined")
        return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
            var i;
            if (summary.showsummary != "False") {
                summary.style.display = "";
                if (typeof(summary.displaymode) != "string") {
                    summary.displaymode = "BulletList";
                }
                switch (summary.displaymode) {
                    case "List":
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        end = "";
                        break;
                    case "BulletList":
                    default:
                        headerSep = "";
                        first = "<ul>";
                        pre = "<li>";
                        post = "</li>";
                        end = "</ul>";
                        break;
                    case "SingleParagraph":
                        headerSep = " ";
                        first = "";
                        pre = "";
                        post = " ";
                        end = "<br>";
                        break;
                }
                s = "";
                if (typeof(summary.headertext) == "string") {
                    s += summary.headertext + headerSep;
                }
                s += first;
                for (i=0; i<Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
                        s += pre + Page_Validators[i].errormessage + post;
                    }
                }
                s += end;
                summary.innerHTML = s;
                window.scrollTo(0,0);
            }
            if (summary.showmessagebox == "True") {
                s = "";
                if (typeof(summary.headertext) == "string") {
                    s += summary.headertext + "\r\n";
                }
                var lastValIndex = Page_Validators.length - 1;
                for (i=0; i<=lastValIndex; i++) {
                    if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
                        switch (summary.displaymode) {
                            case "List":
                                s += Page_Validators[i].errormessage;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "BulletList":
                            default:
                                s += "- " + Page_Validators[i].errormessage;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "SingleParagraph":
                                s += Page_Validators[i].errormessage + " ";
                                break;
                        }
                    }
                }
                alert(s);
            }
        }
    }
}

*/



function Netsoft_ValidationSummaryOnSubmit(validationGroup) {
    if (typeof(Page_ValidationSummaries) == "undefined")
        return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup) && IsInGroup(Page_Controls[summary.id][ControlGroupIndex]) ) {
            var i;
            if (summary.showsummary != "False") {
                summary.style.display = "";
                if (typeof(summary.displaymode) != "string") {
                    summary.displaymode = "BulletList";
                }
                switch (summary.displaymode) {
                    case "List":
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        end = "";
                        break;
                    case "BulletList":
                    default:
                        headerSep = "";
                        first = "<ul>";
                        pre = "<li>";
                        post = "</li>";
                        end = "</ul>";
                        break;
                    case "SingleParagraph":
                        headerSep = " ";
                        first = "";
                        pre = "";
                        post = " ";
                        end = "<br>";
                        break;
                }
                s = "";
                if (typeof(summary.headertext) == "string") {
                    s += summary.headertext + headerSep;
                }
                s += first;
                var messages = new Array();
                for (i=0; i<Page_Validators.length; i++) {
                    var er = GetErrorMessage(Page_Validators[i]);
                    if (!Page_Validators[i].isvalid && typeof(er) == "string") {
                        if (messages[er] == null) {
                        s += pre + er + post;
                        messages[er] = true;
                        }
                    }
                }
                s += end;
                summary.innerHTML = s;
                
                if (IsOutOfScreenY(summary.id))
                {
                    window.scrollTo(0, findPosY(summary.id) - 50);
                }
                else
                {
                    SimulatePageScroll();
                }
                
            }
            if (summary.showmessagebox == "True") {
                s = "";
                if (typeof(summary.headertext) == "string") {
                    s += summary.headertext + "\r\n";
                }
                var lastValIndex = Page_Validators.length - 1;
                for (i=0; i<=lastValIndex; i++) {
                var er = GetErrorMessage(Page_Validators[i]);
                    if (!Page_Validators[i].isvalid && typeof(er) == "string") {
                        switch (summary.displaymode) {
                            case "List":
                                s += er;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "BulletList":
                            default:
                                s += "- " + er;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "SingleParagraph":
                                s += er + " ";
                                break;
                        }
                    }
                }
                alert(s);
            }
        }
    }
}


function SimulatePageScroll()
{
    if (typeof(window.onscroll) == 'function')
    {
        window.onscroll();
    }
    else if (typeof(OnWindowScroll) == 'function')
    {
        OnWindowScroll();
    }
    else
    {
        window.scrollBy(0, 1);
        window.scrollBy(0, -1);
    }
}

/* End */


function Netsoft_ValidatorCompare(operand1, operand2, operator, val) {
    var dataType = val.type;
    val.errormessageIndex = 1;
    var op1, op2;
    if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
    {
        val.errormessageIndex = 0;
        return false;
    }
    if (operator == "DataTypeCheck")
        return true;
    if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
    {
        val.errormessageIndex = 0;
        return true;
    }
    
    switch (operator) {
        case "NotEqual":
            return (op1 != op2);
        case "GreaterThan":
            return (op1 > op2);
        case "GreaterThanEqual":
            return (op1 >= op2);
        case "LessThan":
            return (op1 < op2);
        case "LessThanEqual":
            return (op1 <= op2);
        default:
            return (op1 == op2);
    }
}




function HookupNetsoftFunctions()
{
    ValidatorUpdateDisplay = Netsoft_ValidatorUpdateDisplay;
    ValidatorGetValue = Netsoft_ValidatorGetValue;
    Page_ClientValidate = Netsoft_Page_ClientValidate;
    ValidatorCommonOnSubmit = Netsoft_ValidatorCommonOnSubmit;
    ValidatorValidateIndividual = Netsoft_ValidatorValidateIndividual;
    ValidatorValidate = Netsoft_ValidatorValidate;
    RequiredFieldValidatorEvaluateIsValid = Netsoft_RequiredFieldValidatorEvaluateIsValid;
    ValidationSummaryOnSubmit = Netsoft_ValidationSummaryOnSubmit;
    ValidatorCompare = Netsoft_ValidatorCompare;
}


function Page_ResetValidators(validationGroup)
{
    Page_ClientValidate(validationGroup, true);
}

function GetErrorMessage(val)
{
    if (val.errormessageIndex >= 0 && val.errormessage.indexOf('|') >= 0 && val.errormessage.split('|').length >= val.errormessageIndex)
    {
        return val.errormessage.split('|')[val.errormessageIndex];
    }
    
    return val.errormessage;    
}