﻿// JScript File

var ErrorPageURL = "FM_Error.aspx";

function ProcessAjaxResults(resultSet, updatingControl) {
    if (!resultSet) {return;} 
    if (!resultSet.Results) resultSet.ErrorCode=2; 
    switch (resultSet.ErrorCode) {
        case 1: document.location.reload();return; // Not logged in errorcode, reload will go to the 'must login' screen
        case 2: Sys.Debug.trace(resultSet.ErrorMessage);document.location = ErrorPageURL; return; // if an exception, redirect to the error page.
    }
    // If none of the above, process the results
    if (updatingControl) {
        for (var i=0; i< updatingControl.length;i++) {
            if (updatingControl[i]) Sys.UI.DomElement.removeCssClass(updatingControl[i],"Visible");   
        }     
    }
    if (resultSet.Results.length == 0) return;    
    for (var ri = 0; ri < resultSet.Results.length; ri++) {
        var numScriptsToLoad=0;
        var numScriptsLoaded=0;
        var done=false;    
        var scriptText = "";
        var loadComplete = function() {
            if (this.tagName == "SCRIPT") numScriptsLoaded++;
            if (done && numScriptsToLoad == numScriptsLoaded)
            eval(scriptText);   
        } 
        var result = resultSet.Results[ri];
        if (result.ClientID && result.ClientID != '') {
            var el = $get(result.ClientID);
            if (el) {        
                Sys.UI.DomElement.removeCssClass(el,'ItemRowUpdating');
                var reg = new RegExp("(<script[^\>]*>)((?:.|\\r\\n)*?)(</script>)","gi");               
                el.innerHTML = "";
                ClearOldValidators();
                var insertScriptReg = new RegExp("<script src=\"([^\"]*)\"[^\>]*>(?:.|\\r\\n)*?</script>","gi");
                el.innerHTML = result.innerHTML.replace(insertScriptReg,'').replace(reg,'$1$3').replace(insertScriptReg,'').replace(/<input type='hidden' id='dummy'>/,''); //
                reg.lastIndex=0;
                var myArray;
                while ((myArray = reg.exec(result.innerHTML)) != null)
                {
                  scriptText += myArray[2] + '\n';
                }                
                var existingScripts = document.getElementsByTagName("SCRIPT");
                var base = document.location.protocol + "//" + document.location.host;
                var basewithpath = base + document.location.pathname;
                basewithpath = basewithpath.substring(0,basewithpath.lastIndexOf("/")+1)
                while ((myArray = insertScriptReg.exec(result.innerHTML)) != null)
                {
                    var found=false;
                    var url=myArray[1];
                    url = full_url(url,base,basewithpath);
                    for (var sidx=0;sidx < existingScripts.length;sidx++) {
                        var ex_url = full_url(existingScripts[sidx].src,base,basewithpath);
                        if (ex_url==url) {
                            found=true;
                            break;
                        }
                    }
                    if (!found) {
                       numScriptsToLoad++;
                       var node = document.createElement("script");
                       node.src = url;
                       node.type="text/javascript";
                       if (node.addEventListener)
                            node.addEventListener("load", loadComplete, false);
                        else
                            node.onreadystatechange = function() {
                                if (this.readyState == "complete") loadComplete.call(this);
                            }
                       document.getElementsByTagName("head")[0].appendChild(node); 
                    }
                }
                SetupAllLinks(el);
                setupTextBorders(el);
            }
        }
        if (result.scriptText && result.scriptText != '') {
            scriptText += result.scriptText.trim() + '\n';
        }
        scriptText = scriptText.replace(/<!--/g,'');
        scriptText = scriptText.replace(/-->/g,'');    
        done=true;
        loadComplete();
    }    
}

function full_url(url,base,basewithpath) {
    if (url.substring(0,4)!="http")
        if (url.substring(0,1)!="/")         
            url = basewithpath + url; 
        else if (url.substring(0,2)=="//")
            url = document.location.protocol + url;
        else
            url = base + url;
    url = url.replace("&amp;","&");
    return url;
}

