﻿var __DefinitionDisplayLayoutControls = new Array();

function  InitializeDefinitionDisplayLayoutControls()
{
    for(var index=0;index<__DefinitionDisplayLayoutControls.length;index++)
    {
        __DefinitionDisplayLayoutControls[index].load();
     }   
}

function EvaluateRules()
{
    for(var index=0;index<__DefinitionDisplayLayoutControls.length;index++)
        __DefinitionDisplayLayoutControls[index].evaluateRules();
}

addEvent(window,'load',InitializeDefinitionDisplayLayoutControls);

function DefinitionDisplayLayoutControl(id, readonly,printMode)
{        
    this.id = id;
    this.currentPage = -1;
    this.fieldIds = new Array();
    this.ruleSets = new Array();
    this.fields = new Array();
    this.groups = new Array();
    this.readonly = typeof(readonly) != 'undefined' ? readonly : false;
    this.printMode = typeof(printMode) != 'undefined' ? printMode : false;
    this.showPageEventHandlers = new Array();
    this.formRuleLogger = new FormRuleLogger(this,false);
    
    __DefinitionDisplayLayoutControls.push(this);
}
DefinitionDisplayLayoutControl.prototype.addError = function(fieldName,errorMessage)
{
    var errorUl = document.getElementById("ac-errorul");
    if(!errorUl)
    {
        var myDiv = document.getElementById(this.id);
        this.errorDiv = myDiv.parentNode.insertBefore(document.createElement("div"),myDiv);
        this.errorDiv.className = "AC-ErrorMessage";
        this.errorDiv.innerHTML = "<h5>The following errors have occurred:</h5><div class=\"AC-ErrorsList\"><ul id='ac-errorul'></ul>";
    }
    var errorUl = document.getElementById("ac-errorul");
    var errorLI = errorUl.appendChild(document.createElement("LI"));
    errorLI.innerHTML = "<A href=\"#\" onclick=\"DefinitionDisplayLayoutControl_"+this.id.replace(/\-/g,"_")+".scrollIntoView('"+fieldName+"');return false;\">"+errorMessage+"</A>";
    
}
DefinitionDisplayLayoutControl.prototype.scrollIntoView = function(fieldName)
{
    var definitionField = this.getField(fieldName);
    if(definitionField)
    {
        this.showPage(definitionField.pageIndex);
        definitionField.scrollIntoView();
    }
}
DefinitionDisplayLayoutControl.prototype.focus = function(fieldName)
{
    var definitionField = this.getField(fieldName);
    if(definitionField)
    {
        this.showPage(definitionField.pageIndex);
        definitionField.focus();
    }
}

DefinitionDisplayLayoutControl.prototype.showPage = function(page)
{
    var currentPageHiddenField = document.getElementById(this.id  + "_CurrentPageField");
    
    if(!this.printMode)
    {
        if(this.currentPage == -1)
            this.currentPage = parseInt(currentPageHiddenField.value);
        
        if(typeof page == 'undefined')
            page = this.currentPage;
             
        var index = 0;
        var button = document.getElementById(this.id  + "_NumberedButton" + index);
        
        // make sure all the buttons and pages are set - changed so that the buttons don't disable, keeps the style more consistant
        while(button != null)
        {
            //button.disabled=false;
            button.className="pagebutton";
            document.getElementById(this.id  + "_Page_" + (index + 1)).style.display="none";
            
            index++;
            button = document.getElementById(this.id  + "_NumberedButton" + index);
        }
        
        // now activate the selected page and deactivate the selected button
        var button = document.getElementById(this.id  + "_NumberedButton" + (page-1));
        
        if(button != null)
            button.className="pagebutton selected";
        
        var pageElement = document.getElementById(this.id  + "_Page_" + page);
        
        if(pageElement != null)
            pageElement.style.display="block";
            
        document.getElementById(this.id  + "_CurrentPageField").value=page;
        
        this.currentPage = page;
    }
    else
    {
             
        var index = 0;
        var button = document.getElementById(this.id  + "_NumberedButton" + index);
        
        // make sure all the buttons and pages are set - changed so that the buttons don't disable, keeps the style more consistant
        while(button != null)
        {
            //button.disabled=false;
            button.style.display = "none";
            document.getElementById(this.id  + "_Page_" + (index + 1)).style.display="block";
            
            index++;
            button = document.getElementById(this.id  + "_NumberedButton" + index);
        }
        
            
    }
    
    for(var count = 0 ; count < this.showPageEventHandlers.length; count++)
        this.showPageEventHandlers[count].onPageChanged(this);
}

