﻿
var Class = {
    //创建类
    create: function() {
        return function() {
            this.initialize.apply(this, arguments);
        };
    }
};

var $A = function(a) {
    //转换数组
    return a ? Array.apply(null, a) : new Array;
};

var $$ = function(id) {
    //获取对象
    return document.getElementById(id);
};

Object.extend = function(a, b) {
    //追加方法
    for (var i in b) a[i] = b[i];
    return a;
};

Object.extend(Object, {

    addEvent: function(a, b, c, d) {

        //添加函数
        if (a.attachEvent) a.attachEvent(b[0], c);
        else a.addEventListener(b[1] || b[0].replace(/^on/, ""), c, d || false);
        return c;
    },

    delEvent: function(a, b, c, d) {
        if (a.detachEvent) a.detachEvent(b[0], c);
        else a.removeEventListener(b[1] || b[0].replace(/^on/, ""), c, d || false);
        return c;
    },

    reEvent: function() {
        //获取Event
        return window.event ? window.event : (function(o) {
            do {
                o = o.caller;
            } while (o && !/^\[object[ A-Za-z]*Event\]$/.test(o.arguments[0]));
            return o.arguments[0];
        })(this.reEvent);
    }

});

Function.prototype.bind = function() {
    //绑定事件
    var wc = this, a = $A(arguments), o = a.shift();
    return function() {
        wc.apply(o, a.concat($A(arguments)));
    };
};


var Table = Class.create();

Table.prototype = {

    initialize: function() {
        //初始化
        var wc = this;
        wc.cols = new Array; //创建列
    },

    addCols: function(o) {
        //添加列
        var wc = this, cols = wc.cols, i = cols.length;
        return cols[i] = {
            id: i, div: o, rows: new Array, //创建行
            addRow: wc.addRow, chRow: wc.chRow, inRow: wc.inRow, delRow: wc.delRow
        };
    },

    addRow: function(o) {
        //添加行
        var wc = this, rows = wc.rows, i = rows.length;
        return rows[i] = {
            id: i, div: o, cols: wc
        };
    },

    inRow: function(a, b) {
        //插入行
        var wc = b.cols = this, rows = wc.rows, i;
        if (a < rows.length) {
            for (i = a; i < rows.length; i++) rows[i].id++;
            rows.splice(a, 0, b);
            b.id = a;
            return b;
        } else {
            b.id = rows.length;
            return rows[b.id] = b;
        }
    },

    delRow: function(a) {
        //删除列
        var wc = this, rows = wc.rows, i, r;
        if (a >= rows.length) return;
        r = rows[a];
        rows.splice(a, 1);
        for (i = a; i < rows.length; i++) rows[i].id = i;
        return r;
    }
};
var CDrag = Class.create();

CDrag.IE = /MSIE/.test(window.navigator.userAgent);

