﻿// JScript File
// Relies on some .NET validation js functions.


function FunctionGuts(fn)   {
    //fn is the function for which to extract the guts
     if (typeof(fn) == "function") {
        fn = fn.toString();
    }
     var beginpos,endpos;
    beginpos = fn.indexOf("{");
    endpos = fn.lastIndexOf("}");
     
    return (endpos < 0) ? fn : fn.substring(beginpos + 1, endpos);
}

function FunctionParameterList(fn) {
    if (typeof(fn) == "function") {
        fn = fn.toString();
    }
    return fn.substring(fn.indexOf("(") + 1, fn.indexOf(")",fn.indexOf("(") + 1 ));
}


//function ReplaceFormSubmitHandler(URL, modal, width, height, validationGroup) {
//    var theForm = document.forms[0]; 
//    theForm.onsubmit = null;
//    ValidatorHookupEvent(theForm, "onsubmit", "return ReplacementSubmitFunc('" + URL + "',"  + modal + "," + width + "," + height + ",'" + validationGroup + "')");
//}

//////////////////////////////////////////////////////////////////////////////////////////////////
//Call this next function if the popup summary is loaded, so it hooks in
//////////////////////////////////////////////////////////////////////////////////////////////////
var summaryHandlerReplaced = false;
function ReplaceSummaryHandler() {
    if (summaryHandlerReplaced) {
        return;
    }
   
    if (typeof(ValidationSummaryOnSubmit) == "function") {
          summaryHandlerReplaced=true;
        var oldFuncCode = FunctionGuts(ValidationSummaryOnSubmit);
        ValidationSummaryOnSubmit=null;
        ValidationSummaryOnSubmit = new Function("validationGroup",  "PopupSummaryOnSubmit(validationGroup); " + oldFuncCode);
    }
}
 
//////////////////////////////////////////////////////////////////////////////////////////////////
// add the popup summary to the page validator list so it gets processed at the right time
/////////////////////////////////////////////////////////////////////////////////////////////////
var Popup_ValidationSummaries;

function addPopupSummaryToValidationSummaries(control) {

    if (typeof(control) == "string") {
        control = document.getElementById(control);
    }
 
    if (typeof(Popup_ValidationSummaries) == "undefined") {
        Popup_ValidationSummaries = new Array(control);
    } else {
        Popup_ValidationSummaries(Popup_ValidationSummaries.length) = control;
         
    }
     
}

/*  
function ReplacementSubmitFunc(URL, modal, width, height, validationGroup)    {
    var x = WebForm_OnSubmit();   
    ErrorMasterValidationSummaryOnSubmit(URL, modal, width, height, validationGroup);   
    return x;
}
*/
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////

function PopupSummaryOnSubmit(validationGroup) {
    if (typeof(Popup_ValidationSummaries) == "undefined")
        return;
        
        
    var summary, sums, s;
    for (sums = 0; sums < Popup_ValidationSummaries.length; sums++) {
        summary = Popup_ValidationSummaries[sums];
        summary.style.display = "none";
        
        if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
             
             
            processErrorMasterValidationSummaryOnSubmit(summary);
            
            
        }   //if 
     } //for       
        
}//function


//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////

function HookEvalFunctions() {

    if (typeof(Page_Validators) != "undefined" && Page_Validators) {
        for (var i = 0; i < Page_Validators.length; i++) {  
        
            ReplaceEvaluationFunction(Page_Validators[i],  "ParseValidatorMessageText(val);", "");
        }
    }
}


//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////

function ReplaceEvaluationFunction(val, newFuncPrefix, newFunctionSuffix, replace) {

    if (replace == null) {
        replace = false
    }
    
    //at this point, newFunc is a string
    
    var oldFuncCode, oldFuncParams;
    
     
    
    if (!replace) {
        oldFuncCode = FunctionGuts(val.evaluationfunction);
        oldFuncParams = FunctionParameterList(val.evaluationfunction);
    } else {
        oldFuncCode = '';
        oldFuncParams = '';
    }
    
    
    
    var func;
    //if (navigator.appName.toLowerCase().indexOf('explorer') > -1) {
        func = new Function(oldFuncParams, newFuncPrefix + " " + oldFuncCode + " " + newFunctionSuffix);
   // }
   // else {
   //     if (oldFuncParams.length > 0) {
   //          oldFuncParams = "," + oldFuncParams;
   //     }       
    //    func = new Function("event" + oldFuncParams, newFuncPrefix + " " + oldFuncCode + " " + newFunctionSuffix);
   // }
    
    val.evaluationfunction = func;

}
 
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////

