var boxIndex = 0; //id
var autoScrollActive = false; //拖动模块超出边框后，是否还需要移动
var quchaBoxesArray = new Array(); //纪录拖动模块信息的数组
var dragDropCounter = -1;
var dragObject = false; //当前拖动的对象
var dragObjectNextSibling = false; //拖动对象的兄弟节点
var dragObjectParent = false; //拖动对象的父节点
var destinationObj = false; //拖动对象的目标位置
var mouse_x; //鼠标x
var mouse_y; //鼠标y
var el_x; //当前窗体的x
var el_y; //当前窗体的y
var rectangleDiv; //拖动后显示的 预计存放位置
var okToMove = true; //是否移动
var documentHeight = false; //屏幕高
var documentScrollHeight = false; //滚动条高
//是否是opera浏览器	
var opera = navigator.userAgent.toLowerCase().indexOf('opera') >= 0 ? true : false;
var cookieCounter = 0; //cookie 数量，也是窗体数量
var cookieRSSSources = new Array(); //纪录的rss相关信息
var staticObjectArray = new Array(); //存储静态窗体数组的信息
var column = 2;

function mouseover_CloseButton()//鼠标划过关闭按钮
{
    this.className = 'closeButton_over';
    setTimeout('dragDropCounter=-5', 5);
}
function mouseout_CloseButton()//鼠标离开关闭按钮
{
    this.className = 'closeButton';
}
function closequchaBox(e, inputObj)//关闭一个小窗体
{
    if (window.confirm('关闭订阅器将会删除订阅器，您确定吗？') == false) {
        return;
    }
    if (!inputObj) inputObj = this;
    var numericId = inputObj.id.replace(/[^0-9]/g, ''); //窗体id
    $('quchaBox' + numericId).style.display = 'none';
    //存储信息
    Set_Cookie('qucha_rss_boxes' + cookieRSSSources[quchaBoxesArray[numericId]['rssUrl']], '', -500);
    setTimeout('dragDropCounter=-5', 5);
}
//单击编辑（结束编辑）按钮后触发的事件
function editRSSContent() {
    var numericId = this.id.replace(/[^0-9]/g, ''); //id
    var obj = $('quchaBoxEdit' + numericId);
    if (obj.style.display == 'none')//显示编辑界面
    {
        obj.style.display = 'block';
        this.innerHTML = '结束编辑';
        $('quchaBoxHeader' + numericId).style.height = 'auto';
    }
    else//结束编辑
    {
        obj.style.display = 'none';
        this.innerHTML = '编辑';
        $('quchaBoxHeader' + numericId).style.height = '20px';
    }
    setTimeout('dragDropCounter=-5', 5);
}
//广告条显示广告
function showStatusBarMessage(numericId, message) {
    //$('quchaBoxAdBar' + numericId).innerHTML = message;
}
//当拖动窗体模块的位置超出屏幕时，控制窗体模块定时移动
function autoScroll(direction, yPos) {
    if (document.documentElement.scrollHeight > documentScrollHeight && direction > 0) return;
    if (opera) return;
    window.scrollBy(0, direction);
    if (!dragObject) return; //拖动对象为空，退出
    if (direction < 0) {
        if (document.documentElement.scrollTop > 0)//没有到达指定位置，移动
        {
            dragObject.style.top = (el_y - mouse_y + yPos + document.documentElement.scrollTop) + 'px';
        }
        else//到达指定位置
        {
            autoScrollActive = false;
        }
    }
    else {
        if (yPos > (documentHeight - 50))//没有到达指定位置，移动
        {
            dragObject.style.top = (el_y - mouse_y + yPos + document.documentElement.scrollTop) + 'px';
        }
        else {
            autoScrollActive = false;
        }
    }
    //需要移动，则继续移动
    if (autoScrollActive) setTimeout('autoScroll(' + direction + ',' + yPos + ')', 5);
}
//鼠标在拖动模块的头部按下时，拖动开始初始化	
function initDragDropBox(e) {
    dragDropCounter = 1;
    if (document.all) e = event;
    if (e.target) source = e.target; //事件的目标
    else if (e.srcElement) source = e.srcElement;
    if (source.nodeType == column)
        source = source.parentNode;
    if (source.tagName.toLowerCase() == 'img' || source.tagName.toLowerCase() == 'a' || source.tagName.toLowerCase() == 'input' || source.tagName.toLowerCase() == 'td' || source.tagName.toLowerCase() == 'tr' || source.tagName.toLowerCase() == 'table') return;
    mouse_x = e.clientX; //鼠标x
    mouse_y = e.clientY; //鼠标y	
    var numericId = this.id.replace(/[^0-9]/g, ''); //id
    el_x = getLeftPos(this.parentNode.parentNode) / 1; //本模块的x
    el_y = getTopPos(this.parentNode.parentNode) / 1 - document.documentElement.scrollTop; //本模块的y
    dragObject = this.parentNode.parentNode; //拖动对象
    documentScrollHeight = document.documentElement.scrollHeight + 100 + dragObject.offsetHeight;
    if (dragObject.nextSibling) {
        dragObjectNextSibling = dragObject.nextSibling;
        if (dragObjectNextSibling.tagName != 'DIV') dragObjectNextSibling = dragObjectNextSibling.nextSibling;
    }
    dragObjectParent = quchaBoxesArray[numericId]['parentObj'];
    dragDropCounter = 0;
    initDragDropBoxTimer(); //初始化拖动延时器
    return false;
}
//初始化拖动延时器
function initDragDropBoxTimer() {
    if (dragDropCounter >= 0 && dragDropCounter < 10) {
        dragDropCounter++;
        setTimeout('initDragDropBoxTimer()', 10);
        return;
    }
    if (dragDropCounter == 10)//头部编辑等按钮隐藏
    {
        mouseoutBoxHeader(false, dragObject);
    }
}
//移动一个窗体时
function movequchaElement(e) {
    if (document.all) e = event;
    if (dragDropCounter < 10) return;
    if (document.all && e.button != 1 && !opera)//停止移动
    {
        stop_dragDropElement();
        return;
    }
    if (document.body != dragObject.parentNode)//拖动对象的父亲节点不是body对象
    {
        dragObject.style.width = (dragObject.offsetWidth - (1 * 2)) + 'px';
        dragObject.style.position = 'absolute';
        dragObject.style.textAlign = 'left';
        //拖动对象的滤镜效果
        dragObject.style.filter = 'alpha(opacity=70)';
        dragObject.style.opacity = '0.7';
        //目标位置暂时在原位置
        dragObject.parentNode.insertBefore(rectangleDiv, dragObject);
        rectangleDiv.style.display = 'block'; //目标位置对象显示
        document.body.appendChild(dragObject);
        rectangleDiv.style.width = dragObject.style.width;
        rectangleDiv.style.height = (dragObject.offsetHeight - (1 * 2)) + 'px';
    }
    if (e.clientY < 50 || e.clientY > (documentHeight - 50))//需要自动上下移动
    {
        if (e.clientY < 50 && !autoScrollActive)//需要自动向上移动
        {
            autoScrollActive = true;
            autoScroll((4 * -1), e.clientY);
        }
        //需要自动向下移动
        if (e.clientY > (documentHeight - 50) && document.documentElement.scrollHeight <= documentScrollHeight && !autoScrollActive) {
            autoScrollActive = true;
            autoScroll(4, e.clientY);
        }
    }
    else {
        autoScrollActive = false;
    }
    var leftPos = e.clientX; //x轴位置
    var topPos = e.clientY + document.documentElement.scrollTop; //y轴位置
    dragObject.style.left = (e.clientX - mouse_x + el_x) + 'px';
    dragObject.style.top = (el_y - mouse_y + e.clientY + document.documentElement.scrollTop) + 'px';
    if (!okToMove) return;
    okToMove = false;
    destinationObj = false; //目标对象
    rectangleDiv.style.display = 'none';
    var objFound = false; //是够找到目标位置
    var tmpParentArray = new Array();
    if (!objFound)//目标位置没有找到
    {
        for (var no = 1; no < quchaBoxesArray.length; no++)//遍历每个拖动模块
        {
            if (quchaBoxesArray[no]['obj'] == dragObject) continue;
            tmpParentArray[quchaBoxesArray[no]['obj'].parentNode.id] = true;
            if (!objFound) {
                var tmpX = getLeftPos(quchaBoxesArray[no]['obj']); //本模块的x
                var tmpY = getTopPos(quchaBoxesArray[no]['obj']); //本模块的y
                //分别三种情况，找到目标位置
                if (leftPos > tmpX && leftPos < (tmpX + quchaBoxesArray[no]['obj'].offsetWidth) && topPos > (tmpY - 20) && topPos < (tmpY + (quchaBoxesArray[no]['obj'].offsetHeight / 2))) {
                    destinationObj = quchaBoxesArray[no]['obj'];
                    destinationObj.parentNode.insertBefore(rectangleDiv, quchaBoxesArray[no]['obj']);
                    rectangleDiv.style.display = 'block';
                    objFound = true;
                    break;
                }
                if (leftPos > tmpX && leftPos < (tmpX + quchaBoxesArray[no]['obj'].offsetWidth) && topPos >= (tmpY + (quchaBoxesArray[no]['obj'].offsetHeight / 2)) && topPos < (tmpY + quchaBoxesArray[no]['obj'].offsetHeight)) {
                    objFound = true;
                    if (quchaBoxesArray[no]['obj'].nextSibling) {
                        destinationObj = quchaBoxesArray[no]['obj'].nextSibling;
                        if (!destinationObj.tagName) destinationObj = destinationObj.nextSibling;
                        if (destinationObj != rectangleDiv) destinationObj.parentNode.insertBefore(rectangleDiv, destinationObj);
                    }
                    else {
                        destinationObj = quchaBoxesArray[no]['obj'].parentNode;
                        quchaBoxesArray[no]['obj'].parentNode.appendChild(rectangleDiv);
                    }
                    rectangleDiv.style.display = 'block';
                    break;
                }
                if (!quchaBoxesArray[no]['obj'].nextSibling && leftPos > tmpX && leftPos < (tmpX + quchaBoxesArray[no]['obj'].offsetWidth)
					&& topPos > topPos > (tmpY + (quchaBoxesArray[no]['obj'].offsetHeight))) {
                    destinationObj = quchaBoxesArray[no]['obj'].parentNode;
                    quchaBoxesArray[no]['obj'].parentNode.appendChild(rectangleDiv);
                    rectangleDiv.style.display = 'block';
                    objFound = true;
                }
            }
        }
    }
    if (!objFound)//目标位置仍然没有找到
    {
        for (var no = 1; no <= column; no++)//遍历3个列
        {
            if (!objFound) {
                var obj = $('quchaBoxesColumn' + no);
                var left = getLeftPos(obj) / 1; //本列的x坐标						
                var width = obj.offsetWidth; //列宽
                if (leftPos > left && leftPos < (left + width))//目标位置为该列的底部
                {
                    destinationObj = obj;
                    obj.appendChild(rectangleDiv);
                    rectangleDiv.style.display = 'block';
                    objFound = true; 	//找到目标位置
                }
            }
        }
    }
    setTimeout('okToMove=true', 5);
}
//停止拖拽窗体
function stop_dragDropElement() {
    if (dragDropCounter < 10) {
        dragDropCounter = -1
        return;
    }
    dragDropCounter = -1;
    dragObject.style.filter = null; //停止屡镜显示
    dragObject.style.opacity = null;
    //位置	
    dragObject.style.position = 'static';
    dragObject.style.width = null;
    var numericId = dragObject.id.replace(/[^0-9]/g, ''); //id编号
    if (destinationObj && destinationObj.id != dragObject.id)//拖动对象停留到目标位置
    {
        if (destinationObj.id.indexOf('quchaBoxesColumn') >= 0)//目标对象是列元素，插入列的尾部
        {
            destinationObj.appendChild(dragObject);
            quchaBoxesArray[numericId]['parentObj'] = destinationObj;
        }
        else//否则插入目标元素的前面
        {
            destinationObj.parentNode.insertBefore(dragObject, destinationObj);
            quchaBoxesArray[numericId]['parentObj'] = destinationObj.parentNode;
        }
    }
    else//拖动对象返回原来位置
    {
        if (dragObjectNextSibling)//有兄弟节点，则插入到前面
        {
            dragObjectParent.insertBefore(dragObject, dragObjectNextSibling);
        }
        else//没有兄弟节点，直接添加
        {
            dragObjectParent.appendChild(dragObject);
        }
    }
    autoScrollActive = false;
    rectangleDiv.style.display = 'none'; //消失
    //和拖动相关的几个对象初始化
    dragObject = false;
    dragObjectNextSibling = false;
    destinationObj = false;
    setTimeout('saveCookies()', 100); //保存窗口信息
    documentHeight = document.documentElement.clientHeight;
}
function saveCookies()//保存cookie
{
    cookieCounter = 0;
    var tmpUrlArray = new Array();
    for (var no = 1; no <= column; no++)//遍历3列的各个窗口
    {
        var parentObj = $('quchaBoxesColumn' + no); //当前列
        var items = parentObj.getElementsByTagName('DIV'); //
        if (items.length == 0) continue;
        var item = items[0];
        var tmpItemArray = new Array();
        while (item)//找到每个拖动窗口
        {
            var boxIndex = item.id.replace(/[^0-9]/g, '');
            if (item.id != 'rectangleDiv') {
                tmpItemArray[tmpItemArray.length] = boxIndex;
            }
            item = item.nextSibling;
        }
        var columnIndex = no;
        //遍历当前列的各个窗口，存储他们的信息
        for (var no2 = tmpItemArray.length - 1; no2 >= 0; no2--) {
            var boxIndex = tmpItemArray[no2];
            var url = quchaBoxesArray[boxIndex]['rssUrl']; //url
            var heightOfBox = quchaBoxesArray[boxIndex]['heightOfBox']; //窗体高度
            var maxRssItems = quchaBoxesArray[boxIndex]['maxRssItems']; //显示的最多条数
            var minutesBeforeReload = quchaBoxesArray[boxIndex]['minutesBeforeReload']; //重新加载的间隔
            var keyid = quchaBoxesArray[boxIndex]['keyid']; //唯一标志
            var state = quchaBoxesArray[boxIndex]['boxState']; //窗口状态，展开还是收缩
            if (!tmpUrlArray[url])//有url则存储
            {
                tmpUrlArray[url] = true;
                Set_Cookie('qucha_rss_boxes' + cookieCounter, url + '#;#' + columnIndex + '#;#' + maxRssItems + '#;#' + heightOfBox + '#;#' + minutesBeforeReload + '#;#' + keyid + '#;#' + state, 60000);
                cookieRSSSources[url] = cookieCounter;
                cookieCounter++;
            }
            else {
                Set_Cookie('qucha_rss_boxes' + cookieCounter, '' + '#;#' + columnIndex + '#;#' + '' + '#;#' + heightOfBox + '#;#' + '' + '#;#' + keyid, 60000);
                cookieCounter++;
            }
        }
    }
}