function Updating(UpdateElement) {
    if (!UpdateElement) return null;
    if (UpdateElement.components) {
        for (var i = 0; i < UpdateElement.components.length; i++) {
            if (UpdateElement.components[i].dispose) {
                try {
                    UpdateElement.components[i].dispose();
                } catch (ex) {
                }
            }
            UpdateElement.components[i] = null;
        }        
    }
    UpdateElement.components = null;
    var UpdatingEl = UpdateElement;
    while (UpdatingEl.parentNode && (!UpdatingEl.parentNode.tagName || UpdatingEl.parentNode.tagName != 'DIV')) {
        UpdatingEl = UpdatingEl.parentNode;
    }
    UpdatingEl = UpdatingEl.nextSibling;
    while (UpdatingEl && (!UpdatingEl.tagName || UpdatingEl.tagName != 'DIV')) {
        UpdatingEl = UpdatingEl.nextSibling;
    }
    if (!UpdatingEl) UpdatingEl = UpdateElement.previousSibling;
    while (UpdatingEl && (!UpdatingEl.tagName || UpdatingEl.tagName != 'DIV')) {
        UpdatingEl = UpdatingEl.previousSibling;
    }
    if (!UpdatingEl) return null;
    var UpdateBounds = Sys.UI.DomElement.getBounds(UpdateElement);
    if (UpdateBounds.width > 2) UpdatingEl.style.width = (UpdateBounds.width -2)+ 'px';
    if (UpdateBounds.height > 2) UpdatingEl.style.height = (UpdateBounds.height -2)+ 'px';
    for (i=0;i<UpdatingEl.childNodes.length;i++) {
        if (UpdatingEl.childNodes[i].tagName == 'DIV') {
            if (UpdateBounds.width > 2) UpdatingEl.childNodes[i].style.width = (UpdateBounds.width -2)+ 'px';
            if (UpdateBounds.height > 2) UpdatingEl.childNodes[i].style.height = (UpdateBounds.height -2)+ 'px';
        }
    }
    Sys.UI.DomElement.addCssClass(UpdatingEl,"Visible");
    return UpdatingEl;
}

var ActionPanel = null;

function ShowActionPanel(count,countlimit,doUpdating) {

    if (typeof doUpdating=='undefined') doUpdating=true;

    if (!mpe_ActionPanel) {
        if (!count) count=0;
        if (!countlimit) countlimit = 5;
        if (count > countlimit && countlimit > 0) return;
        setTimeout('ShowActionPanel(' + count+1 + ',' + countlimit + ', ' + doUpdating + ')',200);
        return;
    }      
       
    //ActionPanel = $get(ActionPanelClientID);   
    var Updated = new Object;    
    Updated.ActionPanel = pnlAction;
    
    var PopupEl = $get(mpe_ActionPanel.get_PopupControlID());    // Get the popup element    
    if (PopupEl.style.display != 'none') {
        if (doUpdating) Updated.UpdatingElement = Updating(pnlAction);    
        return Updated;
    }
    
    var pageBound = pageDims(); // get the page dimensions
    
    // set the popup width to be a max of either the page widt or 750px
    var width = pageBound.x - 50;
    if (width > 750) width = 750;
    PopupEl.style.width=width + 'px'; // set the popup width    
    
    PopupEl.style.height=(pageBound.y - 50)+ 'px';    
    mpe_ActionPanel.show();
    
    if (doUpdating) Updated.UpdatingElement = Updating(pnlAction);    
    return Updated;
}

function CloseActionPanel() {
    if (mpe_ActionPanel) {
        changeAllDropDownsVisibility(document,true);
        mpe_ActionPanel.hide();
        if (typeof pnlAction != 'undefined') {
            Updating(pnlAction);
            pnlAction.innerHTML = '';
        }
        ClearOldValidators();
    }
}

function HighlightElement(ID, objID, objType) {
    var wrapper = $get(ID);    
    var orig_border = wrapper.style.border;
    wrapper.style.border = "solid red 2px";    
    var bounds = Sys.UI.DomElement.getBounds(wrapper);
    if (typeof document.documentElement.scrollTop != 'undefined')
        document.documentElement.scrollTop = bounds.y - 150;
    else
        document.location = document.location.href + '#' + ID;
    setTimeout("UnHighlightElement('" + ID + "','" + orig_border + "');", 1000);
}

function UnHighlightElement(ID, original_border) {
    var el = $get(ID);
    el.style.border=original_border;    
}


/*********************
Force Page Validation
*********************/

function ClearOldValidators() {
    if (typeof Page_Validators == 'undefined') return;
    if (!Page_Validators || !Page_Validators.length) return;
    var idx=0;
    while (idx < Page_Validators.length) {
        if (!$get(Page_Validators[idx].id)) 
            Array.removeAt(Page_Validators,idx);
        else
            idx ++;
    }
}

