﻿//
// 8box Scripts Library.
//
var _is_browser_ie = false; //is it IE?
var _is_browser_ff = false; //is it firefox?
var _is_browser_sa = false; //is it Safari?

if(window.navigator.userAgent.indexOf("MSIE") != -1)    _is_browser_ie = true;
if(window.navigator.userAgent.indexOf("Firefox") != -1)    _is_browser_ff = true;
if(window.navigator.userAgent.indexOf("Safari") != -1)    _is_browser_sa = true;

//setup domain
try{document.domain=location.host.substring(location.host.lastIndexOf('.', location.host.lastIndexOf('.')-1)+1);}catch(ex){}

if(!_is_browser_ie){    
    //mock up IE in firefox
    if(_is_browser_ff){
        Event.prototype.__defineSetter__("returnValue",function(b) { if(!b)this.preventDefault(); return b; });
        Event.prototype.__defineSetter__("cancelBubble",function(b){ if(b)this.stopPropagation(); return b; });
        Event.prototype.__defineGetter__("srcElement",function() { var node=this.target; while(node.nodeType!=1) node=node.parentNode; return node; });
        Event.prototype.__defineGetter__("fromElement",function(){
            var node;
            if(this.type=="mouseover") node=this.relatedTarget;
            else if(this.type=="mouseout") node=this.target;
            if(!node) return;
            while(node.nodeType!=1) node=node.parentNode;
            return node;
        });        
    
        Event.prototype.__defineGetter__("toElement", function () {
          var node;
          if (this.type == "mouseout")
            node = this.relatedTarget;
          else if (this.type == "mouseover")
            node = this.target;
          if (!node) return;
          while (node.nodeType != 1) node = node.parentNode;
          return node;
        });
        
        HTMLElement.prototype.contains = function(Node)
        {
            return CheckContains(this, Node);
        }
    }
    
    //apply for safari&firefox
    Event.prototype.__defineGetter__("offsetX",function() {        return this.layerX;        });
    Event.prototype.__defineGetter__("offsetY",function() {        return this.layerY;        });
    
}

String.prototype.Trim = function() 
{ 
    return this.replace(/(^\s*)|(\s*$)/g, ""); 
}

function CheckContains(pnode, node)
{
    if(node == undefined) return false;
    if(_is_browser_ie){ //do ie way
        return pnode.contains(node);
    }else{
        do{
            if(node==pnode)return true;
        }
        while(node=node.parentNode);
        return false;
    }    
}

function AddEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  }
  else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);
    return r;
  }
  else {
    elm['on' + evType] = fn;
  }
}

function SearchEvent()
{
  //IE & Safari & Opera
  if( typeof(window.event)!="undefined" ){
    //alert(window.event.fromElement.parentNode.id);
    return window.event;
  }

  //Firefox
  func=SearchEvent.caller;
  while(func!=null)
  {		
    var arg0=func.arguments[0];		
    if(arg0)
    {
      if(arg0.constructor==Event || arg0.constructor==MouseEvent)
        return arg0;
    }
    func=func.caller;
  }
  return null;
}

function CopyToClipboard(txt)
{
  if(window.clipboardData) {
    window.clipboardData.clearData();
    window.clipboardData.setData("TEXT", txt);
  } else if(navigator.userAgent.indexOf("Opera") != -1)
  {
    window.location = txt;
  } else if (window.netscape)
  {
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
        alert("您的firefox安全限制限制剪贴板操作，请打开’about:config’将signed.applets.codebase_principal_support’设置为true’之后重试");
        return false;
    }
    var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
    if (!clip) return;
    var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
    if (!trans) return;
    trans.addDataFlavor("text/unicode");
    var str = new Object();
    var len = new Object();
    var str = Components.classes['@mozilla.org/supports-string;1'].createInstance(Components.interfaces.nsISupportsString);
    var copytext = txt;
    str.data = copytext;
    trans.setTransferData("text/unicode",str,copytext.length*2);
    var clipid = Components.interfaces.nsIClipboard;
    if (!clip) return false;
    clip.setData(trans,null,clipid.kGlobalClipboard);
  }
}

function RemoteCall(update, url, complete, loading)
{    
    if(update.length>0)
    {
        new Ajax.Updater(update, url, 
            {   asynchronous:true, evalScripts:true,
                onCreate:function(request){ eval(loading); },
                onComplete:function(request){ eval(complete); }
            }
        );
    }
    else{
        new Ajax.Request(url, { asynchronous:true, evalScripts:true,
                                onCreate:function(request){ eval(loading); },
                                onComplete:function(request){ eval(complete);}
                        });
    }
    
    return false;
}

function GetPageURL()
{
  CopyToClipboard(document.URL);
  alert("地址已经复制到剪贴板");
  return false;
}


