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

var autoPlayTimeOutId;
//SlideRight
var currentPhIdx = 1;
var isSetPre = false;
var isSetNext = false;
//region UI common
function ReturnToMainHome()
{
    window.external.ReturnToMainHome();
}

function ReturnToMainHomeByBrowsing()
{
    StopAutoPlay();
    window.external.StoreBrowseProgress();
    window.external.NaviBack();
}

function BackHomeClick()
{
    $(this).removeClass('divBackHome_H').addClass('divBackHome_P');
    window.external.NaviBack();
}

function BackHomeAndRecordProgressClick()
{
    $(this).removeClass('divBackHome_H').addClass('divBackHome_P');
    window.external.StoreBrowseProgress();
    window.external.NaviBack();
}

function PlayAudioAnimate()
{
    $('.imgAkiconBase').each(function ()
	{
        var audio = $(this);
        audio.toggleClass('imgAkicon_N imgAkicon_H');
        setTimeout(function (){ audio.toggleClass('imgAkicon_N imgAkicon_H'); }, 100);
    });
}

function FocusElement(id)
{
    var ele = document.getElementById(id);
    if (ele)
	{
        ele.focus();
        ele.select();
    }
}

function fuzzPage()
{
    $('body').css("filter", "alpha(opacity=30)");
}

function deFuzzPage()
{
    $('body').css("filter", "");
}

//endregion
//region Mode Select page
function ModelStudy()
{
    if (window.external.ModelSelectedStudy())
	{
        $('#divModelSlt').hide();
        $('#divLearn').show();
    }
}

function StartRandomView()
{
    if (window.external.ModelSelectedRandomView())
	{
        $('#divModelSlt').hide();
        $('#divRandomView').show();
    }
}
//endregion

function DocReady()
{
    $('.divDefaultBook').hover(
			function ()
			{
			    $(this).css("border", "1px solid #cceeff");
			},
			function ()
			{
			    $(this).css("border", "1px solid #ffffff");
			}
		);
    $('.divDefaultBook').click(
        function ()
		{
            var flag = window.external.SelectedVocabulary($(this).attr("id"));
            if (flag)
			{
                $('#divModelSlt').show();
                $('#divMain').hide();
            }
        }
    );
    $('.divNoteBook').hover(
			function ()
			{
			    $(this).css("border", "1px solid #cceeff");
			},
			function ()
			{
			    $(this).css("border", "1px solid #ffffff");
			}
		);
    $('.divNoteBook').click(
        function ()
		{
            var flag = window.external.SelectedNotebook($(this).attr("id"));
            if (flag)
			{
                $('#divModelSlt').show();
                $('#divMain').hide();
            }
        }
    );
    $('.divWDBook').hover(
			function ()
			{
			    $(this).css("border", "1px solid #cceeff");
			},
			function ()
			{
			    $(this).css("border", "1px solid #ffffff");
			}
		);
    $('.divWDBook').click(
        function ()
		{
            window.external.SelectWDAlbum($(this).attr("id"));
        }
        );
    $('.divAddWDBook').hover(
			function ()
			{
			    $(this).css("border", "1px solid #cceeff");
			},
			function ()
			{
			    $(this).css("border", "1px solid #ffffff");
			}
		);
    $('.divAddWDBook').click(
        function ()
        {
            javascript: window.external.StartWD();
        }
        );
}

var bCardNotFlippedYet = true;
function cardFlip()
{
    //if already flipping,return
    var bNotFlipping = window.external.GSFlipTime(600);
    if (!bNotFlipping)
	{
        return;
    }
    

    $('.flashCard').quickFlipperWithCallback(DeckCardDefiHeight);
    $('.headWord').html("");
    var arr = $('.definition');
    $(arr[1]).html("");
    $(arr[2]).html("");
    var arr1 = $('.headWord2');
    $(arr1[1]).html("");
    $(arr1[2]).html("");

    window.external.SetEndingAttempt();
    bCardNotFlippedYet = false;
}


