
//reportGrid.ClientSettings.ClientEvents.OnGroupCollapsed = "TestHide";
//reportGrid.ClientSettings.ClientEvents.OnGroupExpanded = "TestShow";

function TestHide(sender, args) {
    // debugger;
    //var obj = sender.get_masterTableView().get_element();

}


var tmpArrObjToRemoveImg = new Array();
function BambooGridViewRemoveImg(sender, args) {
    BambooGridViewRequestEnd();
}

function BambooGridViewRequestEnd() {
    try {
    
        var objForm = document.getElementById(MSOWebPartPageFormName);
        var objArr = document.getElementsByTagName("input");
        for (var i = 0; i < objArr.length; i++) {
            var objSpan = objArr.item(i);
            if (objSpan.getAttribute('BambooGridViewCheckPaging')) {
                objForm.removeChild(objSpan);
            }
        }
        
        var objArr = document.getElementsByTagName("span");
        for (var i = 0; i < objArr.length; i++) {
            var objSpan = objArr.item(i);
            if (objSpan.getAttribute('bambooGridViewCheckedForTotals')) {
                var objtr = objSpan.parentNode.parentNode;
                if (objtr) {
                    //RemoveParentRow(objtr);
                    for (var j = 0; j < objtr.childNodes.length; j++) {
                        var objtd = objtr.childNodes.item(j);
                        if (objtd) {
                            var objimg = objtd.firstChild;
                            if (objimg && objimg.nodeName.toLowerCase() == "input" && objimg.getAttribute('type').toLowerCase() == "image" && (objimg.getAttribute('alt').toLowerCase() == "edit" || objimg.getAttribute('alt').toLowerCase() == "expand")) {
                                objtd.removeChild(objimg);
                            }
                        }
                    }
                }
            }
        }
    } catch (e) { alert(e.message); }
}

function RemoveParentRow(parentRow) {
    //debugger;
    var objtr = parentRow.previousSibling;
    if (objtr) {
        for (var j = 0; j < objtr.childNodes.length; j++) {
            var objtd = objtr.childNodes.item(j);
            if (objtd) {
                var objimg = objtd.firstChild;
                if (objimg && objimg.nodeName.toLowerCase() == "img" && objimg.getAttribute('alt').toLowerCase() == "expand group") {
                    parentRow.style.display = "block";
                    objtr.style.display = "none";
                }
            }
        }
    }
}

//----- Process Totals ------
function ProcessTotals(id, isParent, objTotals) {
    this.dateTime = new Date();
    this.pathUrl = "/_Layouts/Bamboo.SPGridView/CalculatorForTotals.ashx?IdParam=" + id + "&bambooTotals=true&IsParent=" + isParent + "&clearCache=" + this.dateTime;
    this.ObjTotals = objTotals;
    var String = { Empty: "", IsNullOrEmpty: function(str) { if (!str || str.length == 0) return true; return false; }, Trim: function(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g, ""); }, LeftTrim: function(stringToTrim) { return stringToTrim.replace(/^\s+/, ""); }, RightTrim: function(stringToTrim) { return stringToTrim.replace(/\s+$/, ""); }, TrimAll: function(sString) { while (sString.substring(0, 1) == ' ') { sString = sString.substring(1, sString.length); } while (sString.substring(sString.length - 1, sString.length) == ' ') { sString = sString.substring(0, sString.length - 1); } return sString; } };

    this.Calculator = function() {
        for (var j = 0; j < tmpArrObj.length; j++) {
            if (tmpArrObj[j]) {
                tmpArrObj[j].innerText = "Calculating...";
            }
        }
        CreateXMLRequest(this.pathUrl);
    }

    function CreateXMLRequest(url) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                ProcessValues(xmlhttp.responseText);
            }
        };
        xmlhttp.open("POST", url, true);
        xmlhttp.send(null);
    }

    function ProcessValues(value) {
        if (value != 'NoData') {
            var myObject = eval('(' + value + ')');
            for (var i = 0; i < myObject.data.length; i++) {
                var htmlTmp = String.Empty;
                if (myObject.data[i].isBold == 'true')
                    htmlTmp = "<b><nobr>" + myObject.data[i].result + "</nobr></b>";
                else
                    htmlTmp = "<TABLE cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" height=\"100%\"><TR><TD width=\"100%\" height=\"100%\" align=\"" + myObject.data[i].align + "\" ><SPAN width=\"100%\" height=\"100%\" style=\"" + myObject.data[i].style + "\"><nobr>" + myObject.data[i].result + "</nobr></SPAN></TD></TR></TABLE>";

                var tmpId = String.Empty;
                if (isParent == 'true') {
                    tmpId = "Bamboo_" + myObject.data[i].col + "_Totals";
                    document.getElementById(id + "_" + myObject.data[i].col).value = myObject.data[i].result;
                }
                else {
                    tmpId = "Bamboo_" + myObject.data[i].col + "_Totals_true";
                    document.getElementById(id + "_" + myObject.data[i].col + "_true").value = myObject.data[i].result;
                }
                for (var j = 0; j < tmpArrObj.length; j++) {
                    if (tmpArrObj[j] && tmpArrObj[j].id == tmpId) {
                        tmpArrObj[j].innerHTML = htmlTmp;
                    }
                }
            }
        }
    }

    var tmpArrObj = new Array();
    var isCalculater = false;
    this.GetObjectToLoad = function(obj) {
        if (isCalculater == false) {
            this.Calculator();
            isCalculater = true;
        }
        if (obj) {
            var objtemp = obj.parentNode;
            tmpArrObj.push(objtemp);
            objtemp.innerText = "Calculating...";
        }
    }

    this.RefreshObjectsTotals = function(obj) {
        if (obj) {
            var objtemp = obj.parentNode;
            tmpArrObj.push(objtemp);
            if (objtemp)
                objtemp.removeChild(obj);
        }
    }

    this.RefreshValueTotals = function(sender, args) {
        if (isParent && args) {
            args.Menu.Control.onmousedown = function() {
                ClearValueForControl();
            }
        }
        else {
            ClearValueForControl();
        }
    }

    function ClearValueForControl() {
        if (objTotals == null) { alert('Please, Init data'); return; }
        isCalculater = false;
        for (var i = 0; i < objTotals.totals.length; i++) {
            var tmpobj = document.getElementById(id + "_" + objTotals.totals[i].col);
            if (tmpobj)
                tmpobj.value = String.Empty;
        }
    }

    this.RequestStart = function() {

        //alert("RequestStart!");
    }

    this.RequestEnd = function() {

    }
}


var typeTotals = new Array();
typeTotals[0] = "None";
typeTotals[1] = "Count";
typeTotals[2] = "Sum";
typeTotals[3] = "Average";
typeTotals[4] = "Max";
typeTotals[5] = "Min";

function BambooRestoreForTotals() {

    var tmpValueToRestore = "";
    this.BambooValidateForTotalsForRestore = function(obj, idColumn, idType, valueRestore) {
        tmpValueToRestore = valueRestore;
        var objtemp = obj.parentNode;
        if (objtemp)
            objtemp.removeChild(obj);
        var tmpObj = document.getElementById(idColumn);
        if (tmpObj.value != "-1" && valueRestore != "None") {
            this.BambooValidateForTotals(tmpObj, idType);
        }
    }

    this.BambooValidateForTotals = function(obj, idControl) {
        var tmpObj = document.getElementById(idControl);
        var tmpValueSelected = tmpObj.value;
        tmpObj.options.length = 0;
        for (var i = 0; i < typeTotals.length; i++) {
            tmpObj.options.add(AddItem(typeTotals[i], typeTotals[i]));
        }
        tmpObj.value = tmpValueSelected;
        var temp = "";
        for (var i = 0; i < obj.options.length; i++) {
            if (obj.value == obj.options[i].getAttribute("value")) {
                temp = obj.options[i].getAttribute("dataType");
                break;
            }
        }

        if (!CheckForValidateTotals(temp)) {
            if (temp != "DateTime" && temp != "Calculated" && obj.value != "-1") {
                tmpObj.options.remove(2);
                tmpObj.options.remove(2);
                tmpObj.options.remove(2);
                tmpObj.options.remove(2);
            }
            if (temp == "DateTime") {
                tmpObj.options.remove(2);
                tmpObj.options.remove(2);
            }
            if (temp == "Calculated") {
                tmpObj.options.remove(3);
                tmpObj.options.remove(3);
                tmpObj.options.remove(3);
            }
        }
    }

    function AddItem(Text, Value) {
        var opt = document.createElement("option");
        opt.text = Text;
        opt.value = Value;
        if (tmpValueToRestore == Value) {                    //&& IsClickNext == false
            opt.setAttribute("selected", "true");
            tmpValueToRestore = "";
        }
        return opt;
    }

    var regTotals = new Array();
    regTotals[0] = "Currency";
    regTotals[1] = "Number";
    function CheckForValidateTotals(value) {
        for (var i = 0; i < regTotals.length; i++) {
            if (value == regTotals[i])
                return true;
        }
        return false;
    }

    var IsClickNext = false;
    this.ShowNextControlForTotal = function(countControls) {

        //    var objComboBox = document.getElementsByTagName("select");
        //    for (var i = objComboBox.length; i >= 0; i--) {
        //        if (objComboBox[i] != null && objComboBox[i].getAttribute('CheckForColumnNameControl') != null) {
        //            var tmpObj = objComboBox[i];
        //            var tmpObjNext = tmpObj.parentNode.parentNode.nextSibling.firstChild.firstChild;
        //            var value = tmpObj.value;
        //            if (value == "-1" || tmpObjNext.value == "None") {
        //                alert("Please, Select Column Name and Total!");
        //                return false;
        //            }
        //        }
        //    }
        IsClickNext = true;
        return true;
    }
}

