
$(document).bind("contextmenu", function () { return false; });
$(document).keydown(function () 
{
	if (event.keyCode == 116) 
	{
		event.keyCode = 0;
		event.returnValue = false;
		return false;
	}

	if (window.event.ctrlKey) 
	{
		isCtrl = true;
	}
	if (window.event.shiftKey) 
	{
		isShift = true;
	}
});
$(document).keyup(function () 
{
	isCtrl = false;
	isShift = false;
});

$(function () 
{
	$('.syncBTNDefault').parent().find('em').hide();


	$('.syncBTN').bind('click', function (e) 
	{
		new Image().src = 'http://t.msn.com.cn/activity/l.gif?nocache=' + new Date().getTime() + '&pt=' + manto.cookieTool('manto_user_ct') + '&d=client.dict.bing.msn.cn&v=1&c=http://client.dict.bing.msn.cn%60%60click%60BingDict_v2.0_syncBtn';
		window.external.Sync();
		return false;
	});
	$('.addBTN').bind('click', function () 
	{
		window.external.AddPhrase();
		return false;
	});
	$('.deleteBTN').bind('click', function () 
	{
		window.external.DeletePhrases();
		return false;
	});
});

//------------------------------------------------//

//1.默认状态的同步按钮
//1.1
//前端方法:点击同步按钮后发现还没有登录,则显示"默认"的同步按钮,并显示"正在登录"的状态文字
function loginFront()
{
    var $syncBtn = $('.actBTN .syncBTNWrap'),
        $el = $('.syncBTNDefault').parent();
    $el.find('em').hide();
    $('em.syncLogin', $el).show();
}
//1.2
//前端方法,同步完成以后,先显示"同步完成"的同步按钮,然后切换到"默认"的同步按钮,并定期刷新"距上次同步时间"
var timer = null;
function endSyncFront(day)
{
    var $wrap = $('.actBTN'),
        $syncBtn = $('.actBTN .syncBTNWrap'),
        $el = $('.syncBTNDefault', $wrap).parent(),
        day = new Date(day);
    $syncBtn.removeClass('dI');
    $('.syncBTNEnd', $wrap).parent().addClass('dI');

    //定期显示"距上次同步时间"
    setTimeout(function ()
    {
        $syncBtn.removeClass('dI');
        $el.addClass('dI');
        $el.find('em').hide();
        $('em.default', $el).text(checkTime(day)).show();
        clearInterval(timer);
        timer = null;
        timer = setInterval(function ()
        {
            $('em.defualt', $el).text(checkTime(day));
        }, 1000 * 60);
    }, 2000);
}
//1.3 
//前端方法,如果用户没有登录,则仅显示"默认"的同步按钮; 如果用户刚登录还没有开始同步,则显示"默认"的同步按钮,并定期刷新"距上次同步时间"; 如果用户同步失败,则仅显示"默认"的同步按钮
function statusFront(className, day)
{
    var $syncBtn = $('.actBTN .syncBTNWrap'),
		$el = $('.syncBTNDefault').parent(),
		$currentEl = $('em.' + className, $el);
    $syncBtn.removeClass('dI');
    $el.addClass('dI');
    $el.find('em').hide();
    $currentEl.show();

    //定期显示"距上次同步时间"
    if (className === 'default' && day !== undefined)
    {
        $currentEl.text(checkTime(day)).show();
        clearInterval(timer);
        timer = null;
        timer = setInterval(function ()
        {
            $currentEl.text(checkTime(day));
        }, 1000 * 60);
    }
}


//2.有新内容需要同步状态的同步按钮
//2.1
//前端方法,当用户已经登录,并进行了一些操作导致有新的可以同步的内容时,显示"有新内容需要同步"的同步按钮
function hasNewWordFront()
{
    var $wrap = $('.actBTN'),
        $syncBtn = $('.actBTN .syncBTNWrap');
    $syncBtn.removeClass('dI');
    $('.syncBTNNew', $wrap).parent().addClass('dI');
}


