//实例化对象
var CDrag = Class.create();
//添加ie属性
CDrag.IE = /MSIE/.test(window.navigator.userAgent);
//add\ load方法
CDrag.load = function (obj_string, func, time) {
//加载对象
 var index = 0, timer = window.setInterval(function () {
  try {
   if (eval(obj_string + ".loaded")) {
    window.clearInterval(timer);
    func(eval("new " + obj_string));
   }
  } catch (exp) {}
  if (++ index == 20) window.clearInterval(timer);
 }, time + index * 3);
};
//添加database属性
CDrag.database = {
//数据存储
 json : [],
 json_db : '',
 parse : function (id) {
 //查找资源
  var wc = this, json = wc.json, i;
  
  for (i in json) {
   if (json[i].id == id)
    return json[i];
  }
  //return { id : id, title : "新增的", className : "新增的", src : "" };
 },
 
 add : function (){
 	var wc = this, arg = arguments;
 	wc.json[wc.json.length] = arg[0];
 }
};

CDrag.prototype = {
 
 initialize : function () {
 //初始化成员
  var wc = this;
  wc.table = new CDrag.Table; //建立表格对象
  wc.addc = new CDrag.Add(wc); //建立添加对象
  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 = " ";
 },
 
 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 };
 },
 
 execMove : function (status, on_obj, in_obj, place) {
 //处理拖拽过程细节
  var wc = this, obj = wc.obj.on, temp = wc.temp, px;
  
  obj.a = on_obj, obj.b = status;
  
  if (place == 0) {
  //向上
   px = in_obj.element.clientWidth;
   in_obj.element.parentNode.insertBefore(temp.div, in_obj.element);
  } else if (place == 1) {
  //新加入
   px = in_obj.element.clientWidth - 2;
   in_obj.element.appendChild(temp.div);
  } else {
  //向下
   px = in_obj.element.clientWidth;
   in_obj.element.parentNode.appendChild(temp.div);
  }
  
  wc.obj.left = Math.ceil(px / temp.div.offsetWidth * wc.obj.left); //处理拖拽换行后宽度变化，鼠标距离拖拽物的距离的误差.
  //temp.row.style.width = temp.div.style.width = "100%"; 
  //处理换列后对象宽度变化
  //temp.row.style.width = px + "px";
  //temp.div.style.width = px + "px";
 },
 
 sMove : function (o) {
 //当拖动开始时设置参数
  
  var wc = this;
  if (o.locks || wc.iFunc || wc.eFinc) return;
  
  var mouse = wc.reMouse(), obj = wc.obj, temp = wc.temp, div = o.element, 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)); //复制预拖拽对象
  temp.row.style.width = div.clientWidth + "px";
  
  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)";
  }
  
  with (temp.div.style) {
  //设置站位对象
   height = div.clientHeight + "px";
   width = div.clientWidth + "px";
  }
  
  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, mouse = wc.reMouse(), cols = wc.table.items, 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 != obj.row.parent) continue;
   t_position = wc.rePosition(t_cols.element);
   if (t_position.x < mouse.x && t_position.x + t_cols.element.offsetWidth > mouse.x) {
    if (t_cols.items.length > 0) { //如果此列行数大于0
     if (t_cols.items[0] != obj.row && wc.rePosition(t_cols.items[0].element).y + 20 > mouse.y) {
      //如果第一行不为拖拽对象并且鼠标位置大于第一行的位置即是最上。。
      //向上
      wc.execMove("up", t_cols.items[0], t_cols.items[0], 0);
     } else if (t_cols.items.length > 1 && t_cols.items[0] == row &&
      wc.rePosition(t_cols.items[1].element).y + 20 > mouse.y) {
      //如果第一行是拖拽对象而第鼠标大于第二行位置则，没有动。。
      //向上
      wc.execMove("me", t_cols.items[1], t_cols.items[1], 0);
     } else {
      for (j = t_cols.items.length - 1 ; j > -1 ; j --) {
       //重最下行向上查询
       t_rows = t_cols.items[j];
       if (t_rows == obj.row) {
        if (t_cols.items.length == 1) {
        //如果拖拽的是此列最后一行
         wc.execMove("me", t_cols, t_cols, 1);
        }
        continue;
       }
       if (wc.rePosition(t_rows.element).y < mouse.y) {
        //如果鼠标大于这行则在这行下面
        if (t_rows.id + 1 < t_cols.items.length && t_cols.items[t_rows.id + 1] != obj.row) {
         //如果这行有下一行则重这行下一行的上面插入
         wc.execMove("down", t_rows, t_cols.items[t_rows.id + 1], 0);
        } else if (t_rows.id + 2 < t_cols.items.length) {
         //如果这行下一行是拖拽对象则插入到下两行，即拖拽对象返回原位
         wc.execMove("me", null, t_cols.items[t_rows.id + 2], 0);
        } else {
         //前面都没有满足则放在最低行
         wc.execMove("down", t_rows, t_rows, 2);
        }
        return;
       }
      }
     }
    } else {
    //此列无内容添加新行
     wc.execMove("new", t_cols, t_cols, 1);
    }
   }
  }
 },
 eMove : function () {
 //当鼠标释放时设置参数
  var wc = this, obj = wc.obj, temp = wc.temp, row = obj.row, div = row.element, o_cols, n_cols, number;
  
  if (obj.on.b != "me") {
   number = (obj.on.b == "down" ? obj.on.a.id + 1 : 0);
   n_cols = (obj.on.b != "new" ? obj.on.a.parent : obj.on.a);
   o_cols = obj.row.parent;
   n_cols.ins(number, o_cols.del(obj.row.id));
   
   wc.set_db();
  }
  
  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;
 },
 
 reduce : function (o) {
 //变大变小
  var wc = this;
  if ((o.window = (o.window == 1 ? 0 : 1))) {
   o.content.style.display = "block";
   o.reduce.innerHTML = "缩小";
  } else {
   o.content.style.display = "none";
   o.reduce.innerHTML = "放大";
  }
  //wc.set_db();
 },
 
 lock : function (o) {
  //复制
  cur_o = o;
  var wc = this;
  var info = CDrag.database.parse(cur_o.root_id);
  var channel = getChannel(info.type);
  var url = path+channel.buildUrl(portal_id,cur_o.root_id);
  this.oper = "copy";
  openIframe("复制频道",url);
 },
 
 lockCallBack: function(sRet){
 	var wc = this;
 	CDrag.database.add({
 		id:sRet.id,
 		title:sRet.title,
 		className:sRet.title,
 		src:"",
 		type:sRet.contenttype,
 		configs:sRet.configs
 	});
  	wc.add(cur_o.parent.add(sRet.id, 1, false));
  	wc.set_db();
 },
 
 edit : function(o){
  cur_o = o;
  var wc = this;
  var info = CDrag.database.parse(cur_o.root_id);
  var channel = getChannel(info.type);
  var url = path+channel.buildUrl(portal_id,cur_o.root_id);
  this.oper = "edit";
  openIframe("编辑频道",url);
 },
 
 editCallBack: function(sRet){
 	var wc = this;
 	var info = CDrag.database.parse(sRet.id);
 	if(info){
 		info = {
	 		id:sRet.id,
	 		title:sRet.title,
	 		className:sRet.title,
	 		src:"",
	 		type:sRet.contenttype,
	 		configs:sRet.configs
	 	};
	 	cur_o.load();
	 	wc.set_db();
 	}
 },
 
 close : function (o) {
 //关闭对象
  var wc = this;
  wc.remove(o);
  wc.set_db();
 },
 
 remove : function (o) {
 //移除对象
  var wc = this, parent = o.parent;
  
  Object.delEvent(o.close, ["onclick"], o.closeFunc);
  Object.delEvent(o.edit, ["onclick"], o.editFunc);
  Object.delEvent(o.lock, ["onclick"], o.lockFunc);
  Object.delEvent(o.reduce, ["onclick"], o.reduceFunc);
  Object.delEvent(o.title, ["onmousedown"], o.mousedown);
  
  o.mousedown = o.reduceFunc = o.lockFunc = o.editFunc = o.closeFunc = null;
  
  parent.element.removeChild(o.element);
  parent.del(o.id);
  delete wc.Class;
  delete o;
 },
 
 create_json : function () {
 //生成json串
  var wc = this, cols = wc.table.items, a = [], b = [], i, j, r;
  for (i = 0 ; i < cols.length ; i ++) {
   for (r = cols[i].items, j = 0 ; j < r.length ; j ++)
    b[b.length] = "{id:'" + r[j].root_id + "'}";
   a[a.length] = "cols:'" + cols[i].element.id + "',rows:[" + b.splice(0, b.length).join(",") + "]";
  }
  //alert("[{" + a.join("},{") + "}]");
  return "[{" + a.join("},{") + "}]";
 },
 
 set_db : function () {
  //保存到数据库
  var wc = this;
  CDrag.database.json_db = wc.create_json();
 },

 parse : function (o) {
 //初始化成员
  try {
   var wc = this, table = wc.table, cols, rows, div, i, j;
   for (i = 0 ; i < o.length ; i ++) {
    div = getE(o[i].cols), cols = table.add(div);
    for (j = 0 ; j < o[i].rows.length ; j++){
     CDrag.database.add({
     	id:o[i].rows[j].id,
 		title:o[i].rows[j].title,
 		className:o[i].rows[j].title,
 		src:"",
 		type:o[i].rows[j].contenttype,
 		configs:o[i].rows[j].configs
     });
     wc.add(cols.add(o[i].rows[j].id, o[i].rows[j].window, o[i].rows[j].locks));
    }
   }
  } catch (exp) {
  }
 },
 
 add : function (o) {
 //添加对象
  var wc = this;
  o.mousedown = Object.addEvent(o.title, ["onmousedown"], o.lockF(wc, wc.sMove, o));
  o.reduceFunc = Object.addEvent(o.reduce, ["onclick"], o.lockF(wc, wc.reduce, o));
  o.lockFunc = Object.addEvent(o.lock, ["onclick"], wc.lock.bind(wc, o));
  o.editFunc = Object.addEvent(o.edit, ["onclick"], o.lockF(wc, wc.edit, o));
  o.closeFunc = Object.addEvent(o.close, ["onclick"], o.lockF(wc, wc.close, o));
 },
 
 append : function () {
  var wc = this,arg = arguments;
  cur_col = arg[0];
  var url = path+"/portal/dynlayout/addchannel.jsp?portal_id="+portal_id;
  url += "&container_id="+cur_col;
  this.oper = "add";
  openIframe("新增频道",url);
 },
 appendCallBack: function(sRet){
 	var wc = this;
 	CDrag.database.add({
 		id:sRet.id,
 		title:sRet.title,
 		className:sRet.title,
 		src:"",
 		type:sRet.contenttype,
 		configs:sRet.configs
 	});
  	var cols = wc.table.getItemById(cur_col);
  	var rows = cols.add(sRet.id, 1, false);
  	wc.add(rows);
  	wc.set_db();
 },
 handlerCallBack: function(json){
 	var wc = this;
 	switch(wc.oper){
	 	case "add":
	 		wc.appendCallBack(json);
	 		break;
	 	case "edit":
	 		wc.editCallBack(json);
	 		break;
	 	case "copy":
	 		wc.lockCallBack(json);
	 		break;
	 	default:
	 }
 }
 
};