//----End ToTals----

var g_strDateTimeControlIDs = new Array();

function BambooGridViewPaging(clientID) {
    this.BambooPagingSetValue = function(obj, b, NorB, idHidden) {
        var value = "1";
        if (b == true) {
            value = obj;
        } else {
            value = obj.innerText;
        }
        document.getElementById(clientID + '_' + idHidden).value = value;
        var objNext = document.getElementById(clientID + '_' + idHidden + '_Next');
        if (objNext)
            objNext.value = 'null';

        var objBack = document.getElementById(clientID + '_' + idHidden + '_Back');
        if (objBack)
            objBack.value = 'null';

        if (NorB == 'next') {
            if (objNext)
                objNext.value = obj;
        }
        if (NorB == 'back') {
            if (objBack)
                objBack.value = obj;
        }
        UsingToIdentifyPaging(clientID, idHidden);
    }

    function UsingToIdentifyPaging(clientID, value) {
        var objForm = document.getElementById(MSOWebPartPageFormName);
        var BambooGridViewCheckDataSourceSettings = document.createElement("input");
        BambooGridViewCheckDataSourceSettings.setAttribute("id", "BambooGridViewCheckPaging" + clientID);
        BambooGridViewCheckDataSourceSettings.setAttribute("name", "BambooGridViewCheckPaging" + clientID);
        BambooGridViewCheckDataSourceSettings.setAttribute("type", "hidden");
        BambooGridViewCheckDataSourceSettings.setAttribute("BambooGridViewCheckPaging", "yes");
        BambooGridViewCheckDataSourceSettings.setAttribute("value", value);
        if (objForm)
            objForm.appendChild(BambooGridViewCheckDataSourceSettings);
    }
}

function BambooGridViewSorting(clientID) {
    var regSorting = new Array();
    var objSorting = { ColumnName: '', SortType: 'ASC' };
    this.BambooSortingSetValue = function(obj, idHidden) {
        var value = obj.valueSort;
        var tmpObj = this.IsExit(value);
        if (tmpObj) {
            tmpObj.SortType = tmpObj.SortType == 'ASC' ? 'DESC' : 'ASC';
            objSorting.ColumnName = value;
            objSorting.SortType = tmpObj.SortType;
        } else {
            objSorting.ColumnName = value;
            objSorting.SortType = 'ASC';
            regSorting.push(objSorting);
        }
        document.getElementById(clientID + '_' + idHidden).value = objSorting.ColumnName + ';' + objSorting.SortType;
    }

    this.IsExit = function(str) {
        for (var i = 0; i < regSorting.length; i++) {
            if (regSorting[i].ColumnName == str)
                return regSorting[i];
        }
        return null;
    }
}

function BambooEditDocument(strDocument) {
    var objEditor;
    try {
        objEditor = new ActiveXObject("Sharepoint.OpenDocuments.3");
        if (!objEditor.EditDocument2(window, strDocument, ''))
            alert(L_EditDocumentRuntimeError_Text);
        return;
    }
    catch (e) {
    }
    try {
        objEditor = new ActiveXObject("Sharepoint.OpenDocuments.1");
        window.onfocus = null;
        var varProgID = "";
        if (SzExtension(strDocument) == "ppt" && varProgID == "")
            varProgID = "PowerPoint.Slide";
        if (!objEditor.EditDocument(strDocument, varProgID))
            alert(L_EditDocumentRuntimeError_Text);
        return;
    }
    catch (e) {
        alert(L_EditDocumentProgIDError_Text);
    }
}

function ShowQuotedMessages(idDiv) {
    try {
        var objID1 = idDiv + '_1';
        var objID2 = idDiv + '_2';
        var objImgId = idDiv + 'Img';
        var objAId = idDiv + 'theA';
        var obj1 = document.getElementById(objID1);
        var obj2 = document.getElementById(objID2);
        var objImg = document.getElementById(objImgId);
        var objLink = document.getElementById(objAId);
        if (obj1.style.display == 'none') {
            obj1.style.display = 'block';
            obj2.style.display = 'none';
            objLink.innerText = 'Show Quoted Messages';
            objImg.src = '_layouts/images/dlmax.gif';
        }
        else {
            obj1.style.display = 'none';
            obj2.style.display = 'block';
            objLink.innerText = 'Hide Quoted Messages';
            objImg.src = '_layouts/images/dlmin.gif';
        }
    }
    catch (e) {
    }
}

function DisplayElement(btnID, tblID) {
    if (document.getElementById(tblID) && document.getElementById(tblID).style.display == 'none') {
        document.getElementById(tblID).style.display = '';
    }
    else if (document.getElementById(tblID) && document.getElementById(tblID).style.display == '') {
        document.getElementById(tblID).style.display = 'none';
    }

    var src = document.getElementById(btnID).src;
    src = src.substring(src.lastIndexOf("/") + 1, src.length);

    if (src == "expand.gif")
        document.getElementById(btnID).src = resourcesPath + "/collapse.gif";
    else
        document.getElementById(btnID).src = resourcesPath + "/expand.gif";
}

var dragapproved = false;
var z, x, y;
var parentWidth = 0;
//var valueDefault = 200;
var temp1;
var isIE = document.all;
var isN4 = document.layers;
var isHot = false;
var currentWP;
document.onmousedown = down;
document.onmouseup = up;
var IsStart = true;

function move(e) {
    if (dragapproved && event.button == 1) {
        var CurrentPos = (isIE ? event.clientX : e.clientX) + getPosScroll();
        var temp = (findPos(document.getElementById(currentWP + "_TreeCol")) + 50);
        if (temp > CurrentPos || (temp + parentWidth - 100) < CurrentPos) return false;
        z.style.pixelLeft = (isIE ? event.clientX : e.clientX) + getPosScroll();
    } else {
        try {
            document.getElementById(currentWP + "_DragCol").style.backgroundColor = '';
        } catch (e) { }
    }
    return false;
}

function down(e) {

    if (event.srcElement.className == "drag" && event.button == 1) {
        dragapproved = true;
        try {


            var index = event.srcElement.id.lastIndexOf("_");
            currentWP = event.srcElement.id.substring(0, index);
            var NameDragCol = document.getElementById(currentWP + "_DragCol");
            //NameDragCol.setAttribute("class","ms-WPTitle");		
            NameDragCol.style.position = 'absolute';
            NameDragCol.style.backgroundColor = "#FF00AA";
            z = document.getElementById(currentWP + "_DragCol");
            parentWidth = document.getElementById(currentWP + "_TreeCol").offsetParent.offsetWidth;
            if (z.style.pixelLeft < 0) {
                z.style.pixelLeft = 0;
            }
            temp1 = parseInt(z.style.pixelLeft) - 5;
            x = isIE ? event.clientX : e.clientX;

        } catch (e) { }
        document.onmousemove = move;

    }
}