function responseRight()
{
    window.external.KnowClick();
    //if the def has not been shown yet, show the def and show the nextPhrase
    if (bCardNotFlippedYet)
    {
        cardFlip();
        $('.nextPhrase').show();
        $('.judgeMe').hide();
        return;
    }
    else
    {
        //else, leftSlider
        leftSlider(
            function ()
            {
                
            },
            function ()
            {
                window.external.NextPhrase();
                bCardNotFlippedYet = true;
            }
        );
    }
    
}

function responseWrong()
{
    window.external.UnKnowClick();
    //if the def has not been shown yet, show the def and show the nextPhrase
    if(bCardNotFlippedYet)
    {
        cardFlip();
        $('.nextPhrase').show();
        $('.judgeMe').hide();
        return;
    }
    else
    {
        //else, leftSlider
        leftSlider(
            function ()
            {
                
            },
            function ()    
            {
                window.external.NextPhrase();
                bCardNotFlippedYet = true;
            }
        );
    }
    
}

function makeFamiliar()
{
    window.external.SetFamiliarClick();
    showNextPhrase();
}

function makeDeleted()
{
    window.external.SetDeletedClick();
    showNextPhrase();
}


function showNextPhrase()
{
    if (bCardNotFlippedYet)
    {
        window.external.NextPhrase();
        return;
    }

    leftSlider(
       function ()
       {
       },
       function ()
       {
           window.external.NextPhrase();
           bCardNotFlippedYet = true;
       }
   );
}


function leftSlider(f1, f2)
{
    var bNotFlipping = window.external.GSFlipTime(500);
    if (!bNotFlipping)
	{
        return;
    }

    var i = $('#divFlashCard1').offset().left;
    var j = $('#divFlashCard2').offset().left;
    if (i <= 30 && i >= 0) 
	{
        $('#divFlashCard2').css({ left: "0px" });
        z = $('#divFlashCard1').css("z-index");
        z--;
        $('#divFlashCard2').css({ "z-index": z });
        window.external.SetSelectStudyCardIndex(true);
        f1();
        $('#divFlashCard1').animate({ left: "-390px" }, 500);
        z = z + 2;
        $('#divFlashCard1').css({ "z-index": z });
    }
    if (j <= 30 && j >= 0) 
	{
        $('#divFlashCard1').css({ left: "0px" });
        z = $('#divFlashCard2').css("z-index");
        z--;
        $('#divFlashCard1').css({ "z-index": z });
        window.external.SetSelectStudyCardIndex(false);
        f1();
        $('#divFlashCard2').animate({ left: "-390px" }, 500);
        z = z + 2;
        $('#divFlashCard2').css({ "z-index": z });
    }

    f2();
}

function ModelStudyInit()
{
    $(document).keydown(function ()
	{
        if (event.keyCode == 116)
		{//F5
            event.keyCode = 0;
            event.returnValue = false;
            return false;n
        }
        else if ($('.nextPhrase').is(':visible') && (event.keyCode == 0))
		{//Enter/Space
            event.keyCode = 0;
            event.returnValue = 0;
            showNextPhrase();   
        }
        else if ($('.judgeMe').is(':visible') && event.keyCode == 89)
		{//Y
            event.keyCode = 0;
            event.returnValue = 0;
            responseRight();
        }
        else if ($('.judgeMe').is(':visible') && event.keyCode == 78)
		{//N
            event.keyCode = 0;
            event.returnValue = 0;
            responseWrong();
        }
        else if ($('.judgeMe').is(':visible') && event.keyCode == 68)
        {//D
            event.keyCode = 0;
            event.returnValue = 0;
            makeDeleted();
        }
        else if ($('.judgeMe').is(':visible') && !bCardNotFlippedYet && event.keyCode == 70)
        {//F
            event.keyCode = 0;
            event.returnValue = 0;
            makeFamiliar();
        }
		else if(bCardNotFlippedYet && event.keyCode == 32)
		{//Space
			event.keyCode = 0;
            event.returnValue = 0;
			cardFlip();	
		}
        else if (!bCardNotFlippedYet && event.keyCode == 77)
		{//M
            event.keyCode = 0;
            event.returnValue = 0;
            window.external.GetMoreDefForCurrentWord();
        }
        else if (!bCardNotFlippedYet && event.keyCode == 80)
		{//P
            event.keyCode = 0;
            event.returnValue = 0;
            PlayAudioAnimate();
            window.external.PlayCurrentWord();
        }
    });
}