DefinitionDisplayLayoutControl.prototype.nextPage = function()
{
    if(this.currentPage == -1)
        this.currentPage = parseInt(document.getElementById(this.id  + "_CurrentPageField").value);
        
    var nextPage = document.getElementById(this.id  + "_Page_" +  (this.currentPage + 1) );
    
    if(nextPage != null)
        this.showPage( this.currentPage + 1);
        
    nextPage = document.getElementById(this.id  + "_Page_" +  (this.currentPage + 1) );
    
    return nextPage != null;
}

DefinitionDisplayLayoutControl.prototype.previousPage = function()
{
    if(this.currentPage == -1)
        this.currentPage = parseInt(document.getElementById(this.id  + "_CurrentPageField").value);
        
    var previousPage = document.getElementById(this.id  + "_Page_" +  (this.currentPage - 1) );
    
    if(previousPage != null)
        this.showPage( this.currentPage - 1);

    previousPage = document.getElementById(this.id  + "_Page_" +  (this.currentPage - 1) );

    return previousPage != null;
}

DefinitionDisplayLayoutControl.prototype.isLastPage = function()
{
    if(this.currentPage == -1)
        this.currentPage = parseInt(document.getElementById(this.id  + "_CurrentPageField").value);
                
    var nextPage = document.getElementById(this.id  + "_Page_" +  (this.currentPage + 1) );
    
    return nextPage == null;
}

DefinitionDisplayLayoutControl.prototype.isFirstPage = function()
{
    if(this.currentPage == -1)
        this.currentPage = parseInt(document.getElementById(this.id  + "_CurrentPageField").value);
        
    var previousPage = document.getElementById(this.id  + "_Page_" +  (this.currentPage - 1) );

    return previousPage == null;

}

DefinitionDisplayLayoutControl.prototype.load = function()
{
    var myDiv = document.getElementById(this.id);
    if(myDiv)
    {
        this.initializeFields();
        
         // Need to evaluate form rules in readonly mode so that print mode will show the form as it would for the user
         // otherwise rules that hide fields will not fire and the printed form will show them. vjm
//        if(!this.readonly)
//        {
            this.initializeRules();
            this.wireDefinitionRules();
            this.evaluateRules();
//        }
        this.showPage();
    }
}
DefinitionDisplayLayoutControl.prototype.initializeRules= function()
{
    var myDiv = document.getElementById(this.id);
    var ruleXml = myDiv.getAttribute("fieldRules");
    if(ruleXml)
    {
        ruleXml = unescape(ruleXml);
        var xmlDoc = GetXmlParser();
        LoadXml(xmlDoc,ruleXml);
        var ruleSetNodes = xmlDoc.getElementsByTagName("DefinitionRuleSet");
        for(var index=0;index<ruleSetNodes.length;index++)
        {
            var ruleSet = new RuleSet();
            ruleSet.buildFromXmlNode(ruleSetNodes[index],true);
            this.ruleSets.push(ruleSet);
        }
    }
}
DefinitionDisplayLayoutControl.prototype.initializeFields= function(divId)
{
    for(var index=0;index<this.fieldIds.length;index++)
        this.fields.push(new DefinitionFieldControl(this.fieldIds[index],this));
}
DefinitionDisplayLayoutControl.prototype.addField = function(divId)
{
    this.fieldIds.push(divId);
}

DefinitionDisplayLayoutControl.prototype.wireDefinitionRules = function()
{
    for(var index=0;index<this.ruleSets.length;index++)
        this.ruleSets[index].wireEventHandlers(this);
}
DefinitionDisplayLayoutControl.prototype.evaluateRules = function()
{
    for(var index=0;index<this.ruleSets.length;index++)
    {
        this.formRuleLogger.log('Evaluating rule set ' + index);
        this.ruleSets[index].evaluate(this);
    }
    
    this.formRuleLogger.show();
}

DefinitionDisplayLayoutControl.prototype.getField = function(fieldName)
{
    var result = null;
    
    fieldName=((fieldName.indexOf(".")> 0)?fieldName.split(".")[0]:fieldName);
    for(var index=0;index<this.fields.length;index++)
        if(this.fields[index].fieldName == fieldName)
        {
            result = this.fields[index];
            break;
        }
    
                
    return result;    
}

