﻿var containerObj_1; //left
var containerObj_2;	 //right
//alert(isAdmin);
if(isAdmin==null)
	var isAdmin = false;

var Util = new Object();

Util.getUserAgent = navigator.userAgent;
Util.isGecko = Util.getUserAgent.indexOf("Gecko") != -1;
Util.isOpera = Util.getUserAgent.indexOf("Opera") != -1;
Util.getOffset = function (el, isLeft) {
    var retValue = 0;
    while (el != null) {
        retValue += el["offset" + (isLeft ? "Left" : "Top")];
        el = el.offsetParent;
    }
    return retValue;
};

Util.bindFunction = function (el, fucName) {
    return function () {
        return el[fucName].apply(el, arguments);
    };
};

Util.re_calcOff = function (el) {	
    for (var i = 0; i < Util.dragArray.length; i++) {
        var ele = Util.dragArray[i];
        ele.elm.pagePosLeft = Util.getOffset(ele.elm, true);
        ele.elm.pagePosTop = Util.getOffset(ele.elm, false);
    }
    var nextSib = el.elm.nextSibling;
    while (nextSib) {
        nextSib.pagePosTop -= el.elm.offsetHeight;
        nextSib = nextSib.nextSibling;
    }	
};

Util.hide = function () {
    //Util.rootElement.style.display = "none";
};
//??Google Ig????table?????
Util.show = function () {
    //Util.rootElement.style.display = "block";
};

ghostElement = null;

getGhostElement = function () {
    if (!ghostElement) {
        ghostElement = document.createElement("DIV");
        //ghostElement.className = "modbox";
		ghostElement.className = "area ghostDiv";
        ghostElement.backgroundColor = "";
        ghostElement.style.border = "2px dashed #aaa";
        ghostElement.innerHTML = "&nbsp;";
    }
    return ghostElement;
};

function draggable(el) {
    this._dragStart = start_Drag;
    this._drag = when_Drag;
    this._dragEnd = end_Drag;
    this._afterDrag = after_Drag;
    this.isDragging = false;
    this.elm = el;
    this.header = document.getElementById(el.id + "_h");
    this.hasIFrame = this.elm.getElementsByTagName("IFRAME").length > 0;
	
    if (this.header) {
		if(isAdmin)
        	this.header.style.cursor = "move";
        Drag.init(this.header, this.elm);
        this.elm.onDragStart = Util.bindFunction(this, "_dragStart");
        this.elm.onDrag = Util.bindFunction(this, "_drag");
        this.elm.onDragEnd = Util.bindFunction(this, "_dragEnd");
    }
};


function start_Drag() {
    Util.re_calcOff(this);
    this.origNextSibling = this.elm.nextSibling;
    var _ghostElement = getGhostElement();
    var offH = this.elm.offsetHeight;
    if (Util.isGecko) {
        offH -= parseInt(_ghostElement.style.borderTopWidth) * 2;
    }

    var offW = this.elm.offsetWidth;
    var offLeft = Util.getOffset(this.elm, true);
    var offTop = Util.getOffset(this.elm, false);

    Util.hide();

    this.elm.style.width = offW + "px";
    _ghostElement.style.height = offH + "px";
    this.elm.parentNode.insertBefore(_ghostElement, this.elm.nextSibling);
    this.elm.style.position = "absolute";
    this.elm.style.zIndex = 100;
    this.elm.style.left = offLeft +"px";
    this.elm.style.top = offTop + "px";

    Util.show();

    this.isDragging = false;
    return false;
};

function when_Drag(clientX, clientY) {	
    if (!this.isDragging) {
        this.elm.style.filter = "alpha(opacity=70)";
        this.elm.style.opacity = 0.7;
        this.isDragging = true;
    }

    var found = null;
    var max_distance = 100000000;
    for (var i = 0; i < Util.dragArray.length; i++) {
        var ele = Util.dragArray[i];
        var distance = Math.sqrt(Math.pow(clientX - ele.elm.pagePosLeft, 2) + Math.pow(clientY - ele.elm.pagePosTop, 2));
        if (ele == this) {
            continue;
        }

        if (isNaN(distance)) {
            continue;
        }

        if (distance < max_distance) {
            max_distance = distance;
            found = ele;
        }
    }

    var _ghostElement = getGhostElement();
    if (found != null && _ghostElement.nextSibling != found.elm) {
        found.elm.parentNode.insertBefore(_ghostElement, found.elm);
        if (Util.isOpera) {
            document.body.style.display = "none";
            document.body.style.display = "";
        }
    }	
};

function end_Drag() {
    if (this._afterDrag()) {
    }
    return true;
};

