/**
 * 我的javascript库
 */

///=========================================
///全局函数扩展
///====================

//重复n次字符串,此方法相当于vbscript中的string()函数
String.prototype.string = function(n)
{
    var s = "";
    for( var i=0; i<n; i++ ){  s = s + this;    }
    return s;
};

//相当于c#的string.Format函数
String.prototype.format = function()
{
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function(m,i){
            return args[i];
        });
}

// 选中文本
function selectItem(obj){
    //var obj = document.getElementsByName("textRange")[0];
    var range = obj.createTextRange();
    range.moveStart("character",0);
    range.select();
}


///=========================================
/// jQuery扩展
///====================

(function( $ ){

    /**
     * html编码
     */
    $.htmlEncode = function (html)
    {
        var temp = document.createElement ("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    }

    /**
     * html解码
     */
    $.htmlDecode = function (text)
    {
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    }


    /**
     * 分页导航样式
     */
    $.pageNav = function( recordCount, pageCount, curPage, cmd)
    {
        // 检查数据类型
        recordCount = parseInt( recordCount );
        pageCount = parseInt( pageCount );
        curPage = parseInt( curPage );

        // 限定页数在有效的范围
        if ( 1 > curPage ){ curPage = 1;  }
        if ( pageCount < curPage ){ curPage = pageCount;  }

        var startNum,endNum;
        //开始 页码
        if ( 10 >= curPage ){ startNum = 1;   }
        else                { startNum = curPage - 10;  }

        //结束 页码
        endNum = curPage + 10;
        if( endNum > pageCount ){ endNum = pageCount;   }

        var s = "<div>";
        // 上一页
        if( 1 < curPage )
        {   s += '<a href="#' + cmd.args(-1,curPage-1) + '">上一页</a>';    }

        // 页连接列表
        for( var i = startNum; i <= endNum; i++ )
        {
            if(i == curPage)
            {  s += " " + i + " ";    }
            else
            {  s += '<a href="#' + cmd.args(-1,i) + '">[' + i + ']</a>';    }
        }

        // 下一页
        if (curPage < pageCount)
        {    s += '<a href="#' + cmd.args(-1,curPage+1) + '">下一页</a>';    }

        s += "</div>";
        // 记录总数
        s += "<div>共找到记录 " + recordCount + " 篇</div>";

        return s;
    }

    /**
     * 清空select, 此段代码抄自 jQuery in action
     */
    $.fn.emptySelect = function(){
        return this.each(function(){
            if(this.tagName=='SELECT'){ this.options.length = 0; }
        });
    }
    /**
     * 载入select, 此段代码抄自 jQuery in action
     */
    $.fn.loadSelect = function(optionsDataArray){
        return this.emptySelect().each(function(){
            if(this.tagName=='SELECT'){
                var selectElement = this;
                $.each(optionsDataArray, function(index,optionData)
                {
                    var option = new Option(optionData.caption,optionData.value);
                    if($.browser.msie){
                        selectElement.add(option);
                    }
                    else{
                        selectElement.add(option,null);
                    }
                });
            }
        });
    }


    /**
     * fckEditor
     */
    $.fn.fckHtmlEditor = function( basePath, height, toolbarSet )
    {
        // fckEditor
        var oFCKeditor = new FCKeditor( $(this)[0].name );
        oFCKeditor.BasePath = basePath || "fckeditor/";
        oFCKeditor.Height = height || 400;
        oFCKeditor.ToolbarSet = toolbarSet || "Default";
        oFCKeditor.ReplaceTextarea();
    }

    /**
     * ajaxSubmit
     */
    $.fn.ajaxSubmit = function(dataType,dispObj)
    {
        if( 'undefined'==typeof(dataType) ){
            dataType = 'html';
        }

        $(this).submit( function(){
            $.ajax({
                async: false,
                cache: false,
                timeout: 20000,
                type: "POST",
                contentType:"application/x-www-form-urlencoded",

                url: $(this).attr("action"),
                data:$(this).serialize(),
                dataType: dataType,

                //complete:function(dat){alert(dat);},
                success:function(dat){
                    if('json'==dataType){
                        if(dat.error){  dat = dat.error;   }
                        else{           dat = dat.success; }
                    }

                    if('undefined' == App){
                        alert( dat );
                    }else{
                        App.ui.popupAlert(dat);
                    }
                },
                error: function(dat){ alert(dat + ": Error, 发生了错误");  }
            });
            return false;
        });
    }

})(jQuery);



///=========================================
/// 命令管理类
///====================
(function(){
    /**
     * 命令建造类
     */
    var CmdBuilder = window.CmdBuilder = window.CommandBuilder = function()
    {
        arguments.join = Array.prototype.join;       //由于arguments是个不完全的数组,并无join方法
        arguments.slice= Array.prototype.slice;      //同上
        this.m_args = arguments;
        var divider = "/";
        //var cmdName = "cmd";
        //var cmdStr = "{0}={1}";

        if( 1 == this.m_args.length ){                      //当只有一个参数
            this.m_args = this.m_args[0].replace("#","");
            this.m_args = this.m_args.split(divider);
        }

        if( 3 > this.m_args.length ){                       //当零或两个参数时
            throw "the format of cmd is not valid";
        }
                                                     //更多的参数时
        this.subsys = this.m_args[0];
        this.module = this.m_args.slice(0,2).join(divider);
        this.service= this.m_args.slice(0,3).join(divider);
        this.params = this.m_args.slice( 3 ).join(divider);
        this.text = this.m_args.join(divider);

				var _ = this;
        this.args = function(i,val){
            if( 0==arguments.length ){  return _.m_args;      }
            if( 1==arguments.length ){
                if( 0 > i ){ return _.m_args[_.m_args.length+i];  }
                else{        return _.m_args[i];                  }
            }

            if( 0==arguments.length%2 ){
                for( var j=0; j<arguments.length; j+=2 ){
                    var idx = arguments[j];
                    if(0>idx){                 // 支持负数索引
                        idx = _.m_args.length+idx;
                    }
                    _.m_args[idx] = arguments[j+1];
                }
                return _.m_args.join(divider);
            }
        };

        return this.text;
    }

})(); //class Command


///=========================================
/// 历史管理类
///====================

(function(){
/**
 * HistoryStack
 *
 * A JavaScript object for storing resources or identifiers in a
 * history stack.  The history lasts as long as the browser is
 * open (i.e. session cookie).
 *
 * Written by Mike Brittain for IBM developerWorks.
 */

/**
 * Constructor
 */
var HistoryStack = window.HistoryStack = function()
{
    /** Current stack loaded in memory, which will also be
        cached to cookies. */
    this.stack = new Array();

    /** Pointer to current location in the history stack. */
    this.current = -1;

    /** Max size of the history stack. */
    this.stack_limit = 15;
}


/**
 * Return the name of the current resource in the
 * history stack.
 */
HistoryStack.prototype.getCurrent = function ()
{
    return this.stack[this.current];
};

/**
 * Add the resource to the next position after the "current" pointer.
 * If there are items existing past current, they will first be cut
 * off the end of the stack.  The stack will also be truncated to
 * "stack_limit" if it has grown to large.
 */
HistoryStack.prototype.addResource = function(resource)
{
    if (this.stack.length > 0) {
        this.stack = this.stack.slice(0, this.current + 1);
    }
    this.stack.push(resource);
    while (this.stack.length > this.stack_limit) {
        this.stack.shift();
    }
    this.current = this.stack.length - 1;
    this.save();
};


/**
 * Handle navigation within the history stack.  Any negative argument
 * will go backwards in the stack and positive arguments will go
 * forward.  If zero is passed to the method, the page will be
 * reloaded.
 */
HistoryStack.prototype.go = function(increment)
{
    // Go back...
    if (increment < 0) {
        this.current = Math.max(0, this.current + increment);

    // Go forward...
    } else if (increment > 0) {
        this.current = Math.min(this.stack.length - 1,
                                this.current + increment);

    // Reload...
    } else {
        location.reload();
    }

    this.save();
};


/**
 * Returns boolean value whether there is a previous
 * entry in the history stack.
 */
HistoryStack.prototype.hasPrev = function()
{
    return (this.current > 0);
};

/**
 * Returns boolean value whether there is a suceeding
 * entry in the history stack.
 */
HistoryStack.prototype.hasNext = function()
{
    return (this.current < this.stack.length - 1
            && this.current > -1);
};


/**
 * Save the current history stack and pointer to cookies
 */
HistoryStack.prototype.save = function()
{
    this.setCookie('CHStack', this.stack.toString());
    this.setCookie('CHCurrent', this.current);
};

/**
 * Load the history stack and pointer from cookies.
 */
HistoryStack.prototype.load = function()
{
    var tmp_stack = this.getCookie('CHStack');
    if (tmp_stack != '') {
        this.stack = tmp_stack.split(',');
    }

    var tmp_current = parseInt(this.getCookie('CHCurrent'));
    if (tmp_current >= -1) {
        this.current = tmp_current;
    }
};



/**
 * Save a name/value pair as a browser cookie, to expire at
 * end of session.
 */
HistoryStack.prototype.setCookie = function(name, value)
{
    var cookie_str = name + "=" + escape(value);
    document.cookie = cookie_str;
};

/**
 * Retrieve a cookie value by the given name.
 */
HistoryStack.prototype.getCookie = function(name)
{
    if (!name) return '';

  var raw_cookies, tmp, i;
  var cookies = new Array();

  raw_cookies = document.cookie.split('; ');
  for (i=0; i < raw_cookies.length; i++) {
    tmp = raw_cookies[i].split('=');
    cookies[tmp[0]] = unescape(tmp[1]);
  }

  if (cookies[name] != null) {
    return cookies[name];
  } else {
    return '';
  }
};


})();//class HistoryStack
