/**
 * earth.js (Based on prototype.js)
 * 
 * 1.摘自lightbox的对Element元素的扩展；<br />
 * 2.摘自互联网上的对GET参数的解析；<br />
 * 3.常用方法；<br />
 * 4.控件集合；<br />
 *
 * @author Timandes
 */
var earth = Class.create();


// From lightbox.js
// -----------------------------------------------------------------------------------
//
//    Additional methods for Element added by SU, Couloir
//    - further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
    getWidth: function(element) {
           element = $(element);
           return element.offsetWidth; 
    },
    setWidth: function(element,w) {
           element = $(element);
        element.style.width = w +"px";
    },
    setHeight: function(element,h) {
           element = $(element);
        element.style.height = h +"px";
    },
    setTop: function(element,t) {
           element = $(element);
        element.style.top = t +"px";
    },
    setLeft: function(element,l) {
           element = $(element);
        element.style.left = l +"px";
    },
    setSrc: function(element,src) {
        element = $(element);
        element.src = src; 
    },
    setHref: function(element,href) {
        element = $(element);
        element.href = href; 
    },
    setInnerHTML: function(element,content) {
        element = $(element);
        element.innerHTML = content;
    }
});
// -----------------------------------------------------------------------------------


// From Internet
// -----------------------------------------------------------------------------------
//
//    主要用于从location.href字符串中提取GET参数
//
String.prototype.queryString = function(key){
    var sValue = this.match(new RegExp("[\?\&]"+key+"=([^\&]*)(\&?)","i"));
    var retval = (sValue ? sValue[1]:sValue);

    return decodeURIComponent(retval);
}

Object.extend(Object, {
    strftime: function(format, time_stamp) {
        if(!time_stamp) {
            time_stamp = earth.util.getTimeStamp();
        }

        var t = new Date(time_stamp * 1000);
        var retval = format;

        var Y = t.getFullYear().toString();
        var m = t.getMonth() + 1;m = m.toString();
        var d = t.getDate().toString();
        retval = retval.replace(/%Y/, Y);
        retval = retval.replace(/%m/, ((m.length==1)?('0' + m):m) );
        retval = retval.replace(/%d/, ((d.length==1)?('0' + d):d) );

        return retval;
    }
});

Array.prototype.insert = function(index, o) {
    for(i=this.length;i>index;i--) {
        this[i] = this[i - 1];
    }
    this[index] = o;
}
// -----------------------------------------------------------------------------------



// earth.util
// -----------------------------------------------------------------------------------
//
//    常用函数
//
earth.util = Class.create();


/**
 * 设置url为浏览器主页
 * 
 * @param object sender 使用这个函数的HTML元素
 * @param string url
 */