function up() {
    if (dragapproved == true && event.button == 1) {
        if (IsStart && TempalteWeb == "MPS") {
            SetPositionStart();
            IsStart = false;
        } else {
            SetPositionAgain();
        }
        dragapproved = false;
        currentWP = "";
    }
}
function findPos(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
        }
    }
    return curleft;
}
function getPosScroll() {
    var posScrollBar = 0;
    if (isIE) {
        posScrollBar = document.body.scrollLeft;
    } else {
        posScrollBar = window.pageXOffset;
    }
    return posScrollBar;
}
function SetPositionAgain() {
    try {
        var m = document.getElementById(currentWP + "_TreeCol").style.width = (z.style.pixelLeft - (findPos(document.getElementById(currentWP + "_TreeCol")) + 8)) + "px";
        document.getElementById(currentWP + "_TreePanel").style.width = m;
        document.getElementById(currentWP + "_GridCol").style.width = ((parentWidth + findPos(document.getElementById(currentWP + "_TreeCol"))) - (z.style.pixelLeft + 8)) + "px";
        document.getElementById(currentWP + "_ShowResult").style.width = ((parentWidth + findPos(document.getElementById(currentWP + "_TreeCol"))) - (z.style.pixelLeft + 13)) + "px";
        document.getElementById(currentWP + "_DragCol").style.backgroundColor = '';
    } catch (e) { }
}

function SetPositionStart() {
    try {

        var m = document.getElementById(currentWP + "_TreeCol").style.width = (z.style.pixelLeft - (findPos(document.getElementById(currentWP + "_TreeCol")))) + "px";
        document.getElementById(currentWP + "_TreePanel").style.width = (CutString(m) + 5) + "px";
        document.getElementById(currentWP + "_ShowResult").style.width = (((parentWidth + findPos(document.getElementById(currentWP + "_TreeCol"))) - (z.style.pixelLeft + 13))) + "px";
        document.getElementById(currentWP + "_DragCol").style.backgroundColor = '';
    } catch (e) { }
}

function CutString(str) {
    var tempStr = str.replace('p', '').replace('x', '');
    return parseInt(tempStr);
}

function Bamboo_PostBack(homeURL, redirectURL, node, frm) {
    document.forms[frm].action = homeURL;
    document.getElementById(redirectURL) = redirectURL;
    addNodeFromLink(node);
    document.forms[frm].submit();
}

function getNodeID(node) {
    var index = node.lastIndexOf("_", node.length);
    var s = node;
    if (index != -1) {
        s = node.substring(index + 1, node.length);
    }
    return s;
}

// Written by Huu Khang
function Bamboo_Show(obj, obj1, divid) {
    document.getElementById(obj).style.display = "block";
    document.getElementById(obj1).style.display = "none";
}

// Written by Huu Khang
function Bamboo_PostBack(url, row, frm, obj) {
    document.forms[frm].action = url;
    document.getElementById(obj).value = row;
    document.forms[frm].submit();
}

function OnItem_Bamboo(elm) {
    if (!browseris.ie5up || !browseris.win32)
        return false;
    if (IsMenuOn()) {
        StartDeferItem(elm);
        return false;
    }
    if (itemTable != null)
        OutItem();
    itemTable = elm;
    currentItemID = itemTable.ItemId;
    var createCtx = new Function("setupMenuContext(" + itemTable.CTXName + ");");
    itemTable.className = "ms-selectedtitle";
    if (browseris.ie55up) {
        itemTable.onclick = CreateMenu;
    }
    else {
        itemTable.onclick = EditMenuDefaultForOnclick;
    }
    titleRow = itemTable.children[0].children[0];
    i = 0;
    while (titleRow.children[i] != null)
        imageCell = titleRow.children[i++];
    downArrowText = L_Edit_Text;
    imageCell.children[0].src = "/_layouts/images/" + "downarrw.gif";
    imageCell.children[0].alt = downArrowText;
    imageCell.children[0].style.visibility = "visible";
    imageCell.style.visibility = "visible";
    imageCell.className = "ms-menuimagecell";
    return true;
}

function OutItem_Bamboo(elm) {
    itemTable = elm;
    if (!IsMenuOn() && itemTable != null) {
        itemTable.className = "ms-unselectedtitle";
        if (imageCell != null) {
            imageCell.children[0].style.visibility = "hidden";
            imageCell.style.visibility = "hidden";
            imageCell.bgColor = "";
        }
        resetExecutionState();
    }
}

function Bamboo_DeleteItem(DeleteURL, frm) {
    var L_Delete_text = "Are you sure you want to delete this item?";
    if (confirm(L_Delete_text)) {
        document.forms[frm].action = DeleteURL;
        document.forms[frm].submit();
    }
}
//Ajax method

// Written by Hong Phong

function Bamboo_FunctionCallBack(response) {
    alert(response);
}

function Bamboo_DoCallBack(obj, value, funcCallBack) {
    //alert(funcCallBack);
    var xmlhttp = Bamboo_GetXMLHttpRequest();
    var result = null;
    if (!xmlhttp) {
        result = { "value": null, "error": "NOXMLHTTP" };
        Bamboo_DebugError(result.error);
        if (window.Bamboo_Error) {
            Bamboo_Error(result);
        }
        return result;
    }

    xmlhttp.open("POST", Bamboo_DefaultURL, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    xmlhttp.setRequestHeader("Accept-Encoding", "gzip, deflate");
    if (xmlhttp) {
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState != 4) {
                return;
            }
            Bamboo_DebugResponseText(xmlhttp.responseText);
            result = Bamboo_GetResult(xmlhttp);
            if (result.error) {
                Bamboo_DebugError(result.error);
                if (window.Bamboo_Error) {
                    Bamboo_Error(result);
                }
            }
            Bamboo_UpdatePage(result);
            try {
                funcCallBack(true);
            } catch (e) { }
        }
    }

    var form = document.getElementById(Bamboo_FormID);
    var encodedData = "";
    encodedData += "&Bamboo_UpdatePage=true";
    for (var i = 0; i < value.length; i++) {
        encodedData += "&Bamboo_VALUE_GetItems" + i + "=" + value[i];
    }
    encodedData += "&Bamboo_VALUE_Total=" + value.length;
    encodedData += "&__EVENTTARGET=" + escape(obj.split("$").join(":"));
    encodedData += '&__VIEWSTATE=' + escape(form.__VIEWSTATE.value).replace(new RegExp('\\+', 'g'), '%2b');
    xmlhttp.send(encodedData);
}

function utf8(wide) {
    var c, s;
    var enc = "";
    var i = 0;
    while (i < wide.length) {
        c = wide.charCodeAt(i++);
        // handle UTF-16 surrogates
        if (c >= 0xDC00 && c < 0xE000) continue;
        if (c >= 0xD800 && c < 0xDC00) {
            if (i >= wide.length) continue;
            s = wide.charCodeAt(i++);
            if (s < 0xDC00 || c >= 0xDE00) continue;
            c = ((c - 0xD800) << 10) + (s - 0xDC00) + 0x10000;
        }
        // output value
        if (c < 0x80) enc += String.fromCharCode(c);
        else if (c < 0x800) enc += String.fromCharCode(0xC0 + (c >> 6), 0x80 + (c & 0x3F));
        else if (c < 0x10000) enc += String.fromCharCode(0xE0 + (c >> 12), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
        else enc += String.fromCharCode(0xF0 + (c >> 18), 0x80 + (c >> 12 & 0x3F), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    }
    return enc;
}

var hexchars = "0123456789ABCDEF";

function toHex(n) {
    return hexchars.charAt(n >> 4) + hexchars.charAt(n & 0xF);
}

var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

function encodeURIComponentNew(s) {
    var s = utf8(s);
    var c;
    var enc = "";
    for (var i = 0; i < s.length; i++) {
        if (okURIchars.indexOf(s.charAt(i)) == -1)
            enc += "%" + toHex(s.charCodeAt(i));
        else
            enc += s.charAt(i);
    }
    return enc;
}

function Bamboo_Encode(s) {
    if (typeof encodeURIComponent == "function") {
        // Use JavaScript built-in function
        // IE 5.5+ and Netscape 6+ and Mozilla
        return encodeURIComponent(s);
    } else {
        // Need to mimic the JavaScript version
        // Netscape 4 and IE 4 and IE 5.0
        return encodeURIComponentNew(s);
    }
}

function Bamboo_AddEvent(obj, evType, fn, useCapture) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, useCapture);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        alert("Bamboo_AddEvent could not add event!");
    }
}