CDrag.prototype = {

    initialize: function() {
        //初始化成员
        var wc = this;
        wc.table = new Table; //建立表格对象
        wc.iFunc = wc.eFunc = null;
        wc.obj = { on: { a: null, b: "" }, row: null, left: 0, top: 0 };
        wc.temp = { row: null, div: document.createElement("div") };
        wc.temp.div.setAttribute(CDrag.IE ? "className" : "class", "CDrag_temp_div");
        wc.temp.div.innerHTML = "&nbsp;";
    },

    reMouse: function(a) {
        //获取鼠标位置
        var e = Object.reEvent();
        return {
            x: document.documentElement.scrollLeft + e.clientX,
            y: document.documentElement.scrollTop + e.clientY
        };
    },

    rePosition: function(o) {
        //获取元素绝对位置
        var $x = $y = 0;
        do {

            $x += o.offsetLeft;
            $y += o.offsetTop;

        } while ((o = o.offsetParent) && o.tagName != "BODY");
        return { x: $x, y: $y };
    },

    sMove: function(o) {
        //当拖动开始时设置参数

        var wc = this;
        if (wc.iFunc || wc.eFinc) return;
        var mouse = wc.reMouse(), obj = wc.obj, temp = wc.temp, div = o.div, position = wc.rePosition(div);

        obj.row = o;
        obj.on.b = "me";
        obj.left = mouse.x - position.x;
        obj.top = mouse.y - position.y;

        temp.row = document.body.appendChild(div.cloneNode(true)); //复制预拖拽对象

        with (temp.row.style) {
            //设置复制对象
            position = "absolute";
            left = mouse.x - obj.left + "px";
            top = mouse.y - obj.top + "px";
            zIndex = 100;
            opacity = "0.3";
            filter = "alpha(opacity:30)";
            height = (div.clientHeight == 0 ? 200 : div.clientHeight) + "px";
            width = (div.clientWidth == 0 ? 200 : div.clientWidth) + "px";
        }

        with (temp.div.style) {
            //设置站位对象
       

            height = (div.clientHeight == 0 ? 200 : div.clientHeight) + "px";
            width = (div.clientWidth == 0 ? 200 : div.clientWidth) + "px";
        }


        /*div.parentNode.insertBefore(temp.div, div);
        div.style.display = "none"; //隐藏预拖拽对象*/
        div.parentNode.replaceChild(temp.div, div);

        wc.iFunc = Object.addEvent(document, ["onmousemove"], wc.iMove.bind(wc));
        wc.eFunc = Object.addEvent(document, ["onmouseup"], wc.eMove.bind(wc));
        document.onselectstart = new Function("return false");
    },

    iMove: function() {
        //当鼠标移动时设置参数
        var wc = this, cols = wc.table.cols, mouse = wc.reMouse(), obj = wc.obj, temp = wc.temp, row = obj.row, div = temp.row,
t_position, t_cols, t_rows, i, j;

        with (div.style) {
            left = mouse.x - obj.left + "px";
            top = mouse.y - obj.top + "px";
        }

        for (i = 0; i < cols.length; i++) {
            t_cols = cols[i];
            if (t_cols.div == null)
                continue;
            t_position = wc.rePosition(t_cols.div);
            if (t_position.x < mouse.x && t_position.x + t_cols.div.offsetWidth > mouse.x) {
                if (t_cols.rows.length > 0) { //如果此列行数大于0
                    if (wc.rePosition(t_cols.rows[0].div).y + 20 > mouse.y) {
                        //如果鼠标位置大于第一行的位置即是最上。。
                        //向上
                        obj.on.a = t_cols.rows[0];
                        obj.on.b = "up";
                        obj.on.a.div.parentNode.insertBefore(temp.div, obj.on.a.div);
                    } else if (t_cols.rows.length > 1 && t_cols.rows[0] == row &&
wc.rePosition(t_cols.rows[1].div).y + 20 > mouse.y) {
                        //如果第一行是拖拽对象而第鼠标大于第二行位置则，没有动。。
                        //向上
                        obj.on.b = "me";
                        t_cols.rows[1].div.parentNode.insertBefore(temp.div, t_cols.rows[1].div);
                    } else {
                        for (j = t_cols.rows.length - 1; j > -1; j--) {
                            //重最下行向上查询
                            t_rows = t_cols.rows[j];
                            if (t_rows == obj.row) continue;
                            if (wc.rePosition(t_rows.div).y < mouse.y) {
                                //如果鼠标大于这行则在这行下面
                                if (t_rows.id + 1 < t_cols.rows.length && t_cols.rows[t_rows.id + 1] != obj.row) {
                                    //如果这行有下一行则重这行下一行的上面插入
                                    t_cols.rows[t_rows.id + 1].div.parentNode.
insertBefore(temp.div, t_cols.rows[t_rows.id + 1].div);
                                    obj.on.a = t_rows;
                                    obj.on.b = "down";
                                } else if (t_rows.id + 2 < t_cols.rows.length) {
                                    //如果这行下一行是拖拽对象则插入到下两行，即拖拽对象返回原位
                                    t_cols.rows[t_rows.id + 2].div.parentNode.
insertBefore(temp.div, t_cols.rows[t_rows.id + 2].div);
                                    obj.on.b = "me";
                                } else {
                                    //前面都没有满足则放在最低行
                                    t_rows.div.parentNode.appendChild(temp.div);
                                    obj.on.a = t_rows;
                                    obj.on.b = "down";
                                }
                                return;
                            }
                        }
                    }
                } else {
                    //此列无内容添加新行
                    t_cols.div.appendChild(temp.div);
                    obj.on.a = t_cols;
                    obj.on.b = "new";
                }
            }
        }
    }, eMove: function() {
        //当鼠标释放时设置参数
        var wc = this, obj = wc.obj, temp = wc.temp, row = obj.row, div = row.div, o_cols, n_cols;

        if (obj.on.b == "up") {
            //向最上添加
            o_cols = obj.row.cols;
            n_cols = obj.on.a.cols;
            n_cols.inRow(0, o_cols.delRow(obj.row.id));
        } else if (obj.on.b == "down") {
            //相对向下添加
            o_cols = obj.row.cols;
            n_cols = obj.on.a.cols;
            n_cols.inRow(obj.on.a.id + 1, o_cols.delRow(obj.row.id));
        } else if (obj.on.b == "new") {
            //向无内容列添加
            o_cols = obj.row.cols;
            n_cols = obj.on.a;
            n_cols.inRow(0, o_cols.delRow(obj.row.id));
        }

        temp.div.parentNode.replaceChild(div, temp.div);
        temp.row.parentNode.removeChild(temp.row);
        delete temp.row;

        Object.delEvent(document, ["onmousemove"], wc.iFunc);
        Object.delEvent(document, ["onmouseup"], wc.eFunc);
        document.onselectstart = wc.iFunc = wc.eFunc = null;
    },

    add: function(o) {
        //添加对象
        var wc = this;
        Object.addEvent(o.div.childNodes[CDrag.IE ? 0 : 0], ["onmousedown"], wc.sMove.bind(wc, o));
    },

    parse: function(o) {
        //初始化成员
        var wc = this, table = wc.table, cols, i, j;
        for (i = 0; i < o.length; i++) {

            if (o[i] == undefined)
                continue;
            cols = table.addCols(o[i].cols);
            for (j = 0; j < o[i].rows.length; j++) {
                if (o[i].rows[j] == undefined)
                    continue;
                wc.add(cols.addRow(o[i].rows[j]));
            }
        }
    }

};
var IsLaySave = true;
function removeWidget(id) {
    if (confirm('确定要移除此模块吗?')) {
        CreateCallback(KEYwebRoot + "widgeteditor.aspx?remove=" + id + "&rnd=" + Math.random(), null);
        $$("m_widget"+id).style.display = "none";
    }
  
}
 
