var MAXINT = 2147483647;


function confirmDelete(form, message) {
    return confirmSubmit(form, "Delete", message || parent.RES_CONFIRM_DELETE);
}

function confirmRemove(form, message) {
    return confirmSubmit(form, "Remove", message || parent.RES_CONFIRM_REMOVE);
}

function confirmChangeCos(form, message) {
    return confirmSubmit(form, "ChangeCos", message || parent.RES_CONFIRM_MODIFY_USER_COS);
}
function confirmChangeCosForReg(form, message) {
    return confirmSubmit(form, "ChangeCosForReg", message || parent.RES_CONFIRM_MODIFY_USER_COS);
}
function confirmSubmit(form, func, message) {
    if (confirm(message)) {
        if (func && form.func) {
            form.func.value = func;
        }
        form.submit();
        return true;
    }
    return false;
}

function writeDigit(i, fractionDigits) {
    document.write(formatDigit(i, fractionDigits));
}

function writeSize(i) {
    if (i >= 1048576) {
        writeMB(Math.round(i/10485.76)/100);
    } else if (i >= 0) {
        document.write(Math.round(i/10.24) + 'K');
    } else {
        document.write(i);
    }
}

function writeMB(i) {
    if (i >= 1048576) {
        document.write(Math.round(i/10485.76)/100 + 'T');
    } else if (i >= 1024) {
        document.write(Math.round(i/10.24)/100 + 'G');
    } else if (i >= 0) {
        document.write(i + 'M');
    } else {
        document.write(i);
    }
}

// format #,##0.#
function formatDigit(i, fractionDigits) {
    var s = i.toString();
    if (i >= 0) {
        var k = s.indexOf(".");
        if (k < 0) {
            k = s.length;
        } else if (fractionDigits >= 0) {
            var l = Math.min(k + fractionDigits, s.length - 1);
            //for (; l > k && s.charAt(l) == '0'; l--) {}
            s = s.substr(0, (l > k) ? (l + 1) : l);
        }
        var j = (k - 1) % 3 + 1;
        for (var s1 = s.substr(0, j); j < s.length; j += 3) {
            if (j == k) {
                j++;
                s1 += ".";
            } else {
                s1 += ",";
            }
            s1 += s.substr(j, 3);
        }
        return s1;
    } else {
        return s;
    }
}


// ----- checkorg.js --------
function syncMenu() {
    var location = parseLocation(parent.menu)
    var expand = location["expand"];
    if (expand && expand.length > 1) {
        // ABCDX &= 0x3F, mask all expanded sub ous
        expand = (parseInt(expand.substring(expand.length - 2), 16) & 0x3F).toString(16);;
        location["expand"] = expand;
    }
    parent.menu.location.href = getLocationHref(location);
}

function startsWith(s1, s2) {
    return s1.substring(0, s2.length) == s2;
}

function checkOrg(p, o) {
    //alert(p + o);
    var location = parseLocation(parent.menu)
    if (location["P"] == p && location["O"] == o) {
        // org is the same
        return;
    }
    location["P"] = p;
    location["O"] = o;
    var expand = location["expand"];
    if (expand) {
        // ABCDX --> 1X
        expand = "1" + expand.substring(expand.length - 1);
        location["expand"] = expand;
    }
    parent.menu.location.href = getLocationHref(location);
    // loop for a little while
    // for (var i = 0; i < 10000; i ++);
}

function getLocationHref(obj) {
    var result = obj["#base"];
    var first = true;
    for (var i in obj) {
        if (i == "#base") {
            continue;
        }
        if (first) {
            result += '?';
            first = false;
        } else {
            result += '&';
        }
        result = result + i + '=' + obj[i];
    }
    return result;
}

function parseLocation(w) {
    var href = w.location.href;
    var a = href.split('?', 2);
    if (a.length == 2) {
        var result = {"#base" : a[0]};
        var b = a[1].split('&');
        for (var i = 0; i < b.length; i++) {
            var d = b[i].split('=', 2);
            if (d) {
                result[d[0]] = d[1];
            } else {
                result[d] = "";
            }
        }
        return result;
    } else {
        return {"#base" : href};
    }
}