earth.util.setHomepage = function (sender, url) {
    try {
        sender.style.behavior='url(#default#homepage)';
        sender.setHomePage(url);
    } catch(e) {
        if(window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch(e) {
                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', url);
        }
    }
}

/**
 * 添加url到收藏夹
 * 
 * @param string title 默认标题
 * @param string url
 */
earth.util.addToFavorite = function (title, url) {
    try {
        window.external.addFavorite(url, title);
    } catch(e) {
        try {
            window.sidebar.addPanel(title, url, '');
        } catch(e) {
            alert("加入收藏失败，请使用Ctrl+D进行添加");
        }
    }
}


/**
 * 设置Cookie变量值
 * 
 * @param string key 变量名
 * @param mixed value 变量值
 * @param integer expire 多长时间后超时（单位：秒）
 */
earth.util.setCookie = function(key, value, expire) {
    var currentTimeStamp = earth.util.getTimeStamp();
    var expireDate = new Date();
    expireDate.setTime((currentTimeStamp + expire) * 1000);
    document.cookie = key + "=" + escape(value) + ((!expire) ? "" : ";expires=" + expireDate.toGMTString());
}


/**
 * 获取Cookie变量值
 * 
 * @param string key 变量名
 * @return mixed
 */
earth.util.getCookie = function(key) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(key + "=");
        if (c_start != -1) { 
            c_start = c_start + key.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 "";
}


/**
 * 获取当前模型的BODY元素。
 * 
 * @return HtmlElement
 */
earth.util.getBodyElement = function() {
    var bodyElements = document.documentElement.getElementsByTagName('body');
    if(bodyElements.length<1) {
        alert('Cannot get body element!');
    }

    var bodyElement = bodyElements[0];
    return bodyElement;
};



/**
 * 获取当前模型的HEAD元素。
 * 
 * @return HtmlElement
 */
earth.util.getHeadElement = function() {
    var headElements = document.documentElement.getElementsByTagName('head');
    if(headElements.length<1) {
        alert('Cannot get head element!');
    }

    var headElement = headElements[0];
    return headElement;
};


/**
 * 获取当前时间戳记。
 * 
 * @return integer
 */
earth.util.getTimeStamp = function() {
    return (Date.parse(new Date()) / 1000);
};



//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
earth.util.getPageSize = function(){
    
    var xScroll, yScroll;
    
    if (window.innerHeight && window.scrollMaxY) {    
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    
    var windowWidth, windowHeight;
    if (self.innerHeight) {    // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }    
    
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else { 
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){    
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }


    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
    return arrayPageSize;
}


//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
earth.util.getPageScroll = function(){

    var yScroll;

    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){     // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
    }

    arrayPageScroll = new Array('',yScroll) 
    return arrayPageScroll;
}


earth.util.getDomain = function() {
    var resultArray = location.href.match(/[0-9a-zA-Z]+(\.[0-9a-zA-Z]+)+/g);
    if(resultArray.length <= 0) {
        alert('To developer: 无法获得当前页所在的域名，请检查earth.util.getDomain函数的正则表达式是否过于简单。');
        return '';
    }
    return resultArray[0];
};

earth.util.preloadImage = function(url) {
	var img = new Image();
	img.src = url;
};


// -----------------------------------------------------------------------------------






// earth.controls
// -----------------------------------------------------------------------------------
//
//    控件集合
//
earth.controls = Class.create();


/**
 * 列表
 */
earth.controls.list = Class.create();
earth.controls.list.prototype.initialize = function(htmlId, loader, builder) {
    this.htmlId = htmlId;
    this.loader = loader;
    this.builder = builder;
    this.page = 1;
    this.items = new Array();
    this.empty = true;

    var classInstance = this;
};
earth.controls.list.prototype.load = function(append, before, reverse) {
    var classInstance = this;

    this.loader.load(this.page, function(responseValues) {
        if(responseValues.code < 0) {
            alert(responseValues.string);
            return false;
        }

        // 没有返回任何数据
        if(responseValues.data.length == 0) {
            if(classInstance.empty && classInstance.items.length == 0) {
                classInstance.innerAppend(classInstance.builder.build());
            }
            return false;
        }

        var responseData = responseValues.data.slice(0);// clone
        if(reverse) {
            responseData.reverse();
        }

        // 追加
        if(append) {
            // 在前面追加
            if(before) {
                for(i=0;i<responseData.length;i++) {
                    classInstance.insert(i, classInstance.builder.build(responseData[i]));
                }
            } else {
                for(i=0;i<responseData.length;i++) {
                    classInstance.append(classInstance.builder.build(responseData[i]));
                }
            }
        } else {
            classInstance.innerClear();
            for(i=0;i<responseData.length;i++) {
                classInstance.append(classInstance.builder.build(responseData[i]));
            }
        }
    });
};
earth.controls.list.prototype.loadNextPage = function(append, before, reverse) {
    this.page++;
    this.load(append, before, reverse);
};
earth.controls.list.prototype.loadPrevPage = function(append, before, reverse) {
    this.page--;
    this.load(append, before, reverse);
};
/* 私有函数 */
earth.controls.list.prototype.innerAppend = function(item) {
	if(!item) {
		return;
	}

    var bodyElement = earth.util.getBodyElement();

    this.items.push(item);

    var o = $(item.getHtmlId());
    bodyElement.removeChild(o);
    $(this.htmlId).appendChild(o);
    o.style.display = '';
};
earth.controls.list.prototype.append = function(item) {
    // 清除空元素
    if(this.empty) {
        this.innerClear();
    }

    this.innerAppend(item);

    this.empty = false;
};
earth.controls.list.prototype.insert = function(index, item) {
    var bodyElement = earth.util.getBodyElement();

    // 清除空元素
    if(this.empty) {
        this.innerClear();
    }

    this.items.insert(index, item);

    var o = $(item.getHtmlId());
    var l = $(this.htmlId);
    bodyElement.removeChild(o);
    if(!l.childNodes[index]) {
        l.appendChild(o);
    } else {
        l.insertBefore(o, l.childNodes[index]);
    }
    o.style.display = '';

    this.empty = false;
};
/* 私有函数 */
earth.controls.list.prototype.innerClear = function() {
    this.items.clear();

    while($(this.htmlId).hasChildNodes()) {
        $(this.htmlId).removeChild($(this.htmlId).firstChild);
    }
};
earth.controls.list.prototype.removeAt = function(index) {
    if(this.empty) {
        return;
    }

    var a = this.items.splice(index, 1);
    $(this.htmlId).removeChild($(a[0].getHtmlId()));

    if(this.items.length == 0) {
        this.innerAppend(this.builder.build());

        this.empty = true;
    }
}
earth.controls.list.prototype.remove = function(item) {
    var index = -1;
    for(i=0;i<this.items.length;i++) {
        if(this.items[i] == item) {
            index = i;
            break;
        }
    }

    if(index >= 0) {
        this.removeAt(index);
    }
}


/**
 * 列表项
 */
earth.controls.list.item = Class.create();
earth.controls.list.item.prototype.initialize = function(values) {
    this.values = values;
    this.htmlId = 'ListItem' + Math.round(Math.random() * 1000000);
    var classInstance = this;

    if(this.onInitializing) {
        if(this.onInitializing()) {
            return false;
        }
    }

    this.create();
    
    if(this.onInitialized) {
        this.onInitialized();
    }
};
earth.controls.list.item.prototype.getHtmlId = function() {
    return this.htmlId;
};
earth.controls.list.item.prototype.create = function() {
    if(!this.buildElement) {
        alert("无法找到私有方法this.buildElement。");
        return;
    }
    
    var oElement = this.buildElement();
    oElement.id = this.htmlId;
    oElement.style.display = 'none';


    var bodyElement = earth.util.getBodyElement();
    bodyElement.appendChild(oElement);
};


/**
 * 加载器
 */
earth.controls.list.loader = Class.create();
earth.controls.list.loader.prototype.initialize = function(url, params, size) {
    this.url = url;
    this.params = params;
    this.size = size;

    this.loadedEventQueue = new Array();

}
earth.controls.list.loader.prototype.load = function(page, onLoaded) {
    var pageParams = "page=" + encodeURIComponent(page) + "&size=" + encodeURIComponent(this.size);
    var p;
    var classInstance = this;

    if(this.params) {
        p = this.params + "&" + pageParams;
    } else {
        p = pageParams;
    }

    new Ajax.Request
    (
        this.url,
        {
            method: 'post',
            parameters: p,
            onComplete: function(transport) {
                eval("var responseValues = " + transport.responseText);

                if(onLoaded) {
                    onLoaded(responseValues);
                }
                
                for (i=0;i<classInstance.loadedEventQueue.length;i++) {
                    classInstance.loadedEventQueue[i](responseValues);
                }
            }
        }
    );
}
earth.controls.list.loader.prototype.attachLoadedEvent = function(eventHandler) {
    this.loadedEventQueue[this.loadedEventQueue.length] = eventHandler;
};
earth.controls.list.loader.prototype.setParams = function(params) {
    this.params = params;
}


/**
 * 列表项构造者
 */
earth.controls.list.builder = Class.create();
earth.controls.list.builder.prototype.initialize = function() {
};
earth.controls.list.builder.prototype.build = function(values) {
    if(!values) {
        return new earth.controls.list.item(values);
    }
}

/**
 * 搜索输入框
 */
earth.controls.searchInput = Class.create();
earth.controls.searchInput.prototype.initialize = function(htmlId, defaultValue, defaultColor, alternateColor) {
    this.htmlId = htmlId;
    this.defaultValue = defaultValue;
    this.defaultColor = (defaultColor?defaultColor:'#cccccc');
    this.alternateColor = (alternateColor?alternateColor:'#000000');
    this.isFocused = false;

    var classInstance = this;

    this.inputElement = $(this.htmlId);
    if(!this.inputElement) {
        return false;
    }

    this.inputElement.style.color = this.defaultColor;
    if(!this.inputElement.value) {
        this.inputElement.value = this.defaultValue;
    }

    this.inputElement.onmouseover = function() {
        classInstance.inputElement.style.color = classInstance.alternateColor;
    };
    this.inputElement.onmouseout = function() {
        if(!classInstance.isFocused) {
            classInstance.inputElement.style.color = classInstance.defaultColor;
        }
    };
    this.inputElement.onfocus = function() {
        if(classInstance.inputElement.value == classInstance.defaultValue) {
            classInstance.inputElement.value = '';
        }

        classInstance.isFocused = true;
    };
    this.inputElement.onblur = function() {
        if(classInstance.inputElement.value == '') {
            classInstance.inputElement.value = classInstance.defaultValue;
        }

        classInstance.isFocused = false;
        classInstance.inputElement.style.color = classInstance.defaultColor;
    };
};


/** 
 * 对话框基类
 *
 * 子类必须要重载buildDialogElement()方法，用于创建对话框元素并返回。<br />
 *
 * @author Timandes
 */
earth.controls.dialog = Class.create();

/**
 * 初始化函数
 *
 * @param string htmlId 对话款的HTML ID
 */
earth.controls.dialog.prototype.initialize = function(htmlId) {
    this.htmlId = htmlId;

    // custom init
    if(this.onInitializing) {
        this.onInitializing();
    }

    this.create();

    var classInstance = this;

    // close button
    this.closeButtonElement = $(this.htmlId + '_CloseButton');
    if(this.closeButtonElement) {
        this.closeButtonElement.onclick = function() {
            if(classInstance.hideOnClose) {
                classInstance.hide();
            } else {
                classInstance.close();
            }
        }
    }

    // custom init
    if(this.onInitialized) {
        this.onInitialized();
    }
}

earth.controls.dialog.prototype.create = function() {
    if(this.lockWindow) {
        this.createMask();
    }

    this.createDialog();
}



earth.controls.dialog.prototype.createMask = function() {
    var bodyElement = earth.util.getBodyElement();

    var maskId = this.htmlId + '_Mask';
    var maskElement = document.createElement('div');
    maskElement.id = maskId;
    maskElement.style.display = 'none';
    maskElement.style.backgroundColor = '#333333';
    maskElement.style.position = 'absolute';
    maskElement.style.top = '0';
    maskElement.style.left = '0';
    maskElement.style.zIndex = 1000;
    bodyElement.appendChild(maskElement);
};

earth.controls.dialog.prototype.createDialog = function() {
    if(!this.buildDialogElement) {
        alert('Function buildDialogElement is missing!');
        return;
    }

    var bodyElement = earth.util.getBodyElement();

    var dialogElement = this.buildDialogElement();
    dialogElement.id = this.htmlId;
    dialogElement.style.display = 'none';
    dialogElement.style.backgroundColor = '#ffffff';
    dialogElement.style.position = 'absolute';
    dialogElement.style.zIndex = 1001;
    bodyElement.appendChild(dialogElement);
};

/* 显示对话框。
*/
earth.controls.dialog.prototype.show = function() {
    var classInstance = this;

    var maskId = this.htmlId + '_Mask';
    var dialogId = this.htmlId;

    // calculate size of dialog
    var arrayPageSize = earth.util.getPageSize();
    var arrayPageScroll = earth.util.getPageScroll();
    var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 5);
    var iDialogLeft = (arrayPageSize[0] - parseInt($(dialogId).style.width)) / 2;
    Element.setLeft(dialogId, iDialogLeft);
    Element.setTop(dialogId, lightboxTop);


    if(this.lockWindow) {
        // display mask
        var arrayPageSize = earth.util.getPageSize();
        var maskWidth = arrayPageSize[0];
        if(screen.availWidth == arrayPageSize[0]) {
        if(document.documentElement) {// non-IE
            if(document.documentElement.scrollHeight > document.documentElement.clientHeight) {// has vertical scroll
    			maskWidth = arrayPageSize[0] - 17;
            }
        }
        }
        var maskHeight = arrayPageSize[1];
        if(document.all) { // IE
            maskHeight = arrayPageSize[1] + 30;
        }
        Element.setWidth(maskId, maskWidth);
        Element.setHeight(maskId, maskHeight);
        new Effect.Appear(maskId, { duration: 0.2, from: 0.0, to: 0.8, afterFinish: function() {
            // display dialog
            new Effect.Appear(dialogId, { duration: 0.5, queue: 'end', afterFinish: function() {
                if(classInstance.onShown) {
                    classInstance.onShown();
                }
            }
            });
        }
        });
    } else {
        // display dialog
        new Effect.Appear(dialogId, { duration: 0.5, queue: 'end', afterFinish: function() {
            if(classInstance.onShown) {
                classInstance.onShown();
            }
        }
        });
    }
};

/* 隐藏对话框。
*/
earth.controls.dialog.prototype.hide = function() {
    var maskId = this.htmlId + '_Mask';
    var dialogId = this.htmlId;

    var classInstance = this;

    new Effect.Fade(dialogId, { duration: 0.2, afterFinish: function(){
        if(classInstance.lockWindow) {
            new Effect.Fade(maskId, { duration: 0.2});
        }
    }
    });
};


/* 关闭对话框。
*/
earth.controls.dialog.prototype.close = function() {
    var maskId = this.htmlId + '_Mask';
    var dialogId = this.htmlId;

    var classInstance = this;

    var dialogElement = $(this.htmlId);
    if(!dialogElement) {
        return false;
    }

    var bodyElement = earth.util.getBodyElement();

    new Effect.Fade(dialogId, { duration: 0.2, afterFinish: function(){
        if(classInstance.lockWindow) {
            new Effect.Fade(maskId, { duration: 0.2, afterFinish: function(){
                bodyElement.removeChild(dialogElement);
            }
            });
        } else {
            bodyElement.removeChild(dialogElement);
        }
    }
    });
};


/**
 * Tab页
 */
earth.controls.tabPage = Class.create();
earth.controls.tabPage.prototype.initialize = function(htmlId, onLoad, activeCssClass, inactiveCssClass, hoverCssClass) {
    this.htmlId = htmlId;
    this.onLoad = onLoad;
    this.activeCssClass = (activeCssClass?activeCssClass:"");
    this.inactiveCssClass = (inactiveCssClass?inactiveCssClass:"");
    this.hoverCssClass = (hoverCssClass?hoverCssClass:"");
    this.loaded = false;
    this.tabControl = null;
    this.enabled = true;

    if(!$(this.htmlId) && !$(this.htmlId + '_Tab')) {
        return false;
    }

    var classInstance = this;

    $(this.htmlId + '_Page').style.display = 'none';
    $(this.htmlId + '_Tab').className = this.inactiveCssClass;

    if($(this.htmlId)) {
        Event.observe($(this.htmlId), 'click', function(event) {
            if(classInstance.enabled) {
                classInstance.tabControl.activateTabPage(classInstance);
            }
        });
    } else {
        Event.observe($(this.htmlId + '_Tab'), 'click', function(event) {
            if(classInstance.enabled) {
                classInstance.tabControl.activateTabPage(classInstance);
            }
        });
        $(this.htmlId + '_Tab').style.cursor = 'pointer';
        Event.observe($(this.htmlId + '_Tab'), 'mouseover', function(event) {
            if($(classInstance.htmlId + '_Page').style.display != '' && classInstance.enabled) {
                $(classInstance.htmlId + '_Tab').className = classInstance.hoverCssClass;
            }
        });
        Event.observe($(this.htmlId + '_Tab'), 'mouseout', function(event) {
            if($(classInstance.htmlId + '_Page').style.display != '' && classInstance.enabled) {
                $(classInstance.htmlId + '_Tab').className = classInstance.inactiveCssClass;
            }
        });
    }
};
earth.controls.tabPage.prototype.setParent = function(tabControl) {
    this.tabControl = tabControl;
};
earth.controls.tabPage.prototype.activate = function() {
    $(this.htmlId + '_Page').style.display = '';
    $(this.htmlId + '_Tab').className = this.activeCssClass;

    if(!this.loaded && this.onLoad) {
        this.tabControl.setEnabled(false);
        this.onLoad();
        this.loaded = true;
        this.tabControl.setEnabled(true);
    }
};
earth.controls.tabPage.prototype.inactivate = function() {
    $(this.htmlId + '_Page').style.display = 'none';
    $(this.htmlId + '_Tab').className = this.inactiveCssClass;
};
earth.controls.tabPage.prototype.setEnabled = function(enabled) {
    this.enabled = enabled;
};



/**
 * Tab控件
 */
earth.controls.tabControl = Class.create();
earth.controls.tabControl.prototype.initialize = function() {
    this.activeTabPage = null;
    this.tabPages = new Array();
};
earth.controls.tabControl.prototype.addTabPage = function(tabPage) {
    tabPage.setParent(this);
    this.tabPages.push(tabPage);

    if(!this.activeTabPage) {
        this.activeTabPage = tabPage;
        tabPage.activate();
    }
};
earth.controls.tabControl.prototype.activateTabPage = function(tabPage) {
    if(this.activeTabPage == tabPage) {
        return;
    }

    tabPage.activate();

    if(this.activeTabPage) {
        this.activeTabPage.inactivate();
    }

    this.activeTabPage = tabPage;
};
earth.controls.tabControl.prototype.setEnabled = function(enabled) {
    for(var i=0;i<this.tabPages.length;i++) {
        this.tabPages[i].setEnabled(enabled);
    }
};



/**
 * 自动伸缩高度的Tab页
 */
earth.controls.autoScaleTabPage = Class.create();
earth.controls.autoScaleTabPage.prototype.initialize = function(htmlId, maxHeight) {
    this.htmlId = htmlId;          // 当前块ID
    this.maxHeight = maxHeight;    // 当前块可以展开的最大高度
    this.speed = 30;               // 动作速度
    this.beginScaleEventQueue = new Array();
    this.action = 0;                // 1-collapsing; 2-expanding

    var classInstance = this;

    if(!$(this.htmlId)) {
        return false;
    }

    var tabLayer = $(this.htmlId);
    this.titleLayer = tabLayer.getElementsByTagName('dt')[0];
    this.contentLayer = tabLayer.getElementsByTagName('dd')[0];

    Event.observe(this.titleLayer, 'click', function(event) {
        classInstance.onBeginScale();
    });
/*
    Event.observe(this.titleLayer, 'mouseover', function(event) {
        classInstance.onBeginScale();
    });*/
};
earth.controls.autoScaleTabPage.prototype.onBeginScale = function() {
    for(i=0;i<this.beginScaleEventQueue.length;i++) {
        this.beginScaleEventQueue[i](this);
    }
};
earth.controls.autoScaleTabPage.prototype.attachBeginScaleEvent = function(eventHandler) {
    this.beginScaleEventQueue.push(eventHandler);
};
earth.controls.autoScaleTabPage.prototype.expand = function() {
	var maxHeight = this.maxHeight;
	var moveBy = this.speed;
	var mainInstance = this;
	var tabLayer = $(this.htmlId);
/*
    switch(this.action) {
        default:
        case 0:
            this.action = 2;
            break;
        case 1:
            this.action = 2;
            clearInterval(this.timer);
            break;
        case 2:
            break;
    }*/

    var fun = function() {
		var curHeight = tabLayer.offsetHeight;
		var newHeight = curHeight + moveBy;
		if (newHeight < maxHeight) {
			tabLayer.style.height = newHeight + "px";
            setTimeout(fun, 30);
        } else {
            mainInstance.action = 0;
			tabLayer.style.height = maxHeight + "px";
		}
	};
	setTimeout(fun, 30);
};
earth.controls.autoScaleTabPage.prototype.collapse = function() {
	var minHeight = this.titleLayer.offsetHeight;
	var moveBy = this.speed;
	var mainInstance = this;
	var tabLayer = $(this.htmlId);
/*
    switch(this.action) {
        default:
        case 0:
            this.action = 1;
            break;
        case 1:
            break;
        case 2:
            this.action = 1;
            clearInterval(this.timer);
            break;
    }*/

    var fun = function() {
		var curHeight = tabLayer.offsetHeight;
		var newHeight = curHeight - moveBy;
		if (newHeight > minHeight) {
			tabLayer.style.height = newHeight + "px";
            setTimeout(fun, 30);
        } else {
            mainInstance.action = 0;
			tabLayer.style.height = minHeight + "px";
		}
	};
	setTimeout(fun, 30);
};
earth.controls.autoScaleTabPage.prototype.getHtmlId = function() {
    return this.htmlId;
};


/**
 * 自动伸缩高度的Tab页
 */
earth.controls.autoSwitchTabControl = Class.create();
earth.controls.autoSwitchTabControl.prototype.initialize = function() {
    this.tabPages = new Array();
};
earth.controls.autoSwitchTabControl.prototype.add = function(tabPage) {
    var classInstance = this;

    tabPage.attachBeginScaleEvent(function(senderTabPage) {
        senderTabPage.expand();
        for(i=0;i<classInstance.tabPages.length;i++) {
            var tp = classInstance.tabPages[i];
            if(tp.getHtmlId() != senderTabPage.getHtmlId()) {
                tp.collapse();
            }
        }
    });
    this.tabPages.push(tabPage);
};


/**
 * Motion Tab Page
 */
earth.controls.motionTabPage = Class.create();
earth.controls.motionTabPage.prototype.initialize = function(rank, htmlId) {
    this.htmlId = htmlId;
    this.rank = rank;
    this.speed = 30;
    this.beginMoveingEventQueue = new Array();

    var classInstance = this;

    if(!$(this.htmlId)) {
        return false;
    }

    var tabLayer = $(this.htmlId);
    this.titleLayer = tabLayer.getElementsByTagName('dt')[0];
    this.contentLayer = tabLayer.getElementsByTagName('dd')[0];

    Event.observe(this.titleLayer, 'click', function(event) {
        classInstance.onBeginMoving();
    });

    Event.observe(this.titleLayer, 'mouseover', function(event) {
        classInstance.onBeginMoving();
    });
};
earth.controls.motionTabPage.prototype.onBeginMoving = function() {
    for(i=0;i<this.beginMoveingEventQueue.length;i++) {
        this.beginMoveingEventQueue[i](this);
    }
};
earth.controls.motionTabPage.prototype.attachBeginMovingEvent = function(eventHandler) {
    this.beginMoveingEventQueue.push(eventHandler);
};
earth.controls.motionTabPage.prototype.moveUp = function() {
    var minTop = this.rank * this.titleLayer.offsetHeight;
	var moveBy = this.speed;
	var classInstance = this;
	var tabLayer = $(this.htmlId);

    var fun = function() {
        var newTop = tabLayer.offsetTop - moveBy;
        if(minTop < newTop) {
            tabLayer.style.top = newTop + "px";
            setTimeout(fun, 30);
        } else {
            tabLayer.style.top = minTop + "px";
        }
	};
	setTimeout(fun, 30);
};
earth.controls.motionTabPage.prototype.moveDown = function() {
    var maxTop = (this.rank - 1) * this.titleLayer.offsetHeight + $(this.htmlId).offsetHeight;
	var moveBy = this.speed;
	var classInstance = this;
	var tabLayer = $(this.htmlId);

    var fun = function() {
        var newTop = tabLayer.offsetTop + moveBy;
        if(maxTop > newTop) {
            tabLayer.style.top = newTop + "px";
            setTimeout(fun, 30);
        } else {
            tabLayer.style.top = maxTop + "px";
        }
	};
	setTimeout(fun, 30);
};
earth.controls.motionTabPage.prototype.getHtmlId = function() {
    return this.htmlId;
};


/**
 * Motion Tab Control
 */
earth.controls.motionTabControl = Class.create();
earth.controls.motionTabControl.prototype.initialize = function() {
    this.tabPages = new Array();
    this.selectedTabPage = null;
};
earth.controls.motionTabControl.prototype.add = function(tabPage) {
    var classInstance = this;

    tabPage.attachBeginMovingEvent(function(senderTabPage) {
        var senderIndex = classInstance.getIndex(senderTabPage);
        var selectedIndex = classInstance.getIndex(classInstance.selectedTabPage);

        if(senderIndex < 0) {
            return;
        }

        if(selectedIndex < senderIndex) {
            for(i=0;i<=senderIndex;i++) {
                classInstance.tabPages[i].moveUp();
            }
        } else {
            for(i=senderIndex+1;i<classInstance.tabPages.length;i++) {
                classInstance.tabPages[i].moveDown();
            }
        }

        classInstance.selectedTabPage = senderTabPage;
    });
    this.tabPages.push(tabPage);

    if(!this.selectedTabPage) {
        this.selectedTabPage = tabPage;
    }
};
earth.controls.motionTabControl.prototype.getIndex = function(tabPage) {
    if(!tabPage) {
        return -1;
    }

    var retval = -1;

    for(i=0;i<this.tabPages.length;i++) {
        var tp = this.tabPages[i];
        if(tp.getHtmlId() == tabPage.getHtmlId()) {
            retval = i;
            break;
        }
    }
    
    return retval;
}
// -----------------------------------------------------------------------------------