function initialFlip()
{
    $('#divFlashCard1').quickFlip();
}

function ReBindAutoAndPause()
{
    autoAndpauseEvent();
}

function autoAndpauseEvent()
{
    $('#autoBTN').removeClass().unbind();
    $('#pauseBTN').removeClass().unbind();

    clearTimeout(autoPlayTimeOutId);
    $('#autoBTN').addClass("divBTNBase divautoBTN");
    $('#autoBTN').mouseover(function ()
	{
        $(this).removeClass("divautoBTN").addClass("divautoBTN1");
    }).mouseout(function ()
	{
        $(this).removeClass("divautoBTN1").addClass("divautoBTN");
    }).mousedown(function ()
	{
        $(this).removeClass("divautoBTN1").addClass("divautoBTN2")
    }).mouseup(function ()
	{
        $(this).removeClass("divautoBTN2").addClass("divautoBTN");
    }).click(function ()
	{
        AutoPlay();
        $(this).hide();
        $("#pauseBTN").show();
    });

    $('#pauseBTN').addClass("divBTNBase divpauseBTN");
    $('#pauseBTN').mouseover(function ()
	{
        $(this).removeClass("divpauseBTN").addClass("divpauseBTN1");
    }).mouseout(function ()
	{
        $(this).removeClass("divpauseBTN1").addClass("divpauseBTN");
    }).mousedown(function ()
	{
        $(this).removeClass("divpauseBTN1").addClass("divpauseBTN2")
    }).mouseup(function ()
	{
        $(this).removeClass("divpauseBTN2").addClass("divpauseBTN");
    }).click(function ()
	{
        StopAutoPlay();
        $(this).hide();
        $("#autoBTN").show();
    });
    $("#pauseBTN").hide();
}

function preBTNEventNotValid()
{
    $('#preBTN').unbind();
    $('#preBTN').removeClass().addClass("divBTNBase divpreBTN3");
}

function preBTNEvent()
{
    $('#preBTN').removeClass("divpreBTN3").addClass("divpreBTN");
    $('#preBTN').mouseover(function ()
	{
        $(this).removeClass("divpreBTN").addClass("divpreBTN1");
    }).mouseout(function ()
	{
        $(this).removeClass("divpreBTN1").addClass("divpreBTN");
    }).mousedown(function ()
	{
        $(this).removeClass("divpreBTN1").addClass("divpreBTN2");
    }).mouseup(function ()
	{
        $(this).removeClass("divpreBTN2").addClass("divpreBTN");
    });
}

function nextBTNEvent()
{
    isSetNext = true;
    $('#nextBTN').addClass("divBTNBase divnextBTN");
    $('#nextBTN').mouseover(function ()
	{
        $(this).removeClass("divnextBTN").addClass("divnextBTN1");
    }).mouseout(function ()
	{
        $(this).removeClass("divnextBTN1").addClass("divnextBTN");
    }).mousedown(function ()
	{
        $(this).removeClass("divnextBTN1").addClass("divnextBTN2")
    }).mouseup(function ()
	{
        $(this).removeClass("divnextBTN2").addClass("divnextBTN");
    });
}