function after_Drag() {
    var returnValue = false;
    Util.hide();

    this.elm.style.position = "";
    this.elm.style.width = "";
    this.elm.style.zIndex = "";
    this.elm.style.filter = "";
    this.elm.style.opacity = "";

    var ele = getGhostElement();
    if (ele.nextSibling != this.origNextSibling) {
        ele.parentNode.insertBefore(this.elm, ele.nextSibling);
        returnValue = true;
    }

    ele.parentNode.removeChild(ele);
    Util.show();
    if (Util.isOpera) {
        document.body.style.display = "none";
        document.body.style.display = "";
    }
    return returnValue;
};

var Drag = {
	obj:null, 
	init:function (elementHeader, element) {		
    	elementHeader.onmousedown = Drag.start;		
	    elementHeader.obj = element;
	    if (isNaN(parseInt(element.style.left))) {
	        element.style.left = "0px";
	    }
	    if (isNaN(parseInt(element.style.top))) {
	        element.style.top = "0px";
	    }

	    element.onDragStart = new Function();
	    element.onDragEnd = new Function();
	    element.onDrag = new Function();		
	},

	start:function (event) {
	    var element = Drag.obj = this.obj;
		if(!isAdmin)
		{
			element.style.cursor="default";
			return;
		}
	    event = Drag.fixE(event);
	    if (event.which != 1) {
	        return true;
    	}

	    element.onDragStart();

	    element.lastMouseX = event.clientX;
	    element.lastMouseY = event.clientY;

	    document.onmouseup = Drag.end;
	    document.onmousemove = Drag.drag;
	    return false;
	}, 

	drag:function (event) {

	    event = Drag.fixE(event);

	    if (event.which == 0) {
	
	        return Drag.end();
    	}

	    var element = Drag.obj;

	    var _clientX = event.clientY;
	    var _clientY = event.clientX;

	    if (element.lastMouseX == _clientY && element.lastMouseY == _clientX) {
	        return false;
	    }

	    var _lastX = parseInt(element.style.top);
	    var _lastY = parseInt(element.style.left);

	    var newX, newY;

	    newX = _lastY + _clientY - element.lastMouseX;
	    newY = _lastX + _clientX - element.lastMouseY;

	    element.style.left = newX + "px";
	    element.style.top = newY + "px";

	    element.lastMouseX = _clientY;
	    element.lastMouseY = _clientX;

	    element.onDrag(newX, newY);
	    return false;
	},

	end:function (event) {
	    event = Drag.fixE(event);

	    document.onmousemove = null;
	    document.onmouseup = null;

	    var _onDragEndFuc = Drag.obj.onDragEnd();
		
		//***********************************
		// zg update 
		//移动完成后更新位置信息
		updateHiddenPosition();
		//**********************************	
		
	    Drag.obj = null;				
		
	    return _onDragEndFuc;
	}, 

	fixE:function (ig_) {
	    if (typeof ig_ == "undefined") {
	        ig_ = window.event;
	    }
	    if (typeof ig_.layerX == "undefined") {
	        ig_.layerX = ig_.offsetX;
	    }
	    if (typeof ig_.layerY == "undefined") {
	        ig_.layerY = ig_.offsetY;
	    }
	    if (typeof ig_.which == "undefined") {
	        ig_.which = ig_.button;
	    }
    	return ig_;
	}
};


var _IG_initDrag = function (el) {		
    Util.rootElement = el;
	
	//zg add start  [order by data]  date:2009-08-20
	containerObj_1=document.getElementById("left");
	containerObj_2=document.getElementById("right");
	var columns = new Array(containerObj_1,containerObj_2);
	
	_ZG_SetPosition(Util.column);
	//zg update end
	

    Util.dragArray = new Array();
    var counter = 0;
    for (var i = 0; i < columns.length; i++) {
    			
        var ele = columns[i];
        for (var j = 0; j < ele.childNodes.length; j++) { 
            var ele1 = ele.childNodes[j];           
            if (ele1.tagName == "DIV") {				
                Util.dragArray[counter] = new draggable(ele1);
                counter++;				
				//zg update start
				//添加打开隐藏按钮
				if (isAdmin)
				AddCloseOrOpenMenu(ele1);
				//as update end
            }
        }
    }	
};


//************************************************************************************
//zg Add date:2009-08-20
//说明：添加位置记录｜保存|从数据库中加载位置的功能