function Bamboo_GetXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        if (window.Bamboo_XMLHttpRequestProgID) {
            return new ActiveXObject(window.Bamboo_XMLHttpRequestProgID);
        } else {
            var progIDs = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
            for (var i = 0; i < progIDs.length; ++i) {
                var progID = progIDs[i];
                try {
                    var x = new ActiveXObject(progID);
                    window.Bamboo_XMLHttpRequestProgID = progID;
                    return x;
                } catch (e) {
                }
            }
        }
    }
    return null;
}

function Bamboo_CallBack(url, target, id, method, args, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) {
    if (window.Bamboo_PreCallBack) {
        var preCallBackResult = Bamboo_PreCallBack();
        if (!(typeof preCallBackResult == "undefined" || preCallBackResult)) {
            if (window.Bamboo_CallBackCancelled) {
                Bamboo_CallBackCancelled();
            }
            return null;
        }
    }
    var x = Bamboo_GetXMLHttpRequest();
    var result = null;
    if (!x) {
        result = { "value": null, "error": "NOXMLHTTP" };
        Bamboo_DebugError(result.error);
        if (window.Bamboo_Error) {
            Bamboo_Error(result);
        }
        if (clientCallBack) {
            clientCallBack(result, clientCallBackArg);
        }
        return result;
    }
    x.open("POST", url ? url : Bamboo_DefaultURL, clientCallBack ? true : false);
    x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    x.setRequestHeader("Accept-Encoding", "gzip, deflate");
    if (clientCallBack) {
        x.onreadystatechange = function() {
            if (x.readyState != 4) {
                return;
            }
            Bamboo_DebugResponseText(x.responseText);
            result = Bamboo_GetResult(x);
            if (result.error) {
                Bamboo_DebugError(result.error);
                if (window.Bamboo_Error) {
                    Bamboo_Error(result);
                }
            }
            if (updatePageAfterCallBack) {
                Bamboo_UpdatePage(result);
            }
            Bamboo_EvalClientSideScript(result);
            clientCallBack(result, clientCallBackArg);
            x = null;
            if (window.Bamboo_PostCallBack) {
                Bamboo_PostCallBack();
            }
        }
    }
    var encodedData = "";
    if (target == "Page") {
        encodedData += "&Bamboo_PageMethod=" + method;
    } else if (target == "MasterPage") {
        encodedData += "&Bamboo_MasterPageMethod=" + method;
    } else if (target == "Control") {
        encodedData += "&Bamboo_ControlID=" + id.split(":").join("_");
        encodedData += "&Bamboo_ControlMethod=" + method;
    }
    if (args) {
        for (var argsIndex = 0; argsIndex < args.length; ++argsIndex) {
            if (args[argsIndex] instanceof Array) {
                for (var i = 0; i < args[argsIndex].length; ++i) {
                    encodedData += "&Bamboo_CallBackArgument" + argsIndex + "=" + Bamboo_Encode(args[argsIndex][i]);
                }
            } else {
                encodedData += "&Bamboo_CallBackArgument" + argsIndex + "=" + Bamboo_Encode(args[argsIndex]);
            }
        }
    }
    if (updatePageAfterCallBack) {
        encodedData += "&Bamboo_UpdatePage=true";
    }
    if (includeControlValuesWithCallBack) {
        var form = document.getElementById(Bamboo_FormID);
        if (form != null) {
            for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
                var element = form.elements[elementIndex];
                if (element.name) {
                    var elementValue = null;
                    if (element.nodeName.toUpperCase() == "INPUT") {
                        var inputType = element.getAttribute("type").toUpperCase();
                        if (inputType == "TEXT" || inputType == "PASSWORD" || inputType == "HIDDEN") {
                            elementValue = element.value;
                        } else if (inputType == "CHECKBOX" || inputType == "RADIO") {
                            if (element.checked) {
                                elementValue = element.value;
                            }
                        }
                    } else if (element.nodeName.toUpperCase() == "SELECT") {
                        if (element.multiple) {
                            elementValue = [];
                            for (var i = 0; i < element.length; ++i) {
                                if (element.options[i].selected) {
                                    elementValue.push(element.options[i].value);
                                }
                            }
                        } else if (element.length == 0) {
                            elementValue = null;
                        } else {
                            elementValue = element.value;
                        }
                    } else if (element.nodeName.toUpperCase() == "TEXTAREA") {
                        elementValue = element.value;
                    }
                    if (elementValue instanceof Array) {
                        for (var i = 0; i < elementValue.length; ++i) {
                            encodedData += "&" + element.name + "=" + Bamboo_Encode(elementValue[i]);
                        }
                    } else if (elementValue != null) {
                        encodedData += "&" + element.name + "=" + Bamboo_Encode(elementValue);
                    }
                }
            }
            // ASP.NET 1.1 won't fire any events if neither of the following
            // two parameters are not in the request so make sure they're
            // always in the request.
            if (typeof form.__VIEWSTATE == "undefined") {
                encodedData += "&__VIEWSTATE=";
            }
            if (typeof form.__EVENTTARGET == "undefined") {
                encodedData += "&__EVENTTARGET=";
            }
        }
    }
    Bamboo_DebugRequestText(encodedData.split("&").join("\n&"));
    x.send(encodedData);
    if (!clientCallBack) {
        Bamboo_DebugResponseText(x.responseText);
        result = Bamboo_GetResult(x);
        if (result.error) {
            Bamboo_DebugError(result.error);
            if (window.Bamboo_Error) {
                Bamboo_Error(result);
            }
        }
        if (updatePageAfterCallBack) {
            Bamboo_UpdatePage(result);
        }
        Bamboo_EvalClientSideScript(result);
        if (window.Bamboo_PostCallBack) {
            Bamboo_PostCallBack();
        }
    }
    return result;
}

function Bamboo_GetResult(x) {
    var result = { "value": null, "error": null };
    var responseText = x.responseText;
    try {
        result = eval("(" + responseText + ")");
    } catch (e) {
        if (responseText.length == 0) {
            result.error = "NORESPONSE";
        } else {
            result.error = "BADRESPONSE";
            result.responseText = responseText;
        }
    }
    return result;
}

function Bamboo_SetHiddenInputValue(form, name, value) {
    var input = null;
    if (form[name]) {
        input = form[name];
    } else {
        input = document.createElement("input");
        input.setAttribute("name", name);
        input.setAttribute("type", "hidden");
    }
    input.setAttribute("value", value);
    var parentElement = input.parentElement ? input.parentElement : input.parentNode;
    if (parentElement == null) {
        form.appendChild(input);
        form[name] = input;
    }
}

function Bamboo_RemoveHiddenInput(form, name) {
    var input = form[name];
    var parentElement = input.parentElement ? input.parentElement : input.parentNode;
    if (input && parentElement == form) {
        form[name] = null;
        form.removeChild(input);
    }
}

function Bamboo_FireEvent(eventTarget, eventArgument, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) {
    var form = document.getElementById(Bamboo_FormID);
    Bamboo_SetHiddenInputValue(form, "__EVENTTARGET", eventTarget);
    Bamboo_SetHiddenInputValue(form, "__EVENTARGUMENT", eventArgument);
    Bamboo_CallBack(null, null, null, null, null, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack);
    form.__EVENTTARGET.value = "";
    form.__EVENTARGUMENT.value = "";
}

function Bamboo_UpdatePage(result) {
    var form = document.getElementById(Bamboo_FormID);
    if (result.viewState) {
        Bamboo_SetHiddenInputValue(form, "__VIEWSTATE", result.viewState);
    }
    if (result.viewStateEncrypted) {
        Bamboo_SetHiddenInputValue(form, "__VIEWSTATEENCRYPTED", result.viewStateEncrypted);
    }
    if (result.eventValidation) {
        Bamboo_SetHiddenInputValue(form, "__EVENTVALIDATION", result.eventValidation);
    }
    if (result.controls) {
        for (var controlID in result.controls) {
            var containerID = "Bamboo_" + controlID.split("$").join("_") + "__";
            var control = document.getElementById(containerID);
            if (control) {
                control.innerHTML = result.controls[controlID];
                if (result.controls[controlID] == "") {
                    control.style.display = "none";
                } else {
                    control.style.display = "block";
                }
            }
        }
    }
    if (result.pagescript) {
        Bamboo_LoadPageScript(result, 0);
    }
}