// this method is used to provide an alternate way for the definition display layout control to get field values when the 
// controls are not displayed, like when in print mode
DefinitionDisplayLayoutControl.prototype.addFieldValue = function(fieldName,value)
{
    if(!this.fieldValues)
        this.fieldValues = new Object();
    
    this.fieldValues[fieldName] = value;    
}


/*
fields.
*/
function DefinitionFieldControl(divId, definitionDisplayLayoutControl)
{
    this.divId = divId;
    this.definitionDisplayLayoutControl = definitionDisplayLayoutControl;
    var domField = document.getElementById(divId);
    
    if(domField)
    {
        this.fieldName = domField.getAttribute("fieldName");
        this.fieldType = domField.getAttribute("fieldType");
        this.pageIndex = domField.getAttribute("pageIndex");
        this.name = domField.getAttribute("name");
    }
}
DefinitionFieldControl.prototype.scrollIntoView = function()
{
    var div = document.getElementById(this.divId);
    div.scrollIntoView();
}
DefinitionFieldControl.prototype.focus = function()
{
    var div = document.getElementById(this.divId);
    if (div)
    {
        div.scrollIntoView();
        var valueControl = this.findValueControl(div);
        if (valueControl)
            valueControl.focus();
    }
}

DefinitionFieldControl.prototype.getFieldValue = function(subFieldName)
{
    var myDiv = document.getElementById(this.divId);
    var result = null;
    
    if(this.fieldType == 'PostalAddress')
    {   
        var postalAddressControl =new PostalAddressControl(myDiv.id);
        result = postalAddressControl.getComponent(subFieldName);
    }
    else if(this.fieldType == 'RadioButtonList')
    {
        var radioButtons = new Array();
      
        this.findMatchingControls(myDiv,this.radioButtonMatchFunction,radioButtons);
        for (var index=0;index<radioButtons.length;index++)
        {
            if (radioButtons[index].checked) 
            {
                result = radioButtons[index].value;
                break;
            }
        }
    }
    else if(this.fieldType == 'CheckBoxList')
    {
        var checkboxes = new Array();
        this.findMatchingControls(myDiv,this.checkBoxMatchFunction,checkboxes);
        var returnValues = new Array();
        for(var index=0;index<checkboxes.length;index++)
            if (checkboxes[index].checked)
            returnValues.push(checkboxes[index].parentNode.attributes['valueID'].value);
        
        result = returnValues;
    }
    else if(this.fieldType == 'HierarchicalList')
    {
        var dropDowns = new Array();
        this.findMatchingControls(myDiv,this.dropdownMatchFunction,dropDowns);
        var returnValues = new Array();
        for(var index=0;index<dropDowns.length;index++)
            if(dropDowns[index].selectedIndex >= 0 && dropDowns[index].options[dropDowns[index].selectedIndex].text)
            returnValues.push(dropDowns[index].options[dropDowns[index].selectedIndex].text)
        
        result = returnValues;
    }
    else 
    {
        var valueControl = this.findValueControl(myDiv);
        if(valueControl)
        {
            if(valueControl.tagName=="INPUT" &&  valueControl.type == 'text')
                result = valueControl.value;
            else if(valueControl.tagName=="INPUT" &&  valueControl.type == 'checkbox')
                result = valueControl.checked.toString().toLowerCase();
            else if(valueControl.tagName == 'SELECT')
            {
                var returnValues = new Array();
                if(valueControl.multiple)
                {
                    for(var index=0;index<valueControl.options.length;index++)
                    {
                        if(valueControl.options[index].selected)
                            returnValues.push(valueControl.options[index].value);
                    }
                    result = returnValues;
                }
                else                    
                    result = valueControl.options[valueControl.selectedIndex].value;
            }
        }
    }
    
    if(result == null && this.definitionDisplayLayoutControl.fieldValues) 
        result = this.definitionDisplayLayoutControl.fieldValues[this.fieldName];
    
    return result;
}
DefinitionFieldControl.prototype.setFieldValue = function(subFieldName,value)
{
    if(!value)return;
    var myDiv = document.getElementById(this.divId);
    if(this.fieldType == 'PostalAddress')
    {   
        var postalAddressControl =new PostalAddressControl(myDiv.id);
        return postalAddressControl.setComponent(subFieldName,value);
    }
    else if(this.fieldType == 'RadioButtonList')
    {
        var radioButtonLabels = new Array();
        this.findMatchingControls(myDiv,this.labelMatchFunction,radioButtonLabels);
        if(radioButtonLabels.length ==1 ) 
            return radioButtonLabels[0].checked=value;
    }
    else if(this.fieldType == 'CheckBoxList')
    {
        var checkBoxLabels = new Array();
        this.findMatchingControls(myDiv,this.labelMatchFunction,checkBoxLabels);
        var returnValues = new Array();
        for(var index=0;index<checkBoxLabels.length;index++)
            checkBoxLabels[index].checked=value;
    }
    else if(this.fieldType == 'HierarchicalList')
    {
        alert('Not Supported');
    }
    else 
    {
        var valueControl = this.findValueControl(myDiv);
        if(valueControl)
        {
            if(valueControl.tagName=="INPUT" &&  valueControl.type == 'text')
                valueControl.value=value;
            else if(valueControl.tagName=="INPUT" &&  valueControl.type == 'checkbox')
                return valueControl.checked=value;
            else if(valueControl.tagName == 'SELECT')
            {
                var returnValues = new Array();
                for(var index=0;index<valueControl.options.length;index++)
                {
                    if(valueControl.options[index].text==value)
                        valueControl.options[index].selected=true;
                }
            }
        }
    }
}


