var clock = null;
var returnValue = null; //弹出层返回的值，此处是URL
var returnTitle = null; //弹出层返回的值,此处是标题
var headerObject = null; //当前鼠标移动上去的对象（这里为整个Item，方便找到header和content）
var objectid = null; //当前的Item对象

var curPos = null;
var dropTarget = null; //要放下的目标元素 
var iMouseDown = false; //鼠标是否按下 
var lMouseState = false; //前一个iMouseDown状态 
var dragreplaceCont = [];
var mouseOffset = null;
var callbackFunc = null;
var curTarget = null;
Number.prototype.NaN0 = function () { return isNaN(this) ? 0 : this; }

//设置拖动的整体
function setdragreplace(obj, callback) {
    dragreplaceCont.push(obj);
    obj.setAttribute('candrag', '1');
    if (callback != null && typeof (callback) == 'function') {
        callbackFunc = callback;
    }
}
//鼠标移动 
function mouseMove(ev) {
    ev = ev || window.event;
    var target = ev.target || ev.srcElement;
    var id = $(target).attr("id");

    if (typeof target.onselectstart != "undefined") //IE route
        target.onselectstart = function () { return false }
    else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
        target.style.MozUserSelect = "none";
    else //All other route (ie: Opera)
        target.onmousedown = function () { return false }
    //*******************目的是找出拖柄****************
    switch (id) {
        case "c1_header1":
            target = $("#quickItem_1");
        case "t_1":
            target = $("#quickItem_1");
            break;
        case "c1_header2":
            target = $("#quickItem_2");
        case "t_2":
            target = $("#quickItem_2");
            break;
        case "c2_header1":
            target = $("#quickItem_3");
        case "t_3":
            target = $("#quickItem_3");
            break;
        case "c2_header2":
            target = $("#quickItem_4");
        case "t_4":
            target = $("#quickItem_4");
            break;
        case "c3_header1":
            target = $("#quickItem_5");
        case "t_5":
            target = $("#quickItem_5");
            break;
        case "c3_header2":
            target = $("#quickItem_6");
        case "t_6":
            target = $("#quickItem_6");
            break;
    }
    //**********************************************************
    var mousePos = mouseCoords(ev);
    //如果当前元素可拖拽
    var dragObj = null;
    if (target != null) {
        dragObj = $(target[0]).attr('candrag');
    }
    if (dragObj != null) {
        if (iMouseDown && !lMouseState) {
            //刚开始拖拽 
            curTarget = target[0];
            curPos = getPosition(target[0]);
            mouseOffset = getMouseOffset(target[0], ev);
            // 清空辅助层 
            for (var i = 0; i < dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);
            //克隆元素到辅助层，并移动到鼠标位置
            try {
                dragHelper.appendChild(curTarget.cloneNode(true));
            }
            catch (e) { }
            dragHelper.style.display = 'block';
            if (dragHelper.firstChild != null) {
                dragHelper.firstChild.removeAttribute('candrag');
            }
            //记录拖拽元素的位置信息
            if (curTarget != null) {
                $(curTarget).attr('startWidth', parseInt(curTarget.offsetWidth));
                $(curTarget).attr('startHeight', parseInt(curTarget.offsetHeight));
                if (typeof curTarget.style != "undefined") {
                    curTarget.style.display = 'none';
                }
            }
            //记录每个可接纳元素的位置信息，这里一次记录以后多次调用，获取更高性能 
            for (var i = 0; i < dragreplaceCont.length; i++) {
                with (dragreplaceCont[i]) {
                    if (dragreplaceCont[i] == curTarget)
                        continue;
                    var pos = getPosition(dragreplaceCont[i]);
                    setAttribute('startWidth', parseInt(offsetWidth));
                    setAttribute('startHeight', parseInt(offsetHeight));
                    setAttribute('startLeft', pos.x);
                    setAttribute('startTop', pos.y);
                }
            } //记录end 
        } //刚开始拖拽end 
    }
    //正在拖拽 
    if (curTarget != null) {
        try {
            dragHelper.style.top = mousePos.y - mouseOffset.y + "px";
            dragHelper.style.left = mousePos.x - mouseOffset.x + "px";
        } catch (e) { };
        //拖拽元素的中点
        var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) / 2);
        var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight')) / 2);
        var havedrop = false;
        for (var i = 0; i < dragreplaceCont.length; i++) {
            with (dragreplaceCont[i]) {
                if (dragreplaceCont[i] == curTarget)
                    continue;
                var content = $(dropTarget).children().next();
                if ((parseInt(getAttribute('startLeft')) < xPos) &&
(parseInt(getAttribute('startTop')) < yPos) &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)) {
                    havedrop = true;
                    dropTarget = dragreplaceCont[i];
                    $(content).removeClass("quickShadow");
                    $(dropTarget).addClass("quickRound");
                    $(dropTarget).addClass("quickShadow1");
                    $(dropTarget).removeClass("quickItem");
                    $(dropTarget).addClass("moveClass");
                    break;
                }
                else {
                    $(content).addClass("quickShadow");
                    $(dropTarget).removeClass("moveClass");
                    $(dropTarget).addClass("quickItem");
                    $(dropTarget).removeClass("quickRound");
                    $(dropTarget).removeClass("quickShadow1");
                }
            }
        }
        if (!havedrop && dropTarget != null) {
            dropTarget = null;
        }
    } //正在拖拽end 
    lMouseState = iMouseDown;
    if (curTarget) return false; //阻止其它响应（如：鼠标框选文本） 

}
//鼠标松开 
function mouseUp(ev) {
    if (curTarget) {
        dragHelper.style.display = 'none'; //隐藏辅助层 
        if (curTarget.style.display == 'none' && dropTarget != null && curTarget.tagName == dropTarget.tagName) {
            //if (curTarget.style.display == 'none' && dropTarget != null ) {
            //***************************************************************************************************************************************
            var content = $(dropTarget).children().next();
            //交换后处理CSS样式 
            $(content).addClass("quickRound");
            $(content).addClass("quickShadow");
            $(dropTarget).removeClass("moveClass");
            $(dropTarget).addClass("quickItem");
            $(dropTarget).addClass("quickRound");
            $(dropTarget).removeClass("quickShadow1");

            //交换标题
            var temp = $(dropTarget).find(".quickHeaderTitle").html();
            $(dropTarget).find(".quickHeaderTitle").html($(curTarget).find(".quickHeaderTitle").html());
            $(curTarget).find(".quickHeaderTitle").html(temp);
            //交换内容
            temp = $(dropTarget).find(".quickContent a").attr("href");
            $(dropTarget).find(".quickContent a").attr("href", $(curTarget).find(".quickContent a").attr("href"));
            $(curTarget).find(".quickContent a").attr("href", temp);
            temp = $(dropTarget).find(".quickContent img").attr("src");
            $(dropTarget).find(".quickContent img").attr("src", $(curTarget).find(".quickContent img").attr("src"));
            $(curTarget).find(".quickContent img").attr("src", temp);

            //排序
            var curTargetId = $(curTarget).attr("id").split('_')[1];
            var dropTargetId = $(dropTarget).attr("id").split('_')[1];

            dropTarget = null;
            if (callbackFunc != null) {
                callbackFunc(curTarget);
            }
            $.post(basePath + 'ajax.aspx?HandlerName=AdminAjaxHandler', "<?xml version='1.0' encoding='utf-8'?><root><type>sortmodule</type><changeids>" + curTargetId + "," + dropTargetId + "</changeids></root>", function (s) {
                var success = $("status", s).text();
                if (success == "false") {
                    alert($("msg", s).text());
                    window.location.reload();
                }
            });

        }
        curTarget.style.display = '';
        curTarget.style.visibility = 'visible';
        curTarget.setAttribute('candrag', '1');
    }
    curTarget = null;
    iMouseDown = false;

}
//鼠标按下 
function mouseDown(ev) {
    //记录变量状态
    $(".quickHeader").mousedown(function () {
        iMouseDown = true;
    })

    //获取事件属性 
    ev = ev || window.event;
    var target = ev.target || ev.srcElement;
    if (target.onmousedown || target.getAttribute('candrag')) {//阻止其它响应（如：鼠标双击文本） 
        return false;
    }
}
//返回当前item相对页面左上角的坐标 
function getPosition(e) {
    var left = 0;
    var top = 0;
    while (e.offsetParent) {
        left += e.offsetLeft + (e.currentStyle ? (parseInt(e.currentStyle.borderLeftWidth)).NaN0() : 0);
        top += e.offsetTop + (e.currentStyle ? (parseInt(e.currentStyle.borderTopWidth)).NaN0() : 0);
        e = e.offsetParent;
    }
    left += e.offsetLeft + (e.currentStyle ? (parseInt(e.currentStyle.borderLeftWidth)).NaN0() : 0);
    top += e.offsetTop + (e.currentStyle ? (parseInt(e.currentStyle.borderTopWidth)).NaN0() : 0);
    return { x: left, y: top };
}
//返回鼠标相对页面左上角的坐标 
function mouseCoords(ev) {
    if (ev.pageX || ev.pageY) {
        return { x: ev.pageX, y: ev.pageY };
    }
    return {
        x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y: ev.clientY + document.body.scrollTop - document.body.clientTop
    };
}
//鼠标位置相对于item的偏移量 
function getMouseOffset(target, ev) {
    ev = ev || window.event;
    var docPos = getPosition(target);
    var mousePos = mouseCoords(ev);
    return { x: mousePos.x - docPos.x, y: mousePos.y - docPos.y };
}
//鼠标移动附加样式
function mouseMoveAndOut() {
    var content = null;
    var table = null;
    $(".quickItem").mouseover(function () {
        headerObject = this;
        objectid = $(headerObject).attr("id");
        var childrens = $(this).children();
        headerObject = childrens[0]; //得到Header
        content = childrens[1]; //得到对应的ContentId
        $(this).addClass("quickRound"); //给鼠标移动上去的item加Css样式
        $(this).addClass("quickShadow1");
        $(this).removeClass("quickItem");
        $(this).addClass("moveClass");
        $(content).removeClass("quickShadow");
        table = $(this).children().children().next(); //得到整个编辑区域(编辑和删除)
        $(table).removeClass("quickHeaderTable");
    }).mouseout(function () {
        $(this).removeClass("moveClass");
        $(this).addClass("quickRound");
        $(this).addClass("quickItem");
        $(this).removeClass("quickShadow1");
        $(content).addClass("quickShadow");
        $(content).addClass("quickRound");
        $(table).addClass("quickHeaderTable");
    });
}
//获得返回值
function getReturnValue(title, value) {
    returnValue = value;
    returnTitle = title;
    var itemId = $(headerObject).attr("id");
    var headId = $("#" + itemId).children().attr("id");
    var headChild = $("#" + headId).children();
    var headChildId = headChild.attr("id");
    $("#" + headChildId).text(returnTitle);
    var hnUrl = $("#HnUrl").val(returnValue);
    var hnUrlValue = $("#HnUrl").val();
}
//删除图片事件
function deletePic() {
    var head = $("#" + objectid).children();
    var headId = head.attr("id");
    var span = $("#" + headId).children().children();
    var spanId = span.attr("id");
    var con = $("#" + objectid).children().next();
    var conId = con.attr("id");
    var a = $("#" + conId).children()
    var img = $("#" + conId).children().children();
    var imgId = img.attr("id");
    var aId = a.attr("id");
    var modelIds = objectid.split('_');
    var modelId = modelIds[1];
    var href = $("#" + aId).attr("href");
    if (href == "" || href == undefined) {
        return false;
    }
    if (confirm("您确定要删除:" + $("#" + spanId).text() + "?")) {
        $.post(basePath + 'ajax.aspx?HandlerName=AdminAjaxHandler', "<?xml version='1.0' encoding='utf-8'?><root><type>delepic</type><ItemId>" + modelId + "</ItemId></root>", function (s) {
            var success = $("status", s).text();
            if (success == "true") {
                $("#" + spanId).text("新建快捷方式")
                $("#" + aId).attr("href", "");
                $("#" + imgId).attr("src", "#");
                return;
            }
            else {
                alert("删除失败!");
                return;
            }
        });
    }
}