// Load each script in order and wait for each one to load before proceeding
function Bamboo_LoadPageScript(result, index) {
    if (index < result.pagescript.length) {
        try {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            if (result.pagescript[index].indexOf('src=') == 0) {
                script.src = result.pagescript[index].substring(4);
            } else {
                if (script.canHaveChildren) {
                    script.appendChild(document.createTextNode(result.pagescript[index]));
                } else {
                    script.text = result.pagescript[index];
                }
            }
            document.getElementsByTagName('head')[0].appendChild(script);
            if (typeof script.readyState != "undefined") {
                script.onreadystatechange = function() {
                    if (script.readyState != "complete" && script.readyState != "loaded") {
                        return;
                    } else {
                        Bamboo_LoadPageScript(result, index + 1);
                    }
                }
            } else {
                Bamboo_LoadPageScript(result, index + 1);
            }
        } catch (e) {
            Bamboo_DebugError("Error adding page script to head. " + e.name + ": " + e.message);
        }
    }
}

function Bamboo_EvalClientSideScript(result) {
    if (result.script) {
        for (var i = 0; i < result.script.length; ++i) {
            try {
                eval(result.script[i]);
            } catch (e) {
                alert("Error evaluating client-side script!\n\nScript: " + result.script[i] + "\n\nException: " + e);
            }
        }
    }
}

function Bamboo_DebugRequestText(text) {
}

function Bamboo_DebugResponseText(text) {
}

function Bamboo_DebugError(text) {
}

//Fix for bug #1429412, "Reponse callback returns previous response after file push".
//see http://sourceforge.net/tracker/index.php?func=detail&aid=1429412&group_id=151897&atid=782464
function Bamboo_Clear__EVENTTARGET() {
    var form = document.getElementById(Bamboo_FormID);
    Bamboo_SetHiddenInputValue(form, "__EVENTTARGET", "");
}

function Bamboo_InvokePageMethod(methodName, args, clientCallBack, clientCallBackArg) {
    Bamboo_Clear__EVENTTARGET(); // fix for bug #1429412
    return Bamboo_CallBack(null, "Page", null, methodName, args, clientCallBack, clientCallBackArg, true, true);
}

function Bamboo_InvokeMasterPageMethod(methodName, args, clientCallBack, clientCallBackArg) {
    Bamboo_Clear__EVENTTARGET(); // fix for bug #1429412
    return Bamboo_CallBack(null, "MasterPage", null, methodName, args, clientCallBack, clientCallBackArg, true, true);
}

function Bamboo_InvokeControlMethod(id, methodName, args, clientCallBack, clientCallBackArg) {
    Bamboo_Clear__EVENTTARGET(); // fix for bug #1429412
    return Bamboo_CallBack(null, "Control", id, methodName, args, clientCallBack, clientCallBackArg, true, true);
}

function Bamboo_PreProcessCallBack(
    control,
    e,
    eventTarget,
    causesValidation,
    validationGroup,
    imageUrlDuringCallBack,
    textDuringCallBack,
    enabledDuringCallBack,
    preCallBackFunction,
    callBackCancelledFunction,
    preProcessOut
) {
    preProcessOut.Enabled = !control.disabled;
    var preCallBackResult = true;
    if (preCallBackFunction) {
        preCallBackResult = preCallBackFunction(control);
    }
    if (typeof preCallBackResult == "undefined" || preCallBackResult) {
        var valid = true;
        if (causesValidation && typeof Page_ClientValidate == "function") {
            valid = Page_ClientValidate(validationGroup);
        }
        if (valid) {
            var inputType = control.getAttribute("type");
            inputType = (inputType == null) ? '' : inputType.toUpperCase();
            if (inputType == "IMAGE" && e != null) {
                var form = document.getElementById(Bamboo_FormID);
                if (e.offsetX) {
                    Bamboo_SetHiddenInputValue(form, eventTarget + ".x", e.offsetX);
                    Bamboo_SetHiddenInputValue(form, eventTarget + ".y", e.offsetY);
                } else {
                    Bamboo_SetHiddenInputValue(form, eventTarget + ".x", e.clientX - control.offsetLeft + 1);
                    Bamboo_SetHiddenInputValue(form, eventTarget + ".y", e.clientY - control.offsetTop + 1);
                }
            }
            preProcessOut.OriginalText = control.innerHTML;
            if (imageUrlDuringCallBack || textDuringCallBack) {
                if (control.nodeName.toUpperCase() == "INPUT") {
                    if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") {
                        preProcessOut.OriginalText = GetLabelText(control.id);
                        SetLabelText(control.id, textDuringCallBack);
                    } else if (inputType == "IMAGE") {
                        if (imageUrlDuringCallBack) {
                            preProcessOut.OriginalText = control.src;
                            control.src = imageUrlDuringCallBack;
                        } else {
                            preProcessOut.ParentElement = control.parentElement ? control.parentElement : control.parentNode;
                            if (preProcessOut.ParentElement) {
                                preProcessOut.OriginalText = preProcessOut.ParentElement.innerHTML;
                                preProcessOut.ParentElement.innerHTML = textDuringCallBack;
                            }
                        }
                    } else if (inputType == "SUBMIT") {
                        preProcessOut.OriginalText = control.value;
                        control.value = textDuringCallBack;
                    }
                } else if (control.nodeName.toUpperCase() == "SELECT") {
                    preProcessOut.OriginalText = GetLabelText(control.id);
                    SetLabelText(control.id, textDuringCallBack);
                } else {
                    control.innerHTML = textDuringCallBack;
                }
            }
            control.disabled = (typeof enabledDuringCallBack == "undefined") ? false : !enabledDuringCallBack;
            return true;
        } else {
            return false;
        }
    } else {
        if (callBackCancelledFunction) {
            callBackCancelledFunction(control);
        }
        return false;
    }
}

function Bamboo_PreProcessCallBackOut() {
    // Fields
    this.ParentElement = null;
    this.OriginalText = '';
    this.Enabled = true;
}

function Bamboo_PostProcessCallBack(
    result,
    control,
    eventTarget,
    clientCallBack,
    clientCallBackArg,
    imageUrlDuringCallBack,
    textDuringCallBack,
    postCallBackFunction,
    preProcessOut
) {
    if (postCallBackFunction) {
        postCallBackFunction(control);
    }
    control.disabled = !preProcessOut.Enabled;
    var inputType = control.getAttribute("type");
    inputType = (inputType == null) ? '' : inputType.toUpperCase();
    if (inputType == "IMAGE") {
        var form = document.getElementById(Bamboo_FormID);
        Bamboo_RemoveHiddenInput(form, eventTarget + ".x");
        Bamboo_RemoveHiddenInput(form, eventTarget + ".y");
    }
    if (imageUrlDuringCallBack || textDuringCallBack) {
        if (control.nodeName.toUpperCase() == "INPUT") {
            if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") {
                SetLabelText(control.id, preProcessOut.OriginalText);
            } else if (inputType == "IMAGE") {
                if (imageUrlDuringCallBack) {
                    control.src = preProcessOut.OriginalText;
                } else {
                    preProcessOut.ParentElement.innerHTML = preProcessOut.OriginalText;
                }
            } else if (inputType == "SUBMIT") {
                control.value = preProcessOut.OriginalText;
            }
        } else if (control.nodeName.toUpperCase() == "SELECT") {
            SetLabelText(control.id, preProcessOut.OriginalText);
        } else {
            control.innerHTML = preProcessOut.OriginalText;
        }
    }
    if (clientCallBack) {
        clientCallBack(result, clientCallBackArg);
    }
}