//鼠标划过窗体头部
function mouseoverBoxHeader() {
    if (dragDropCounter == 10) return;
    var id = this.id.replace(/[^0-9]/g, '');
    $('quchaBoxExpand' + id).style.visibility = 'visible';
    $('quchaBoxRefreshSource' + id).style.visibility = 'visible';
    $('quchaBoxCloseLink' + id).style.visibility = 'visible';
    if ($('quchaBoxEditLink' + id))
        $('quchaBoxEditLink' + id).style.visibility = 'visible';
}
//鼠标移出窗体头部
function mouseoutBoxHeader(e, obj) {
    if (!obj) obj = this;
    var id = obj.id.replace(/[^0-9]/g, '');
    $('quchaBoxExpand' + id).style.visibility = 'hidden';
    $('quchaBoxRefreshSource' + id).style.visibility = 'hidden';
    $('quchaBoxCloseLink' + id).style.visibility = 'hidden';
    if ($('quchaBoxEditLink' + id)) $('quchaBoxEditLink' + id).style.visibility = 'hidden';
}
//显示（隐藏）一个窗体模块的内容
function showHideBoxContent(e, inputObj) {
    if (document.all) e = event; //event
    if (!inputObj) inputObj = this;
    var numericId = inputObj.id.replace(/[^0-9]/g, '');
    var obj = $('quchaBoxContent' + numericId); //窗体内容元素
    obj.style.display = inputObj.src.indexOf('images/arrow_right.gif') >= 0 ? 'none' : 'block'; //显示或者隐藏
    inputObj.src = inputObj.src.indexOf('images/arrow_right.gif') >= 0 ? 'images/arrow_down.gif' : 'images/arrow_right.gif'
    //拖动窗体数组中记录下状态
    quchaBoxesArray[numericId]['boxState'] = obj.style.display == 'block' ? 1 : 0;
    saveCookies(); //保存
    setTimeout('dragDropCounter=-5', 5);
}