var SiteMap =
{
    amsn: 'http://profile.live.com/badge?url={0}',
    asina: 'http://v.t.sina.com.cn/share/share.php?title={1}...{0}',
    asohu: 'http://t.sohu.com/third/post.jsp?url={0}&title={1}&content=utf-8',
    adouban: 'http://www.douban.com/recommend/?url={0}&title={1}',
    a163: 'http://t.163.com/article/user/checkLogin.do?info={1}+{0}',
    atianya: 'http://share.tianya.cn/openapp/restpage/activity/appendDiv.jsp?ccTitle={1}&ccUrl={0}',
    arenren: 'http://share.xiaonei.com/share/buttonshare.do?link={0}',
    akaixin: 'http://www.kaixin001.com/~repaste/repaste.php?rtitle={1}&rurl={0}'
};
var cnts =
{
    url: "https://cn.bing.com/dict/",
    ctent: '我正在使用必应背单词，记忆曲线模型记单词，还可以按照词频，后缀，乱序记单词，很有效哦！'
};
function SendShareMsg(el, wsite, isEncode)
{
    u = SiteMap[wsite];
    en = encodeURIComponent;
    window.open (isEncode ? fmt(u, en(cnts.url), en(cnts.ctent)) : fmt(u, cnts.url, cnts.ctent));
}
function fmt(src, ag1, ag2)
{
    return src.replace("{0}", ag1).replace("{1}", ag2);
}

function setPreBTNNotValid()
{
    isSetPre = false;
    preBTNEventNotValid();
}

function setPreBTNValid()
{
    var api = $('.scroll-pane').data('jsp');
    preBTNEvent();
    $('#preBTN').unbind('click');
    $('#preBTN').bind('click', function ()
	{
        SetPreviousButton(api);
    });
    isSetPre = true;
}

function destroyJSP()
{
    var api = $('.scroll-pane').data('jsp');
    api.destroy();
    window.external.SetEndUnitCnt();
    isSetNext = false;
}

function unitLinkClick(obj, idx)
{
    if (!$(obj).hasClass("current"))
	{
        $('.unitPav .current').removeClass();
        $(obj).addClass("current");
        window.external.GetUnitWordsByLink(idx);
    }
}

function GotoNextUnit()
{
    $('.unitPav .current').removeClass();
    window.external.SetNextUnitCnt();
}

function GotoPreUnit()
{
    $('.unitPav .current').removeClass();
    window.external.SetPreUnitCnt();
}

function pageLinkClick(obj, idx)
{
    if (!$(obj).hasClass("current"))
	{
        window.external.GetUnitPages(idx);
    }
}

function setScrollWidth1(obj)
{
    $('#scroll').css({ width: obj });
    var api = $('.scroll-pane').data('jsp');
    api.reinitialise();
    api.scrollToX(0);
}

function SetNextButton(api)
{
    xy = api.getContentPositionX();

    yy = xy % 360;
    if (yy != 0)
	{
        xy = xy - yy + 360;
    }
    if (xy == 0)
	{
        var w = api.getContentPane().css("width");
        //if (w != "360px")
		{
            api.scrollToX(360);
        }
    }
    else
	{
        api.scrollToX(xy + 360);
    }

    xy = api.getContentPositionX();
    yy = xy % 360;
    if (yy != 0)
	{
        xy = xy - yy + 360;//to ensure it is a integer multiples of 360
    }
    var i = xy / 360;

    if (!isSetPre)
	{
        preBTNEvent();
        $('#preBTN').bind('click', function ()
		{
            SetPreviousButton(api);
        });
        isSetPre = true;
    }

    var j = window.external.SetPhIdxInUnitByButton(true);
    if (j != i + 2)
	{
        j--;
        api.scrollToX(j * 360);
    }
    return false;
}

function SetPreviousButton(api)
{
    xy = api.getContentPositionX();
    yy = xy % 360;
    if (yy != 0)
	{
        xy = xy - yy + 360;
    }
    api.scrollToX(xy - 360);
    x = api.getContentPositionX();
    if (x <= 360)
	{
        isSetPre = false;
        preBTNEventNotValid();
    }
    xy = api.getContentPositionX();
    yy = xy % 360;
    if (yy != 0)
	{
        xy = xy - yy + 360;
    }
    var i = xy / 360;
    var j = window.external.SetPhIdxInUnitByButton(false);
    if (j != i)
	{
        j--;
        api.scrollToX(j * 360);
    }
    //clear timer
    StopAutoPlay();
    return false;
}

function AutoPlay()
{
    clearTimeout(autoPlayTimeOutId);
    autoPlayTimeOutId = setTimeout(function ()
	{
        window.external.SetAutoPlayStatus(true);
        SetAutoPlayToActive();
    }, "300");
}