function Bamboo_FireCallBackEvent(
	control,
	e,
	eventTarget,
	eventArgument,
	causesValidation,
	validationGroup,
	imageUrlDuringCallBack,
	textDuringCallBack,
	enabledDuringCallBack,
	preCallBackFunction,
	postCallBackFunction,
	callBackCancelledFunction,
	includeControlValuesWithCallBack,
	updatePageAfterCallBack
) {
    var preProcessOut = new Bamboo_PreProcessCallBackOut();
    var preProcessResult = Bamboo_PreProcessCallBack(
	    control,
	    e,
	    eventTarget,
	    causesValidation,
	    validationGroup,
	    imageUrlDuringCallBack,
	    textDuringCallBack,
	    enabledDuringCallBack,
	    preCallBackFunction,
	    callBackCancelledFunction,
	    preProcessOut
	);
    if (preProcessResult) {
        Bamboo_FireEvent(
		    eventTarget,
		    eventArgument,
		    function(result) {
		        Bamboo_PostProcessCallBack(
                    result,
                    control,
                    eventTarget,
                    null,
                    null,
                    imageUrlDuringCallBack,
                    textDuringCallBack,
                    postCallBackFunction,
                    preProcessOut
                );
		    },
		    null,
		    includeControlValuesWithCallBack,
		    updatePageAfterCallBack
	    );
    }
}

function BambooListControl_OnClickExHW37(
    e,
	causesValidation,
	validationGroup,
	textDuringCallBack,
	enabledDuringCallBack,
	preCallBackFunction,
	postCallBackFunction,
	callBackCancelledFunction,
	includeControlValuesWithCallBack,
	updatePageAfterCallBack
) {
    var target = e.target || e.srcElement;
    //Bamboo_GetValueControlHW37(target.value);
    if (target.nodeName.toUpperCase() == "LABEL" && target.htmlFor != '')
        return;

    var eventTarget = target.id.split("_").join("$");
    Bamboo_FireCallBackEvent(
	    target,
	    e,
	    eventTarget,
	    '',
	    causesValidation,
	    validationGroup,
	    '',
	    textDuringCallBack,
	    enabledDuringCallBack,
	    preCallBackFunction,
	    postCallBackFunction,
	    callBackCancelledFunction,
	    true,
	    true
	);
}

function GetLabelText(id) {
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        if (labels[i].htmlFor == id) {
            return labels[i].innerHTML;
        }
    }
    return null;
}

function SetLabelText(id, text) {
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        if (labels[i].htmlFor == id) {
            labels[i].innerHTML = text;
            return;
        }
    }
}
function Bamboo_SetCursor() {
    document.body.style.cursor = "wait";
}

function Bamboo_RemoveCursor() {
    document.body.style.cursor = "auto";
    var dataSourceSettings = document.getElementById("bambooDataSourceSettingsForBDA");
    if(dataSourceSettings)
    {
        if (checkDataSourceSettings)
            dataSourceSettings.style.display = "block";
        else
            dataSourceSettings.style.display = "none";
    }
}


var checkDataSourceSettings = false;
function GetRadioButtonValue(obj, bdaItem) {
    var objForm = document.getElementById(MSOWebPartPageFormName);
    var objArr = document.getElementsByTagName("input");
    for (var i = 0; i < objArr.length; i++) {
        var objSpan = objArr.item(i);
        if (objSpan.getAttribute('BambooGridViewCheckDataSourceSettings')) {
            objForm.removeChild(objSpan);
        }
    }

    var BambooGridViewCheckDataSourceSettings = document.createElement("input");
    BambooGridViewCheckDataSourceSettings.setAttribute("id", "BambooGridViewCheckDataSourceSettings");
    BambooGridViewCheckDataSourceSettings.setAttribute("name", "BambooGridViewCheckDataSourceSettings");
    BambooGridViewCheckDataSourceSettings.setAttribute("type", "hidden");
    BambooGridViewCheckDataSourceSettings.setAttribute("BambooGridViewCheckDataSourceSettings", obj.value);
    BambooGridViewCheckDataSourceSettings.setAttribute("value", obj.value);
    if (objForm)
        objForm.appendChild(BambooGridViewCheckDataSourceSettings);
    
    if (obj.value == bdaItem) {
        checkDataSourceSettings = true;
    }
    else {
        checkDataSourceSettings = false;
    }
    
}

//ItemPerPage

function ValidateNumber(obj) {
    var values = document.getElementById(obj);
    if (values.value == "") {
        alert("Please enter a number");
        values.value = "20";
    }
    else if (isNaN(values.value)) {
        alert("Invalidation Number!");
        values.value = "20";
    }
    else if (trimAll(values.value) == '0') {
        alert("Number must greater than 0");
        values.value = "20";
    }
    else {
        var tempValue = values.value.replace('-', '').replace('.', '');
        values.value = tempValue;
    }
    if (values.value.substring(0, 1) == '0' && values.value.length == 3) {
        values.value = values.value.substring(1, 3);
    }
    if (values.value.length == 2 && values.value.substring(0, 1) == '0' && values.value.substring(1, 2) == '0') {
        values.value = "20";
    }
}

function trimAll(sString) {
    while (sString.substring(0, 1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length - 1, sString.length) == ' ') {
        sString = sString.substring(0, sString.length - 1);
    }
    return sString;
}

//--------------------------------Validate Filter----------------------------


var L_InvalidNumber_Text = "Filter value is not a valid number.";
var L_InvalidBoolean_Text = "Filter value is not a valid Yes\u002fNo value. Please specify \u0027Yes\u0027 or \u0027No\u0027.";
var L_InvalidBooleanOperator_Text = "Filter operator is not a valid. Please specify \u0027Equal to\u0027 or \u0027Not Equal To\u0027 operator.";
var L_InvalidDate_Text = "Filter value is not a valid date.";
var L_InvalidDateFormat_Text = "Filter value is not in a supported date format.";
var L_InvalidOperatorNote_Text = "The filter type you selected cannot be used with this field. To filter fields that contain multiple lines of text, use the \u0027contains\u0027 or \u0027begins with\u0027 operators. You cannot use the \u0027begins with\u0027 operator if rich HTML is allowed for the field.";
var L_InvalidOperatorMultiChoice_Text = "The filter type you selected cannot be used with this field. To filter fields that use the Choice type and the Checkboxes optional setting, choose either the \u0027contains\u0027, \u0027begins with\u0027, \u0027is equal to\u0027, or \u0027is not equal to\u0027 operators.";
var L_NoContainsFilter_Text = "The filter type you selected cannot be used with this type of column. You can apply the \u0027contains\u0027 operator only to columns that have the type Single line of text, Multiple lines of text, or Choice. Specify a different operator for the filter or change the column type. You can then attempt to create the filter again.";
var L_NoBeginsWithFilter_Text = "The filter type you selected cannot be used with this type of column. You can apply the \u0027begins with\u0027 operator only to columns that have the type Single line of text, Multiple lines of text \u0028without rich HTML\u0029, or Choice. Specify a different operator for the filter or change the column type. You can then attempt to create the filter again.";
var L_None_Text = "None";
var today = "[Today]".toLowerCase();
function ValidData(frm, fieldName, selectedField, Operator, OperatorField, fieldValue, fieldType) {
    //var displayField = frm[FrmLocalFieldName(fieldName)];
    //var userInputValue = TrimSpaces(displayField.value);	
    //var Type = g_FieldType[selectedField];

    var userInputValue = fieldValue;
    var Type = fieldType;

    if (Type == "") {
        return true;
    }
    if ((Type == "Note" || Type == "BambooRichText") && Operator != "BeginsWith" && Operator != "Contains") {
        BB_AlertAndSetFocusForDropdown(L_InvalidOperatorNote_Text, OperatorField);
        return false;
    }
    if (Type == "RichText" && Operator != "Contains") {
        BB_AlertAndSetFocusForDropdown(L_InvalidOperatorNote_Text, OperatorField);
        return false;
    }
    if (Type == "MultiChoice" && Operator != "BeginsWith" && Operator != "Contains"
				&& Operator != "Eq" && Operator != "Neq") {
        BB_AlertAndSetFocusForDropdown(L_InvalidOperatorMultiChoice_Text, OperatorField);
        return false;
    }
    if ((Operator == "Contains") &&
		 ((Type != "Computed") && (Type != "Note") && (Type != "RichText") && (Type != "Text") && (Type != "Calculated") && (Type != "MultiChoice") && (Type != "Choice") && (Type != "File") && (Type != "BambooSingleSelector") && (Type != "BambooLinkedSelectorSingle") && (Type != "BambooRichText"))) {
        BB_AlertAndSetFocusForDropdown(L_NoContainsFilter_Text, OperatorField);
        return false;
    }
    if ((Operator == "BeginsWith") &&
		 ((Type != "Computed") && (Type != "Note") && (Type != "Text") && (Type != "Calculated") && (Type != "MultiChoice") && (Type != "Choice") && (Type != "File") && (Type != "BambooSingleSelector") && (Type != "BambooLinkedSelectorSingle") && (Type != "BambooRichText"))) {
        BB_AlertAndSetFocusForDropdown(L_NoBeginsWithFilter_Text, OperatorField);
        return false;
    }

    if (Type == "DateTime" && Operator != "Eq" && Operator != "Neq") {
        BB_AlertAndSetFocus(L_InvalidDate_Text);
        return false;
    }


    if (Type == "Number" || Type == "Currency" || Type == "Counter" ||
		Type == "PercentageNumber") {
        var num = userInputValue;
        //num = num.replace(\,/g,"");
        if (isNaN(num)) {
            BB_AlertAndSetFocus(L_InvalidNumber_Text);
            return false;
        }
    }
    else if (Type == "Boolean" || Type == "Attachments" ||
		Type == "Recurrence" || Type == "CrossProjectLink" ||
		Type == "AllDayEvent") {
        if (Operator != "Eq" || Operator != "Neq") {
            var userInputValue = userInputValue.toLowerCase();

            if (userInputValue == "yes" || userInputValue == "1") {

                //frm[fieldName].value = 1;

            }
            else if (userInputValue == "no" || userInputValue == "0") {

                //frm[fieldName].value = 0;			
            }

        }
        else {
            if (Operator == "BeginsWith") {
                BB_AlertAndSetFocusForDropdown(L_NoBeginsWithFilter_Text, OperatorField);
                return false;
            }
            if (Operator == "Contains") {
                BB_AlertAndSetFocusForDropdown(L_NoContainsFilter_Text, OperatorField);
                return false;
            }
            else {
                BB_AlertAndSetFocus(L_InvalidBooleanOperator_Text);
                return false;
            }
        }
    }
    else if ((Type == "DateTime" || Type == "Lookup") &&
				userInputValue.toLowerCase() != today) {
        var userInputValueLower = userInputValue.toLowerCase();
        if (userInputValueLower.indexOf(today) == 0) {
            var offset = userInputValueLower.substr(today.length);
            if (/^[+-]\d{1,4}$/.test(offset)) {
                //frm[fieldName].value = userInputValueLower;
            }
            else {
                BB_AlertAndSetFocus(L_InvalidDateFormat_Text);
                return false;
            }
        }
        /*else
        {
        var date = dopt.ParseLocaleDate(userInputValue, g_DateCalType[selectedField]);
        if (!isNaN(date))
        {
        frm[fieldName].value = DateOptions.StISODate(date);
        }
        else if (Type == "Lookup")
        {
        //frm[fieldName].value = userInputValue;
        }
        else
        {
        BB_AlertAndSetFocus(L_InvalidDateFormat_Text);
        return false;
        }
        }*/
    }
    else {
        if (Type == "Text") {
            var userInputValueLower = userInputValue.toLowerCase();
            if (userInputValueLower == me || userInputValueLower == today) {
                BB_AlertAndSetFocus("Filter value is not a valid text string.");
                return false;
            }
        }
        //frm[fieldName].value = userInputValue;
    }

    return true;
}