//保存rss输入信息
function saveFeed(boxIndex) {
    //高度
    var heightOfBox = quchaBoxesArray[boxIndex]['heightOfBox'] = $('heightOfBox[' + boxIndex + ']').value;
    var intervalObj = quchaBoxesArray[boxIndex]['intervalObj']; //自动更新的间隔
    if (intervalObj) clearInterval(intervalObj); //清除上次设置
    if (heightOfBox && heightOfBox > 10)//设置高度
    {
        var contentObj = $('quchaBoxContent' + boxIndex);
        contentObj.style.height = heightOfBox + 'px';
        contentObj.setAttribute('heightOfBox', heightOfBox);
        contentObj.heightOfBox = heightOfBox;
        if (document.all) contentObj.style.overflowY = 'auto';
        else
            contentObj.style.overflow = '-moz-scrollbars-vertical;';
        if (opera) contentObj.style.overflow = 'auto';
    }
    //添加此rss模块的各种属性
    quchaBoxesArray[boxIndex]['rssUrl'] = $('rssUrl[' + boxIndex + ']').value;
    quchaBoxesArray[boxIndex]['heightOfBox'] = heightOfBox;
    quchaBoxesArray[boxIndex]['maxRssItems'] = $('maxRssItems[' + boxIndex + ']').value;
    quchaBoxesArray[boxIndex]['heightOfBox'] = $('heightOfBox[' + boxIndex + ']').value;
    quchaBoxesArray[boxIndex]['minutesBeforeReload'] = $('minutesBeforeReload[' + boxIndex + ']').value;
    //添加自动更新内容设置
    if (quchaBoxesArray[boxIndex]['minutesBeforeReload'] && quchaBoxesArray[boxIndex]['minutesBeforeReload'] > 5) {
        var tmpInterval = setInterval("refreshRSS(" + boxIndex + ")", (quchaBoxesArray[boxIndex]['minutesBeforeReload'] * 1000 * 60));
        quchaBoxesArray[boxIndex]['intervalObj'] = tmpInterval;
    }
    //重新加载rss数据
    refreshRSS(boxIndex);
    setTimeout('saveCookies()', 100);
}
//添加rss编辑选项
function addRSSEditContent(parentObj) {
    //编辑的超链接
    var editLink = document.createElement('A');
    editLink.href = '#';
    editLink.onclick = cancelEvent;
    editLink.style.cssText = 'float:right';
    editLink.style.styleFloat = 'right';
    editLink.id = 'quchaBoxEditLink' + boxIndex;
    editLink.innerHTML = '编辑';
    editLink.className = 'quchaBoxEditLink';
    editLink.style.cursor = 'pointer';
    editLink.style.visibility = 'hidden';
    editLink.onmousedown = editRSSContent;
    parentObj.appendChild(editLink);
    //编辑选项的父节点
    var editBox = document.createElement('DIV');
    editBox.style.clear = 'both';
    editBox.id = 'quchaBoxEdit' + boxIndex;
    editBox.style.display = 'none';

    //编辑的具体内容
    var content = '<form><table cellpadding="1" cellspacing="1" border="0" style="width:100%"><tr><td>RSS 源:<\/td><td><input type="text" id="rssUrl['
		+ boxIndex + ']" value="' + quchaBoxesArray[boxIndex]['rssUrl'] + '" size="38" maxlength="255"><\/td><\/tr>'
		+ '<tr><td>显示条数:<\/td><td ><input type="text" id="maxRssItems[' + boxIndex +
		']" onblur="this.value = this.value.replace(/[^0-9]/g,\'\');if(!this.value)this.value=' + quchaBoxesArray[boxIndex]['maxRssItems']
		+ '" value="' + quchaBoxesArray[boxIndex]['maxRssItems'] + '" size="2" maxlength="2"><\/td><\/tr><tr><td>固定高度:<\/td><td><input type="text" id="heightOfBox['
		+ boxIndex + ']" onblur="this.value = this.value.replace(/[^0-9]/g,\'\');if(!this.value)this.value=' + quchaBoxesArray[boxIndex]['heightOfBox']
		+ '" value="' + quchaBoxesArray[boxIndex]['heightOfBox'] + '" size="2" maxlength="3"><\/td><\/tr><tr>'
		+ '<tr><td>刷新间隔:<\/td><td ><input type="text" id="minutesBeforeReload[' + boxIndex +
		']" onblur="this.value = this.value.replace(/[^0-9]/g,\'\');if(!this.value || this.value/1<5)this.value=' +
		quchaBoxesArray[boxIndex]['minutesBeforeReload'] + '" value="' + quchaBoxesArray[boxIndex]['minutesBeforeReload'] + '" size="2" maxlength="3">分钟<\/td><\/tr>'
		+ '<tr><td><input type="button" onclick="saveFeed(' + boxIndex + ')" value="保存"><\/td><\/tr><\/table><\/form>';
    editBox.innerHTML = content;
    //添加编辑选项
    parentObj.appendChild(editBox);
}
//添加模块的头部
function addBoxHeader(parentObj, externalUrl, notDrabable) {
    var div = document.createElement('DIV'); //创建头部元素
    div.className = 'quchaBoxHeader';
    div.id = 'quchaBoxHeader' + boxIndex;
    div.onmouseover = mouseoverBoxHeader;
    div.onmouseout = mouseoutBoxHeader;
    if (!notDrabable)//可以拖动
    {
        div.onmousedown = initDragDropBox;
        div.style.cursor = 'move';
    }
    //创建展开、折叠图片按钮
    var image = document.createElement('IMG');
    image.id = 'quchaBoxExpand' + boxIndex;
    image.src = 'images/arrow_right.gif';
    image.style.visibility = 'hidden';
    image.style.cursor = 'pointer';
    image.onmousedown = showHideBoxContent;
    div.appendChild(image);
    //创建头部标题显示区域
    var textSpan = document.createElement('SPAN');
    textSpan.id = 'quchaBoxHeader_txt' + boxIndex;
    div.appendChild(textSpan);
    //创建关闭按钮
    var closeLink = document.createElement('A');
    closeLink.style.cssText = 'float:right';
    closeLink.style.styleFloat = 'right';
    closeLink.id = 'quchaBoxCloseLink' + boxIndex;
    closeLink.innerHTML = 'x';
    closeLink.className = 'closeButton';
    closeLink.onmouseover = mouseover_CloseButton;
    closeLink.onmouseout = mouseout_CloseButton;
    closeLink.style.cursor = 'pointer';
    closeLink.style.visibility = 'hidden';
    closeLink.onmousedown = closequchaBox;
    div.appendChild(closeLink);
    //创建刷新图片按钮
    var image = document.createElement('IMG');
    image.src = 'images/refresh.gif';
    image.id = 'quchaBoxRefreshSource' + boxIndex;
    image.style.cssText = 'float:right';
    image.style.styleFloat = 'right';
    image.style.visibility = 'hidden';
    image.onclick = refreshRSS;
    image.style.cursor = 'pointer';
    if (!externalUrl) image.style.display = 'none';
    div.appendChild(image);
    //添加窗体头部
    parentObj.appendChild(div);
}
//添加拖动模块内容的容器
function addBoxContentContainer(parentObj, heightOfBox) {
    var div = document.createElement('DIV'); //内容的容器
    div.className = 'quchaBoxContent';
    if (opera) div.style.clear = 'none';
    div.id = 'quchaBoxContent' + boxIndex;
    parentObj.appendChild(div);
    if (heightOfBox && heightOfBox / 1 > 10)//设置内容容器的高度，高度需要大于10
    {
        div.style.height = heightOfBox + 'px';
        div.setAttribute('heightOfBox', heightOfBox);
        div.heightOfBox = heightOfBox;
        if (document.all) div.style.overflowY = 'auto'; else div.style.overflow = '-moz-scrollbars-vertical;';
        if (opera) div.style.overflow = 'auto';
    }
}
//添加窗口底部的广告条
function addBoxAdBar(parentObj) {
    var div = document.createElement('DIV');
    div.className = 'quchaBoxAdBar';
    div.id = 'quchaBoxAdBar' + boxIndex;
    //div.innerHTML=boxIndex+"  号广告位！"        //静态窗体的广告位
    parentObj.appendChild(div);
}
//创建一个新窗体
//columnIndex：窗体将存放的列编号；heightOfBox：窗体的高度；externalUrl：rss的url；
//keyid：窗体的标志符；notqucha：是否可以拖动
function createABox(columnIndex, heightOfBox, externalUrl, keyid, notqucha) {
    boxIndex++; //编号增加
    //窗体的最外层框架
    var maindiv = document.createElement('DIV');
    maindiv.className = 'quchaBox';
    maindiv.id = 'quchaBox' + boxIndex;
    //窗体内层框架
    var div = document.createElement('DIV');
    div.className = 'quchaBoxInner';
    maindiv.appendChild(div);
    //添加窗体的头部
    addBoxHeader(div, externalUrl, notqucha);
    //添加窗体内容
    addBoxContentContainer(div, heightOfBox);
    addBoxAdBar(div); //添加窗体的广告条
    //要存放窗体的列
    var obj = $('quchaBoxesColumn' + columnIndex);
    var subs = obj.getElementsByTagName('DIV');
    if (subs.length > 0)//此列中有子元素，插入第一个窗体的前面
    {
        obj.insertBefore(maindiv, subs[0]);
    }
    else//没有子元素，添加为子元素
    {
        obj.appendChild(maindiv);
    }
    //窗体数组增加一个窗体
    quchaBoxesArray[boxIndex] = new Array();
    //设置好这个窗体的数据
    quchaBoxesArray[boxIndex]['obj'] = maindiv;
    quchaBoxesArray[boxIndex]['parentObj'] = maindiv.parentNode;
    quchaBoxesArray[boxIndex]['keyid'] = keyid;
    quchaBoxesArray[boxIndex]['heightOfBox'] = heightOfBox;
    quchaBoxesArray[boxIndex]['boxState'] = 1; // 展开
    //记录下静态窗体的标志
    staticObjectArray[keyid] = boxIndex;
    return boxIndex; //窗口的数量
}