function StopAutoPlay()
{
    if (autoPlayTimeOutId != undefined && autoPlayTimeOutId != null)
	{
        clearTimeout(autoPlayTimeOutId);
        window.external.SetAutoPlayStatus(false);
        $("#autoBTN").show();
        $("#pauseBTN").hide();
    }
}

function SetAutoPlayToActive()
{
    $('#nextBTN').click();
    clearTimeout(autoPlayTimeOutId);
    autoPlayTimeOutId = setTimeout(SetAutoPlayToActive, "5000");
}

function MOver()
{
    if (autoPlayTimeOutId != undefined && autoPlayTimeOutId != null)
	{
        clearTimeout(autoPlayTimeOutId);
        window.external.SetAutoPlayStatus(false);
    };
}

function MOut()
{
    var tempx = event.clientX - document.body.scrollLeft;
    var tempy = event.clientY - document.body.scrollTop;
    if (tempx < 26 || tempx > 360 || tempy < 41 || tempy > 239)
	{
        autoPlayTimeOutId = setTimeout(function ()
		{
            if ($('#pauseBTN').is(":visible") == true)
			{
                window.external.SetAutoPlayStatus(true);
                SetAutoPlayToActive();
            }
        }, "400");
    }
}

function PlayWord(headword)
{
    var hash = window.external.GetHeadwordHash(headword);
    var url = "https://dictionary.blob.core.chinacloudapi.cn/media/audio/tom/" + hash + ".mp3";
    //var audioPlayer = document.getElementById("_aplayer");
    //audioPlayer.Settings.PlayCount = 1;
    //audioPlayer.URL = url;
    var audioPlayer = document.getElementById("_aplayer");
    try
	{
        audioPlayer.SetVariable("hash", url);
        audioPlayer.GotoFrame(2); // Stop potentially any playing sounds
        audioPlayer.GotoFrame(1);
    }
    catch (e)   
	{
        if (audioPlayer.Settings)
		{
            audioPlayer.Settings.PlayCount = 1; //Call Settings.PlayCount especially to draw an exception if this is not present
            audioPlayer.URL = url;
        }
    }
}

function fixPNG(myImage)
{
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);
    if ((version >= 5.5) && (version < 7) && (document.body.filters))
	{
        var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
        var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
        var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' ";
        var imgStyle = "display:inline-block;" + myImage.style.cssText;
        var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + myImage.width
			+ "px; height:" + myImage.height
			+ "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
        myImage.outerHTML = strNewHTML;
    }
}

function CleanCardDefiHeight()
{
    $('.definition').each(function ()
	{
        $(this).css("overflow", "visible");
        $(this).parent().find('.omitMark').hide();
    });
}

//if deck card has not enough space for definition display, hide the overflown chars and show the omit mark
function DeckCardDefiHeight()
{
    $('.definition').each(function ()
	{
        if (this.scrollHeight > parseInt($(this).css("max-height")))
		{
            $(this).css("overflow", "hidden");
            $(this).parent().find('.omitMark').show();
        }
    });
}