DefinitionFieldControl.prototype.radioButtonMatchFunction = function(evalControl)
{
    return (evalControl && evalControl.tagName=="INPUT" &&  evalControl.type == "radio" );
}
DefinitionFieldControl.prototype.checkBoxMatchFunction = function(evalControl)
{
    return (evalControl && evalControl.tagName=="INPUT" &&  evalControl.type == "checkbox" );
}
DefinitionFieldControl.prototype.dropdownMatchFunction = function(evalControl)
{
    var i=0;
    
    i=i;
    
    return (evalControl 
    && evalControl.tagName=="SELECT" 
    );
}
DefinitionFieldControl.prototype.labelMatchFunction = function(evalControl)
{
    if(evalControl && evalControl.tagName=="LABEL")
    {
        var inputs=evalControl.parentNode.getElementsByTagName("input");
        if(inputs.length==1)
            return (inputs[0].checked);
    }
    return false;
}
DefinitionFieldControl.prototype.wireEventHandler = function(subField)
{
    var myDiv = document.getElementById(this.divId);
    if(this.fieldType == 'PostalAddress')
    {
        var postalAddressControl =new PostalAddressControl(myDiv.firstChild.id);
        addEvent(postalAddressControl.findComponentField(subField),'change',EvaluateRules);
    }
    else if(this.fieldType == 'RadioButtonList')
    {
        var radioButtons = new Array();
        this.findMatchingControls(myDiv,this.radioButtonMatchFunction,radioButtons);
        for(var index=0;index<radioButtons.length;index++)
            addEvent(radioButtons[index],'click',EvaluateRules);
    }
    else if(this.fieldType == 'HierarchicalList')
    {
        var dropdowns = new Array();
        this.findMatchingControls(myDiv,this.dropdownMatchFunction,dropdowns);
        for(var index=0;index<dropdowns.length;index++)
            addEvent(dropdowns[index],'change',EvaluateRules);
    }
    else if(this.fieldType == 'CheckBoxList')
    {
        var checkBoxes = new Array();
        this.findMatchingControls(myDiv,this.checkBoxMatchFunction,checkBoxes);
        for(var index=0;index<checkBoxes.length;index++)
            addEvent(checkBoxes[index],'click',EvaluateRules);
    }
    else
    {
        var valueControl = this.findValueControl(myDiv);
        if(valueControl)
            addEvent(valueControl,'change',EvaluateRules);
    }
}
DefinitionFieldControl.prototype.findValueControl= function(control)
{
    var results = new Array();
    this.findMatchingControls(control, 
                                new Function('evalControl', 'return (evalControl && evalControl.getAttribute && evalControl.getAttribute("propertyBoundControl") )'),
                                results);
    if(results.length == 1)
    {
        var result = results[0];
        if(result.tagName == "SPAN")
        {
            var inputs  = result.getElementsByTagName("INPUT");
            if(inputs.length>0)
                return inputs[0];
        }
        else
            return result;
    }
    else
        return null;
}
DefinitionFieldControl.prototype.findMatchingControls = function(control, matchFunction, results)
{
    if(matchFunction(control)) results.push(control);
    for (var index=0;index<control.childNodes.length;index++)
        this.findMatchingControls(control.childNodes[index], matchFunction, results);
}

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();