//3.同步中的同步按钮
//3.1
//前端方法,当正式开始同步的时候,显示"正在和云端同步"状态
function setSyncBTNIngVisible()
{
    $loadingWrap = $('.actBTN .syncBTNIng').parent();
    if ($loadingWrap.hasClass('dI'))
    {
        return;
    }

    $('.actBTN .syncBTNWrap').removeClass('dI');//先隐藏所有的sync button wrappers
    $loadingWrap.addClass('dI');//再显示syncing button wrapper

    $('>em', $loadingWrap).hide();//先隐藏所有syncing button wrapper下面的所有文字
    $loadingWrap.find('.syncProcess').show();//再显示syncing button wrapper下面文字"正在和云端同步"
}
//3.2
//前端方法,让前端切换到"正在和云端同步"状态
function startSyncFront()
{
    var $wrap = $('.actBTN'),//action buttons
        $syncBtn = $('.actBTN .syncBTNWrap'),//sync button wrappers
        $el,//currently displayed syncBTN
        $loadingWrap = $('.syncBTNIng', $wrap).parent();//syncing button wrapper

    //find currently displaying syncBTN
    $('.syncBTNWrap').each(function ()
    {
        if ($(this).hasClass('dI'))
        {
            $el = $('.syncBTN', this);
        }
    });

    //切换到"正在和云端同步"状态
    if ($el.hasClass('syncBTNDefault') || $el.hasClass('syncBTNEnd') || $el.hasClass('syncBTNNew')) //如果当前正在展示的是以下状态:默认状态,同步完成,有新内容需要同步.
    {
        $syncBtn.removeClass('dI');//先隐藏所有的sync button wrappers
        $loadingWrap.addClass('dI');//再显示syncing button wrapper

        $('>em', $loadingWrap).hide();//先隐藏所有syncing button wrapper下面的所有文字
        $loadingWrap.find('.syncProcess').show();//再显示syncing button wrapper下面文字"正在和云端同步"
    }
};
//3.3
//前端方法,在同步过程中,用于改变同步中的状态文字
function checkTextFront(statusCode)
{
    var $wrap = $('.syncBTNIng').parent(), $em = $('>em', $wrap);
    $em.hide();
    switch (statusCode)
    {
        case 'upload':
            $wrap.find('.syncUpload').show(); break;
        case 'download':
            $wrap.find('.syncDownload').show(); break;
        case 'merge':
            $wrap.find('.syncMerge').show(); break;
        case 'login':
            $wrap.find('.syncSignin').show(); break;
        default:;
    }
}


//前端方法,用于生成"距上次同步时间"的状态文字
function checkTime(time)
{
    var date = new Date(time);
    var now = new Date();
    var date_year = date.getFullYear();
    var date_month = date.getMonth() + 1;
    var date_day = date.getDate();
    var date_hour = date.getHours();
    var now_year = now.getFullYear();
    var now_month = now.getMonth() + 1;
    var now_day = now.getDate();
    var now_hour = now.getHours();
    if (now_year > date_year || now_month > date_month || now_day > date_day)
    {
        date = '上次同步:' + date.getFullYear() + '/' + date_month + '/' + date_day;
        if (date_year < 2001)
        {
            date = '您还未同步过';
        }
    }
    else
    {
        if ((now_hour - date_hour) > 0)
        {
            if (now_hour - date_hour === 1 && now.getMinutes() < date.getMinutes())
            {
                date = '上次同步:' + (now.getMinutes() - date.getMinutes() + 60) + '分钟前';
            }
            else
            {
                date = '上次同步:' + (now_hour - date_hour) + '小时前';
            }
        }
        else
        {
            var minutes = now.getMinutes() - date.getMinutes();
            if (minutes < 2)
            {
                date = '上次同步：刚刚';
            }
            else
            {
                date = '上次同步:' + (now.getMinutes() - date.getMinutes()) + '分钟前';
            }
        };
    };
    return date;
}