function GetData() {
    var subDivs = $$("root").getElementsByTagName('div');
    var countEl = 0;
    var rows = "";
    var cols = "";
    for (var no = 0; no < subDivs.length; no++) {
        var id = subDivs[no].id;
        if (subDivs[no].className.indexOf('cell') == 0 && subDivs[no].id.indexOf('m_') == 0) {
            cols += id + "|";
            var subDivs2 = subDivs[no].getElementsByTagName('div');
            for (var subno = 0; subno < subDivs2.length; subno++) {
                if (subDivs2[subno].className.indexOf('Square') == 0 && subDivs2[subno].id.indexOf('m_') == 0 && subDivs2[subno].style.display != "none") {

                    rows += subDivs2[subno].id + ',';

                }

            }

            rows += ';';



        }

    }

    
    return cols + "[" + rows ;


};
function ResponseTable() {

    var subDivs = $$("root").getElementsByTagName('div');
    var countEl = 0;
    var parsestr = '  var wc = new CDrag;wc.parse([';
    for (var no = 0; no < subDivs.length; no++) {
        var id = subDivs[no].id;
        if (subDivs[no].className.indexOf('cell') == 0 && subDivs[no].id.indexOf('m_') == 0) {
            parsestr += '{cols: $$("' + id + '"), rows: [';
            var subDivs2 = subDivs[no].getElementsByTagName('div');
            for (var subno = 0; subno < subDivs2.length; subno++) {
                if (subDivs2[subno].className.indexOf('Square') == 0 && subDivs2[subno].id.indexOf('m_') == 0 && subDivs2[subno].style.display != "none") {

                    parsestr += '$$("' + subDivs2[subno].id + '"),';

                }

            }



            parsestr += "]},";
        }

    }
    parsestr += "]);";



    eval(parsestr);
    eval(" Object.addEvent(window, [\"onload\"], function() {" + parsestr + "});");

};
function Save(groupid, page) {
    IsLaySave = true;

    CreateCallback(KEYwebRoot + "widgeteditor.aspx?gid=" + groupid + "&page=" + page + "&action=save&move=" + GetData() + "&rnd=" + Math.random(), operateMsg);
};
function operateMsg(response) {
    if (response != ""&&response.length<200) {
        alert(response);
    } else {
        alert("操作失败,请重新登录!");
    }
}
function editWidget(name, id) {
    if (IsLaySave == false) {
        alert("请首先保存布局,再进行编辑模块");
        return;
    }
    document.body.style.overflow = 'hidden';
    var argbody = getPageSize();    
    
    var width = argbody[2] + document.documentElement.scrollLeft;
    var height = argbody[3] + document.documentElement.scrollTop;

    var layer = document.createElement('div');
    layer.style.zIndex = 2;
    layer.id = 'layer';
    layer.style.position = 'absolute';
    layer.style.top = '0px';
    layer.style.left = '0px';
    layer.style.height = height + 'px';
    layer.style.width = width + 'px';
    layer.style.backgroundColor = 'black';
    layer.style.opacity = '.6';
    layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
    document.body.appendChild(layer);

    var size = { 'height': 100, 'width': 750 };
    var iframe = document.createElement('iframe');
    iframe.name = 'Widget Editor';
    iframe.id = 'WidgetEditor';
    iframe.src = KEYwebRoot + 'widgeteditor.aspx?area=group&widget=' + name + '&id=' + id;
    iframe.style.height = size.height + 'px';
    iframe.style.width = size.width + 'px';
    iframe.style.position = 'absolute';
    iframe.style.zIndex = 3;
    iframe.style.backgroundColor = 'white';
    iframe.style.border = '4px solid silver';
    iframe.frameborder = '0';

    iframe.style.top = ((height + document.documentElement.scrollTop) / 2) - (size.height / 2) + 'px';
    iframe.style.left = (width / 2) - (size.width / 2) + 'px';
 
    
    document.body.appendChild(iframe);
};
function closeEditor() {
    document.body.removeChild($$('WidgetEditor'));
    document.body.removeChild($$('layer'));
};
function appendWidget(response) {



    var m = document.getElementById('m_1');
    if (!m)
        return;
    if (m.style.display == "none")
        m = document.getElementById('m_3');
    if (!m)
        return;

    m.innerHTML += response;

    ResponseTable();


};
function addWidget(gid, type) {
    IsLaySave = false;
    CreateCallback(KEYwebRoot + "widgeteditor.aspx?gid="+gid+"&area=m_1&add=" + escape(type) + "&rnd=" + Math.random(), appendWidget);
};

/// <summary>
/// Creates a client callback back to the requesting page
/// and calls the callback method with the response as parameter.
/// </summary>
function CreateCallback(url, callback) {

    var http = GetHttpObject();
    http.open("GET", url, true);

    http.onreadystatechange = function() {
        if (http.readyState == 4) {
            if (http.responseText.length > 0 && callback != null)
                callback(http.responseText);
        }
    }

    http.send(null);
};

/// <summary>
/// Creates a XmlHttpRequest object.
/// </summary>
function GetHttpObject() {
    if (typeof XMLHttpRequest != 'undefined')
        return new XMLHttpRequest();

    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) { }
    }

    return false;
};


//判断浏览器的类型：
var ua = navigator.userAgent.toLowerCase ();
var os = new Object();
os.isFirefox = ua.indexOf ("gecko") != -1;
os.isOpera = ua.indexOf ("opera") != -1;
os.isIE = !os.isOpera && ua.indexOf ("msie") != -1;

//获取浏览器区域的大小：//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){
 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;
}
 
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
 
 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;
}