function jumpou(ouid) {
    var loc = parseLocation(window);
    loc["U"] = ouid;
    location.href = getLocationHref(loc);
}

// ----- end of checkorg.js --------

// ----- begin of checkcos.js ------
function checkInput(s){
  var cosItemIds = document.getElementsByName("X");
  var i;
  for(i = 0;i < cosItemIds.length;i++){
    var cosItemId = cosItemIds[i].value;
    var cosItemValueType = document.getElementById("cos_item_value_type_"+cosItemId).value;
    if (cosItemValueType == "N"){
      var cosItemValue = document.getElementById("cos_item_value_"+cosItemId).value;
      var matchInt = /^(-1|0|[1-9]\d*)$/gi;
      if(!cosItemValue.match(matchInt)){
        var cosItemName = document.getElementById("cos_item_name_"+cosItemId).innerText;
        alert(cosItemName+":\n"+parent.RES_NOT_INT_INPUT+":\""+cosItemValue+"\"");
        return false;
      }else{
        if (parseInt(cosItemValue) > MAXINT){
          var cosItemName = document.getElementById("cos_item_name_"+cosItemId).innerText;
          alert(cosItemName+":\n"+parent.RES_EXCEED_MAXINT_INPUT+":\""+cosItemValue+"\"");
          return false;
        }
      }
    }
  }
  return confirm(s);
}
// ----- end of checkcos.js ------

// IE's function encodeURIComponent will force UTF8 encode, so we use another
var URI_E_CHARS = {" ":"+"};
for (var i = 0x00; i < 0x80; i++) {
    var c = String.fromCharCode(i);
    if (i < 0x10) {
        URI_E_CHARS[c] = "%0" + i.toString(16);
    } else if (c >= '0' && c <= '9') {
    } else if (c >= 'A' && c <= 'Z') {
    } else if (c >= 'a' && c <= 'z') {
    } else {
        URI_E_CHARS[c] = "%" + i.toString(16);
    }
}

function encodeURIC(s) {
    var s0 = String(s), s1 = "";
    for (var i = 0; i < s0.length; i++) {
        var c0 = s0.charAt(i);
        var c1 = URI_E_CHARS[c0];
        s1 += c1 ? c1 : c0;
    }
    return s1;
}
//alert(encodeURIC(" \t\r\n\f\\http://host:port/c?a=s&b c"));
function getText(tag) {
    if (tag.firstChild) return tag.firstChild.data;
    return "";
}

function selectCosSubsetItem(obj, cosItemId) {
    var numberValue = document.getElementById("number_" + cosItemId);
    var boolValue = document.getElementById("cos_item_value_" + cosItemId);
    var stringValue = document.getElementById("string_" + cosItemId);
    var itemSelected = obj.checked;
    obj.value = itemSelected ? "1" : "0";
    if (numberValue) {
        numberValue.disabled = !itemSelected;
    }
    if (boolValue) {
        boolValue.disabled = !itemSelected;
    }
    if (stringValue) {
        stringValue.disabled = !itemSelected;
    }
}

var activateCache = {};

function activateReg(name) {
    activateCache[name] = 1;
}

function disableExecute() {
    var nodes = document.getElementsByTagName("*");
    for (var i = 0, node; node = nodes[i]; i++) {
        var activate = node.getAttribute("activate");
        var display = node.getAttribute("display");
        if (activate != null) {
            if (!and(activate)) {
                disableElement(node);
            }
        } else if (display != null) {
            if (!or(display)) {
                node.parentNode.removeChild(node);
            }
        }
    }
    function and(exp) {
        var ands = exp.split(",");
        for (var j = 0, length = ands.length; j < length; j++) {
            if (ands[j] && !activateCache[ands[j]]) return false;
        }
        return true;
    }
    function or(exp) {
        var ors = exp.split("|");
        for (var j = 0, length = ors.length; j < length; j++) {
            if (ors[j] && activateCache[ors[j]]) return true;
        }
        return false;
    }
}