//获得rss数据后的回调函数
function showRSSData(req) {
    var rssContent = req.responseXML; //服务器返回的xml数据
    var headerrssItems0 = getXmlNodeValue(rssContent.documentElement.childNodes[0].firstChild); //rss的标题
    var headerrssItems1 = getXmlNodeValue(rssContent.documentElement.childNodes[0].lastChild); //rss纪录的条数
    var tmpIndex = getXmlNodeValue(rssContent.documentElement.lastChild); //当前模块的编号
    $('quchaBoxHeader_txt' + tmpIndex).innerHTML = '<span>' + headerrssItems0 + '&nbsp;<\/span><span class="rssNumberOfItems">(' + headerrssItems1 + '条)<\/span>'; // title
    //rss数据内容
    var rssItems = rssContent.getElementsByTagName("item");
    var string = '<table cellpadding="1" cellspacing="0">'; //显示rss的字符串
    for (var no = 1; no < rssItems.length; no++)// 遍历每条rss数据
    {
        var itemrssItems = rssItems[no]; //当前的这条数据			
        string = string + '<tr><td><img src="' + 'images/small_arrow.gif' + '"><td><p class=\"boxItemHeader\"><a class=\"boxItemHeader\" href="';
        string += getXmlNodeValue(itemrssItems.childNodes[1]) + '" onclick="var w = window.open(this.href);return false">';
        string += getXmlNodeValue(itemrssItems.childNodes[0]) + '<\/a><\/p><\/td><\/tr>';
    }
    string = string + '<\/table>';
    $('quchaBoxContent' + tmpIndex).innerHTML = string;
    showStatusBarMessage(tmpIndex, tmpIndex + ' 号广告位？'); //显示默认的广告内容
}
//刷新rss内容
function refreshRSS(numericId) {
    if (!numericId)//没有指定id
        numericId = this.id.replace(/[^0-9]/g, '')
    //向服务器请求刷新
    Request.sendGET("handler.ashx?rssURL=" + escape(quchaBoxesArray[numericId]['rssUrl']) + '&maxRssItems=' + quchaBoxesArray[numericId]['maxRssItems'] + '&tmpIndex=' + numericId, showRSSData)
    setTimeout('dragDropCounter=-5', 5);
}
//创建一个rss窗体
function createARSSBox(url, columnIndex, heightOfBox, maxRssItems, minutesBeforeReload, keyid, state) {


    if (url == "" || url == "undefined") {
        return;
    }
    if (keyid == "undefined") {
        keyid = url;
    }
    //高度和自动更新时间没有设置，则初始化为0
    if (!heightOfBox) heightOfBox = '0';
    if (!minutesBeforeReload) minutesBeforeReload = '0';
    var tmpIndex = createABox(columnIndex, heightOfBox, true); //创建一个拖动窗体模块
    if (!cookieRSSSources[url])//如果是rss模块，则纪录相关信息
    {
        cookieRSSSources[url] = cookieCounter;
        Set_Cookie('qucha_rss_boxes' + cookieCounter, url + '#;#' + columnIndex + '#;#' + maxRssItems + '#;#' + heightOfBox + '#;#' + minutesBeforeReload + '#;#' + keyid + '#;#' + state, 60000);
        cookieCounter++;
    }
    //给拖动数组对象添加相应信息
    quchaBoxesArray[tmpIndex]['rssUrl'] = url;
    quchaBoxesArray[tmpIndex]['maxRssItems'] = maxRssItems ? maxRssItems : 100;
    quchaBoxesArray[tmpIndex]['minutesBeforeReload'] = minutesBeforeReload;
    quchaBoxesArray[tmpIndex]['heightOfBox'] = heightOfBox;
    quchaBoxesArray[tmpIndex]['keyid'] = keyid;
    quchaBoxesArray[tmpIndex]['state'] = state;
    if (state == 0)//不显示模块内容
        showHideBoxContent(false, $('quchaBoxExpand' + tmpIndex));
    staticObjectArray[keyid] = tmpIndex; //当前id
    var tmpInterval = false;
    if (minutesBeforeReload && minutesBeforeReload > 0)//自动更新rss数据
        var tmpInterval = setInterval("refreshRSS(" + tmpIndex + ")", (minutesBeforeReload * 1000 * 60));
    quchaBoxesArray[tmpIndex]['intervalObj'] = tmpInterval; //纪录下自动更新的时间
    addRSSEditContent($('quchaBoxHeader' + tmpIndex))//添加编辑选项
    if (!$('quchaBoxContent' + tmpIndex).innerHTML) $('quchaBoxContent' + tmpIndex).innerHTML = '正在加载RSS数据......';
    if (url.length > 0 && url != 'undefined')//向服务器请求rss数据
        Request.sendGET("handler.ashx?rssURL=" + escape(url) + '&maxRssItems=' + maxRssItems + '&tmpIndex=' + tmpIndex, showRSSData)
    else
        hideHeaderOptionsForStaticBoxes(tmpIndex); //隐藏编辑选项
}
//取消选中事件
function cancelSelectionEvent(e) {
    if (document.all) e = event;
    if (e.target) source = e.target;
    else if (e.srcElement) source = e.srcElement;
    if (source.nodeType == 3)
        source = source.parentNode;
    if (source.tagName.toLowerCase() == 'input')//如果是input元素，则可以选中
        return true;
    if (dragDropCounter >= 0) return false;
    else return true;
}
//取消事件
function cancelEvent() {
    return false;
}