//region SelectView
function UnitCntView()
{
    isSetPre = false;
    $('.scroll-pane').jScrollPane(
	{
		clickOnTrack: false,
		animateScroll: true,
		horizontalDragMinWidth: 20
	});
    var api = $('.scroll-pane').data('jsp');

    $('#preBTN').unbind('click');
    $('#nextBTN').unbind('click');
    $('#nextBTN').bind('click', function ()
	{
        SetNextButton(api);
    });
    $(document).keydown(function ()
	{
        if (event.keyCode == 116 || event.keyCode == 13)
		{//F5,Enter
            event.keyCode = 0;
            event.returnValue = false;
        }
        else if (event.keyCode == 37 && isSetPre)
		{//<-
            event.keyCode = 0;
            event.returnValue = 0;
            $('#preBTN').click();
        }
        else if (event.keyCode == 39 && isSetNext)
		{//->
            event.keyCode = 0;
            event.returnValue = 0;
            $('#nextBTN').click();
        }
        else if (event.keyCode == 32)
		{//space
            event.keyCode = 0;
            event.returnValue = 0;
            if (!$("#pauseBTN").is(":hidden"))
			{
                StopAutoPlay();
                $('#autoBTN').show();
                $("#pauseBTN").hide();
            }
            else
			{
                AutoPlay();
                $('#autoBTN').hide();
                $("#pauseBTN").show();
            }
        }
        else if (event.keyCode == 34)
		{//page down
            event.keyCode = 0;
            event.returnValue = 0;
            GotoNextUnit();
        }
        else if (event.keyCode == 33)
		{//page up
            event.keyCode = 0;
            event.returnValue = 0;
            GotoPreUnit();
        }
        else if (event.keyCode == 77)
		{//M
            event.keyCode = 0;
            event.returnValue = 0;
            window.external.GetMoreDefForCurrentWord();
        }
        else if (event.keyCode == 80)
		{//P
            event.keyCode = 0;
            event.returnValue = 0;
            PlayAudioAnimate();
            window.external.PlayCurrentWord();
        }
        else if ($('.againBTN').length && event.keyCode == 82)
		{//R
            event.keyCode = 0;
            event.returnValue = 0;
            window.external.ReBrowsingUnit();
        }
        else if (!$('.nextUnit').length && event.keyCode == 34)
		{//page down
            event.keyCode = 0;
            event.returnValue = 0;
            GotoNextUnit();
        }
        return false;
    });
}

function ScrollToZero()
{
    $('.jspPane').css("left", "0px");
    $('.jspDrag').css("left", "0px");
}

function ScrollToJSPWithDelay(oIdx)
{
    setTimeout(function ()
	{
        var api = $('.scroll-pane').data('jsp');
        var idx = parseInt(oIdx);
        idx = (idx - 1) * 360;
        api.scrollToX(idx);
        if (idx != 0)
		{
            setPreBTNValid();
        }
    },
    100 //dasons: add 100ms delay to wait function setScrollWidth finish reinitialise operations
    );
}

function ScrollToJSP(oIdx)
{
    var api = $('.scroll-pane').data('jsp');
    var idx = parseInt(oIdx);
    idx = (idx - 1) * 360;
    api.scrollToX(idx);
    if (idx != 0)
	{
        setPreBTNValid();
    }
}

function setScrollWidth(obj)
{
    $('#scroll').css({ width: obj });

    var api = $('.scroll-pane').data('jsp');

    var throttleTimeout;
    if ($.browser.msie)
	{
        if (!throttleTimeout)
		{
            throttleTimeout = setTimeout(
				function ()
				{
					api.reinitialise();
					throttleTimeout = null;
				},
				50  //dasons: doesn't know why this 50ms needed, but maybe a previous bug, just let them stay here.
			);
        }
    }
    ScrollToZero();
}

//endregion
//region RandomView
function UnitRandomViewInit()
{
    isSetPre = false;
    sliderMutex = true;

    $('#preBTN').unbind('click');
    $('#nextBTN').unbind('click');
    $('#nextBTN').bind('click', function A()
	{
        if (!sliderMutex)
		{
            return;
        }

        $('#nextBTN').unbind('click');

        leftSliderForRandomView(
        function ()
		{
            window.external.RandomViewNextClick();
        },
        function ()
		{
            $('#nextBTN').bind('click', A);
        }
        );
    });
    isSetNext = true;

    $(document).keydown(function ()
	{
        if (event.keyCode == 116 || event.keyCode == 13)
		{
            event.keyCode = 0;
            event.returnValue = false;
        }
        else if (event.keyCode == 37 && isSetPre)
		{//<-
            event.keyCode = 0;
            event.returnValue = 0;
            $('#preBTN').click();
        }
        else if (event.keyCode == 39 && isSetNext)
		{//->
            event.keyCode = 0;
            event.returnValue = 0;
            $('#nextBTN').click();
        }
        else if (event.keyCode == 77 || event.keyCode == 109)
		{//m or M
            event.keyCode = 0;
            event.returnValue = 0;
            window.external.GetMoreDefForCurrentWord();
        }
        else if (event.keyCode == 80 || event.keyCode == 112)
		{//p or P
            event.keyCode = 0;
            event.returnValue = 0;
            PlayAudioAnimate();
            window.external.PlayCurrentWord();
        }
        return false;
    });
}