function disableElement(node) {
    var tn = node.tagName;
    if (tn == "INPUT"
            || tn == "SELECT"
            || tn == "OPTGROUP"
            || tn == "OPTION"
            || tn == "TEXTEARA"
            || tn == "BUTTON") {
        node.disabled = true;
    } else if (tn == "A") {
        node.href = null;
    } else {
        for (var name in node) {
            if (name.indexOf("on") == 0 && typeof node[name] == "function") {
                node[name] = null;
            }
        }
    }
}

// ----- Start rank edit --------
function editUserRank(anchorElement, userEmail) {
    var value = promptRank(anchorElement);
    if (value != null) {
        anchorElement.href = "../user/SubmitUser?func=Edit&user_email=" + userEmail
                + "&user_list_rank=" + value
                + "&infoskip=true";
    }
}

function editObjectRank(anchorElement, objUid) {
    var value = promptRank(anchorElement);
    if (value != null) {
        anchorElement.href = "../user/SubmitExtUser?func=Edit&obj_uid=" + objUid
                + "&obj_list_rank=" + value
                + "&infoskip=true";
    }
}

function editOrgUnitRank(anchorElement, providerId, orgId, orgUnitId) {
    var value = promptRank(anchorElement);
    if (value != null) {
        anchorElement.href = "SubmitOrgUnit?func=Edit&P=" + providerId + "&O=" + orgId
                + "&U=" + orgUnitId
                + "&org_unit_list_rank=" + value
                + "&infoskip=true";
    }
}

function editOrgRank(anchorElement, providerId, orgId) {
    var value = promptRank(anchorElement);
    if (value != null) {
        anchorElement.href = "../org/SubmitOrg?P=" + providerId + "&O=" + orgId
                + "&org_list_rank=" + value
                + "&infoskip=true";
    }
}

function promptRank(anchorElement) {
    var value = anchorElement.previousSibling.data.replace(/(^\s+)|(\s+$)/g, "");  
    value = prompt(parent.tips_edit_rank, value);
    if (value == null) {
        return null;
    }

    if(!value.match(/^(0|[1-9]\d*)$/gi)){
        alert(parent.RES_NOT_INT_INPUT + ":\"" + value + "\"");
        return null;
    }

    return value;
}
// ----- End rank edit --------

// extends prototype support
// $ is not supported in our template module, so we have to use '_' instead
var _ = $;
var _A = $A;

Object.extend(String.prototype, {
    trim : function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    },
    startsWith : function(prefix) {
        return (this.substring(0, prefix.length) == prefix);
    },

    endsWith : function(suffix) {
        return (this.substring(this.length - suffix.length) == suffix);
    },
    getSuffix : function(dot) {
        if (!dot) dot = "."
        var i = this.lastIndexOf(dot);
        return (i != -1) ? this.substring(i + 1) : "";
    }
})

function confirmMoveToOrg() {
    var moveToOrgform = $("moveToOrgform");
    var cur_org_id = moveToOrgform.cur_org_id.value;
    var cur_org_name = moveToOrgform.cur_org_name.value;
    var org_selects = moveToOrgform.org_selected;
    var selectedIndex = org_selects.selectedIndex;
    if (selectedIndex == -1) {
        alert(parent.RES_NO_ORG_SELECTED);
        return false;
    }
    var org_selected = org_selects.options[selectedIndex];
    var new_org_id = org_selected.value;
    var new_org_name = org_selected.text;
    return cur_org_id != new_org_id
            && confirm(formatMessage(parent.RES_CONFIRM_MOVE_USER_TO_ORG, [cur_org_name, new_org_name]));
}

/**
 *
 * @param message -- 信息格式(String)
 * @param args    -- 信息参数(Array of String)
 */
function formatMessage(message, args) {
    if (!message) {
        return "?????";
    }
    args = args || [];
    for (var i = 0, len = args.length; i < len; i++) {
        message = message.replace(new RegExp("\\\{" + i + "\\\}", "g"), args[i]);
    }
    return message;
}