function ParseValidatorMessageText(val) {
     
    var tmp; 
    if ((val) && (typeof(val.contextsource) != "undefined")) {
        if ((val.contextsource != null) && (val.contextsource.length > 0)) {
        
            var contextvalues = BuildContextValues(val); //gets the values of all of the context sources
        
        
            if ((contextvalues != null) && (contextvalues.length > 0)) {
                var contextValueArray = contextvalues.split(",");
     
                //now get the values for the context sources
                 val.errormessage = val.originalerrormessage
                for (var j = 0; j < contextValueArray.length; j++) {
                    val.errormessage = val.errormessage.replace( '\{' + j.toString() + '\}' ,contextValueArray[j]);
                    
                } //end for
                if ((val.dynamicreplace != null) && (val.dynamicreplace)) {
                    val.innerHTML=val.errormessage;
                }
            } //end if
        }   //end if
    }
} //end function
  
  

//////////////////////////////////////////////////////////////////////////////////////////////////
// Summary related script
//////////////////////////////////////////////////////////////////////////////////////////////////

function processErrorMasterValidationSummaryOnSubmit(summary) {

    var url = summary.url;
    var modalflag = summary.modalflag;
    var width = summary.width;
    var height = summary.height;
    var validationGroup = summary.validationGroup;
    var showsummary = summary.showsummary;
    var headertext = summary.headertext;
 
    var QS;
    var codes;
    var msgs;
    
    
    
    if (validationGroup =='') {
        validationGroup = null;
    }
     
    //for every validator on the page
    //NOTE: These must have already been evaluated by the standard MS code!
    for (var i = 0; i < Page_Validators.length; i++) {
        var val = Page_Validators[i];
        //is this flagged as invalid?
         
        if ((!val.isvalid) && IsValidationGroupMatch(val,validationGroup)) {
            //build it's info into the querystring
            
            if (val.ErrorNumber != null) {
                if ((codes != null) && (codes.length > 0))   {
                    codes+= ";";
                } else {
                    codes='';
                }
                codes += BuildErrorParameterForValidatorCode(val);
            } else {
                if (typeof(Page_Validators[i].errormessage) == "string") {
                    //no error number, so just get the static message for the validator if it's there
                    if ((msgs != null) && (msgs.length > 0))   {
                        msgs=msgs + ";";
                    } else {
                        msgs='';
                    }
                    msgs += encodeURIComponent(Page_Validators[i].errormessage);
                }
            }
            
            
            
        }
        
    }
    QS = addErrorInfoToQueryString(msgs,codes);
    // well, did we wind up with anything in the querystring (we should have!)
     
  
    
    if ((typeof(QS) !="undefined") && (QS !=null) && (QS.length > 0))   {
    //pop up the requested window, baby!  
    
    //build features
    
        var features;
        var args;
       
       //couple more things for the QS
       QS += "&show=" + showsummary;
       
        if (typeof(modalflag) == "string") {
            if (modalflag.toLowerCase() == "false")     {
                modalflag = false;
            } else {
                modalflag=true;
            }
        } else {
            modalflag=true;
        }

        if (modalflag) {
            features = "dialogHeight=" + height + "px";
            features += ";dialogWidth=" + width + "px";
            features +=";status=0";
            args = headertext;
             
            window.showModalDialog(url + QS, args, features);
        } else {
            //as of now, opera can't do modals
            features =  "height=" + height;
            features += ";width=" + width;
            features +=";status=0";
            
            window.open(url + QS + "&headertext=" + encodeURIComponent(headertext) , "Errors",features);
        }
    }
}  




////////////////////////////////////////////////////////////////////////////////////////////

function addErrorInfoToQueryString(msgs,codes) {

    var qs;
    qs="";

    if ((codes != null) && (codes.length > 0))   {
        qs = "?Errors=" + codes 
    } 



    if ((msgs != null) && (msgs.length > 0))   {
        if (qs.length > 0) {
            qs += "&";
        } else {
            qs = "?"
        }
        qs += "EMsg=" + msgs;
    }

    return qs;

}

////////////////////////////////////////////////////////////////////////////////////////////

function BuildContextValues(val) {

    var tmp;
    var contextArray;

    if ((val.contextsource != null) && (val.contextsource.length > 0)) {
        contextArray = val.contextsource.split(",");
        tmp = "";
        //now get the values for the context sources
        for (var j = 0; j < contextArray.length; j++) {
        
            if (tmp.length > 0) {
                 tmp += ",";
            }
        
            if (document.getElementById(contextArray[j]) != null) {
                tmp +=  encodeURIComponent(ValidatorGetValue(contextArray[j]));
            } else {
                tmp +=   encodeURIComponent((contextArray[j]));
            }
           
        }
        return tmp;
    }


}



////////////////////////////////////////////////////////////////////////////////////////////
function BuildErrorParameterForValidatorCode(val) {
      
    //return one segment 

    var tmp;
   

    if (val.errornumber != null) {
        tmp = val.errornumber
    }
    
    var cv = BuildContextValues(val);
    if ((cv != null) && (cv.length > 0)) {
        tmp += ',' + cv
    }
    
    return tmp;
    
}