function nextBTN_RV_Event()
{
    isSetNext = true;
    $('#nextBTN').addClass("divBTNRandomviewBase divNextBTNRVC");
    $('#nextBTN').mouseover(function ()
	{
        $(this).removeClass("divNextBTNRVC").addClass("divNextBTNRVH");
    }).mouseout(function ()
	{
        $(this).removeClass("divNextBTNRVH").addClass("divNextBTNRVC");
    }).mousedown(function ()
	{
        $(this).removeClass("divNextBTNRVH").addClass("divNextBTNRVA")
    }).mouseup(function ()
	{
        $(this).removeClass("divNextBTNRVA").addClass("divNextBTNRVC");
    });
}

function preBTNEvent_RV_NotValid()
{
    $('#preBTN').unbind();
    $('#preBTN').removeClass().addClass("divBTNRandomviewBase divPreBTNRVF");
}

function setPreBTN_RV_NotValid()
{
    isSetPre = false;
    preBTNEvent_RV_NotValid();
}

function preBTN_RV_Event()
{
    $('#preBTN').removeClass("divPreBTNRVF").addClass("divPreBTNRVC");
    $('#preBTN').mouseover(function ()
	{
        $(this).removeClass("divPreBTNRVC").addClass("divPreBTNRVH");
    }).mouseout(function ()
	{
        $(this).removeClass("divPreBTNRVH").addClass("divPreBTNRVC");
    }).mousedown(function ()
	{
        $(this).removeClass("divPreBTNRVH").addClass("divPreBTNRVA");
    }).mouseup(function ()
	{
        $(this).removeClass("divPreBTNRVA").addClass("divPreBTNRVC");
    });
}

var sliderMutex = true;
function leftSliderForRandomView(f1, f2)
{
    sliderMutex = false;
    var fl = window.external.GSFlipTime(500);
    if (!fl)
	{
        return;
    }
    var i = $('#divFlashCard1').offset().left;
    var j = $('#divFlashCard2').offset().left;
    if (i <= 30 && i >= 0)
	{
        $('#divFlashCard2').css({ left: "0px" });
        z = $('#divFlashCard1').css("z-index");
        z--;
        $('#divFlashCard2').css({ "z-index": z });
        window.external.SetSelectStudyCardIndex(true);
        f1();
        $('#divFlashCard1').animate({ left: "-390px" }, 500, function ()
		{
            sliderMutex = true;
            z = z + 2;
            $('#divFlashCard1').css({ "z-index": z });
            f2();

        });

    }
    if (j <= 30 && j >= 0)
	{
        $('#divFlashCard1').css({ left: "0px" });
        z = $('#divFlashCard2').css("z-index");
        z--;
        $('#divFlashCard1').css({ "z-index": z });
        window.external.SetSelectStudyCardIndex(false);
        f1();
        $('#divFlashCard2').animate({ left: "-390px" }, 500, function ()
		{
            sliderMutex = true;
            z = z + 2;
            $('#divFlashCard2').css({ "z-index": z });
            f2();

        });
    }
}

function rightSliderForRandomView(f1, f2)
{
    sliderMutex = false;
    var fl = window.external.GSFlipTime(500);
    if (!fl)
	{
        return;
    }
    var i = $('#divFlashCard1').offset().left;
    var j = $('#divFlashCard2').offset().left;
    if (i <= 30 && i >= 0)
	{
        $('#divFlashCard2').css({ left: "0px" });
        z = $('#divFlashCard1').css("z-index");
        z--;
        $('#divFlashCard2').css({ "z-index": z });
        window.external.SetSelectStudyCardIndex(true);
        f1();
        $('#divFlashCard1').animate({ left: "390px" }, 500, function ()
		{
            sliderMutex = true;
            z = z + 2;
            $('#divFlashCard1').css({ "z-index": z });
            f2();

        });
    }
    if (j <= 30 && j >= 0)
	{
        $('#divFlashCard1').css({ left: "0px" });
        z = $('#divFlashCard2').css("z-index");
        z--;
        $('#divFlashCard1').css({ "z-index": z });
        window.external.SetSelectStudyCardIndex(false);
        f1();
        $('#divFlashCard2').animate({ left: "390px" }, 500, function ()
		{
            sliderMutex = true;
            z = z + 2;
            $('#divFlashCard2').css({ "z-index": z });
            f2();

        });
    }
}