function BB_AlertAndSetFocus(msg) {
    //fieldName.focus();
    //fieldName.select();
    window.alert(msg);
}

function BB_AlertAndSetFocusForDropdown(msg) {
    //fieldName.focus();
    window.alert(msg);
}

//--------------------END Validate filter-------------------


//**********************HW41 Color Column******************

var offsetxpoint = -60 //Customize x offset of tooltip
var offsetypoint = 20 //Customize y offset of tooltip
var ie = document.all
var ns6 = document.getElementById && !document.all
var enabletip = true;
var tipobj;
var curX, curY;

function getElementCount(colorTable) {
    //debugger;
    var result = "";
    var strXml = EEDecodeSpecialChars(colorTable);
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(strXml);
    var columns = xmlDoc.documentElement.selectNodes("Column");
    return columns.length;
}
function getElementColor(colorTable, i) {
    //debugger;
    //var tagSubItem = "$#*"; 
    //var tagItem = "*#$*";
    var result = "";
    var strXml = EEDecodeSpecialChars(colorTable);
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(strXml);
    var columns = xmlDoc.documentElement.selectNodes("Column");

    result = columns[i].getAttribute("HexColor");

    return result;
}
function getElementText(colorTable, i) {
    //debugger;
    var result = "";
    var strXml = EEDecodeSpecialChars(colorTable);
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(strXml);
    var columns = xmlDoc.documentElement.selectNodes("Column");
    result = columns[i].getAttribute("DisplayName");
    return result;
}
function ddrivetip(objactive, colorTable) {
    if (ns6 || ie) {
        tipobj = document.getElementById ? document.getElementById("dhtmltooltip") : document.all["dhtmltooltip"];
        if (typeof thewidth != "undefined") {
            tipobj.style.width = thewidth + "px"
        }

        var strobj = "<table cellpadding='0' cellspacing='0' width='100%'>";
        var count = getElementCount(colorTable);
        var realHeight = 0;
        for (var i = 0; i < count; i++) {
            strobj += "<tr>";
            strobj += "	<td width='2%' valign='middle'><div style='margin: 2px 0px;width: 15px; height: 15px; background-color: " + getElementColor(colorTable, i) + "'></div></td>";
            strobj += "	<td width='98%' valign='middle' style='padding-left: 5px'><div>" + getElementText(colorTable, i) + "</div></td>";
            strobj += "</tr>";
        }
        strobj += "</table>";

        tipobj.innerHTML = strobj;

        tipobj.style.height = "auto";
        tipobj.style.overflowY = "visible";
        tipobj.style.width = "150px";

        enabletip = true;
        positiontip(event);

        if (parseInt(tipobj.style.top) < curY) {
            if (tipobj.offsetHeight > curY) {
                tipobj.style.height = curY - 5 + "px";
                tipobj.style.top = document.body.scrollTop + "px";

                tipobj.style.overflowY = "scroll";
                objactive.onmouseout = null;
                document.onclick = hideddrivetip;
            }
            else {
                if ((tipobj.offsetTop - document.body.scrollTop) < 0) {
                    tipobj.style.top = document.body.scrollTop + "px";
                }
            }
        }
        else {
            if ((parseInt(tipobj.style.top) + tipobj.offsetHeight) > document.body.offsetHeight) {
                tipobj.style.height = document.body.offsetHeight - parseInt(tipobj.style.top) + "px";
                tipobj.style.top = document.body.scrollTop + "px";
                tipobj.style.overflowY = "scroll";
            }
        }
        tipobj.style.top = tipobj.offsetTop + 15 + "px";

        return false;
    }
}

function hideddrivetip() {
    if (ns6 || ie) {
        tipobj = document.getElementById ? document.getElementById("dhtmltooltip") : document.all["dhtmltooltip"];
        enabletip = false
        tipobj.style.visibility = "hidden"
        tipobj.style.left = "-1000px"
        tipobj.style.backgroundColor = ''
        tipobj.style.width = ''
    }
}

function positiontip(e) {
    if (ie || ns6) {
        tipobj = document.getElementById ? document.getElementById("dhtmltooltip") : document.all["dhtmltooltip"];
    }
    if (enabletip) {
        curX = (ns6) ? e.pageX : event.clientX + ietruebody().scrollLeft;
        curY = (ns6) ? e.pageY : event.clientY + ietruebody().scrollTop;

        var rightedge = ie && !window.opera ? ietruebody().clientWidth - event.clientX - offsetxpoint : window.innerWidth - e.clientX - offsetxpoint - 20
        var bottomedge = ie && !window.opera ? ietruebody().clientHeight - event.clientY - offsetypoint : window.innerHeight - e.clientY - offsetypoint - 20

        var leftedge = (offsetxpoint < 0) ? offsetxpoint * (-1) : -1000

        tipobj.style.left = getPost(event.srcElement, "left") + event.srcElement.offsetLeft + event.srcElement.offsetWidth + "px";

        tipobj.style.top = ie ? ietruebody().scrollTop + event.clientY - tipobj.offsetHeight - offsetypoint + "px" : window.pageYOffset + e.clientY - tipobj.offsetHeight - offsetypoint + "px"
        tipobj.style.visibility = "visible";

        //alert(document.body.offsetWidth);
        //alert(parseInt(tipobj.style.left)  + tipobj.offsetWidth);
        if ((parseInt(tipobj.style.left) + tipobj.offsetWidth) > (document.body.offsetWidth + document.body.scrollLeft)) {
            tipobj.style.left = parseInt(tipobj.style.left) - 175 + "px";
        }
    }
}