//------------------------------------------------//
var isCtrl = false;
var isShift = false;
var ls = -1;
function MOutBgColor(obj) 
{
    if (obj.style.backgroundColor != "#e2e2e2") 
	{
        obj.style.backgroundColor = "white";
    }
}
function MOverBgColor(obj) 
{
    if (obj.style.backgroundColor != "#e2e2e2")
	{
        obj.style.backgroundColor = "#f7ecea";
    }
}
function Open(obj) 
{
    ItemSingleSelect(obj);
    window.external.SeeMoreForPhrase();
}
function MDown(obj) 
{
    //trace right button of mouse
    if (event.button == 2) 
	{
        var bgColor = obj.style.backgroundColor;
        if (bgColor != "#e2e2e2") 
		{
            ItemSingleSelect(obj);
        }
        window.external.ShowRightClickContextMenuStrip(event.clientX,event.clientY);
    }
}

function selectAllPhrasesClick(obj) 
{
    if (obj.checked == true) 
	{
        var ids = "";
        $("#phraseListDiv table").each(function () 
		{
            $(this).css("backgroundColor", "#e2e2e2");
            ids = ids + $(this).attr("id") + ",";
        });
        window.external.GetSuccessiveSlt(ids);
    }
    else 
	{
        window.external.GetSuccessiveSlt("");
        ClearSelected();
    }
}

function ItemSingleSelect(obj) 
{
    var selectAllCheckBox = $("#selectAllButton");
    if (selectAllCheckBox.attr("checked") == true) 
	{
        selectAllCheckBox.attr("checked", false);
    }

    ls = $(obj).find("td").eq(0).text();
    $("table").each(function () 
	{
        if ($(this).attr("id") != obj.id) 
		{
            $(this).css("backgroundColor", "white");
        }
    });
    var bgColor = obj.style.backgroundColor;
    //unselected
    if (bgColor != "#e2e2e2") 
	{
        obj.style.backgroundColor = "#e2e2e2";
    }
    window.external.GetPhraseSingleSelected(obj.id);
}
function ItemSelect(obj) 
{
    var selectAllCheckBox = $("#selectAllButton");
    if (selectAllCheckBox.attr("checked") == true) 
	{
        selectAllCheckBox.attr("checked", false);
    }

    var i = 0;

    if (!isShift) 
	{
        ls = $(obj).find("td").eq(0).text();
    }

    if (!isShift) 
	{
        if (!isCtrl) 
		{
            $("table").each(function () 
			{
                if ($(this).css("backgroundColor") == "#e2e2e2") 
				{
                    i++;
                }
                if ($(this).attr("id") != obj.id) 
				{
                    $(this).css("backgroundColor", "white");
                }
            });
        }
        var bgColor = obj.style.backgroundColor;
        //unselected
        if (bgColor == "#e2e2e2") 
		{
            if (i <= 1) 
			{
                obj.style.backgroundColor = "#f7ecea";
            }
        }
        else 
		{
            obj.style.backgroundColor = "#e2e2e2";
        }

        window.external.GetPhraseSelected(obj.id, isCtrl);
    }
    else 
	{
        if (ls == -1) 
		{
            ls = $(obj).find("td").eq(0).text();
            var bgColor = obj.style.backgroundColor;
            obj.style.backgroundColor = "#e2e2e2";
            window.external.GetPhraseSelected(obj.id, isCtrl);           
        }
        else 
		{
            var tm = $(obj).find("td").eq(0).text();
            var ils = parseInt(ls);
            var itm = parseInt(tm);
            if (ils > itm) 
			{
                ils = ils + itm;
                itm = ils - itm;
                ils = ils - itm;
            }
            var ids = "";
            
            $("table").each(function () 
			{
                var t = $(this).find("td").eq(0).text();
                var it = parseInt(t);
                if (ils <= it && it <= itm) 
				{
                    $(this).css("backgroundColor", "#e2e2e2");
                    ids = ids + $(this).attr("id") + ",";
                }
                else 
				{
                    $(this).css("backgroundColor", "white");
                }
            });

            window.external.GetSuccessiveSlt(ids);
        }
    }
    i = 0;
}

function initializelLs() 
{
    ls = -1;
}