function setpreBTNValidForRandomView()
{
    if (!isSetPre)
	{
        preBTN_RV_Event();

        $('#preBTN').bind('click', function B()
		{
            if (!sliderMutex)
			{
                return;
            }

            $('#preBTN').unbind('click');
            rightSliderForRandomView(
			function ()
			{
				window.external.RandomViewPreviousClick();
			}
			,
			function ()
			{
				$('#preBTN').bind('click', B);
			}
			);
        });
    }
    isSetPre = true;
}
//endregion

/*********************************************/
function sync_btn_onclick()
{
	if($('#sync_btn').hasClass('sync_btn_syncing'))
	{
		return false;
	}
	window.external.Sync();
}

//1.默认状态的同步按钮
//1.1
//前端方法:点击同步按钮后发现还没有登录,则显示"默认"的同步按钮,并显示"正在登录"的状态文字
function loginFront()
{
	$('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_normal');
	$('#sync_txt').html('正在登录');
}

//1.2
//前端方法,同步完成以后,先显示"同步完成"的同步按钮,然后切换到"默认"的同步按钮,并定期刷新"距上次同步时间"
var timer = null;
function endSyncFront(day)
{
    $('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_normal');
	$('#sync_txt').html('同步完成');

    //定期显示"距上次同步时间"
    setTimeout(function ()
    {
        $('#sync_txt').html(checkTime(day));
        clearInterval(timer);
        timer = null;
        timer = setInterval(function ()
        {
            $('#sync_txt').html(checkTime(day));
        }, 1000 * 60);
    }, 2000);
}

//1.3 
//前端方法,如果用户没有登录,则仅显示"默认"的同步按钮; 如果用户刚登录还没有开始同步,则显示"默认"的同步按钮,并定期刷新"距上次同步时间"; 如果用户同步失败,则仅显示"默认"的同步按钮
function statusFront(className, day)
{
    $('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_normal');
	$('#sync_txt').html('');

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


//2.有新内容需要同步状态的同步按钮
//2.1
//前端方法,当用户已经登录,并进行了一些操作导致有新的可以同步的内容时,显示"有新内容需要同步"的同步按钮
function hasNewWordFront()
{
    $('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_new');
	$('#sync_txt').html('您有新的内容要同步');
}


//3.同步中的同步按钮
//3.1
//前端方法,当正式开始同步的时候,显示"正在和云端同步"状态
function setSyncBTNIngVisible()
{
    $('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_syncing');
	$('#sync_txt').html('正在和云端同步');
}

//3.2
//前端方法,让前端切换到"正在和云端同步"状态
function startSyncFront()
{
    $('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_syncing');
	$('#sync_txt').html('正在和云端同步');
};

//3.3
//前端方法,在同步过程中,用于改变同步中的状态文字
function checkTextFront(statusCode)
{
    $('#sync_btn').removeClass('sync_btn_normal sync_btn_syncing sync_btn_new').addClass('sync_btn_syncing');
	
    switch (statusCode)
    {
		case 'login':
            $('#sync_txt').html('正在登录'); break;
        case 'download':
            $('#sync_txt').html('正在从云端同步到本地'); break;
        case 'merge':
            $('#sync_txt').html('正在合并云端数据'); break;
        case 'upload':
            $('#sync_txt').html('正在同步到云端'); break;
        default:
            break;
    }
}


//前端方法,用于生成"距上次同步时间"的状态文字
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;
}