/* 清空cookie */
function clearCookiesForquchaBoxes() {
    var cookieValue = Get_Cookie('qucha_rss_boxes0'); //获取cookie值
    alert(cookieValue);
    while (cookieValue && cookieValue != '') {
        Set_Cookie('qucha_rss_boxes' + cookieCounter, '', -500);
        alert('qucha_rss_boxes' + cookieCounter);
        cookieCounter++;
        var cookieValue = Get_Cookie('qucha_rss_boxes' + cookieCounter); //下一个模块的cookie
    }
}
//对静态窗体隐藏头部的编辑选项
function hideHeaderOptionsForStaticBoxes(boxIndex) {
    if ($('quchaBoxRefreshSource' + boxIndex)) $('quchaBoxRefreshSource' + boxIndex).style.display = 'none';
    if ($('quchaBoxCloseLink' + boxIndex)) $('quchaBoxCloseLink' + boxIndex).style.display = 'none';
    if ($('quchaBoxEditLink' + boxIndex)) $('quchaBoxEditLink' + boxIndex).style.display = 'none';
}
/* 清除一个窗体的拖拽事件*/
function disableBoxDrag(boxIndex) {
    $('quchaBoxHeader' + boxIndex).onmousedown = '';
    $('quchaBoxHeader' + boxIndex).style.cursor = 'default';
}
/* 删除所有窗体 */
function deleteAllquchaBoxes() {
    var divs = document.getElementsByTagName('DIV');
    for (var no = 0; no < divs.length; no++) {
        if (divs[no].className == 'quchaBox')
            closequchaBox(false, divs[no]);
    }
}
/* 还原页面布局 */
function resetquchaBoxes() {
    cookieCounter = 0;
    clearCookiesForquchaBoxes(); //清空cookie
    deleteAllquchaBoxes(); //删除所有窗体
    cookieCounter = 0;
    cookieRSSSources = new Array();
    staticObjectArray = new Array(); //清空静态窗体
    createDefaultBoxes(); //创建默认窗体
}
//创建一个新的rss模块
function createFeed(formObj) {
    var url = formObj.rssUrl.value; //url
    var items = formObj.items.value; //最多显示的条数
    var height = formObj.height.value; //模块高度
    var reloadInterval = formObj.reloadInterval.value; //内容更新的间隔
    if (isNaN(height) || height / 1 < 40) height = false;
    if (isNaN(reloadInterval) || reloadInterval / 1 < 5) reloadInterval = false;
    createARSSBox(url, 1, height, items, reloadInterval); //创建
}
//根据cookie值创建rss模块
function createRSSBoxesFromCookie() {

    var tmpArray = new Array();
    var cookieValue = Get_Cookie('qucha_rss_boxes' + '0'); //第一个模块

    while (cookieValue && cookieValue != '') {
        var items = cookieValue.split('#;#'); //取得该模块的数据信息

        var index = items[0];
        if (!items[0]) index = items[5];
        if (items.length > 1 && !tmpArray[index])//创建rss模块
        {
            tmpArray[index] = true;
            createARSSBox(items[0], items[1], items[3], items[2], items[4], items[5], items[6]);
            cookieRSSSources[items[0]] = cookieCounter;
        }
        else {
            cookieCounter++;
        }
        var cookieValue = Get_Cookie('qucha_rss_boxes' + cookieCounter); //下一个cookie值
    }
}