//order by data
function _ZG_SetPosition()
{	
	//如果没有位置信息，则不重新排序
	if(!document.getElementById("position"))return;
	var position=$("#position").val();
	if(position==""){return;}
	
	//显示遮罩层，待加载完后再移除
	showMarkDiv();
	
	var position=$("#position").val();
	if(position==""){return;}
	
	var tempCon=$("doagTemp");
	if(!tempCon){$(body.append("<div id='doagTemp'></div>"))}
	//var td1=$("#t_1");
	//var td2=$("#t_2");
	var td1=$(containerObj_1);
	var td2=$(containerObj_2);
	
	var arr = Array();
	var Array1 = Array();
	var Array2 = Array();
	
	//try{
		$.each(position.split(";"),
			function(i, n) {
				if($.trim(n)=="") return;
				var temp = n.split(":");
				var position = temp[1].split(",");
				if (position[0] == 0) {
					Array1[position[1]] = temp[0];
				} else {
				if (position[0] == 1) {
					Array2[position[1]] = temp[0];
				}
			}
		});
	//}catch(e)
	//{}
	
	arr.push(Array1);
	arr.push(Array2);	

	reOrderTd(td1,tempCon,Array1);
	reOrderTd(td2,tempCon,Array2);
	
	//移除进度条
	setTimeout("hidenMarkDiv()",100);
}

//按数组指的定的顺序重排序
function reOrderTd(td,tempCon,arr)
{
	//把TD中所有Mode移到tempCon中
	td.appendTo(tempCon);
	//删除多余的Div
	td.find(".dm").each(function(){$(this).remove();})
	
	//把内容排序后回移到TD中
	var namePre="#Nuabc_Box_";
	$.each(arr,function(i,n){
		$(namePre+n).appendTo(td);		
	})
	
	//在最后加上一个div，让模板可以拖到最后
	td.append("<div class=\"dm\"></div>");
}

//更新隐藏域中所存的位置的值
function updateHiddenPosition()
{	
	var td1=$(containerObj_1);
	var td2=$(containerObj_2);
	
	var position=getTdPosition(td1,"0");
	if(position!="")
	{
		position=position+";"+getTdPosition(td2,"1");
	}
	else
	{
		position=getTdPosition(td2,"1");
	}	
	//alert(position);
	$("#position").val(position);
	
	return position;
}

//获取指定表格内doag的位置信息
function getTdPosition(jTd,tdIndex)
{
	var str="";
	var index=1;
	//jTd.find(".modbox").each(function(){	
	jTd.find("[name=DragPannel]").each(function(){
		var id=$(this).attr("id");		
		str+=";"+id.split("Nuabc_Box_")[1]+":"+tdIndex+","+index;
		index++;
	})	
	if(str.length>0)
	{
		str=str.substring(1);	
	}
	return str;
}

//Ajax提交position信息
function UpdatePosition()
{
	var position=escape(updateHiddenPosition());	
	var url="/Ajax/Person.aspx?type=UpdatePosition&position="+position+"&callback=?&random="+Math.random();
	$.ajaxSetup({ cache: false });
	$.getJSON(url,function(data){
			if(parseInt(data.result)==1){alert("保存成功！");}else{alert("保存失败!");};	
		}
	)
}

function AjaxGetPositionMsg()
{
	var UserId=59817;
	
	$.ajax({
		url:"http://p"+config.webRootDomain+"/sys/AjaxHandler.ashx?type=getPosition&UserId="+UserId+"&d="+new Date(),
		type:"get",
		dataType:"html",
		success:function(msg){alert(msg); if(msg!=""){ $("#position").val(msg); _ZG_SetPosition(); } },
		error:function(msg){alert("error:"+msg);}
	})
}

//添加收起和打开按钮
function AddCloseOrOpenMenu(boxObj)
{
	$(boxObj).find(".title").each(function(){
		$(this).append('<input name="CloseOrOpen" type="button" class="button2" value="收缩" onclick="HiddenOrShow(this)" />');	
	})	
}
//隐藏显示内容
function HiddenOrShow(obj)
{		
	var p=$(obj).parent().parent();
	
	p.children().each(function(){
		if($(this).attr("class")!="title")
		{
			var d="";
			d=$(this).css("display");			
			if(d!="none" && d!="")
			{
				$(this).css("display","none");
				$(p.find("[name=CloseOrOpen]")[0]).attr("value","展开");
			}
			else
			{				
				$(this).css("display","block");				
				$(p.find("[name=CloseOrOpen]")[0]).attr("value","收缩");
			}	
		}
	})		
}

function showMarkDiv()
{
	$("#left").css("display","none");
	$("#right").css("display","none");
	$("#modules").append("<div id=\"maskDivId\" style=\"width:100%; height:200px; text-align:center; font-size:24px; line-height:200px; font-weight:bold; color:#000;\">页面正在加载中...</div>")
}

function hidenMarkDiv()
{
	$("#left").css("display","block");
	$("#right").css("display","block");
	$("#maskDivId").remove();
}

// zg add end
//*************************************************************************************

//page start
$(document).ready(function(){
	_table=document.getElementById("modules");
	_IG_initDrag(_table);
	
	//test
	//AjaxGetPositionMsg();
	//test
 	//setTimeout("AjaxGetPositionMsg()",2000);
})