//关闭弹出层
function closeWindow(flag) {
    if (flag) {
        $(".floatingDialogClose").click();
        ScreenShot(returnTitle, returnValue, objectid);
    }
    if (!flag) {
        $(".floatingDialogClose").click();
    }
}
//Ajax方法请求生成图片
function ScreenShot(title, url, obj) {
    var con = $("#" + obj).children().next();
    var conId = con.attr("id");
    var img = $("#" + conId).children().children();
    var modelIds = obj.split('_');
    var modelId = modelIds[1];
    $(img).attr("src", "" + basePath + "Admin/Images/loading.gif");

    $.get(basePath + adminPath + "/" + url.split('|')[0], function (data) {
        $.post(basePath + 'ajax.aspx?HandlerName=AdminAjaxHandler', "<?xml version='1.0' encoding='utf-8'?><root><type>ScreenShot</type><url>" + escape(url) + "</url><title>" + title + "</title><moduleId>" + modelId + "</moduleId><content>" + escape(data) + "</content></root>", function (s) {
            var success = $("status", s).text();
            if (success == "true") {
                clock = SetPathMethod(obj);
            }
            else {
                alert($("msg", s).text());
            }
        });
    }); 
}
function SetPathMethod(d) {
    return window.setTimeout(function () { setPath(d) }, 1000);

}
//请求Ajax.xml文件，判断图片是否已经生成
function setPath(id) {
    var path = null;
    $.ajax({
        type: "Get",
        cache: false,
        url: basePath + 'Admin/ScreenShot/' + id + '_' + adminId + 'Ajax.xml',
        error: function (msg) {
            alert('Ajax请求出错！错误信息为：' + msg);
        },
        success: function (xml) {
            if ($("iscompleted", xml).text() == "True") {
                path = basePath + "Admin/Images/QuickImage/" + $("fileName", xml).text();
                var con = $("#" + id).children().next();
                var conId = con.attr("id");
                var img = $("#" + conId).children().children();
                $(img).attr("src", path + "?r=" + Math.random());
                var a = $("#" + conId).children();
                aId = a.attr("id");
                $("#" + aId).attr("href", "javascript:ShowMain('" + returnValue.split('|')[1] + "','" + returnValue.split('|')[0] + "')");
                if ($("iserror", xml).text() == "True") {
                    path = basePath + "Images/err.gif";
                    alert($("errMsg", xml).text());
                }
                window.clearTimeout(clock);
            } else {
                SetPathMethod(id);
            }

        }
    });
}

//拖拽
function StartDrag() {
    document.onmousemove = mouseMove;
    document.onmousedown = mouseDown;
    document.onmouseup = mouseUp;
    //辅助层用来显示拖拽 
    dragHelper = document.createElement('DIV');
    dragHelper.style.cssText = 'position:absolute;display:none;';
    document.body.appendChild(dragHelper);
    setdragreplace(document.getElementById('quickItem_1'));
    setdragreplace(document.getElementById('quickItem_2'));
    setdragreplace(document.getElementById('quickItem_4'));
    setdragreplace(document.getElementById('quickItem_3'));
    setdragreplace(document.getElementById('quickItem_5'));
    setdragreplace(document.getElementById('quickItem_6'));
}
//JS程序运行入口
function Init() {
    mouseMoveAndOut();
    StartDrag();
}