/* 创建默认窗体 */
function createDefaultBoxes() {
    if (cookieCounter == 0) {

        //			createARSSBox('http://news.baidu.com/n?cmd=1&class=autonews&tn=rss',2,false,7);			
        //			createARSSBox('http://news.baidu.com/n?cmd=1&class=socianews&tn=rss',2,false,9,10);			
        //			createARSSBox('http://news.baidu.com/n?cmd=7&loc=0&name=%B1%B1%BE%A9&tn=rss',1,false,10);			
    }
    /* 创建静态窗体，本窗体的作用是添加一个rss窗口 */
    var htmlContentOfNewBox = '<form method="post" action="#">\
			<table cellpadding="0" cellspacing="0">\
				<tr><td colspan="4"><strong>添加新模块</strong></td></tr>\
				<tr><td>RSS 地址: </td><td colspan="4"><input type="text" name="rssUrl" size="30" value="http://news.baidu.com/n?cmd=1&class=civilnews&tn=rss" maxlength="255"></td></tr>\
				<tr>\
					<td>显示的条数: </td>\
					<td><input type="text" name="items" value="10" size="2" maxlength="2"></td>\
					<td>&nbsp;自动刷新间隔:</td>\
					<td><input type="text" name="reloadInterval" value="10" size="2" maxlength="2"></td>\
					<td>&nbsp;分钟</td>\
				</tr>\
				<tr>\
					<td>限制高度:</td>\
					<td><input type="text" name="height" value="150" size="2" maxlength="3"> </td>\
					<td><input type="button" onclick="createFeed(this.form)" value=" 添 加 "></td>\
				</tr>\
			</table>\
			</form>';
    var titleOfNewBox = '添加新模块';
    if (!staticObjectArray['staticObject1'])// 如果这个静态窗体没有存储在cookie中，不存在，则创建.
    {
        var newIndex = createABox(1, 100, false, 'staticObject1');
        $('quchaBoxContent' + newIndex).innerHTML = htmlContentOfNewBox;
        $('quchaBoxHeader_txt' + newIndex).innerHTML = titleOfNewBox;
    }
    else// 此静态窗体已经存在，把内容和标题赋予它.
    {
        $('quchaBoxContent' + staticObjectArray['staticObject1']).innerHTML = htmlContentOfNewBox;
        $('quchaBoxHeader_txt' + staticObjectArray['staticObject1']).innerHTML = titleOfNewBox;
    }
    hideHeaderOptionsForStaticBoxes(staticObjectArray['staticObject1']); //因为是静态窗体，所以去除头部的编辑选项
    //创建一个不能拖动的静态窗体
    var htmlContentOfNewBox = '<div>这里的RSS浏览器都是用Cookie保存，清空了Cookie就都消失了！<hr /><input type="button" value="还原页面布局" onclick="resetquchaBoxes();"/></div>'; // HTML content of new box
    var titleOfNewBox = '说明';
    if (!staticObjectArray['staticObject2'])// 如果这个静态窗体没有存储在cookie中，则创建.
    {
        var newIndex = createABox(2, 100, false, 'staticObject2', true); // 第5个参数为true，表示这个窗体是静止的，不能拖动
        $('quchaBoxContent' + newIndex).innerHTML = htmlContentOfNewBox;
        $('quchaBoxHeader_txt' + newIndex).innerHTML = titleOfNewBox;
    }
    else// 此静态窗体已经存在，把内容和标题赋予它.
    {
        $('quchaBoxContent' + staticObjectArray['staticObject2']).innerHTML = htmlContentOfNewBox;
        $('quchaBoxHeader_txt' + staticObjectArray['staticObject2']).innerHTML = titleOfNewBox;
        disableBoxDrag(staticObjectArray['staticObject2']); // 不能拖动
    }
    hideHeaderOptionsForStaticBoxes(staticObjectArray['staticObject2']); //因为是静态窗体，所以去除头部的编辑选项	
}