//Cookie Operation
function getCookie(name)
{
  if (document.cookie.length>0)
  {
    c_start=document.cookie.indexOf(name + "=");
    if (c_start!=-1)
    { 
      c_start=c_start + name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
  return "";
}

function setCookie(name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=name+ "=" +escape(value)+ ";path=/"+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

/////////////////////////////////////////

function Stylize(tag, newclass) {
  if (window.attachEvent) { //only apply to IE    
    window.attachEvent("onload", function() {
      var ele = document.getElementsByTagName(tag);
      for (var i=0; i<ele.length; i++) {
        ele[i].onfocus=function() {
          this.className+=" "+newclass;
        }
        ele[i].onblur=function() {
          this.className=this.className.replace(new RegExp(" "+newclass+"\\b"), "");
        }
      }
    });
  }
}

function StylizeLink(relname, method) {
    if (!window.attachEvent) return;
    //apply to IE && Mozilla/FF
    AddEvent(window, "load", function() {
      var ele = document.getElementsByTagName("A");
      for (var i=0; i<ele.length; i++) {        
        if(ele[i].getAttribute("href") && ele[i].getAttribute("rel") == relname)
            
            ele[i].onclick = function(){
                method(this.href, this.title);
                return false;
            }
      }
    }, false);
}

function StylizeInput(typename, newclass) {
  if (window.attachEvent) { //only apply to IE
    window.attachEvent("onload", function() {
      var ele = document.getElementsByTagName("INPUT");
      for (var i=0; i<ele.length; i++) {
        if(ele[i].type==typename){
          ele[i].className=newclass;
        }
      }
    });
  }
}

function StylizeImage(img, maxw, maxh)
{
    if(_is_browser_ie && img.readyState != 'complete') return;
    if(maxw > 0 && img.width > maxw){ 
        img.width = maxw; 
    }else if(maxh > 0 && img.height > maxh){ 
        img.height = maxh;
    }
}

//
// form operations
//
function checkSize(eID, min, max, name)
{
  return checkSize2($(eID).value, min, max, name);
}

function checkSize2(str, min, max, name)
{
  str = str.Trim();
  if(str.length < min && min > 0){
    if(min == 1)
        alert(name + "不能为空");
    else
        alert(name + "长度不能少于" + min + "个字");
    return false;
  }
  else
  if(str.length > max && max > 0){
    alert(name + "长度不能超过" + max + "个字");
    return false;
  }
  return true;
}

function chkall2(elements, flag)
{
    var objLen = elements.length;
    for (var iCount = 0; iCount < objLen; iCount++)
    {
        if (flag == true)
        {
            elements[iCount].checked = true;
        }
        else
        {
            elements[iCount].checked = false;
        }
    }
}

function chkall(input1,input2)
{
    var objForm = document.forms[input1];
    var objLen = objForm.length;
    for (var iCount = 0; iCount < objLen; iCount++)
    {
        if (input2.checked == true)
        {
            if (objForm.elements[iCount].type == "checkbox")
            {
                objForm.elements[iCount].checked = true;
            }
        }
        else
        {
            if (objForm.elements[iCount].type == "checkbox")
            {
                objForm.elements[iCount].checked = false;
            }
        }
    }
}

//Tab Control
function Tabs(ca, cai){
    
    this.classActive = ca;
    this.classInactive = cai;
    
    this._tabs = new Array();
    this._tabs_ids = new Array();
    this._tabs_btns = new Array();

    this.add=function(id, btn_id, loaded){
        this._tabs[id] = loaded;
        this._tabs_ids[this._tabs_ids.length] = id;
        this._tabs_btns[id] = btn_id;
    };

    this.load=function(id, url){
        for (var i=0; i<this._tabs_ids.length; i++) {
            Element.hide(this._tabs_ids[i]);
            $(this._tabs_btns[this._tabs_ids[i]]).className=this.classInactive;
        }
        if(this._tabs[id] == false){
            RemoteCall(id, url);
            this._tabs[id] = true;
        }
        this.activate(id);
    };
    
    this.activate=function(id){
        Element.show(id);
        $(this._tabs_btns[id]).className=this.classActive;        
    };
}

function openImportEmailWin(sURL){
         window.open(sURL,"","modal=yes,width=500px,height=530px,center=yes,resizable=no,scrollbars=yes");
}

function addEmails(emails){
     var emailInput = document.getElementById("emails");
     var result=emailInput.value;
     if(result.indexOf(result.length-1)!=","){
         result=result+",";
     }
     for(i=0;i<emails.length;i++){
         email=emails[i].split(";");
         result=result+email[0]+"<"+email[1]+">,";
     }
     emailInput.value=result;
        
}

function insert2Textbox(element, type, tip){
  switch(type){
    case "img":
      tip = "请输入图片的网络地址(http://...)";break;
    case "url":
      tip = "请输入链接地址(http://...)";break;
    default:
      tip = "请输入" + tip;
  }
  var result = prompt(tip, tip);
  if(result != null){
    var text = "["+type+"]"+result+"[/"+type+"]";
    
    window.clipboardData.setData("text",text);
    $(element).focus();
    document.execCommand("Paste");
  }
}