function ClearSelected() 
{
    $("table").each(function () 
	{
        $(this).css("backgroundColor","white")
    });
}
function PhraseKeyUp() 
{
    if (event.keyCode == 13) 
	{
        if ($.trim($('#txtDefi').text()) != "") 
		{
            window.external.AddClick();
        }
        else 
		{
            if ($.trim($('#txtPhrase').val()) != "") 
			{
                $('#txtDefi').focus();
            }
        }
    }
    else 
	{
        window.external.txtPhraseKeyUp();
    }
}
function InitinalSort(ca, ud) 
{
    $('#thPh').click(function () 
	{
        u = window.external.GetSortedDirection();
        if (u) 
		{
            window.external.SortPhrase('false', 'false');
        }
        else 
		{
            window.external.SortPhrase('false', 'true');
        }
    });
    $('#thTime').click(function ()
	{
        u = window.external.GetSortedDirection();
        if (u) 
		{
            window.external.SortPhrase('true', 'false');
        }
        else 
		{
            window.external.SortPhrase('true', 'true');
        }
    });


    $('#thPh').mouseover(function () 
	{
        if (ud) 
		{
            $('#aalup').show();
        }
        else 
		{
            $('#aaldown').show();
        }
    });
    $('#thPh').mouseout(function () 
	{
        ca = window.external.GetSortedColumn();
        if (ca) 
		{
            $('#aalup').hide();
            $('#aaldown').hide();
        }
    });
    $('#thTime').mouseover(function () 
	{
        if (ud) 
		{
            $('#achup').show();
        }
        else 
		{
            $('#achdown').show();
        }
    });
    $('#thTime').mouseout(function () 
	{
        ca = window.external.GetSortedColumn();
        if (!ca) 
		{
            $('#achup').hide();
            $('#achdown').hide();
        }
    });

    $('#aalup').css({ display: "none" });
    $('#aaldown').css({ display: "none" });
    $('#achup').css({ display: "none" });
    $('#achdown').css({ display: "none" });
    if (ca) 
	{
        if (ud) 
		{
            $('#achup').show();
        }
        else 
		{
            $('#achdown').show();
        }
    }
    else 
	{
        if (ud) 
		{
            $('#aalup').show();
        }
        else 
		{
            $('#aaldown').show();
        }
    }
    $("div").css({ "cursor": "default" });
}
function SearchInBing(obj) 
{
    window.open('https://cn.bing.com/search?mkt=zh-CN&setLang=zh&form=BDCN21&q=' + encodeURIComponent(String(obj)).substring(0, 1800));
}

//region scrollbar ops
var offset=0;
function ResetScrollBarPos()
{
    $('#phraseListDiv').scrollTop(offset);
}
function InitScrollBar() 
{
    $('#phraseListDiv').scroll(function () 
	{
		offset = $('#phraseListDiv').scrollTop();
	});
}

var lastBodyHeight = 0;
var lastBodyWidth=0;
function AdjustWordListSize() 
{
    var lastDivHeight = parseInt($("#phraseListDiv").css("height"));
    var curClientHeight = document.body.clientHeight;
    $("#phraseListDiv").css("height", lastDivHeight + curClientHeight - lastBodyHeight);
    lastBodyHeight = curClientHeight;

    var lastVocaWidth = $(".divVoca").width();
    var curBodyWidth = $("body").width();
    $(".divVoca").width(lastVocaWidth + curBodyWidth - lastBodyWidth);
    lastBodyWidth = $('body').width();
}
function RecordBodySize() 
{
    lastBodyHeight = document.body.clientHeight;
    lastBodyWidth = $('body').width();
    var divMainMargineTop = $("#divMain").outerHeight(true) - $("#divMain").outerHeight();
    var otherHeight = $(".actBTN").outerHeight(true) + $("#phraseListPageTail").outerHeight(true) + $("#phraseListHead").outerHeight(true) + divMainMargineTop;
    $("#phraseListDiv").height(lastBodyHeight - otherHeight);

    var vocaArea = $(".divVoca");
    vocaArea.width(lastBodyWidth - parseInt(vocaArea.css("margin-left")) - parseInt(vocaArea.css("margin-right")));
}
//endregion