function UpdateEnabledValidators() {
    for (var idx=0;idx<Page_Validators.length;idx++) {
        Page_Validators[idx].enabled = IsElementVisible($get(Page_Validators[idx].controltovalidate));
    }
}

function FM_Page_Valid(Validate) {
    if (Validate) {        
        ClearOldValidators();
        UpdateEnabledValidators();
        Page_ClientValidate();
        return AllValidatorsValid(Page_Validators);        
    } 
    return true;
}

/****************************************************
 DataObject Definition
 ****************************************************/

DataObject = function(Container) {    
    var __hiddenMembers = new Object();
    this.setVal = function(element, values) {
        var id = this.elementFieldName(element);        
        var base = this;
        if (!IsElementVisible(element)) {
            base = __hiddenMembers;
        }
        if (typeof values == "object") {
            for (k in values) {
                base[id + k] = values[k];
            }
        } else {        
            base[id] = values;
        }
    }
    
    this.clearVal = function(element, appendList) {
        var id = this.elementFieldName(element);        
        var base = this;
        if (!IsElementVisible(element)) {
            base = __hiddenMembers;
        }
        if (typeof appendList == "array") {
            for (var idx=0;idx < appendList.length;idx++) {
                delete base[id + appendList[idx]];
            }
        } else {        
            delete base[id];
        }
    }
    
    this.getHiddenMembers = function () {
        for (k in __hiddenMembers)
            if (typeof this[k] == "undefined")
                this[k] = __hiddenMembers[k];        
    }
    
    if (Container) this.getAttributes(Container);
}
    
DataObject.prototype = {

    toAttributeArray: function() {
        var ItemAttributes = new Array();
        for (key in this) {
            var obj = this[key];
            var type = typeof(obj);
            var FieldName = key.replace(/__/g,"$");
            if (obj && type == 'object' && obj.constructor.toString().indexOf('Array') == -1) {
                var ChildRows = new Array();
                for (childkey in obj) {
                    if (obj[childkey] && obj[childkey].toAttributeArray) 
                        ChildRows.push(obj[childkey].toAttributeArray());
                }
                ItemAttributes.push({"FieldName":FieldName,"Value":ChildRows});    
            } else if (type != 'function') {
                ItemAttributes.push({"FieldName":FieldName,"Value":this[key]});
            }
        }
        return ItemAttributes;
    }, 
    
  
    elementFieldName:function(el) {
        if (el.attributes['name']) {
            var namebits = el.attributes['name'].nodeValue.split("$");
            return namebits[namebits.length-1];
        }
        else
            return el.id.replace('ctl00_','');    
    },
    
    getAttributes: function(Container) {
        if (Container.className && Sys.UI.DomElement.containsCssClass(Container,'NotAjaxForm')) return;
        for (var idx=0;idx<Container.childNodes.length;idx++) {
            var child = Container.childNodes[idx];
            if (child.tagName) {
                switch (child.tagName) {
                    case 'INPUT': switch(child.type) {
                        case 'text': this.getInputAttribute(child);break;
                        case 'password': this.getInputAttribute(child);break;
                        case 'hidden': this.getHiddenFieldAttribute(child);break;            
                        case 'radio': this.getRadioFieldAttribute(child);break;                        
                        case 'checkbox': this.getCheckBoxFieldAttribute(child);break;                                                
                    } break;
                    case 'TEXTAREA': this.getInputAttribute(child);break;
                    case 'SELECT': this.getSelectAttribute(child);break;                                    
                }
            }
            this.getAttributes(child);        
        }
        this.getHiddenMembers();
    },

    getInputAttribute: function(TextBox) {
        this.setVal(TextBox,TextBox.value);
        //this[DataObject.elementFieldName(TextBox)] = TextBox.value;    
    },

    getSelectAttribute: function(DropDown) {
        this.clearVal(DropDown,["","_Text"]);
        //delete this[DataObject.elementFieldName(DropDown)];
        //delete this[DataObject.elementFieldName(DropDown)+'_Text'];
        if (DropDown.multiple) {
            var vals = new Array();
            var texts = new Array();
            //this[DataObject.elementFieldName(DropDown)] = new Array();
            //this[DataObject.elementFieldName(DropDown)+'_Text'] = new Array();
            for (i = 0 ; i < DropDown.options.length; i++) {
                if (DropDown.options[i].selected) {                    
                    vals.push(DropDown.options[i].value);            
                    texts.push(DropDown.options[i].text);            
                }
            }            
            this.setVal(DropDown,{'':vals,'_Text':texts});
        } else if (DropDown.options.length > 0) {
            this.setVal(DropDown,{'':DropDown.value,'_Text':DropDown.options[DropDown.selectedIndex].text});
            //this[DataObject.elementFieldName(DropDown)] = DropDown.value;
            //this[DataObject.elementFieldName(DropDown)+'_Text'] = ;
        }
    },
    
    getHiddenFieldAttribute: function(HiddenField) {
        if (this.getFCKEditorAttribute(HiddenField)) return;
        this.getInputAttribute(HiddenField);
    },
    
    getRadioFieldAttribute: function(RadioField) {
        if (RadioField.checked) this.getInputAttribute(RadioField);
    },
    
    getCheckBoxFieldAttribute: function(CheckBoxField) {
        if (CheckBoxField.checked) 
            this.setVal(CheckBoxField,'True');
            //this[DataObject.elementFieldName(CheckBoxField)] = 'True';
        else
            this.setVal(CheckBoxField,'False');
            //this[DataObject.elementFieldName(CheckBoxField)] = 'False';
    },

    getFCKEditorAttribute: function(FCKIframe) {
        var fckEditor = null;
        if (typeof FCKeditorAPI != 'undefined' && FCKeditorAPI) {
            fckEditor = FCKeditorAPI.GetInstance(FCKIframe.id) ;            
        }
        if (!fckEditor) return false;
        this.setVal(FCKIframe,fckEditor.GetXHTML(false));
        //this[DataObject.elementFieldName(FCKIframe)] = fckEditor.GetXHTML(false);    
        return true;
    }
}