function ietruebody() {
    return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}

function getPost(obj, v) {
    var p = 0;
    while (obj.parentElement != null) {
        p += v == "left" ? obj.parentElement.offsetLeft : obj.parentElement.offsetTop;
        obj = obj.parentElement;
    }
    return p;
}



//****************END HW41*************


//**************MashPoint***************************

function bambooMashPointHandleStateChange() {
    for (var i = 0; i < xmlhttps.length; i++) {
        if (!handleStatus[i]) {
            var xmlhttp = xmlhttps[i];
            var tableId = tableIds[i];
            if (xmlhttp.readyState == 4) {
                var buttonDiv = document.getElementById(tableId);
                buttonDiv = GetParentNode(buttonDiv, 'div');
                var menuDiv = buttonDiv.nextSibling;
                var xmldom;
                //debugger;
                if (window.ActiveXObject) {
                    ProcessXmlHttpResponseIE(buttonDiv, menuDiv, xmlhttp);
                }
                else {
                    ProcessXmlHttpResponseNonIE(buttonDiv, menuDiv, xmlhttp);
                }

                handleStatus[i] = true;
            }
        }
    }

}
function bambooMashPointShowActionMenu(loadingMsg, menuText, showMenuImage, appName, entityName, itemID) {
    //debugger;
    var e = window.event ? window.event : arguments.callee.caller.arguments[0];
    bambooMashPointDisplayActionMenu(loadingMsg, menuText, showMenuImage, appName, entityName, itemID, e);
}

function bambooMashPointDisplayActionMenu(loadingMsg, menuText, showMenuImage, appName, entityName, itemID, e) {
    //debugger;
    var prefix = 'prefix_' + xmlhttps.length;
    var tableId = prefix + '_t';
    tableIds[tableIds.length] = tableId;
    var menuId = 'menu_' + prefix;
    var aId = prefix;
    var imageId = prefix + '_ti';
    var menuItemId = 'menuitem_' + prefix;
    var placeHolderButtonHtml = '';
    var effectiveMenuText = '';
    if (menuText != null) {
        effectiveMenuText = menuText;
    }
    if ((menuText != null) && (menuText != '')) {
        placeHolderButtonHtml =
'<table ' +
	'height="100%" ' +
	'cellspacing="0" ' +
	'class="ms-unselectedtitle" ' +
	'id="' + tableId + '" ' +
	'foa="' + aId + '" ' +
	'onmouseover="MMU_EcbTableMouseOverOut(this, true)" ' +
	'hoverActive="ms-selectedtitle" ' +
	'hoverInactive="ms-unselectedtitle" ' +
	'onclick="try { MMU_Open(byid(\'' + menuId + '\'), MMU_GetMenuFromClientId(\'' + aId + '\'),event,false, null, 0); } catch (ex) { alert(\'An unhandled excepttion occurred: \' + ex); }" ' +
	'oncontextmenu="this.click(); return false;" ' +
	'menuformat="ArrowOnHover" ' +
	'downArrowTitle="Open Menu">' +
	'<tr>' +
		'<td class="ms-vb">' +
			'<a id="' + aId + '" ' +
			'onclick="event.cancelBubble=true" ' +
			'onfocus="MMU_EcbLinkOnFocusBlur(byid(\'' + menuId + '\'),this,true);" ' +
			'onkeydown="return MMU_EcbLinkOnKeyDown(byid(\'' + menuId + '\'),this,event);" ' +
			'tabindex="0" ' +
			'menuTokenValues="MENUCLIENTID=' + aId + ',TEMPLATECLIENTID=' + menuId + '"> ';
        if (showMenuImage) {
            placeHolderButtonHtml = placeHolderButtonHtml + '<img border="0" align="absmiddle" src="/_layouts/images/bizdataactionicon.gif" alt=""> ';
        }
        placeHolderButtonHtml = placeHolderButtonHtml + effectiveMenuText +
				'<img src="/_layouts/images/blank.gif" border="0" alt=""/> ' +
			'</a> ' +
		'</td> ' +
		'<td class="ms-menuimagecell" style="visibility:hidden" id="' + imageId + '"> ' +
			'<img src="/_layouts/images/downarrw.gif" width="13" alt=""/> ' +
		'</td> ' +
	'</tr> ' +
'</table> ';
    }
    else {
        placeHolderButtonHtml =
'<span id="' + tableId + '" class="ms-SPLink ms-hovercellinactive" onmouseover="this.className=\'ms-SPLink ms-hovercellactive\'" onmouseout="this.className=\'ms-SPLink ms-hovercellinactive\'" onclick=" MMU_Open(document.getElementById(\'' + menuId + '\'), document.getElementById(\'' + aId + '\'))"><a id="' + aId + '" accesskey="" style="cursor:hand;white-space:nowrap;" onkeydown="MMU_EcbLinkOnKeyDown(document.getElementById(\'' + menuId + '\'), this);" onclick=" MMU_Open(document.getElementById(\'' + menuId + '\'), this, event);" tabindex="0" menuTokenValues="TEMPLATECLIENTID=' + menuId + ',MENUCLIENTID=' + tableId + '"> ';
        if (showMenuImage) {
            placeHolderButtonHtml = placeHolderButtonHtml + '<img border="0" align="absmiddle" src="/_layouts/images/bizdataactionicon.gif" alt="">';
        }
        placeHolderButtonHtml = placeHolderButtonHtml + effectiveMenuText +
	'</a> ' +
        '<img src="/_layouts/images/menudark.gif" alt="" />' +
'</span>';
    }
    var placeHolderMenuHtml = '<span style="display: none"><menu class=ms-SrvMenuUI id="' + menuId + '"><ie:menuitem id="' + menuItemId + '" type="option">' + loadingMsg + '</ie:menuitem></menu></span>';
    var targetEl = e.srcElement ? e.srcElement : e.target;
    var buttonDiv = GetParentNode(targetEl, 'div');
    var menuDiv = buttonDiv.nextSibling;
    buttonDiv.innerHTML = placeHolderButtonHtml;
    menuDiv.innerHTML = placeHolderMenuHtml;
    OpenMenu(menuId, aId);
    var url = '';
    var proxyPageUrlObj = document.getElementById('BDC_ActionsMenuProxyPageWebUrl');
    if (proxyPageUrlObj != null) {
        url += proxyPageUrlObj.value;
    }
    url += "/_layouts/BambooMashPointProxy.aspx?ProxyCmd=ActionMenu";
    url += "&Application=" + encodeURIComponent(appName);
    url += "&Entity=" + encodeURIComponent(entityName);
    url += "&ItemID=" + encodeURIComponent(itemID);
    if (menuText != null) {
        url += "&MenuText=" + encodeURIComponent(menuText);
    }
    if (showMenuImage) {
        url += "&ShowMenuImage=true";
    }

    if (window.XMLHttpRequest) {
        bambooMashPointDoXmlHttpNonIE(url);
    }
    else {
        bambooMashPointDoXmlHttpIE(url);
    }
}

function bambooMashPointDoXmlHttpIE(url) {
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = bambooMashPointHandleStateChange;
    xmlhttps[xmlhttps.length] = xmlhttp;
    handleStatus[handleStatus.length] = false;
    xmlhttp.open("POST", url, true);
    xmlhttp.send();
}

function bambooMashPointDoXmlHttpNonIE(url) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = bambooMashPointHandleStateChange;
    xmlhttps[xmlhttps.length] = xmlhttp;
    handleStatus[handleStatus.length] = false;
    xmlhttp.open("POST", url, true);
    xmlhttp.send(null);
}

//***********END MASHPOINT*******************************

//AttachMent
function myOnCientFileSelected(radUpload, eventArgs) {
    //alert( eventArgs.FileInputField.value);
    //debugger;
    var idwebpart = radUpload.Id.substring(0, radUpload.Id.indexOf("_BambooRadGridViewHW37"));
    //alert(idwebpart);
    objHidden = document.getElementById(idwebpart + "_hiddenUpload");
    objHidden.value = eventArgs.FileInputField.value;

}