function initScript()//初始化rss各个窗体
{
    //创建窗体的3列
    columnParentBox = $('Container'); //各列的容器
    var columnWidth = Math.floor(100 / 2); //3列，平均每列的宽度
    var sumWidth = 0; //总宽度
    for (var no = 0; no < 2; no++)//创建3列
    {
        var div = document.createElement('DIV');
        if (no == (2 - 1)) columnWidth = 99 - sumWidth;
        sumWidth = sumWidth + columnWidth;
        div.style.cssText = 'float:left;width:' + columnWidth + '%;padding:0px;margin:0px;';
        div.style.height = '100%';
        div.style.styleFloat = 'left';
        div.style.width = columnWidth + '%';
        div.style.padding = '0px';
        div.style.margin = '0px';
        div.id = 'quchaBoxesColumn' + (no + 1); //id
        columnParentBox.appendChild(div); //添加一个列
    }
    //创建拖动窗体模块时的目标位置对象
    rectangleDiv = document.createElement('DIV');
    rectangleDiv.id = 'rectangleDiv';
    rectangleDiv.style.display = 'none';
    document.body.appendChild(rectangleDiv);
    //初始化窗体的相关事件
    document.body.onmousemove = movequchaElement;
    document.body.onmouseup = stop_dragDropElement;
    document.body.onselectstart = cancelSelectionEvent;
    document.body.ondragstart = cancelEvent;
    //屏幕的高度
    documentHeight = document.documentElement.clientHeight;
    createRSSBoxesFromCookie(); // 从cookie中创建rss窗体
    createDefaultBoxes(); // 创建默认窗体
}
window.onload = initScript;