/***********************
DisposableArray
***********************/

DisposableArray = function(arr, numToRemove) {
    this.TheArray = arr;
    this.numToRemove = numToRemove;
}

DisposableArray.prototype.dispose = function() {
    for (var i = 0;i < this.numToRemove; i ++ ) {
        Array.removeAt(this.TheArray,this.TheArray.length-1);
    }
}

/*** General Global Functions ***/

function CancelActionPanel() {
    CloseActionPanel();   
}

function GetQuantityFromElement(element, New_Quantity) {
    if (New_Quantity == null && element != null) {
        switch (element.tagName) {
            case 'SELECT': return New_Quantity = element.value;break;
            case 'INPUT': return New_Quantity = (element.checked ? 1 : 0);break;
        }
    }
    return New_Quantity;
}

function SetQuantityOnElement(element, New_Quantity) {
    if (New_Quantity && element) {
        switch (element.tagName) {
            case 'SELECT': element.value = New_Quantity;break;
            case 'INPUT': element.checked = (New_Quantity > 0);break;
        }
    }
}

function RemovePanelComponent(componentID, panel) {
    if (!panel && typeof pnlAction != 'undefined') panel = pnlAction;    
    var c = $find(componentID);
    if (c && panel && panel.components)
        for (var idx = 0;idx < panel.components.length;idx++)
            if (panel.components[idx].get_id() == componentID)
                panel.components.splice(idx,1);    
    if (c && c.dispose) c.dispose();
}

function AddPanelComponent(component, panel) {
    if (!panel && typeof pnlAction != 'undefined') panel = pnlAction;    
    if (!panel) return;
    if (!panel.components) panel.components = new Array();           
    panel.components.push(component);   
}

function SelectTab(Tab, TabStripClientID, OnClick) {
    var TabStrip = $get(TabStripClientID);
    if (!TabStrip) return;
    var Tabs = TabStrip.getElementsByTagName('A');
    for (var idx=0;idx<Tabs.length;idx++) {
        SwitchClass(Tabs[idx],'_selected',false,false);
    }
    SwitchClass(Tab, '_selected', false, true);
    if (typeof OnClick == 'function') OnClick();
}

// checks if an element is visible based on it's own visibility and all parents being visible
function IsElementVisible(element, checkParents) {
    if (element.tagName == "BODY") return true; // end the recursion    
    if (checkParents == null) checkParents = true;    
    var st;
    if( window.getComputedStyle ) {
        st = window.getComputedStyle(element,null);           
    } else if( element.currentStyle ) {
        st = element.currentStyle;
    }
    // if we can't get the complete style, do a naive check
    if (!st) return (element.style.display == "" || element.style.display == "block") && (element.style.visibility == "" || element.style.visibility == "visible");
    if (st.display == "none" || st.visibility == "hidden") return false;
    if (!checkParents) return true;
    return IsElementVisible(element.parentNode, checkParents);      
}