var ww = {
  empty: function (sType) {
    if (sType=='function') return (function () {});
    if (sType=='object') return ({});
    if (sType=='array') return ([]);
    return (null);
  },
  msg: function (msgText) {
    ww.msgbox.show('Windows', msgText);
  },
  msgbox: {
    show: function (msgTitle, msgText, msgIcon, msgButton, oExtend) {
      var oInit = {
        title: (msgTitle)?msgTitle:'Window',
        msg: msgText,
        minWidth: 500,
        modal: true,
        icon: msgIcon,
        buttons: (msgButton)?msgButton:Ext.Msg.OK
      }
      oInit = ww.extend(oInit, oExtend);
      Ext.Msg.show(oInit);
    },
    alert: function (msgTitle, msgText) {
      Ext.Msg.alert((msgTitle)?msgTitle:'Windows', msgText);
    },
    prompt: function (msgTitle, msgText, fnCallback) {
      Ext.Msg.prompt((msgTitle)?msgTitle:'Windows', msgText, function(btn, sInput){
          if (btn == 'ok'){
              fnCallback(sInput);
          }
      });
    },
    confirm: function (msgText, fnYes, fnNo) {
      this.fnYes = (typeof(fnYes)=='function')?fnYes:ww.empty('function');
      this.fnNo = (typeof(fnNo)=='function')?fnNo:ww.empty('function');
      ww.msgbox.yn(msgText, {
        fn: function (btn) {
          if (btn=='yes') ww.msgbox.fnYes();
          if (btn=='no') ww.msgbox.fnNo();
          ww.msgbox.fnYes = ww.empty('function');
          ww.msgbox.fnNo = ww.empty('function');
        }
      });
    },
    err: function (msgText, oExtend) {
      ww.msgbox.show('Error', msgText, Ext.Msg.ERROR, Ext.Msg.OK, oExtend);
    },
    warning: function (msgText, oExtend) {
      ww.msgbox.show('Warning', msgText, Ext.Msg.WARNING, Ext.Msg.OK, oExtend);
    },
    info: function (msgText, oExtend) {
      ww.msgbox.tInfo('Information', msgText, oExtend);
    },
    tInfo: function (msgTitle, msgText, oExtend) {
      ww.msgbox.show(msgTitle, msgText, Ext.Msg.INFO, Ext.Msg.OK, oExtend);
    },
    cancel: function (msgText, oExtend) {
      ww.msgbox.show('Information', msgText, Ext.Msg.INFO, Ext.Msg.CANCEL, oExtend);
    },
    yn: function (msgText, oExtend) {
      ww.msgbox.show('Question', msgText, Ext.Msg.QUESTION, Ext.Msg.YESNO, oExtend);
    },
    yncancel: function (msgText, oExtend) {
      ww.msgbox.show('Question', msgText, Ext.Msg.QUESTION, Ext.Msg.YESNOCANCEL, oExtend);
    },
    okcancel: function (msgText, oExtend) {
      ww.msgbox.show('Question', msgText, Ext.Msg.QUESTION, Ext.Msg.OKCANCEL, oExtend);
    }
  },

  thisdoc: {
    filename: function () {return ww.doc.filename(window.location.toString());},
    scriptname: function () {return ww.doc.scriptname(window.location.toString());},
    scriptpath: function () {return ww.doc.scriptpath(window.location.toString());}
  },
  
  doc: {
    getProtocol: function (sn) {
      return ((sn.indexOf('https') > -1)?'https://':'http://');
    },
    domainname: function (sn) {
      sn = (sn.indexOf('https') > -1)?sn.replace('https://', ''):sn.replace('http://', '');
      sn = sn.substring(0, sn.indexOf('/'));
      return sn;
    },
    filename: function (sn) {
      sn = sn.substring(sn.lastIndexOf('/')+1, sn.length);
      if (sn.indexOf('?') > 0) sn = sn.substring(0, sn.indexOf('?'));
      if (sn.indexOf('#') > 0) sn = sn.substring(0, sn.indexOf('#'));
      return sn;
    },
    scriptname: function (sn) {
      sn = (sn.indexOf('https') > -1)?sn.replace('https://', ''):sn.replace('http://', '');
      sn = sn.substring(sn.indexOf('/'), sn.length);
      if (sn.indexOf('?') > 0) sn = sn.substring(0, sn.indexOf('?'));
      if (sn.indexOf('#') > 0) sn = sn.substring(0, sn.indexOf('#'));
      return sn;
    },
    scriptpath: function (url) {
      var sn = ww.doc.scriptname(url);
      var fn = ww.doc.filename(url);
      return sn.substring(0, sn.length - fn.length);
    },
    details: function (url) {
      return {
        http: ww.doc.getProtocol(url),
        dn: ww.doc.domainname(url),
        sn: ww.doc.scriptname(url),
        fn: ww.doc.filename(url),
        path: ww.doc.scriptpath(url)
      }
    }
  },

  cms: {
    _createWindow: function (sTitle, iWidth, iHeight, oExt) {
      var oInit = {
        title: sTitle,
        layout: 'fit',
        plain: true,
        bodyStyle:'padding:5px;'
      };
      if ((iWidth != 0) || (typeof(iWidth) != 'undefined')) oInit = ww.extend(oInit, {width: iWidth})
        else oInit = ww.extend(oInit, {autoWidth: true});
      if ((iHeight != 0) || (typeof(iWidth) != 'undefined')) oInit = ww.extend(oInit, {height: iHeight})
        else oInit = ww.extend(oInit, {autoHeight: true});
      oInit = ww.extend(oInit, oExt);
      return (new Ext.Window(oInit));
    },
    createWindow: function (sTitle, iWidth, iHeight, oExt) {
      index = ww.cms.windows.items.length;
      ww.cms.windows.items[index] = ww.cms._createWindow(sTitle, iWidth, iHeight, oExt);
    },
    createTabWindow: function (sTitle, iWidth, iHeight, oExt) {
      var oInit = ww.extend(oExt, {items: new Ext.TabPanel({id: 'wintab'})});
      ww.cms.createWindow(sTitle, iWidth, iHeight, oInit);
    },
    popWindow: function (sTitle, html, iWidth, iHeight, oExt) {
      var oInit = ww.extend(oExt||{}, {html: html});
      ww.cms._createWindow(sTitle, iWidth, iHeight, oInit).show();
    },
    windows :{
      items: []
    },
    tabs: {
      items: [],
      add: function (sID, sTitle, html) {
        if (!ww.ex.tabs) return false;
        ww.ex.tabs.add({
          id: sID,
          title: sTitle,
          html: html,
          autoScroll:true, 
          closable:true
        }).show();
      },
      show: function (sID) {
        if (!ww.ex.tabs) return false;
        var oTab = ww.ex.tabs.getComponent(sID);
        if (!oTab) return false;
        oTab.show();
        return true;
      },
      close: function (sID) {
        if (!ww.ex.tabs) return false;
        ww.ex.tabs.remove(sID);
      }
    },
    addtab_image: function (sID, sTitle, src, oExtend) {
      if (!ww.cms.tabs.show(sID)) {
        var resize = '/resize_image.v2.aspx?FilePath=' + src + '&m=t';
        var html = '<img src="[SRC]" border="0" />';
        if (typeof(oExtend)=='object') {
          if (oExtend.width) {
            resize += '&mwidth=' + (oExtend.width.toString()).replace('px', '');
            oExtend.resize = true;
          }
          if (oExtend.height) {
            resize += '&mheight=' + (oExtend.height.toString()).replace('px', '');
            oExtend.resize = true;
          }
        } else { oExtend = {resize: false} }
        html = (oExtend.resize)?html.replace('[SRC]', resize):html.replace('[SRC]', src);
        ww.cms.tabs.add(sID, sTitle, html);
      }
    },
    addtab_iframe: function (sID, sTitle, url) {
      if (!ww.cms.tabs.show(sID)) {
        var html = '<iframe id="' + sID + '" name="' + sID + '" src ="' + url + '" width="100%" height="100%" frameborder="0"></iframe>';
        ww.cms.tabs.add(sID, sTitle, html);
      }
    },
    addtab_ajax: function (sID, sTitle, url, params, callbackHandler, isPost) {
      if (!ww.cms.tabs.show(sID)) {
        var fnSuccess = function (xhr) {
          ww.cms.tabs.add(sID, sTitle, xhr.responseText);
        }
        ww.ajax.prefixParameter(params, {'CMSTab': '1'});
        ww.ajax.request(url, params, fnSuccess, callbackHandler, isPost);
      }
    }
  },
  
  dbStore: {
    JSON: function (key, oFields, oParams) {
      return (
        new Ext.data.JsonStore({
          proxy: new Ext.data.HttpProxy({
            url: '/CMSControl/storage.asp'
          }),
          baseParams: ww.extend((oParams||{}), {key: key||''}),
          root: 'records',
          totalProperty: 'totalCount',
          fields: oFields
        })
      );
    }
  },

  ajax: {
    request: function (url, params, successHandler, callbackHandler, isPost) {
      Ext.Ajax.request({
        url: url,
        params: params,
        success: successHandler,
        callback: callbackHandler,
        method: (isPost)?'POST':'GET',
        failure: this.failureHandler
      });
    },
    failureHandler : function () {
      ww.msgbox.err("Server communication failure");
    },
    prefixParameter: function (params, objs) {
      var oParams = (params)?params:[];
      for (var i in objs) oParams[i.toString()] = objs[i].toString();
      return oParams;
    },
    defineAJAXParameter: function (params) {
      return this.prefixParameter(params, {'AJAX': '1'});
    },
    fireJavascript: function (sText) {
      var sScript = ''
      var arrScripts = sText.match(/<script type="text\/javascript">([\S ]+)<\/script>/g);
      if (arrScripts) {
        for (var i=0; i<arrScripts.length; i++) {
          sScript = arrScripts[i];
          sScript = sScript.substring(sScript.indexOf('>')+1, sScript.lastIndexOf('<'));
          eval(sScript);
        }
      }
    },
    executeResponseScript: function (params, isSucc, xhr) {
      if (isSucc) ww.ajax.fireJavascript(xhr.responseText);
    },
    toElement: function (url, params, el, isPost) {
      params = this.defineAJAXParameter(params);
      succ = function (xhr) {
        if (el) el.innerHTML = xhr.responseText;
          else ww.msgbox.err("Error", "Unable to locate targeted element.");
      }
      this.request(url, params, succ, this.executeResponseScript, isPost);
    },
    postback: function (params) {
      url = ww.thisdoc.scriptname();
      params = this.defineAJAXParameter(params);
      succ = function (xhr) {
        var sText = xhr.responseText;
        var oMsg = ww.msgbox.info;
        if (sText.substring(0, 5).toLowerCase() == 'error') oMsg = ww.msgbox.err;
        if (sText.substring(0, 5).toLowerCase() == 'warning') oMsg = ww.msgbox.warning;
        oMsg(xhr.responseText);
      }
      this.request(url, params, succ, this.executeResponseScript, true);
    }
  },
  getFunction_parameters: function (func) {
    if (typeof(func) != 'function') return false;
    var sFunction = func.toString();
    sFunction = sFunction.replace(/\n/g, '');
    oParameter = sFunction.match(/\(([0-9a-zA-Z, ^\)]+)\)/i);
    return (oParameter)?oParameter[0]:'()';
  },
  getFunction_code: function (func) {
    if (typeof(func) != 'function') return false;
    var sFunction = func.toString();
    sFunction = sFunction.replace(/\n/g, '');
    var sTemp = (sFunction.match(/\{(.*)/g)).toString();
    sTemp = sTemp.substring(1, sTemp.length-1)
    return sTemp;
  },
  _extendFunction: function (st, nd, isAppendTop) {
    if (typeof(st) != 'function') return st;
    if (typeof(nd) != 'function') return st;
    sParam = this.getFunction_parameters(st);
    if (!isAppendTop) {
      eval('var newFunc = function ' + sParam + '{' + this.getFunction_code(st) + ';' + this.getFunction_code(nd) + '}');
    } else {
      eval('var newFunc = function ' + sParam + '{' + this.getFunction_code(nd) + ';' + this.getFunction_code(st) + '}');
    }
    return newFunc;
  },
  _extendJSON: function (st, nd) {
    if (typeof(st) != 'object') return st;
    if (typeof(nd) != 'object') return st;
    var newJSON = st;
    for(var i in nd) newJSON[i] = nd[i];
    return newJSON;
  },
  extend: function (st, nd, isAppendTop) {
    if ((typeof(st) == 'object') && (typeof(nd) == 'object')) return this._extendJSON(st, nd);
    if ((typeof(st) == 'function') && (typeof(nd) == 'function')) return this._extendFunction(st, nd, isAppendTop);
    return st;
  }
}
/*Ext.onReady(function () {
  window.alert = function (sMsg) {
    ww.msgbox.warning(sMsg);
  }
});*/
