/* Minification failed. Returning unminified contents.
(1681,25-26): run-time error JS1003: Expected ':': (
(1682,9-10): run-time error JS1009: Expected '}': {
(1691,5-11): run-time error JS1006: Expected ')': window
(2572,1-2): run-time error JS1002: Syntax error: }
(2574,29-30): run-time error JS1195: Expected expression: )
(2574,31-32): run-time error JS1004: Expected ';': {
(2576,2-3): run-time error JS1195: Expected expression: )
 */
/* =============================================================
 * bootstrap3-typeahead.js v3.0.3
 * https://github.com/bassjobsen/Bootstrap-3-Typeahead
 * =============================================================
 * Original written by @mdo and @fat
 * =============================================================
 * Copyright 2014 Bass Jobsen @bassjobsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */


!function ($) {

    "use strict";
    // jshint laxcomma: true


    /* TYPEAHEAD PUBLIC CLASS DEFINITION
     * ================================= */

    var Typeahead = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.typeahead.defaults, options);
        this.matcher = this.options.matcher || this.matcher;
        this.sorter = this.options.sorter || this.sorter;
        this.select = this.options.select || this.select;
        this.autoSelect = typeof this.options.autoSelect == 'boolean' ? this.options.autoSelect : true;
        this.highlighter = this.options.highlighter || this.highlighter;
        this.updater = this.options.updater || this.updater;
        this.source = this.options.source;
        this.delay = typeof this.options.delay == 'number' ? this.options.delay : 250;
        this.$menu = $(this.options.menu);
        this.shown = false;
        this.listen();
        this.showHintOnFocus = typeof this.options.showHintOnFocus == 'boolean' ? this.options.showHintOnFocus : false;
    };

    Typeahead.prototype = {

        constructor: Typeahead

    , select: function () {
        var val = this.$menu.find('.active').data('value');
        if (this.autoSelect || val) {
            this.$element
              .val(this.updater(val))
              .change();
        }
        var myTypeahead = this;
        setTimeout(function () {
            return myTypeahead.hide();
        }, 100);

    }

    , updater: function (item) {
        var split = item.split('~');
        return split[0];
    }

    , setSource: function (source) {
        this.source = source;
    }

    , show: function () {
        var pos = $.extend({}, this.$element.position(), {
            height: this.$element[0].offsetHeight
        }), scrollHeight;

        scrollHeight = typeof this.options.scrollHeight == 'function' ?
            this.options.scrollHeight.call() :
            this.options.scrollHeight;

        this.$menu
          .insertAfter(this.$element)
          .css({
              top: pos.top + pos.height + scrollHeight
          , left: pos.left
          })
          .show();

        this.shown = true;
        return this;
    }

    , hide: function () {
        this.$menu.hide();
        this.shown = false;
        return this;
    }

    , lookup: function (query) {
        var items;
        if (typeof (query) != 'undefined' && query !== null) {
            this.query = query;
        } else {
            this.query = this.$element.val() || '';
        }

        if (this.query.length < this.options.minLength) {
            return this.shown ? this.hide() : this;
        }

        var worker = $.proxy(function () {
            items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source;
            if (items) {
                this.process(items);
            }
        }, this)

        clearTimeout(this.lookupWorker)
        this.lookupWorker = setTimeout(worker, this.delay)
    }

    , process: function (items) {
        var that = this;

        items = $.grep(items, function (item) {
            return that.matcher(item);
        });

        items = this.sorter(items);

        if (!items.length) {
            return this.shown ? this.hide() : this;
        }

        if (this.options.items == 'all') {
            return this.render(items).show();
        } else {
            return this.render(items.slice(0, this.options.items)).show();
        }
    }

    , matcher: function (item) {
        return ~item.toLowerCase().indexOf(this.query.toLowerCase());
    }

    , sorter: function (items) {
        var beginswith = []
          , caseSensitive = []
          , caseInsensitive = []
          , item;

        while ((item = items.shift())) {
            if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item);
            else if (~item.indexOf(this.query)) caseSensitive.push(item);
            else caseInsensitive.push(item);
        }

        return beginswith.concat(caseSensitive, caseInsensitive);
    }

    , highlighter: function (item) {
        var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
        return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
            return '<strong>' + match + '</strong>';
        });
    }

    , render: function (items) {
        var that = this;

        items = $(items).map(function (i, item) {
            i = $(that.options.item).data('value', item);
            var res = that.highlighter(item).split('$');
            i.find('a').html(res[0]);
            i.find('a').parent().append(res[1]);
            return i[0];
        });

        if (this.autoSelect) {
            items.first().addClass('active');
        }
        this.$menu.html(items);
        return this;
    }

    , next: function (event) {
        var active = this.$menu.find('.active').removeClass('active')
          , next = active.next();

        if (!next.length) {
            next = $(this.$menu.find('li')[0]);
        }

        next.addClass('active');
    }

    , prev: function (event) {
        var active = this.$menu.find('.active').removeClass('active')
          , prev = active.prev();

        if (!prev.length) {
            prev = this.$menu.find('li').last();
        }

        prev.addClass('active');
    }

    , listen: function () {
        this.$element
          .on('focus', $.proxy(this.focus, this))
          .on('blur', $.proxy(this.blur, this))
          .on('keypress', $.proxy(this.keypress, this))
          .on('keyup', $.proxy(this.keyup, this));

        if (this.eventSupported('keydown')) {
            this.$element.on('keydown', $.proxy(this.keydown, this));
        }

        this.$menu
          .on('click', $.proxy(this.click, this))
          .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
          .on('mouseleave', 'li', $.proxy(this.mouseleave, this));
    }
    , destroy: function () {
        this.$element.data('typeahead', null);
        this.$element
          .off('focus')
          .off('blur')
          .off('keypress')
          .off('keyup');

        if (this.eventSupported('keydown')) {
            this.$element.off('keydown');
        }

        this.$menu.remove();
    }
    , eventSupported: function (eventName) {
        var isSupported = eventName in this.$element;
        if (!isSupported) {
            this.$element.setAttribute(eventName, 'return;');
            isSupported = typeof this.$element[eventName] === 'function';
        }
        return isSupported;
    }

    , move: function (e) {
        if (!this.shown) return;

        switch (e.keyCode) {
            case 9: // tab
            case 13: // enter
            case 27: // escape
                e.preventDefault();
                break;

            case 38: // up arrow
                e.preventDefault();
                this.prev();
                break;

            case 40: // down arrow
                e.preventDefault();
                this.next();
                break;
        }

        e.stopPropagation();
    }

    , keydown: function (e) {
        this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40, 38, 9, 13, 27]);
        if (!this.shown && e.keyCode == 40) {
            this.lookup("");
        } else {
            this.move(e);
        }
    }

    , keypress: function (e) {
        if (this.suppressKeyPressRepeat) return;
        this.move(e);
    }

    , keyup: function (e) {
        switch (e.keyCode) {
            case 40: // down arrow
            case 38: // up arrow
            case 16: // shift
            case 17: // ctrl
            case 18: // alt
                break;

            case 9: // tab
            case 13: // enter
                if (!this.shown) return;
                this.select();
                break;

            case 27: // escape
                if (!this.shown) return;
                this.hide();
                break;
            default:
                this.lookup();
        }

        e.stopPropagation();
        e.preventDefault();
    }

    , focus: function (e) {
        if (!this.focused) {
            this.focused = true;
            if (this.options.minLength === 0 && !this.$element.val() || this.options.showHintOnFocus) {
                this.lookup();
            }
        }
    }

    , blur: function (e) {
        this.focused = false;
        if (!this.mousedover && this.shown) this.hide();
    }

    , click: function (e) {
        e.stopPropagation();
        e.preventDefault();
        this.select();
        //this.$element.focus();
        oSearch.GetTranslation();
    }

    , mouseenter: function (e) {
        this.mousedover = true;
        this.$menu.find('.active').removeClass('active');
        $(e.currentTarget).addClass('active');
    }

    , mouseleave: function (e) {
        this.mousedover = false;
        if (!this.focused && this.shown) this.hide();
    }

    };


    /* TYPEAHEAD PLUGIN DEFINITION
     * =========================== */

    var old = $.fn.typeahead;

    $.fn.typeahead = function (option) {
        var arg = arguments;
        return this.each(function () {
            var $this = $(this)
              , data = $this.data('typeahead')
              , options = typeof option == 'object' && option;
            if (!data) $this.data('typeahead', (data = new Typeahead(this, options)));
            if (typeof option == 'string') {
                if (arg.length > 1) {
                    data[option].apply(data, Array.prototype.slice.call(arg, 1));
                } else {
                    data[option]();
                }
            }
        });
    };

    $.fn.typeahead.defaults = {
        source: []
    , items: 8
    , menu: '<ul id="autocomplete_ul" class="typeahead dropdown-menu"></ul>'
    , item: '<li><a href="#"></a></li>'
    , minLength: 1
    , scrollHeight: 0
    , autoSelect: true
    };

    $.fn.typeahead.Constructor = Typeahead;


    /* TYPEAHEAD NO CONFLICT
     * =================== */

    $.fn.typeahead.noConflict = function () {
        $.fn.typeahead = old;
        return this;
    };


    /* TYPEAHEAD DATA-API
     * ================== */

    $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
        var $this = $(this);
        if ($this.data('typeahead')) return;
        $this.typeahead($this.data());
    });

}(window.jQuery);;

var GameListType;
var GameResultsManager = {
    GAME_RESULT_KEY: "GAME_RESULT_KEY",
    GAME_LAST_PICKED: "GAME_LAST_PICKED",
    LAST_PICKED_KEY: "LAST_PICKED_KEY",
    MAX_QUIZ_SIZE : 10 ,

    /*
    {
   "ListID":123,
   "CorrectAnswers":[],
   "WrongAnswers":[],
   "LastUpdated" :12313231
    }
    */

    GetGameResultByID: function (id) {
        var key = localStorage[GameResultsManager.GAME_RESULT_KEY + id];
        if (key != null)
            return JSON.parse(localStorage[GameResultsManager.GAME_RESULT_KEY + id]);
        else
            return null;
    },

    GetFullGamesResult : function()
    {
        var result = '[';
        for (var i = 0; i < localStorage.length; i++) {
            var currKey = localStorage.key(i);
            if (currKey.indexOf(GameResultsManager.GAME_RESULT_KEY) == 0)
                result +=  localStorage.getItem(currKey) + ',';
        }
        if (result.length > 1)
            result = result.substring(0, result.lastIndexOf(","));

        result += ']';

        return result ;
    },

    SaveGameResult: function (currGameResult) {

        var dbGameResult = GameResultsManager.GetGameResultByID(currGameResult.ListID);
        if (!GameResultsManager.isGameExist(currGameResult.ListID)) {
            GameResultsManager.SaveToStorage(currGameResult);
        }
        else {
            //merge data
            currGameResult.MergeGameResult(dbGameResult);
            GameResultsManager.SaveToStorage(dbGameResult);
        }
     
    },

    SynchResultFromServer: function (pDBGameResults)
    {
        if (pDBGameResults == undefined)
            return;
        try
        {
            if (typeof (pDBGameResults) == "string")
                pDBGameResults = JSON.parse(pDBGameResults);

            var size = pDBGameResults.length;
            
            for (var i = 0; i < size; i++) {
                GameResultsManager.SaveToStorage(pDBGameResults[i]);
            }
        }
        catch(ex)
        {
            console.log(ex.message);
        }
        
    },

    SaveToStorage: function (currGameResult) {
        localStorage[GameResultsManager.GAME_RESULT_KEY + currGameResult.ListID] = JSON.stringify(currGameResult);
    },

    isGameExist: function (id) {
        return (localStorage[GameResultsManager.GAME_RESULT_KEY + id] != undefined && localStorage[GameResultsManager.GAME_RESULT_KEY + id] != "");
    },

    setLastPicked: function (level, order) {
        localStorage[GameResultsManager.GAME_LAST_PICKED +level] = order;
    },

    getLastPicked: function (level) {
        var ret = localStorage[GameResultsManager.GAME_LAST_PICKED +level];
        if (ret != null)
            return ret;
        else
            return 1;
    },
    GetList: function (arr) {
        var result = [];
        var isFromTeaser = (localStorage["LastTranslationTeaser"] != undefined && localStorage["LastTranslationTeaser"] != null) && GameListType == "lookups" ? true : false;
        if (isFromTeaser) {
            try 
            {
                var tempresult = [];
                tempresult.push(JSON.parse(localStorage["LastTranslationTeaser"]));

                var rndArray = arr;
                var currentIndex = rndArray.length, temporaryValue, randomIndex;
                while (0 !== currentIndex) {
                    randomIndex = Math.floor(Math.random() * currentIndex);
                    currentIndex -= 1;
                    if (tempresult[0].EntryPOCO.Entry != rndArray[currentIndex].EntryPOCO.Entry) {
                        temporaryValue = rndArray[currentIndex];
                        rndArray[currentIndex] = rndArray[randomIndex];
                        rndArray[randomIndex] = temporaryValue;
                    }
                }
                result = tempresult.concat(rndArray.slice(0, GameResultsManager.MAX_QUIZ_SIZE - 1));
            }
            catch (err)
            {
                result = Utility.shuffle(arr, true).slice(0, GameResultsManager.MAX_QUIZ_SIZE);
            }
            localStorage["LastTranslationTeaser"] = null;
        }
        else {
            result = Utility.shuffle(arr, true).slice(0, GameResultsManager.MAX_QUIZ_SIZE);
        }
        
        return result;
    },
    getQuizQuestion: function () {
  
        var gameResult = GameResultsManager.GetGameResultByID(oGame.WordListID)
        oGameWordsList = [];
        if (gameResult == null || (localStorage["LastTranslationTeaser"] != undefined && localStorage["LastTranslationTeaser"] != null)) {
            oGameWordsList = GameResultsManager.GetList(oTotalWordList);
            return;
        }
            var rndArrayQuestion = Utility.shuffle(oTotalWordList, true).slice();
            var nCountToAdd = oTotalWordList.length - gameResult.CorrectAnswers.length;
          

            if (oTotalWordList.length <= GameResultsManager.MAX_QUIZ_SIZE || nCountToAdd <= 0)
            {
                var sizeToSLice = oTotalWordList.length > GameResultsManager.MAX_QUIZ_SIZE ? GameResultsManager.MAX_QUIZ_SIZE : oTotalWordList.length;
                oGameWordsList = oTotalWordList.slice(0, sizeToSLice);
                return;
            }

            var index = 0;
             nCountToAdd = GameResultsManager.MAX_QUIZ_SIZE - nCountToAdd;
            while (oGameWordsList.length < GameResultsManager.MAX_QUIZ_SIZE) {
                if (nCountToAdd < GameResultsManager.MAX_QUIZ_SIZE && index < nCountToAdd) {
                    oGameWordsList.push(rndArrayQuestion[index]);
                }
                
                if (gameResult.CorrectAnswers.indexOf(rndArrayQuestion[index].EntryPOCO.MelingoId) < 0) {
                    oGameWordsList.push(rndArrayQuestion[index]);
                }

                index++;
            }
            $('#TotalItems').val(oGameWordsList.length);
    }
}



function LocalGameResult(ListID, CorrectAnswers, WrongAnswers, LastUpdated) {
    this.ListID = ListID;
    this.CorrectAnswers = CorrectAnswers;
    this.WrongAnswers = WrongAnswers;
    this.LastUpdated = LastUpdated;
    this.TotalQuestions;

    this.MergeGameResult = function (MergeTo) {

        //correct answer to remove, now the user question result is incorrect so we need to remove from the corrct answers
        for(answer in this.WrongAnswers)
        {
            var isFound = MergeTo.CorrectAnswers.indexOf(answer);
            if (isFound > -1) {
                MergeTo.CorrectAnswers.splice(index, 1);
            }
        }

        //wrong answer to remove now the user result is correct opposite from above
        for (answer in this.CorrectAnswers) {
            var isFound = MergeTo.WrongAnswers.indexOf(answer);
            if (isFound > -1) {
                MergeTo.WrongAnswers.splice(index, 1);
            }
        }


        Array.prototype.push.apply(MergeTo.CorrectAnswers, this.CorrectAnswers);
        Array.prototype.push.apply(MergeTo.WrongAnswers, this.WrongAnswers);
        
        MergeTo.CorrectAnswers =  Utility.getUnique(MergeTo.CorrectAnswers);
        MergeTo.WrongAnswers =  Utility.getUnique(MergeTo.WrongAnswers);
    }


    this.GetCorrectAnswerSize = function () {
        return this.CorrectAnswers.length;
    }

}


var QuickQuizResultsManager =
{
    GAME_RESULT_KEY: "QQ_GAME_RESULT_KEY",
    GetResultByID: function (id) {
        var key = localStorage[QuickQuizResultsManager.GAME_RESULT_KEY + id];
        if (key != null)
            return JSON.parse(localStorage[QuickQuizResultsManager.GAME_RESULT_KEY + id]);
        else
            return null;
    },

    SaveToStorage: function (pQuizPoints,id) {
        localStorage[QuickQuizResultsManager.GAME_RESULT_KEY + id] = pQuizPoints;
    },
    GetFullGamesResult: function () {
        var score;
        var listID;
        var result = '[';
        for (var i = 0; i < localStorage.length; i++) {
            var currKey = localStorage.key(i);
            if (currKey.indexOf(QuickQuizResultsManager.GAME_RESULT_KEY) == 0) {
                score = localStorage.getItem(currKey);
                listID = currKey.substring(QuickQuizResultsManager.GAME_RESULT_KEY.length);
                result += QuickQuizResultsManager.GetJsonGameResult(listID, score) + ",";
            }
        }
        if (result.length > 1)
            result = result.substring(0, result.lastIndexOf(","));

        result += ']';

        return result;
    },

    GetJsonGameResult : function(pListID,pScore)
    {
        return  "{ \"ListID\":" + pListID + ", \"Score\":" + pScore + "}";
    },

    SynchResultFromServer: function (pDBGameResults) {
        if (pDBGameResults == undefined)
            return;
        try {
            if (typeof (pDBGameResults) == "string")
                pDBGameResults = JSON.parse(pDBGameResults);

            var size = pDBGameResults.length;

            for (var i = 0; i < size; i++) {
                QuickQuizResultsManager.SaveToStorage(pDBGameResults[i].Score, pDBGameResults[i].ListID);
            }
        }
        catch (ex) {
            console.log(ex.message);
        }

    }
}
;
(function () {
    var unlockPercentage = 80;
    var startingSeconds;
    var GameListType;
    var seconds;
    var temp;
    var AllowBtnPlayClicks = true;
    var StopTimer = false;
    var CorrectAnswCount = 0;
    var GameOver = false;
    var IsQQgames = false;
    var metaItems = [];
    var timeoutMyOswego = null;
    var points = 0;
    var VocabGameCounter = 0;
    var audioCorrectAnswer = document.createElement('audio');
    var audioWrongAnswer = document.createElement('audio');
    window['oQQGameWordsList'] = {}
    window['oGameWordsList'] = {}
    window['oTotalWordList'] = {}
    window['oCurrentEntry'] = {}
    window['oGameProperties'] = {}
    window['oGameLocalization'] = {}
    window['oGame'] =
    {
        LoginCheckBeforStart:function(IsLogedIn)
        {
            if (IsLogedIn != 'True' && $.cookie("LoginDialogShown")!='True'){
                $("#BeforStartGameModal").modal('show');
                $.cookie("LoginDialogShown", 'True', { expires: 1, path: '/' });
            }
        },
        setAudio:function()
        {
            audioCorrectAnswer.setAttribute('src', $("#correct_answer_sound").val());
            audioWrongAnswer.setAttribute('src', $("#incorrect_answer_sound").val());
        },
        playActualSound:function(isCurrent)
        {
            if (isCurrent) {
                audioCorrectAnswer.play();
            }
            else {
                audioWrongAnswer.play();
            }
        },
        setGame: function (seconds) {
            startingSeconds = seconds;
            $("#countdown").html(seconds);
            $('#TotalItems').html(oGameWordsList.length);
            StopTimer = true;
        },
        InitQQGameList: function (obj) {
            oQQGameWordsList = obj;
        },
        InitGameList:function()
        {
            GameResultsManager.getQuizQuestion();
        },
        InitTotalWordList:function(obj)
        {
            oTotalWordList = obj;
           
        },
        InitGameLocalization:function(obj)
        {
            oGameLocalization = obj;
        },
        countdown: function () {
            if (timeoutMyOswego != null)
                clearTimeout(timeoutMyOswego);
            if(StopTimer == false)
            {
                seconds = document.getElementById('countdown').innerHTML;
                seconds = parseInt(seconds, 10);

                if (seconds == 5) {
                    temp = document.getElementById('countdown');
                    $('#TimerDiv').addClass('TimeOver');
                    $('#TimerDiv').find('*').addClass('TimeOverColor');
                }
                if (seconds == 0) {
                    if (IsQQgames)
                    {
                        oGame.CheckAnswerQQ(null);
                    }
                    else
                    {
                        oGame.CheckAnswer(null);
                    }
                    
                    return;
                }

                seconds--;
                temp = document.getElementById('countdown');
                temp.innerHTML = seconds < 10 ? "0" + seconds : seconds;
                timeoutMyOswego = setTimeout(oGame.countdown, 1000);
                oGame.seconds = seconds;
            }
        },
        StartPlayClick: function ()
        {
            ga('send', 'pageview');
            //   var TotalPlayListCount = parseInt($("#PlayWordsListCount").val());
            var TotalPlayListCount = oGameWordsList.length;

            var CurrentGameNum = parseInt($("#CurrentGameNum").text());
            if (CurrentGameNum == TotalPlayListCount) {
                oGame.GameOver();
                return;
            }
            $("#NextButton").addClass("Hide");
            var currnum = parseInt($("#CurrentGameNum").text());
            currnum++;
            $("#CurrentGameNum").text(currnum);
            $(".GamesCenterBottom_div").fadeOut(500, function () {
                oGame.StartPlay();
            });
        },
        StartPlay:function()
        {
            GameOver = false;
            AllowBtnPlayClicks = true;
            oGame.ClearGameTimer();
            $('#BeginButton').hide();
            $('#PlayWordspan').addClass('SingleWord');
            $('.QuestionDiv').addClass('always_english');
            
            oGame.CreatePlayList();
            StopTimer = false;
            $(".GamesCenterBottom_div").fadeIn(500, function () {
                oGame.countdown();
            });
        },
        StartPlayQQClick: function () {
            ga('send', 'pageview');
            var TotalPlayListCount = parseInt($("#PlayWordsListCount").val());
            var CurrentGameNum = parseInt($("#CurrentGameNum").text());
            if (CurrentGameNum == TotalPlayListCount) {
                oGame.GameOverQQ();
                return;
            }
            $("#NextButton").addClass("Hide");
            var currnum = parseInt($("#CurrentGameNum").text());
            currnum++;
            $("#CurrentGameNum").text(currnum);
            $(".GamesQQCenterBottom_div").fadeOut(500, function () {
                oGame.StartPlayQQ();
            });
        },
        StartPlayQQ: function () {
            IsQQgames = true;
            GameOver = false;
            AllowBtnPlayClicks = true;
            $(".shadow_contant").addClass("Hide");
            oGame.ClearGameTimer();
            $('#BeginButton').hide();
            oGame.CreateQQPlayList();
            StopTimer = false;
            $(".GamesQQCenterBottom_div").fadeIn(500, function () {
                oGame.countdown();
            });
        },
        CreateQQPlayList:function()
        {
            $('#AnswerUl').removeClass("Hide");
            $('#AnswerUl li').remove();
            window['oCurrentEntry'] = oGame.GetCurrentQQByID();
            if (oCurrentEntry != undefined && oCurrentEntry != null)
            {
                if (oCurrentEntry.ChallengeQuizzesPOCO.Question.split(" ").length == 1)
                    $('#QQPlayWordspan').css({ 'font-size': '36px' });
                $('#QQPlayWordspan').html(oCurrentEntry.ChallengeQuizzesPOCO.Question.replace("~", "_________"));
                $('#CurrentGameWordID').val(oCurrentEntry.ChallengeQuizzesPOCO.ID);

                Utility.matchCssToLang(".QuestionQQDiv", oCurrentEntry.ChallengeQuizzesPOCO.Question);

                var arr = [];
                oGame.AddQQLi(arr, oCurrentEntry.ChallengeQuizzesPOCO.Distractor1, false);
                oGame.AddQQLi(arr, oCurrentEntry.ChallengeQuizzesPOCO.Distractor2, false);
                oGame.AddQQLi(arr, oCurrentEntry.ChallengeQuizzesPOCO.Answer, true);
                oGame.AddQQLi(arr, oCurrentEntry.ChallengeQuizzesPOCO.Distractor3, false);
                oGame.RandomizeList(arr);
                Utility.matchCssToLang("#AnswerUl", oCurrentEntry.ChallengeQuizzesPOCO.Answer);
            }
        },
        AddQQLi:function(arr, text,isTrueAnswerLi)
        {
            if (isTrueAnswerLi) {
                arr.push("<li id='corA'><span  onclick=\"oStuff.gaLog('QuickQuizzes', 'AnswerClick', oCurrentEntry.ChallengeQuizzesPOCO.ID, oGame.seconds);oGame.CheckAnswerQQ(this);\" class='WordPlayButton'>" + text + "</span><img class ='GameAnswerImg Hide' src='" + $('#CorrectAnswerImgURL').val() + "' /></li>");
            }
            else {
                if (text != null && text.trim() != "")
                    arr.push("<li><span  onclick=\"oStuff.gaLog('QuickQuizzes', 'AnswerClick', oCurrentEntry.ChallengeQuizzesPOCO.ID, oGame.seconds);oGame.CheckAnswerQQ(this);\" class='WordPlayButton'>" + text + "</span><img class ='GameAnswerImg Hide' src='" + $('#WrongAnswerImgURL').val() + "' /></li>");
            }
        },
        CheckAnswerQQ:function(obj)
        {
            if (AllowBtnPlayClicks) {
                AllowBtnPlayClicks = false;
                StopTimer = true;
                var currentQuestion = oGame.GetCurrentQQByID();
                if (currentQuestion != null)
                {
                    currentQuestion.IsCorrect = false;
                    $(".shadow_contant").html(currentQuestion.Answer.replace("[MORE]", ""));
                    if (obj != null && oCurrentEntry.ChallengeQuizzesPOCO.Answer == $(obj).text()) {
                        oGame.playActualSound(true);
                        $(obj).parent().parent().find('li').addClass("Hide");
                        currentQuestion.IsCorrect = true;
                        $(obj).parent().removeClass("Hide");
                        $(obj).addClass('bgR');
                        $(obj).parent().find('img').removeClass("Hide");
                        points = points + 10;
                        CorrectAnswCount++;
                        setTimeout(function () {
                            $(".shadow_contant").removeClass("Hide");
                            $(".shadow_contant").fadeOut(0);
                            $(".shadow_contant").fadeIn(500);
                            $("#NextButton").removeClass("Hide");
                            oGame.FillAnswerQQ();
                        }, 500);
                    }
                    else if (obj == null) {
                        $(obj).parent().parent().find('li').addClass("Hide");
                        $(".shadow_contant").removeClass("Hide");
                        $("#corA").parent().find('li').addClass("Hide");
                        $("#corA").removeClass("Hide");
                        $("#corA").find("span").addClass("bgR");
                        $("#corA").find('img').removeClass("Hide");
                        $("#NextButton").removeClass("Hide");
                        currentQuestion.WrongAswer = "Time Up"
                        oGame.FillAnswerQQ();
                    }
                    else {
                        oGame.playActualSound(false);
                        $(obj).addClass('bgW');
                        $(obj).parent().find('img').removeClass("Hide");
                        currentQuestion.WrongAswer = $(obj).text();
                        setTimeout(function () {
                            $(obj).parent().parent().find('li').addClass("Hide");
                            $("#corA").find('span').addClass("bgR");
                            $("#corA").removeClass("Hide");
                            $(obj).parent().removeClass("Hide");
                            $("#corA").find('img').removeClass("Hide");
                            setTimeout(function () {
                                $(".shadow_contant").removeClass("Hide");
                                $(".shadow_contant").fadeOut(0);
                                $(".shadow_contant").fadeIn(500);
                                $("#NextButton").removeClass("Hide");
                                oGame.FillAnswerQQ();
                            }, 500);
                        },500);
                    }
                    $("#PointSpan").text(points);
                }
            }
        },
        FillAnswerQQ: function () {
            if (oCurrentEntry.ChallengeQuizzesPOCO.Question.indexOf('~')>=0)
                $('#QQPlayWordspan').html(oCurrentEntry.ChallengeQuizzesPOCO.Question.replace("~", "<u>"+oCurrentEntry.ChallengeQuizzesPOCO.Answer+"</u>"));
        },
        GameOverQQ:function()
        {
            $(".shadow_contant").addClass("Hide");
            $(".GamesCenter_div").hide();
            $(".GamesCenterVocab_div").hide("Hide");
            $("#GameOverQQDiv").removeClass("Hide");
            var Percent = Math.round(CorrectAnswCount / oQQGameWordsList.length * 100);
            var PointsNum = parseInt($("#PointSpan").text());
            var PointsTitleText = oGame.GetActualResultGameTitle(Percent);
            var PointsText = oGame.GetActualResultGamePointstext().replace("{-}", PointsNum);

            var highResult = QuickQuizResultsManager.GetResultByID(oGame.WordListID);
            if (highResult == null || highResult < PointsNum) 
            {
                QuickQuizResultsManager.SaveToStorage(PointsNum,oGame.WordListID);
                highResult = PointsNum;
            }


            var GameResult = {
                "Points": PointsNum,
                "Percent": Percent,
                "PointsTitleText": PointsTitleText,
                "PointsText": PointsText
            }
            oUI.AddToPlaceHolder($("#GameOverQQDiv"), Handlebars.compile($('#GameResultHeaderDiv').html()), GameResult);
            var isAnswerEnglish = Utility.isEnglish(oQQGameWordsList[0].ChallengeQuizzesPOCO.Answer);
            for (var i = 0; i < oQQGameWordsList.length; i++) {
                oQQGameWordsList[i].ChallengeQuizzesPOCO.Question = oQQGameWordsList[i].ChallengeQuizzesPOCO.Question.replace("~", "_________")
                oUI.AddToPlaceHolder($("#GameOverQQDiv"), Handlebars.compile($('#GameResultCardDiv').html()), oQQGameWordsList[i]);
                oGame.CreatePopover(i, isAnswerEnglish);
            }
            Utility.matchCssToLang(".top_trunover", oQQGameWordsList[0].ChallengeQuizzesPOCO.Question);
            Utility.matchCssToLang(".bottom_trunover", oQQGameWordsList[0].ChallengeQuizzesPOCO.Answer);
            CorrectAnswCount = 0;
            GameOver = true;

            if (oSite.IsLogedIn) {
                
                var jsonResult = QuickQuizResultsManager.GetJsonGameResult(oGame.WordListID, QuickQuizResultsManager.GetResultByID(oGame.WordListID));
              
                oGame.RemoteSaveQuickGameResult('[' + jsonResult + ']');
            }

            oUI.refreshAds();
        },
        CreatePopover: function (i, isEnglish) {
            if (!isEnglish) {
                $("#example" + oQQGameWordsList[i].ChallengeQuizzesPOCO.ID).popover({
                    placement: 'right',
                    html: 'true',
                    title: '',
                    content: oQQGameWordsList[i].Answer.replace("[MORE]", "")
                }).css("left", $("#example" + oQQGameWordsList[i].ChallengeQuizzesPOCO.ID).offset().left + $("#example" + oQQGameWordsList[i].ChallengeQuizzesPOCO.ID).width() + " !important");
            }
            else {
                $("#example" + oQQGameWordsList[i].ChallengeQuizzesPOCO.ID).popover({
                    placement: 'left',
                    html: 'true',
                    title: '',
                    content: oQQGameWordsList[i].Answer.replace("[MORE]", "")
                });
            }
        },
        CreatePlayList: function ()
        {
            $('#AnswerUl').removeClass("Hide");
            $('#AnswerUl li').remove();
            window['oCurrentEntry'] = oGame.GetCurrentEntryByID();
            if (oCurrentEntry  != undefined && oCurrentEntry != null)
            {
                $('#PlayWordspan').text(oCurrentEntry.Entry);
                $("QuestionSoundImg").removeAttr("onclick");
                $("QuestionSoundImg").addClass("Hide");
                if (oCurrentEntry.PronunciationFile != null && oCurrentEntry.PronunciationFile.trim() != "") {
                    $('#QuestionSoundImg').removeClass("Hide");
                    $('#QuestionSoundImg').click(function () {
                        oStuff.gaLog('Dictionary', 'Play sound', oCurrentEntry.Entry);
                        oSound.playSound(this, oCurrentEntry.PronunciationFile.trim(), '');
                    });
                }
                $('#CurrentGameWordID').val(oCurrentEntry.MelingoId);
                var arr = [];
                arr.push("<li><span  onclick=\"oStuff.gaLog('VoacbBuilderGame', 'AnswerClick', oCurrentEntry.MelingoId, oGame.seconds);oGame.CheckAnswer(this);\" class='WordPlayButton'>" + oCurrentEntry.Distractor1 + "</span><img class ='GameAnswerImg Hide' src='" + $('#WrongAnswerImgURL').val() + "' /></li>");
                arr.push("<li><span  onclick=\"oStuff.gaLog('VoacbBuilderGame', 'AnswerClick', oCurrentEntry.MelingoId, oGame.seconds);oGame.CheckAnswer(this);\" class='WordPlayButton'>" + oCurrentEntry.Distractor2 + "</span><img class ='GameAnswerImg Hide' src='" + $('#WrongAnswerImgURL').val() + "' /></li>");
                arr.push("<li id='corA'><span  onclick=\"oStuff.gaLog('VoacbBuilderGame', 'AnswerClick', oCurrentEntry.MelingoId, oGame.seconds);oGame.CheckAnswer(this);\" class='WordPlayButton'>" + oCurrentEntry.CorrectAns + "</span><img class ='GameAnswerImg Hide' src='" + $('#CorrectAnswerImgURL').val() + "' /></li>");
                arr.push("<li><span  onclick=\"oStuff.gaLog('VoacbBuilderGame', 'AnswerClick', oCurrentEntry.MelingoId, oGame.seconds);oGame.CheckAnswer(this);\" class='WordPlayButton'>" + oCurrentEntry.Distractor3 + "</span><img class ='GameAnswerImg Hide' src='" + $('#WrongAnswerImgURL').val() + "' /></li>");
                oGame.RandomizeList(arr);
                Utility.matchCssToLang("#AnswerUl", oCurrentEntry.CorrectAns);
            }
        },
        RandomizeList:function(arr)
        {
            for (var i = arr.length; i > 0; i--) {
                var rand = Math.floor(Math.random() * i);
                var picked = arr.splice(rand, 1);
                $("#AnswerUl").append(picked);
            }
        },
        ClearGameTimer:function()
        {
            $("#countdown").text(startingSeconds);
            $('#TimerDiv').removeClass('TimeOver');
            $('#TimerDiv').find('*').removeClass('TimeOverColor');
        },
        CheckAnswer:function(obj)
        {
            if (AllowBtnPlayClicks)
            {
                AllowBtnPlayClicks = false;
                StopTimer = true;
                VocabGameCounter++;
                var currentQuestion = oGame.GetCurrentEntryByID();
                var TotalPlayListCount = oGameWordsList.length;
                if (currentQuestion != null)
                {
                    currentQuestion.IsCorrect = false;
                    if (obj != null && oCurrentEntry.CorrectAns == $(obj).text()) {
                        oGame.playActualSound(true);
                        currentQuestion.IsCorrect = true;
                        $("#corA").find('img').removeClass("Hide");
                        $(obj).addClass('bgR');
                        points = points + 100 / TotalPlayListCount ;
                        CorrectAnswCount++;
                        if (oSite.IsAnonimousQuiz && VocabGameCounter >= oSite.QuizAnonymousMaxGameCount)
                        {
                            $(".GamesCenterVocab_div").fadeOut(500, function () {
                                setTimeout(function () { oUI.SignInHome(); }, 500);
                            });
                        }
                            
                        setTimeout(oGame.StartPlayClick, 500);
                    }
                    else if (obj == null) {
                        $("#corA").find('img').removeClass("Hide");
                        $("#corA").find("span").addClass("bgR");
                        $("#NextButton").removeClass("Hide");
                        currentQuestion.WrongAswer = "Time Up"
                        if (oSite.IsAnonimousQuiz)
                        {
                            $(".GamesCenterVocab_div").fadeOut(500, function () {
                                setTimeout(function () { oUI.SignInHome(); }, 500);
                            });
                        }
                        VocabGameCounter = 0;
                    }
                    else {
                        oGame.playActualSound(false);
                        $(obj).addClass('bgW');
                        $(obj).parent().find('img').removeClass("Hide");
                        setTimeout(function () {
                            $("#corA").find("span").addClass("bgR");
                            $("#corA").find('img').removeClass("Hide");
                            setTimeout(function () {
                                $("#NextButton").removeClass("Hide");
                            }, 500);
                        }, 500);
                        currentQuestion.WrongAswer = $(obj).text();
                        if (oSite.IsAnonimousQuiz && VocabGameCounter >= oSite.QuizAnonymousMaxGameCount)
                        {
                            $(".GamesCenterVocab_div").fadeOut(500, function () {
                                setTimeout(function () { oUI.SignInHome(); }, 500);
                            });
                        }
                    }
                    $("#PointSpan").text(Math.round(points));
                }

                
            }
            
        },
        GetCurrentEntryByID: function ()
        {
            var CurrentGameNum = (parseInt($("#CurrentGameNum").text()) - 1);
            if (oGameWordsList[CurrentGameNum] != undefined) {
                return oGameWordsList[CurrentGameNum].EntryPOCO;
            }
            return null;
        },
        GetCurrentQQByID:function()
        {
            var CurrentGameNum = (parseInt($("#CurrentGameNum").text()) - 1);
            if (oQQGameWordsList[CurrentGameNum] != undefined)
            {
                return oQQGameWordsList[CurrentGameNum];
            }
            return null;
        },
        GameOver: function ()
        {
            $(".GamesCenter_div").hide();
            $(".GamesCenterVocab_div").hide("Hide");
            $("#GameOverDiv").removeClass("Hide");
            var Percent = Math.round(100 * CorrectAnswCount / oGameWordsList.length);
            var PointsNum = parseInt($("#PointSpan").text());
            var PointsTitleText = oGame.GetActualResultGameTitle(Percent);
            var PointsText = oGame.GetActualResultGamePointstext().replace("{-}", PointsNum);
            var NextRound = parseInt(oGameLocalization.Vuelta) + 1;
            var LevelName = oGameLocalization.LevelName;
            var currGameResult = new LocalGameResult(oGame.WordListID, [], []);

            var gameHtmlObj = "";

            for (var i = 0; i < oGameWordsList.length; i++) {
                gameHtmlObj += oUI.AddToPlaceHolder($("#GameOverDiv"), Handlebars.compile($('#GameResultCardDiv').html()), oGameWordsList[i].EntryPOCO,true);
                
                //fill local game result
                var nMelingoID = oGameWordsList[i].EntryPOCO.MelingoId;
                if (oGameWordsList[i].EntryPOCO.IsCorrect)
                    currGameResult.CorrectAnswers.push(nMelingoID);
                else
                    currGameResult.WrongAnswers.push(nMelingoID);
            }

            GameResultsManager.SaveGameResult(currGameResult);
            
            var userProgress = Math.round(100 * GameResultsManager.GetGameResultByID(oGame.WordListID).CorrectAnswers.length / oTotalWordList.length);

            var description = (PointsNum == 100 ? oGameLocalization.PerfectPersonalShareDescription : oGameLocalization.PersonalShareDescription);
            description = encodeURIComponent(description.replace("#", PointsNum));

            var GameResult = {
                "Points": PointsNum,
                "Percent": Percent,
                "PointsTitleText": PointsTitleText,
                "PointsText": PointsText,
                "UserProgress": userProgress,
                "Level": LevelName,
                "NextRound": NextRound,
                "Description": description
            }

            oUI.AddToPlaceHolder($("#GameOverDiv"), Handlebars.compile($('#GameResultHeaderDiv').html()), GameResult);
            
            if(oSite.DefaultCulture == "es")
                oGame.ShowPopUps(userProgress,unlockPercentage,GameResult);

            $("#GameOverDiv").append(gameHtmlObj);

            learn.onLoad(false);
            CorrectAnswCount = 0;
            GameOver = true;

            oGame.RemoteSaveGameResult(JSON.stringify(currGameResult));
            
            oUI.refreshAds();
        },
        ShowPopUps:function(userProgress,unlockPercentage,GameResult)
        {
            var newGameProperties = {};
            if (userProgress >= unlockPercentage && oGameLocalization.IsLastRoundInTheLevel == false && oGameLocalization.IsUserLists == false)
            {
                oGameProperties = oGame.GetGamePropertiesByKey(oGameLocalization.Level + "_" + oGameLocalization.Vuelta);
                if (oGameProperties != null) {
                    if(!oGameProperties.NextRoundPopUpIsShowed)
                    {
                        oGameProperties.NextRoundPopUpIsShowed = true;
                        localStorage[oGameLocalization.Level + "_" + oGameLocalization.Vuelta] = JSON.stringify(oGameProperties);
                        oGame.ShowNextRoundPopUp(GameResult);
                    }
                }
                else {
                    newGameProperties.Level = oGameLocalization.Level;
                    newGameProperties.Round = parseInt(oGameLocalization.Vuelta);
                    newGameProperties.NextRoundPopUpIsShowed = true;
                    newGameProperties.NextLevelPopUpIsShowed = false;
                    localStorage[oGameLocalization.Level + "_" + oGameLocalization.Vuelta] = JSON.stringify(newGameProperties);
                    oGame.ShowNextRoundPopUp(GameResult);
                }
            }
            else if (userProgress >= unlockPercentage && oGameLocalization.IsLastRoundInTheLevel && oGameLocalization.IsUserLists == false)
            {
                oGameProperties = oGame.GetGamePropertiesByKey(oGameLocalization.Level + "_" + oGameLocalization.Vuelta);
                if (oGameProperties != null) {
                    if(!oGameProperties.NextLevelPopUpIsShowed)
                    {
                        oGameProperties.NextLevelPopUpIsShowed = true;
                        localStorage[oGameLocalization.Level + "_" + oGameLocalization.Vuelta] = JSON.stringify(oGameProperties);
                        oGame.ShowNextLevelPopUp(GameResult);
                    }
                }
                else {
                    newGameProperties.Level = oGameLocalization.Level;
                    newGameProperties.Round = parseInt(oGameLocalization.Vuelta);
                    newGameProperties.NextLevelPopUpIsShowed = true;
                    newGameProperties.NextRoundPopUpIsShowed = false;
                    localStorage[oGameLocalization.Level + "_" + oGameLocalization.Vuelta] = JSON.stringify(newGameProperties);
                    oGame.ShowNextLevelPopUp(GameResult);
                }
                
            }
        },
        ShowNextRoundPopUp:function(GameResult)
        {
            oUI.AddToPlaceHolder($("#BeforGameOverModal"), Handlebars.compile($('#GameOverNextRound').html()), GameResult);
            $("#BeforGameOverModal").modal('show');
        },
        ShowNextLevelPopUp:function(GameResult)
        {
            oUI.AddToPlaceHolder($("#BeforGameOverModal"), Handlebars.compile($('#GameOverNextLevel').html()), GameResult);
            $("#BeforGameOverModal").modal('show');
        },
        GetGamePropertiesByKey: function (key) {
            var key = localStorage[key];
            if (key != null)
                return JSON.parse(key);
            else
                return null;
        },
        RemoteSaveGameResult: function (currGameResult) {
            if (!oSite.IsLogedIn)
                return;
        var destURL = oSite.BaseSiteUrl + "/LearnPrivate/SaveGameResult";
        ajaxHelper.AjaxReqest(currGameResult, destURL, 'post', false, GameResultsManager.SynchResultFromServer);
        },
        RemoteSaveQuickGameResult: function (currGameResult) {
            if (!oSite.IsLogedIn)
                return;
            var destURL = oSite.BaseSiteUrl + "/GameResult/SetQuickQuizResult";
            ajaxHelper.AjaxReqest(currGameResult, destURL, 'post', false, GameResultsManager.SynchResultFromServer);
        },
        RemoteSaveFullResult: function () {

            ajaxHelper.AjaxReqest(GameResultsManager.GetFullGamesResult(), oSite.BaseSiteUrl + "/LearnPrivate/SaveFullGameResult", 'post', false, learn.dummyFunc);
            ajaxHelper.AjaxReqest(QuickQuizResultsManager.GetFullGamesResult(), oSite.BaseSiteUrl + "/GameResult/SetQuickQuizResult", 'post', false, learn.dummyFunc);
          
        },
        GetActualResultGameTitle: function (Percent)
        {
            var ResultGameTitles = oGameLocalization.ResultGameTitleDict;
            if (Percent >= 0 && Percent <= 20)
            {
                return oGameLocalization.ResultGameTitleDict[0];
            }
            else if (Percent > 20 && Percent <= 50)
            {
                return oGameLocalization.ResultGameTitleDict[20];
            }
            else if (Percent > 50 && Percent <= 70)
            {
                return oGameLocalization.ResultGameTitleDict[50];
            }
            else if (Percent > 70 && Percent <= 90) {
                return oGameLocalization.ResultGameTitleDict[70];
            }
            else if (Percent > 90 && Percent <= 100) {
                return oGameLocalization.ResultGameTitleDict[90];
            }

        },
        GetActualResultGamePointstext:function()
        {
           return  oGameLocalization.ResultGamePointsText;
        },
        CreateflashcardView:function(cardname,firstTime)
        {
            var CurrentCardNum = (parseInt($("#CurrentCardNum").text()) - 1);
            $("#ShowCardsDiv").html("");
            var ListExampleSentencesFC = JSON.stringify(oTotalWordList[CurrentCardNum].ListExampleSentencesFC).replace("{it}", "<b>").replace("{/it}", "</b>");
            oTotalWordList[CurrentCardNum].ListExampleSentencesFC = JSON.parse(ListExampleSentencesFC);
            var AdditionalContentList = JSON.stringify(oTotalWordList[CurrentCardNum].AdditionalContentList).replace("{it}", "<b>").replace("{/it}", "</b>");
            oTotalWordList[CurrentCardNum].AdditionalContentList = JSON.parse(AdditionalContentList);
            
            switch (cardname) {
                case "en":
                    oUI.AddToPlaceHolder($("#ShowCardsDiv"), Handlebars.compile($('#ShowEnCard').html()), oTotalWordList[CurrentCardNum]);
                    break;
                case "nonen":
                    oUI.AddToPlaceHolder($("#ShowCardsDiv"), Handlebars.compile($('#ShowNonEnCard').html()), oTotalWordList[CurrentCardNum]);
                    break;
                case "full":
                    oUI.AddToPlaceHolder($("#ShowCardsDiv"), Handlebars.compile($('#ShowFullCard').html()), oTotalWordList[CurrentCardNum]);
                    if (firstTime)
                    {
                        $("#FullViewImg").addClass("Hide");
                    }
                    else
                    {
                        $("#FullViewImg").removeClass("Hide");
                        $("PreviousViewImg").removeAttr("onclick");
                        $("NextViewImg").removeAttr("onclick");
                        $("#PreviousViewImg").click(function () { oGame.Previous('', false); });
                        $("#NextViewImg").click(function () { oGame.Next('', false); });
                    }
                    break;
                case "":
                    var radiobtn = $('input[name=ViewChoose]:checked', '#flashcardTopDiv');
                    switch (radiobtn.attr('id')) {
                        case "radio1":
                            oGame.CreateflashcardView("en",false);
                            break;
                        case "radio2":
                            oGame.CreateflashcardView("nonen",false);
                            break;
                        case "radio3":
                            oGame.CreateflashcardView("full",true);
                            break;
                    }
                    break;
            }
            if (CurrentCardNum == (oTotalWordList.length - 1)) {
                $("#NextViewImg").addClass("Hide");
            }
            else if (CurrentCardNum == 0) {
                $("#PreviousViewImg").addClass("Hide");
            }
            else {
                $("#PreviousViewImg").removeClass("Hide");
                $("#NextViewImg").removeClass("Hide");
            }

            learn.onLoad(false);
        },
        Previous: function (cardname, firstTime)
        {
            var CurrentCardNum = parseInt($("#CurrentCardNum").text());
            CurrentCardNum --;
            $("#CurrentCardNum").text(CurrentCardNum);
            oGame.CreateflashcardView(cardname, firstTime);
        },
        Next: function (cardname, firstTime) {
            var CurrentCardNum = parseInt($("#CurrentCardNum").text());
            CurrentCardNum++;
            $("#CurrentCardNum").text(CurrentCardNum);
            oGame.CreateflashcardView(cardname, firstTime);
        },
        TabClick: function (tabname)
        {
            
            switch (tabname) {
                case "multichoice":
                    window.history.pushState("", "", oGameLocalization.CurrentURL + "/multichoice");
                    ga('send', 'pageview', oGameLocalization.CurrentURL + "/multichoice");
                    
                    if (GameOver) {
                        $("#GameOverDiv").removeClass("Hide");
                        $(".GamesCenter_div").addClass("Hide");
                        $(".GamesCenterVocab_div").addClass("Hide");
                    }
                    else {
                        $("#GameOverDiv").addClass('Hide')
                        $(".GamesCenter_div").removeClass("Hide");
                        $(".GamesCenterVocab_div").removeClass("Hide");
                    }
                    $("#listTab").removeClass("SelectedTab");
                    $("#flashcardTab").removeClass("SelectedTab");
                    $("#flashcardDiv").addClass("Hide");
                    $("#listDiv").addClass("Hide");
                    $("#multichoiceTab").addClass("SelectedTab");
                    if (StopTimer && AllowBtnPlayClicks && seconds < startingSeconds)
                        StopTimer = false;

                    if (oGameLocalization.NeedChangeTitleOnTabClick)
                    {
                        $("#CardTitleLast").text(oGameLocalization.TabNameList[0])
                    }
                    oGame.countdown();
                     
                    break;
                case "flashcard":
                    window.history.pushState("", "", oGameLocalization.CurrentURL + "/flashcard");
                    ga('send', 'pageview', oGameLocalization.CurrentURL + "/flashcard");

                    $("#multichoiceTab").removeClass("SelectedTab");
                    $("#listTab").removeClass("SelectedTab");
                    $("#flashcardDiv").removeClass("Hide");
                    $("#GameOverDiv").addClass("Hide");
                    $(".GamesCenter_div").addClass("Hide");
                    $(".GamesCenterVocab_div").addClass("Hide");
                    $(".GameOverDiv").addClass("Hide");
                    $("#listDiv").addClass("Hide");
                    $("#flashcardTab").addClass("SelectedTab");
                    StopTimer = true;
                    oGame.CreateflashcardView("",true);
                    var HideFullViewBtn = $('input[name=ViewChoose]:checked', '#flashcardTopDiv').attr('id') == "radio3";
                    if (HideFullViewBtn)
                        $("#FullViewImg").addClass("Hide");
                    else
                        $("#FullViewImg").removeClass("Hide");

                    if (oGameLocalization.NeedChangeTitleOnTabClick) {
                        $("#CardTitleLast").text(oGameLocalization.TabNameList[1])
                    }

                    break;
                case "list":
                    window.history.pushState("", "", oGameLocalization.CurrentURL + "/list");
                    ga('send', 'pageview', oGameLocalization.CurrentURL + "/list");

                    $("#multichoiceTab").removeClass("SelectedTab");
                    $("#flashcardTab").removeClass("SelectedTab");
                    $("#listDiv").removeClass("Hide");
                    $("#GameOverDiv").addClass("Hide");
                    $(".GamesCenter_div").addClass("Hide");
                    $(".GamesCenterVocab_div").addClass("Hide");
                    $(".GameOverDiv").addClass("Hide");
                    $("#flashcardDiv").addClass("Hide");
                    $("#listTab").addClass("SelectedTab");
                    StopTimer = true;

                    if (oGameLocalization.NeedChangeTitleOnTabClick) {
                        $("#CardTitleLast").text(oGameLocalization.TabNameList[2])
                    }

                    break;
            }

            $('.PersonalCard_imgTopWhite').each((function (index) {
                learn.MarkStar(false, this);
            }));

            oUI.refreshAds();
        },
        setMetaItem: function (from) {
            $.each($(".meta_item"), function () {
                var item = $(this);
                var level = item.data("list-level");
                var order = item.data("list-order");
                if (metaItems[level] == null) {
                    metaItems[level] = new Object();
                    metaItems[level].items = [];
                    metaItems[level].min = 1;
                    metaItems[level].size = 0;
                }
                metaItems[level].items[order] = item;
                metaItems[level].size++;
                item.hammer().on("swipeleft swiperight", function (ev) {
                    oGame.shiftMetaList(level, ev.type == "swipe" + from ? 1 : -1);
                });
            });
            oGame.onResize();
            $(window).on('resize', function () { oGame.onResize(); });
        },
        onResize:function(){
            for (var level in metaItems) {
                oGame.shiftMetaList(level, 0);
            }
        },
        setMetaItemProgress: function (dbGameResults) {

            GameResultsManager.SynchResultFromServer(dbGameResults);

            for (var level in metaItems) {
                var lastPicked = GameResultsManager.getLastPicked(level);
                for (var i = 1; i <= metaItems[level].size; i++) {
                    var item = metaItems[level].items[i];
                    var listId = item.data("list-id");
                    var listSize = item.data("list-size");
                    var result = GameResultsManager.GetGameResultByID(listId);
                    var unlocked = (i == 1 || metaItems[level].items[i - 1].data("list-percentage") >= unlockPercentage || oSite.DefaultCulture == "ar")
                    var percentage;
                    var correct = 0;
                    if (result != null) {
                        correct = result.CorrectAnswers.length;
                        percentage = 100 * correct / listSize;
                    }
                    else
                        percentage = 0;
                    metaItems[level].items[i].data("list-percentage",percentage);
                    var progressBar = $("#progressbar_" + listId);
                    progressBar.attr("aria-valuenow", percentage);
                    progressBar.css("width", percentage + "%");

                    var progressText = $("#progressText_" + listId);
                    progressText.html(correct + "/" + listSize);

                    var lock = $("#lock_" + listId);
                    if (unlocked) {
                        lock.hide();
                    }

                    var lockedText = $("#lockedText_" + listId);
                    var listIcon = $("#listIcon_" + listId);
                    var startText = $("#startText_" + listId);
                    var div = item.children();

                    if (unlocked) {
                        lockedText.css("display", "none");
                        if (lastPicked == i) {
                            listIcon.css("display", "block");
                        }
                    } else {
                        item.attr("href", null);
                        item.attr("onclick", "");
                        progressBar.parent().css("display", "none");
                        progressText.css("display", "none");
                        div.children().not('.locked_text').css("color", "#A9A9A9");
                        div.children().not('.locked_text').css("border-color", "#A9A9A9");
                        div.css("background-color", "rgba(236, 233, 230, 0.43)")
                        item.removeClass("enlargeHover")
                    }

                    if (percentage >= 80)
                        progressBar.css("background-color", "LightGreen")
                    if(percentage>=100)
                        progressBar.css("background-color", "DarkGreen")
                }
            }
        },
        shiftMetaList: function (level, delta) {
            var showNum = 4;
            if (window.innerWidth < 1200)
                showNum = 3;
            if (window.innerWidth < 768)
                showNum = 1;
            var min = metaItems[level].min;
            if (min + delta >= 1 && min + delta + showNum <= metaItems[level].size+1)
                metaItems[level].min += delta;
            min = metaItems[level].min;

            var allowPrevToggle = (min > 1);
            var allowNextToggle = (metaItems[level].size - min >= showNum);

            var arrowPrev = $('#metaArrowPrev_' + level);
            if (allowPrevToggle)
                arrowPrev.css("display", "block");
            else
                arrowPrev.css("display", "none");
            var arrowNext = $('#metaArrowNext_' + level);
            if (allowNextToggle)
                arrowNext.css("display", "block");
            else
                arrowNext.css("display", "none");

            for (var itemName in metaItems[level].items) {
                var item = metaItems[level].items[itemName];
                var order = item.data("list-order");
                if (order > min + showNum-1 || order < min)
                    item.css("display", "none");
                else
                    item.css("display", "block");
            }
        },
        setMetaQuizHighscore: function(prefix,gamesResult)
        {
            QuickQuizResultsManager.SynchResultFromServer(gamesResult);

            $.each($(".meta_highscore"), function () {
                var hsDiv = $(this);
                var highscore = QuickQuizResultsManager.GetResultByID(hsDiv.data("list-id"));
                if (highscore == null) {
                    hsDiv.addClass("no_score");
                    return;
                }
                hsDiv.html(prefix + " " + highscore);
            });
        }

    }

   
})();


;
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = 50;
var audioElement = document.createElement('audio');
var MobileSize = 768;

(function () {
    window['oSite'] = {}
    window['oAdvertisement'] = {}
    window['oAdvLearn'] = {}
    window['oAdvResult'] = {}
    window['oSound'] =
            {
                playSoundMP3:function(obj, url, origenalsrc)
                {
                    oSound.playSound(obj, url + ".mp3", origenalsrc);
                },
                playSound: function (obj, url, origenalsrc) {
                    audioElement.setAttribute('src', url);
                    var startTime = new Date().getTime();
                    var listner = function () {
                        oStuff.gaLog("Measurement", "Sound clicked", url, new Date().getTime() - startTime);
                        startTime = 0;
                        audioElement.removeEventListener("canplaythrough", listner);
                    };
                    audioElement.addEventListener("canplaythrough", listner);
                    audioElement.play();
                }
            }
    window['oStuff'] =
    {
        gaLog: function (sCategory, sAction, sLabel, nCount) {
            try {
                if (oSite.GoolgeAnalyticsEnabled) {
                    if (!sCategory || !sAction) {
                        // not valid situation
                        return;
                    }
                    sLabel = sLabel || "";
                    ga('set', 'dimension1', oSite.CurrentCulture);
                    if (typeof nCount == 'number') {
                        ga('send', 'event', sCategory, sAction, sLabel, nCount);
                    } else {
                        ga('send', 'event', sCategory, sAction, sLabel);
                    }
                }
            } catch (e) {
                // do nothing
            }
        },
        htmlDecode: function (value) {
            return $('<div/>').html(value).text();
        } ,
        runMethod: function (method) {
            method();
        },
        evalMethod: function (method) {
            eval(method);
        },
        urlencode: function (str) {
            str = (str + '').toString();

            return encodeURIComponent(str)
              .replace(/!/g, '%21')
              .replace(/'/g, '%27')
              .replace(/\(/g, '%28')
              .replace(/\)/g, '%29')
              .replace(/\*/g, '%2A')
              .replace(/ /g, '%20')
              .replace(/\./g, '%2E');
        },
        getParameterByName: function (name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        },
        IsEmail: function (email) {
            var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (!regex.test(email)) {
                return false;
            } else {
                return true;
            }
        },
        SortAutoComplete(a, b)
        {
            a = a.replace("~L1", "").replace("~L2", "");
            b = b.replace("~L1", "").replace("~L2", "");
            if (a < b) return -1;
            if (a > b) return 1;
            return 0;
        }
    }

    window['oUI'] =
    {
        InnitSite: function () {
            oUI.SetSearchBoxID();
            if (oSite.GoolgeAnalyticsEnabled) {
                $('head').append(oStuff.htmlDecode(oSite.GoogleAnalyticsScript));
            }
            if (oSite.AdvertisementJsonStr != "") {
                oAdvertisement = JSON.parse(oStuff.htmlDecode(oSite.AdvertisementJsonStr));
            }
            if (oSite.IsHomePage) {
                oRender.RenderAdvertisementsHome();
            }
            else {
                oRender.RenderAdvertisementsSide();
            }
            oUI.InitWaterMarkText();
            oRender.RenderAutoComplete();
            oUI.AddMaxLimit();
            oLogin.FBinit();
            oRender.RenderSearchBox();
            var resizeEvt;
            $(window).on('resize', function () {
                clearTimeout(resizeEvt);
                resizeEvt = setTimeout(function () {
                    oUI.SetSearchBoxID();
                    oUI.InitWaterMarkText();
                    oRender.RenderSearchBox();
                    oRender.RenderAutoComplete();
                }, 100);
            });
            oUI.InitHideHeader();
            oUI.InitMobileMenu();
            if (oSite.IsLogedIn)
            {
                learn.InnitPersonalIds(oSite.PrivateMelingoIDsList);
            }
            if (oSite.CurrentQuery != '') {
                $("#searchField").val(oSite.CurrentQuery);
                oUI.HideWaterMark(true);
            }
        },
        InitMobileMenu: function () {
            var sideslider = $('[data-toggle=collapse-side]');
            var sel = sideslider.attr('data-target');
            var sel2 = sideslider.attr('data-target-2');
            sideslider.click(function (event) {
                $(sel).toggleClass('in');
                $(sel2).toggleClass('out');
            });
        },
        InitHideHeader: function () {
            $(window).scroll(function (event) {
                didScroll = true;
            });

            setInterval(function () {
                if (didScroll) {
                    hasScrolled();
                    didScroll = false;
                }
            }, 250);

            function hasScrolled() {
                var st = $(this).scrollTop();
                if (st > lastScrollTop && st > navbarHeight) {
                    // Scroll Down
                    $(document.body).addClass('body_scrolled_down');
                } else {
                    // Scroll Up
                    if (st == 0) {
                        $(document.body).removeClass('body_scrolled_down');
                    }
                }

                lastScrollTop = st;
            }
        },
        InitoAdvLearn:function(obj)
        {
            oAdvLearn = JSON.parse(oStuff.htmlDecode(obj));
        },
        InitAdvertisement: function (obj) {
            oAdvertisement = JSON.parse(oStuff.htmlDecode(obj));
        },
        InitLocalization: function (obj) {
            oLocalization = JSON.parse(oStuff.htmlDecode(obj));
        },
        InitoSite: function (obj) {
            oSite = obj;
        },
        ShowMore: function (obj) {
            var ul = $(obj).parent();
            ul.find('[name="backLink"]').show();
            ul.find('[name="hidden"]').show();
            $(obj).hide();
        },
        Back: function (obj) {
            var ul = $(obj).parent();
            ul.find('[name="hidden"]').hide();
            ul.find('[name="showMoreLink"]').show();
            $(obj).hide();
        },
        InitWaterMarkText: function () {
            $("#searchField").focus(function () {
                oUI.HideWaterMark(false);
            });

            $("#searchField").keypress(function () {
                oUI.HideWaterMark(true);
            });

            $("#searchDesc").focus(function () {
                oUI.HideWaterMark(true);
                $("#searchField").select();
            });

            $("#searchField").blur(function () {
                oUI.ShowWaterMark();
            });

        },
        ShowWaterMark: function () {
            if ($("#searchField").val() == '') {
                $("#searchField").hide();
                $("#searchDesc").show();
            }
        },
        HideWaterMark: function (forceHide) {
            if (!forceHide || forceHide == undefined) {
                if ($("#searchField").val() != '')
                    $("#searchDesc").hide();

            }
            else {
                $("#searchDesc").hide();
                $("#searchField").show();
            }
        },
        GoTo: function (category, className, val) {
            oStuff.gaLog(category, className, val);
            setTimeout(function () { window.location = val; }, 1000);
        },
        GoToQuizTeaser: function (url, from, category)
        {
            oStuff.gaLog(from, 'QuizTeaser', category);
            setTimeout(function () { window.location = url; }, 1000);
        },
        GoToTranslationTeaser: function (url, from, category) {
            oStuff.gaLog(from, 'MyTranslationsTeaserClick', category);
            setTimeout(function () { window.location = url; }, 1000);
        },
        AlphabetPagerGoTo: function (url) {
            if ($("#AlphabetPager").val() != "") {
                var index = $("#AlphabetPager").val();
                setTimeout(function () { window.location = url + index; }, 1000);
            }
        },
        CheckInputKey: function (e) {
            if (e.keyCode == '13') { // Enter
                setTimeout(function () {
                    oSearch.GetTranslation();
                    document.activeElement.blur();
                }, 300);
                $('#autocomplete_ul').hide();
                oSite.IsOccursAjax = false;
                return false;
            }
            else {
                if ($('#searchField').val().length >= oSite.maxCharacterCountInput)
                    return false;
                oSite.IsOccursAjax = false;
            }
        },
        changeSearchFieldDir: function () {
            if (oSite.SearchDetectDirection) {
                var $field = $("#searchField");
                var $serachbox_input_content = null; 

                if (window.innerWidth >= MobileSize) {
                    $serachbox_input_content = $("#serachbox_input_content");
                }
                else {
                    $serachbox_input_content = $(".input_areaM");
                }

                if ($field.length != 0 && $field.val() != '') {
                    var english = /[a-zA-Z]/
                    var text = $field.val();

                    var direction = (text.match(english)) ? "direction_en" : "direction_ar";
                    var fontLang = (text.match(english)) ? "font_en" : "font_ar";
                    $serachbox_input_content.addClass('disable_transitions');
                    $field.removeClass('direction_en').removeClass('direction_ar').addClass(direction);
                    $field.removeClass('font_en').removeClass('font_ar').addClass(fontLang);
                    if (text.match(english)) {
                        $serachbox_input_content.removeClass('input_area_ar');
                    } else {
                        $serachbox_input_content.addClass('input_area_ar');
                    }
                    setTimeout(
                      function () {
                          $serachbox_input_content.removeClass('disable_transitions');
                      }, 10);
                }
            }
        },
        GetAutoCompleteLngImage: function (type) {
            switch (type) {
                case "L1":
                    return oSite.AutoCompleteImageNameL1;
                case "L2":
                    return oSite.AutoCompleteImageNameL2;
            }
        },
        forgotPassword:function()
        {
            ajaxHelper.forgotPassword();
        },
        ContactUs:function()
        {
            ajaxHelper.ContactUs();
        },
        ChangePassword:function()
        {
            ajaxHelper.ChangePassword();
        },
        FormatQuery: function (query) {
            query = query.replace(/[�~!@$%^&#*()_|+\=?;:,<>\{\}\[\]\\]/gi, '')
            return query;
        },
        AddMaxLimit: function () {
            var limit = '' + oSite.maxCharacterCountInput
            $('#searchField').attr('maxLength', limit);
            $('#searchDesc').attr('maxLength', limit);
        },
        DictionaryRender: function (html) {
            $("#disqus_thread").hide();
            $("#renderBody").empty();
            $("#renderBody").html(html);
            $('#autocomplete_ul').hide();
            oSite.IsOccursAjax = true;
            oUI.changeSearchFieldDir();
            oSite.IsHomePage = false;
            
            if ($("#actualTitle_hdn").val() != "")
                document.title = oStuff.htmlDecode($("#actualTitle_hdn").val());
            oSite.ShowResultSearchBox = true;
            oRender.RenderSearchBox();
            oRender.RenderAdvertisementsSide();
            $("#loadingBar").removeClass("animated");
        },
        SignInHome:function()
        {
            $('body').removeClass('modal-open');
            var destURL = oSite.CurrentSiteURL + "users/SignIn";
            var dataRequest = "";
            if (oSite.IsAnonimousQuiz)
            {
                dataRequest = "IsAnonimousQuiz=" + oSite.IsAnonimousQuiz;
            }
            ajaxHelper.AjaxReqest(dataRequest, destURL, 'post');
        },
        LoginForm: function (IsFormRequest)
        {
            IsFormRequest = typeof IsFormRequest !== 'undefined' ? IsFormRequest : false;
            ajaxHelper.LoginForm(IsFormRequest);
        },
        LoginFormHome:function(IsFormRequest)
        {
            IsFormRequest = typeof IsFormRequest !== 'undefined' ? IsFormRequest : false;
            ajaxHelper.LoginForm(IsFormRequest,true);
        },
        RegisterUser: function (IsFormRequest)
        {
            IsFormRequest = typeof IsFormRequest !== 'undefined' ? IsFormRequest : false;
            ajaxHelper.RegisterUser(IsFormRequest);
        },
        RegisterUserHome: function (IsFormRequest)
        {
            IsFormRequest = typeof IsFormRequest !== 'undefined' ? IsFormRequest : false;
            ajaxHelper.RegisterUser(IsFormRequest, true);
        },
        OnPostLogin: function (response, IsHome)
        {
            oGame.RemoteSaveFullResult();
            
            if (response.indexOf("window.location") > -1) {
                if (oSite.isPopup) {
                    open(location, '_self').close();
                } else {
                    setTimeout(function () {
                        if (oSite.isLoginPage)
                            window.location = oSite.CurrentSiteURL;
                        else
                            window.location = val;
                    }, 500);
                }
                return;
            }
            else {
                if (IsHome) {
                    oRender.RegistrationFormHomeRender(response);
                    return;
                }
                else {
                    $("#renderBody").empty();
                    $("#renderBody").html(response);
                    return;
                }
            }
            
            
        },
        Logout: function () {
            var destURL = oSite.CurrentSiteURL + "users/LogOut";
            ajaxHelper.AjaxReqest("", destURL, 'post', false, true, true, false);
            localStorage.clear();
        },
        RemoveScriptFormHeader: function (id) {
            var head = document.getElementsByTagName("head")[0];
            var scriptToRemove = document.getElementById(id);
            if (scriptToRemove) {
                head.removeChild(scriptToRemove);
            }
        },
        CheckIsAdUnitSupprres: function (source, distList) {
            if ($("#" + source).length == 0)
                return false;
            var MinResolutionToShowAds = 1216;
            var result = true;
            if (window.screen.width >= MinResolutionToShowAds)
                return result;
            var TempList = distList.split(',');
            for (var i = 0; i < TempList.length; i++) {
                if (source == TempList[i]) {
                    result = false;
                    $("#" + source).hide();
                    break;
                }
            }
            return result;
        },
        ExistAdvertisementResultPageScript: function (scriptName) {
            var scriptToRemove = document.getElementById(scriptName);
            if (scriptToRemove) {
                return true;
            }
            return false;
        },
        refreshAds: function () {
            try {
                googletag.pubads().refresh();
            } catch (e) {

            }
        },
        readCookie: function (name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        },
        MobileScreen: function ()
        {
            var SearchBoxContentDiv = $("#SearchBoxContent");
            var SearchMobileButton = $("#SearchMobile");
            var SearchBoxDiv = $("#SearchBoxDiv");
            var searchField = $("#searchField");
            
            var searchDesc = $("#searchDesc");
            $.scrollLock(false);

            searchDesc.val( oSite.SearchBoxMobileText);

            if (!oSite.IsHomePage) {
                SearchBoxContentDiv.removeClass("SearchBoxContent");
                SearchMobileButton.removeClass("Hide");
                SearchBoxDiv.removeClass("SearchBox");
                searchField.removeClass("searchField");
               
                if (!SearchBoxContentDiv.hasClass("input-group")) {
                    SearchBoxContentDiv.addClass("input-group");
                }
                if (!SearchBoxContentDiv.hasClass("custom-search-form")) {
                    SearchBoxContentDiv.addClass("custom-search-form");
                }
                if (!SearchBoxDiv.hasClass("SearchBoxMobile")) {
                    SearchBoxDiv.addClass("SearchBoxMobile");
                }
                if (!searchField.hasClass("searchFieldMobile")) {
                    searchField.addClass("searchFieldMobile");
                }
            }
            else {
                if (!SearchBoxContentDiv.hasClass("SearchBoxContent")) {
                    SearchBoxContentDiv.addClass("SearchBoxContent");
        }
    }

        },
        FullScreen: function () {
            var SearchBoxContentDiv = $("#SearchBoxContent");
            var SearchMobileButton = $("#SearchMobile");
            var SearchBoxDiv = $("#SearchBoxDiv");
            var searchField = $("#searchField");
            var searchDesc = $("#searchDesc");

            searchDesc.val( oSite.SearchBoxDesktopText);

            SearchBoxContentDiv.removeClass("input-group").removeClass("custom-search-form").removeClass("SearchBoxContent");
            SearchBoxDiv.removeClass("SearchBoxMobile");
            searchField.removeClass("searchFieldMobile");
            if (!SearchMobileButton.hasClass("Hide")) {
                SearchMobileButton.addClass("Hide");
            }
            if (!SearchBoxDiv.hasClass("SearchBox")) {
                SearchBoxDiv.addClass("SearchBox");
            }
            if (!searchField.hasClass("searchField")) {
                searchField.addClass("searchField");
            }
        },
        MobileMenuButtonClick: function ()
        {
            var opened = $('#menu_mobile_div').hasClass('in');
            oStuff.gaLog('Menu', 'MobileDrawer', opened ? "Open drawer" : "Close drawer");
            if (opened) {
                $.scrollLock(true);
            }
            else {
                $.scrollLock(false);
            }
        },
        AddToPlaceHolder: function (placeHolder, tmpl, json,rtnHTML) {
            if (rtnHTML)
                return tmpl(json);

            placeHolder.append(tmpl(json));
        },
        SendMailRequest: function ()
        {
            var email = $("#SendEmailInput").val();
            if (email == "")
                return;
            if (oStuff.IsEmail(email)) {
                var destURL = oSite.CurrentSiteURL + "users/RegisterNewsletter";

                $.ajax({
                    type: 'POST',
                    async: true,
                    url: destURL,
                    data: email,
                    cache: false,
                    success: function (response) {
                        $(".wordoftheday_newsletter_btn").hide();
                        $(".wordoftheday_newsletter_error").hide();
                        $(".wordoftheday_newsletter_aswer").show();
                    },
                    error: function (e) {
        
                    }
                });
            }
            else {
                $(".wordoftheday_newsletter_error").show();
            }
        },
        SetSearchBoxID: function ()
        {
            var mobSearchField_ID = $('[name="searchFieldM"]').attr("id");
            var mobSearchDesc_ID = $('[name="searchDescM"]').attr("id");
            var descSearchField_ID = $('[name="searchField"]').attr("id");
            var descSearchDesc_ID = $('[name="searchDesc"]').attr("id");

            
            if (window.innerWidth < MobileSize) {
                if (mobSearchField_ID != "searchField")
                {
                    $('#' + descSearchField_ID).attr("id", "searchField" + window.screen.width);
                    $('#' + descSearchDesc_ID).attr("id", "searchDesc" + window.screen.width);
                    $('#' + mobSearchField_ID).attr("id", "searchField");
                    $('#' + mobSearchDesc_ID).attr("id", "searchDesc");
                }
            }
            else {
                if (descSearchField_ID != "searchField") {
                    $('#' + descSearchField_ID).attr("id", "searchField");
                    $('#' + descSearchDesc_ID).attr("id", "searchDesc");
                    $('#' + mobSearchField_ID).attr("id", "searchField" + window.screen.width);
                    $('#' + mobSearchDesc_ID).attr("id", "searchDesc" + window.screen.width);
                }
            }
        },
        SetCurrentUserName: function ()
        {
            var username = localStorage["UserName"];
            if (username != "")
            {
                $(".navbar_UserName").html(username);
            }
        },
        PayPalSendForm: function (id)
        {
            $("#" + id).submit();
        },
        hideAllPopovers: function ()
        {
            $('.popover').each(function () {
                $(this).popover('hide');
            });
        },
        ChangeURL: function (name)
        {
            var SearchURL = oSite.CurrentSiteURL;
            switch (name) {
                case "not-found":
                    SearchURL = SearchURL + "dictionary/not-found"
                    window.history.pushState("", "", SearchURL);
                    break;
            }
        },
        scrollToWord: function (view, id) {
            $('html, body').animate({
                scrollTop: $("#word_" + id).offset().top - $(".top_Container").height() - $(".Translationresult_header").height()
            }, 500);
            $("span[class^='pos_link_']").removeClass("last_pos_clicked");
            $(view).addClass("last_pos_clicked");
        },
        NoResultSerachboxCheckInput: function ()
        {
            var input = $('#NoResult_serachbox').val();
            $('#searchField').val(input);
            oUI.HideWaterMark(true);
        }
    }

    window['oRender'] =
    {
        RenderSearchBox:function()
        {
            $(document.body).addClass("disable_transitions");
            if (window.innerWidth >= MobileSize) {
                navbarHeight = 150;
                if ($('#translationContent').length) {
                    $('.CentralDivInner').css("margin-top", ($(".Translationresult_header").height() + navbarHeight + 20)); 
                    $('.Translationresult_header').css("padding-left", $('#translationContent').offset().left + 15);
                    $('.Translationresult_header').css("padding-right", $(window).width() - ($('#translationContent').offset().left + $('#translationContent').innerWidth()) + 15);
                }
                else {
                    $('.CentralDivInner').css("margin-top", navbarHeight + 20);
                }
                $('.top_Container').height(navbarHeight);
            } else {
                navbarHeight = 50;
                $('.top_Container').removeAttr('style');
                $('.CentralDivInner').removeAttr('style');
                $('.Translationresult_header').removeAttr('style');
            }
            setTimeout(function () {
                $(document.body).removeClass("disable_transitions");
            }, 1);
            
        },
        RenderAutoComplete: function () {
            if (oSite.DefaultCulture == "ar") {
                if ($.fn.typeahead != 'undefined') {
                    var _show = $.fn.typeahead.Constructor.prototype.show;

                    $.fn.typeahead.Constructor.prototype.show = function () {
                        if (typeof this.options.onshow == 'function') {
                            this.options.onshow();
                        }
                        var pos = this.$element.offset()
                        this.$menu.css({
                            left: $(window).width() - pos.right - this.$element.outerWidth(),
                            right: 'auto'
                        })
                        // Call parent
                        _show.apply(this, []);
                    };
                }(window.jQuery);

                $('#searchField').typeahead({
                    autoSelect: false,
                    items: "all",
                    source: function (query, process) {
                        return $.ajax({
                            url: oSite.AutoCompleteServicePath + query.replace(/ /g, "_"),
                            type: 'GET',
                            data: {},
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'jsonp',
                            success: function (obj) {
                                var json = typeof obj.Results == 'undefined' || obj.Results.length == 0 ? obj.ResultsL2 : obj.Results;
                                if (!oSite.IsOccursAjax)
                                    return typeof json == 'undefined' ? false : process(json);
                            }
                        });
                    }
                });

            }
            else {
                $('#searchField').typeahead({
                    autoSelect: false,
                    items: "all",
                    source: function (query, process) {
                        return $.ajax({
                            url: oSite.AutoCompleteServicePath + query.replace(/ /g, "_"),
                            type: 'GET',
                            data: {},
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'jsonp',
                            success: function (obj) {
                                var json = typeof obj.Results == 'undefined' ? obj.ResultsL2 : obj.Results;
                                if (typeof obj.Results != 'undefined') {
                                    for (var i in obj.Results) {
                                        obj.Results[i] += "~L1";
                                    }
                                }
                                if (typeof obj.ResultsL2 != 'undefined') {
                                    for (var i in obj.ResultsL2) {
                                        obj.ResultsL2[i] += "~L2";
                                        if (typeof obj.Results != 'undefined')
                                            json.push(obj.ResultsL2[i]);
                                    }
                                }
                                obj.Results.sort(oStuff.SortAutoComplete)
                                if (!oSite.IsOccursAjax)
                                    return typeof json == 'undefined' ? false : process(json);
                            }
                        });
                    },
                    highlighter: function (item) {
                        var split = item.split('~');
                        return split[0] + "$<img src='" + oSite.CurrentImagePath + oUI.GetAutoCompleteLngImage(split[1]) + "' class='autocomplete_image'  alt='' >";
                    }
                });
            }
        },
        RegistrationFormHomeRender: function (response) {
            $("#LoginHomeDiv").empty();
            $("#LoginHomeDiv").html(response);
        },
        RenderAdvertisementsSide: function ()
        {
            var destURL = oSite.CurrentSiteURL + "users/RenderAdvertisement";
            ajaxHelper.AjaxReqest('maxHeight=' + $("#renderBody").height(), destURL, 'get', true, oRender.RenderAdvertisementResponse);
        },
        RenderAdvertisementResponse: function (html)
        {
            $("#Advertisement_div").empty();
            $("#Advertisement_div").html(html);
            $('#autocomplete_ul').hide();
            oRender.RenderAdvertisementsResultPage();
            oRender.RenderAdvertisementsResult();
            oUI.refreshAds();
        },
        RenderAdvertisementsHome: function () {
            oUI.RemoveScriptFormHeader('AdvertisementScript');
            var head = document.getElementsByTagName("head")[0];
            var script = document.createElement("script");
            script.id = "AdvertisementScript";
            script.type = "text/javascript";
            var NeedToAdd = false;
            if (oAdvertisement != null && oAdvertisement != "") {
                var method = "googletag.cmd.push(function() {";
                for (var i = 0; i < oAdvertisement.length; i++) {
                    if (!oAdvertisement[i].IsResultPage && oSite.CurrentCulture == oAdvertisement[i].Lng) {
                        if (oUI.CheckIsAdUnitSupprres(oAdvertisement[i].ID, "TopRightRadvertisement,MiddleRightRadvertisement,BottomRightRadvertisement")) {
                            if (oAdvertisement[i].ID == "Topadvertisement") {
                                if (window.screen.width < 1216) {
                                    NeedToAdd = true;
                                    method = method + " var slot" + i + "=" + oAdvertisement[i].Header + ".addService(googletag.pubads());";
                                }
                            }
                            else {
                                NeedToAdd = true;
                                method = method + " var slot" + i + "=" + oAdvertisement[i].Header + ".addService(googletag.pubads());";
                            }
                        }
                    }
                }
                method = method + "googletag.pubads().enableSingleRequest();googletag.pubads().enableAsyncRendering(); googletag.enableServices(); });";
                script.innerHTML = method;
                if (NeedToAdd)
                    head.appendChild(script);

                for (var i = 0; i < oAdvertisement.length; i++) {
                    if (!oAdvertisement[i].IsResultPage && oSite.CurrentCulture == oAdvertisement[i].Lng) {
                        if (oUI.CheckIsAdUnitSupprres(oAdvertisement[i].ID, "TopRightRadvertisement,MiddleRightRadvertisement,BottomRightRadvertisement")) {
                            if (oAdvertisement[i].ID == "Topadvertisement") {
                                if (window.screen.width < 1216) {
                                    $("#" + oAdvertisement[i].ID).empty();
                                    $("#" + oAdvertisement[i].ID).html(oAdvertisement[i].Body);
                                }
                            }
                            else {
                                $("#" + oAdvertisement[i].ID).empty();
                                $("#" + oAdvertisement[i].ID).html(oAdvertisement[i].Body);
                            }
                        }
                    }
                }
            }
        },
        RenderAdvertisementsResultPage: function () {
            if (!oUI.ExistAdvertisementResultPageScript("AdvertisementScript")) {
                oUI.RemoveScriptFormHeader('AdvertisementScript');
                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                script.id = "AdvertisementScript";
                script.type = "text/javascript";
                var NeedToAdd = false;
                if (oAdvertisement != null && oAdvertisement != "") {
                    var method = "googletag.cmd.push(function() {";
                    for (var i = 0; i < oAdvertisement.length; i++) {
                        if (oSite.CurrentCulture == oAdvertisement[i].Lng) {
                            if (oUI.CheckIsAdUnitSupprres(oAdvertisement[i].ID, "TopRightRadvertisement,MiddleRightRadvertisement,BottomRightRadvertisement")) {
                                if (oAdvertisement[i].ID == "Topadvertisement") {
                                    if (window.screen.width < 1216) {
                                        method = method + " var slot" + i + "=" + oAdvertisement[i].Header + ".addService(googletag.pubads());";
                                        NeedToAdd = true;
                                    }
                                }
                                else {
                                    NeedToAdd = true;
                                    method = method + " var slot" + i + "=" + oAdvertisement[i].Header + ".addService(googletag.pubads());";
                                }
                            }
                        }
                    }
                    method = method + "googletag.pubads().enableSingleRequest();googletag.pubads().enableAsyncRendering(); googletag.enableServices(); });";
                    script.innerHTML = method;
                    if (NeedToAdd)
                        head.appendChild(script);
                }
            }
            for (var i = 0; i < oAdvertisement.length; i++) {
                if (oSite.CurrentCulture == oAdvertisement[i].Lng) {
                    if (oUI.CheckIsAdUnitSupprres(oAdvertisement[i].ID, "TopRightRadvertisement,MiddleRightRadvertisement,BottomRightRadvertisement")) {
                        if (oAdvertisement[i].ID == "Topadvertisement") {
                            if (window.screen.width < 1216) {
                                $("#" + oAdvertisement[i].ID).empty();
                                $("#" + oAdvertisement[i].ID).html(oAdvertisement[i].Body);
                            }
                        }
                        else {
                            $("#" + oAdvertisement[i].ID).empty();
                            $("#" + oAdvertisement[i].ID).html(oAdvertisement[i].Body);
                        }
                    }
                }
            }
        },
        RenderAdvertisementsResult:function()
        {
            if (!oUI.ExistAdvertisementResultPageScript("AdvertisementResultScript")) {
                oUI.RemoveScriptFormHeader('AdvertisementResultScript');
                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                script.id = "AdvertisementResultScript";
                script.type = "text/javascript";
                var NeedToAdd = false;
                if (oAdvResult != null && oAdvResult != "") {
                    var method = "googletag.cmd.push(function() {";
                    for (var i = 0; i < oAdvResult.length; i++) {
                        if (oSite.CurrentCulture == oAdvResult[i].Lng) {
                            if (window.screen.width > 740) {
                                if (oAdvResult[i].ID != "MobileWordFromSponsorAdvertisement") {
                                    NeedToAdd = true;
                                    method = method + " var slot" + i + "=" + oAdvResult[i].Header + ".addService(googletag.pubads());";
                                    break;
                                }
                            }
                            else 
                            {
                                if (oAdvResult[i].ID == "MobileWordFromSponsorAdvertisement")
                                {
                                    NeedToAdd = true;
                                    method = method + " var slot" + i + "=" + oAdvResult[i].Header + ".addService(googletag.pubads());";
                                    break;
                                }
                            }
                         }
                    }
                    method = method + "googletag.pubads().enableSingleRequest();googletag.pubads().enableAsyncRendering(); googletag.enableServices(); });";
                    script.innerHTML = method;
                    if (NeedToAdd)
                        head.appendChild(script);
                }
            }

            for (var i = 0; i < oAdvResult.length; i++) {
                if (oSite.CurrentCulture == oAdvResult[i].Lng) {
                    if (window.screen.width > 740) {
                        if (oAdvResult[i].ID != "MobileWordFromSponsorAdvertisement")
                        {
                            $("#" + oAdvResult[i].ID).empty();
                            $("#" + oAdvResult[i].ID).html(oAdvResult[i].Body);
                            break;
                        }
                    }
                    else {
                        if (oAdvResult[i].ID == "MobileWordFromSponsorAdvertisement") {
                            $("#" + oAdvResult[i].ID.replace('Mobile', '')).empty();
                            $("#" + oAdvResult[i].ID.replace('Mobile', '')).html(oAdvResult[i].Body);
                            break;
                        }
                    }
                    
                }
            }
        },
        RenderAdvLearn: function (id) {
            if ($("#Advertisement_" + id).html().trim() == "" && AdvLearnCounter <= MaxAdvLearnCounter && oAdvLearn != null && oAdvLearn != "") {
                oUI.RemoveScriptFormHeader('AdvLearnScript_' + id);
                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                script.id = "AdvLearnScript_" + id;
                script.type = "text/javascript";
                var num = 0;
                if (oAdvLearn != null && oAdvLearn != "") {
                    var method = "googletag.cmd.push(function() {";
                    for (var i = 0; i < oAdvLearn.length; i++) {
                        if (!oAdvLearn[i].IsShown) {
                            oAdvLearn[i].ID = "Advertisement_" + id + "'";
                            num = i;
                            method = method + " var slot0" + i + "=" + oAdvLearn[i].Header + ".addService(googletag.pubads());";
                            break;
                        }
                    }
                    method = method + "googletag.pubads().enableSingleRequest();googletag.pubads().enableAsyncRendering(); googletag.enableServices(); });";
                    script.innerHTML = method;
                    head.appendChild(script);
                    $("#Advertisement_" + id).html(oAdvLearn[num].Body);
                    oAdvLearn[num].IsShown = true;
                }
                AdvLearnCounter = AdvLearnCounter + 1;
            }
            else if ($("#Advertisement_" + id).html().trim() != "") {
                $("#Advertisement_" + id).show();
            }
        }
    }
    window['oSearch'] =
    {
        GetTranslation: function () {
            oUI.hideAllPopovers();
            var query = $('#searchField').val().trim();
            query = oStuff.urlencode(oUI.FormatQuery(query));
            var SearchURL = oSite.CurrentSiteURL + query;

            if (query != "" && window.location != SearchURL) {
                try {
                    if (oSite.PushState) {
                        window.history.pushState("", "", SearchURL);

                        $("#loadingBar").addClass("animated");
                        ajaxHelper.dictionaySearch(query);
                        ga('send', 'pageview', SearchURL);
                    }

                    else {
                        window.location = SearchURL;
                    }
                    
                } catch (e) {
                    window.location = SearchURL;
                }

            }
        }
    }

   
})();

$(document).ready(function () {
    oUI.InnitSite();
});

 var ajaxHelper =
    {
        dictionaySearch: function (query) {
            //var query = oSite.DefaultCulture == "ar" ? query : "?Query=" + query ;
            var destURL = oSite.CurrentSiteURL + "d?Query=" + query;
            ajaxHelper.AjaxReqest('', destURL, 'get', true, oUI.DictionaryRender);
            },
        forgotPassword: function () {
            var destURL = oSite.CurrentSiteURL + "/user/forgotpassword";
            var email = $('#ForgotPasswordCardEmail').val();
            ajaxHelper.AjaxReqest("email=" +email, destURL, 'post');
        },
        ContactUs: function () {
            var destURL = oSite.CurrentSiteURL + "info/contactus";
            var root = $.cookie("Queries");
            var lastTranslations = " ";
            if (root != null && root != "") {
                var QueryList = root.split('~');
                for (var i = 0; i < QueryList.length; i++) {
                    lastTranslations = lastTranslations + QueryList[i] + ",";
                }
            }
            var Data = {
                "about": $("#textarea_aboutBritanica").val(),
                "added": $("#textarea_addedToBritanica").val(),
                "email": $("#input_email").val(),
                "lastTranslations": lastTranslations
            }

            ajaxHelper.AjaxReqest("Data=" +JSON.stringify(Data), destURL, 'post');
        },
        ChangePassword: function () {
            var destURL = oSite.CurrentSiteURL + "user/changepassword";
            var Data = {
                "OldPass": $("#ChangePasswordCardOLDPass").val(),
                "NewPass": $("#ChangePasswordCardPass").val(),
                "NewRePass": $("#ChangePasswordCardRePass").val()
            }

            ajaxHelper.AjaxReqest("Data=" +JSON.stringify(Data), destURL, 'post');
        },
        LoginForm: function (IsFormRequest,IsHome)
        {
            IsHome = typeof IsHome !== 'undefined' ? IsHome : false;
            wordID = typeof wordID !== 'undefined' && wordID != "" ? wordID : 0;
            var destURL = oSite.CurrentSiteURL + "users/" + (IsHome ? "LoginHome" : "Login");
            var dataRequest = "isPopup=" + oSite.isPopup;

            if (IsFormRequest)
            {
                localStorage["UserName"] = IsHome ? $("#SiteLoginEmail").val() : $("#SiteLoginCardEmail").val();
                var Data = {
                    "UserPass": IsHome ? $("#SiteLoginPassword").val() : $("#SiteLoginCardPassword").val(),
                    "Mail": IsHome ? $("#SiteLoginEmail").val() : $("#SiteLoginCardEmail").val(),
                    "mID": wordID,
                    "IsAnonimousQuiz": oSite.IsAnonimousQuiz
                }
                dataRequest = "UserDetails=" + JSON.stringify(Data);
                ajaxHelper.AjaxReqest(dataRequest, destURL, 'post', false, oUI.OnPostLogin, false, IsHome);
            }
            else
            {
                IsHome ? ajaxHelper.AjaxReqest(dataRequest, destURL, 'post', false, oUI.OnPostLogin, false, IsHome) : ajaxHelper.AjaxReqest(dataRequest, destURL, 'post');
            }
        },
        RegisterUser: function (IsFormRequest, IsHome) {
            IsHome = typeof IsHome !== 'undefined' ? IsHome : false;
            wordID = typeof wordID !== 'undefined' && wordID != "" ? wordID : 0;
            var destURL = oSite.CurrentSiteURL + "users/" + (IsHome ? "RegisterUserHome" : "RegisterUser");
            var dataRequest = "";
            if (IsFormRequest)
            {
                localStorage["UserName"] = IsHome ? $("#NewUserEmail").val() : $("#SiteNewUserCardHomeEmail").val();
                var Data = {
                    "UserEmail": IsHome ? $("#NewUserEmail").val() : $("#SiteNewUserCardHomeEmail").val(),
                    "UserPass": IsHome ? $("#NewUserPass").val() : $("#SiteNewUserCardHomePass").val(),
                    "UserRePass": IsHome ? $("#NewUserRePass").val() : $("#SiteNewUserCardHomeRePass").val(),
                    "mID": wordID,
                    "NewsletterRegistration": $('input[id="newslater_chkb"]:checked').length > 0 ? true : false,
                    "IsAnonimousQuiz": oSite.IsAnonimousQuiz
                }
                dataRequest = "UserDetails=" + JSON.stringify(Data);
                ajaxHelper.AjaxReqest(dataRequest, destURL, 'post', false, oUI.OnPostLogin,false,IsHome);
            }
            else {
                IsHome ? ajaxHelper.AjaxReqest(dataRequest, destURL, 'post', false, oUI.OnPostLogin, false, IsHome) : ajaxHelper.AjaxReqest(dataRequest, destURL, 'post');
            }
        },
        UpdateWord: function (id, bAddWord, onSuccess) {
            var destURL = oSite.CurrentSiteURL + "LearnPrivate/UpdateWord/" + id + "/" + bAddWord;
            ajaxHelper.AjaxReqest('', destURL, 'get', true,onSuccess,true);
        },
        AjaxReqest: function (data, destURL, method, onError, onSuccess,bEval , IsHome) {

            if (!method)
                method = 'post';

            $.ajax({
                type: method,
                async: true,
                url: destURL,
                data:  data,
                cache: false,
                success: function (response) {
                    if(response) {
                        if (onSuccess) {
                            bEval ? oStuff.evalMethod(response) : onSuccess(response,IsHome);
                            return;
                        }
                        $("#disqus_thread").hide();
                        $("#renderBody").empty();
                        if (oSite.IsAnonimousQuiz) {
                            var tar = $('#renderBody').html(response);
                            tar.animate({
                                top: '-=200',
                            }, 0, function () {
                                // Animation complete.
                            });
                            tar.animate({
                                top: '+=200',
                            }, 1000, function () {
                                // Animation complete.
                            });
                        }
                        else {
                            $("#renderBody").html(response);
                        }
                        
                        return;
                    }
                },
                error: function (e) {
                    if (onError) {
                        onError();
                    }
                }
            });
        }
    }
 $.scrollLock = (function scrollLockClosure() {
     'use strict';

     var $html = $('html'),
         // State: unlocked by default
         locked = false,
         // State: scroll to revert to
         prevScroll = {
             scrollLeft: $(window).scrollLeft(),
             scrollTop: $(window).scrollTop()
         },
         // State: styles to revert to
         prevStyles = {},
         lockStyles = {
             'overflow-y': 'scroll',
             'position': 'fixed',
             'width': '100%'
         };

     // Instantiate cache in case someone tries to unlock before locking
     saveStyles();

     // Save context's inline styles in cache
     function saveStyles() {
         var styleAttr = $html.attr('style'),
             styleStrs = [],
             styleHash = {};

         if (!styleAttr) {
             return;
         }

         styleStrs = styleAttr.split(/;\s/);

         $.each(styleStrs, function serializeStyleProp(styleString) {
             if (!styleString) {
                 return;
             }

             var keyValue = styleString.split(/\s:\s/);

             if (keyValue.length < 2) {
                 return;
    }
    
             styleHash[keyValue[0]] = keyValue[1];
         });

         $.extend(prevStyles, styleHash);
     }

     function lock() {
         var appliedLock = {};

         // Duplicate execution will break DOM statefulness
         if (locked) {
             return;
         }

         // Save scroll state...
         prevScroll = {
             scrollLeft: $(window).scrollLeft(),
             scrollTop: $(window).scrollTop()
         };

         // ...and styles
         saveStyles();

         // Compose our applied CSS
         $.extend(appliedLock, lockStyles, {
             // And apply scroll state as styles
             'left': -prevScroll.scrollLeft + 'px',
             'top': -prevScroll.scrollTop + 'px'
         });

         // Then lock styles...
         $html.css(appliedLock);

         // ...and scroll state
         $(window)
             .scrollLeft(0)
             .scrollTop(0);

         locked = true;
     }

     function unlock() {
         // Duplicate execution will break DOM statefulness
         if (!locked) {
             return;
         }

         // Revert styles
         $html.attr('style', $('<x>').css(prevStyles).attr('style') || '');

         // Revert scroll values
         $(window)
             .scrollLeft(prevScroll.scrollLeft)
             .scrollTop(prevScroll.scrollTop);

         locked = false;
     }

     return function scrollLock(on) {
         // If an argument is passed, lock or unlock depending on truthiness
         if (arguments.length) {
             if (on) {
                 lock();
             }
             else {
                 unlock();
             }
         }
             // Otherwise, toggle
         else {
             if (locked) {
                 unlock();
             }
             else {
                 lock();
             }
         }
     };
 }());
 // Used to detect initial (useless) popstate.
 // If history.state exists, assume browser isn't going to fire initial popstate.
 var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;

 $(window).bind('popstate', function (event) {
     // Ignore inital popstate that some browsers fire on page load
     var initialPop = !popped && location.href == initialURL
     popped = true
     if (initialPop) return;
     if (oSite.PushState) {
         window.location = window.location.pathname;
     }
 });


 var Utility = {
     shuffle: function (array, bCopy) {
         var rndArray;
         if (bCopy)
             rndArray = array.slice();
         else
             rndArray = array;

         var currentIndex = rndArray.length, temporaryValue, randomIndex;

         // While there remain elements to shuffle...
         while (0 !== currentIndex) {

             // Pick a remaining element...
             randomIndex = Math.floor(Math.random() * currentIndex);
             currentIndex -= 1;

             // And swap it with the current element.
             temporaryValue = rndArray[currentIndex];
             rndArray[currentIndex] = rndArray[randomIndex];
             rndArray[randomIndex] = temporaryValue;
         }

         return rndArray;
     },

     getUnique : function(array){
       var u = {}, a = [];
       for(var i = 0, l = array.length; i < l; ++i){
          if(u.hasOwnProperty(array[i])) {
             continue;
          }
          a.push(array[i]);
          u[array[i]] = 1;
       }
       return a;
    },
     isEnglish: function (text) {
         if (oSite.DefaultCulture == "es")
             return true;
         var NonEnglishPattern = oSite.isNonEnglishRegex;
         if (text.match(NonEnglishPattern))
             return false;
         else
             return true;
      },
      matchCssToLang: function(id, text) {
         $(id).removeClass("always_english");
         $(id).removeClass("always_non_english");
         $(id).addClass(Utility.isEnglish(text) ? "always_english" : "always_non_english");
     }
 };
var AdvLearnCounter = 0;
var MaxAdvLearnCounter = 4;
var personalIds = new userIds("personalIds");
var wordID = "";
var _starPos = "";

function userIds(pUserID) {
    var arrids = localStorage[pUserID] == null ? [] : localStorage[pUserID].split(',');
    var _userID = pUserID;

    this.updateId = function (id) {
        var old = localStorage.getItem(_userID);
        if (old === null) old = "";
        if (old.indexOf(id) == -1)
        {
            if (old.charAt(old.length - 1) == ",") {
                localStorage.setItem(_userID, old + id);
            }
            else {
                localStorage.setItem(_userID, old + (old == "" ? "" : ",") + id);
            }
        }
        arrids = localStorage[_userID] == null ? [] : localStorage[_userID].split(',');
    }

    this.deleteID = function (id) {
        // Find and remove item from an array
        var i = arrids.indexOf(id);
        if (i != -1) {
            arrids.splice(i, 1);
        }
        localStorage[_userID] = arrids.toString();
    }

    this.isIdExist = function (id) {
        return (arrids[id] != "" && arrids.indexOf(id) != -1);
    }

    this.clearStorage = function () {
        localStorage.removeItem(_userID);
    }

}


var learn = 
{
    InnitPersonalIds:function(arr)
    {
        localStorage.setItem("personalIds", arr);
        arrids = localStorage["personalIds"] == null ? [] : localStorage["personalIds"].split(',');
        personalIds = new userIds("personalIds");
        $('.PersonalCard_imgTopWhite').each((function (index) {
            learn.MarkStar(false, this);
        }));
    },
    ShowMore: function (obj,id) {
        var ul = $(obj).parent();
        ul.find('[name="backLink"]').show();
        ul.find('[name="hidden"]').show();
        oRender.RenderAdvLearn(id);
        $(obj).hide();
    },

    Back: function (obj,id) {
        var ul = $(obj).parent();
        ul.find('[name="hidden"]').hide();
        ul.find('[name="showMoreLink"]').show();
        $("#Advertisement_" + id).hide();
        $(obj).hide();
    },

    MarkStar: function (bUserList, star,bAjaxCall,word)
    {
        var objID = $(star).attr('id')
        var mID = objID.split("_")[0];
        mID = mID.replace("StarWhite", "").replace("StarOrange","");
        var eID = "StarOrange" + mID;
        _starPos = objID.split("_")[1];
        _starPos = (_starPos == null) ? "" : "_" + _starPos;
        if (oSite.IsLogedIn) {
            if (bUserList) {
                personalIds.updateId(mID);
                $('#' + eID).removeClass('Hide');
                $('#' + eID + "_a").removeClass('Hide');
                $('#' + eID + "_b").removeClass('Hide');
                $('#' + eID + "_c").removeClass('Hide');
                $(star).addClass('Hide');
            }
            else if (personalIds.isIdExist(mID)) {
                $('#' + eID).removeClass('Hide');
                $('#' + eID + "_a").removeClass('Hide');
                $('#' + eID + "_b").removeClass('Hide');
                $('#' + eID + "_c").removeClass('Hide');
                $(star).addClass('Hide');
            }
        }

        if (bAjaxCall)
        {
            oStuff.gaLog('Learn', 'AddWord', word);
            wordID = mID;
            if (oSite.IsLogedIn) {
                learn.UpdateWordOnServer(mID, star, true);
            }
            else {
                var destURL = oSite.CurrentSiteURL + "users/RenderNotLogedInForm";
                ajaxHelper.AjaxReqest('', destURL, 'get', true);
            }
        }
    },

    RemoveStar: function (star, bAjaxCall, word) {
        var objID = $(star).attr('id')
        var mID = objID.split("_")[0];
        mID = mID.replace("StarOrange", "");
        var eID = "StarWhite" + mID;
        var fID = "StarOrange" + mID;
        personalIds.deleteID(mID);
        $('#' + eID).removeClass('Hide');
        $('#' + eID + "_a").removeClass('Hide');
        $('#' + eID + "_b").removeClass('Hide');
        $('#' + eID + "_c").removeClass('Hide');
        $('#' + fID).addClass('Hide');
        $('#' + fID + "_a").addClass('Hide');
        $('#' + fID + "_b").addClass('Hide');
        $('#' + fID + "_c").addClass('Hide');

        

        if (bAjaxCall)
        {
            oStuff.gaLog('Learn', 'RemoveWord', word);
            learn.UpdateWordOnServer(mID, star, false);
        }
    },

    onLoad: function (bUserList) {
        if (bUserList)
            personalIds.clearStorage();

        $('.PersonalCard_imgTopWhite').each((function (index) {
            learn.MarkStar(bUserList,this);
        }));
    },

    UpdateWordOnServer: function (id,elment,bAddWord)
    {        
        ajaxHelper.UpdateWord(id,bAddWord, oStuff.evalMethod);
    },

    RollBackFavorite : function(id,bAddWord,showPopup)
    {
        var eID = "StarOrange" + id + _starPos;
        if (bAddWord) {
            learn.RemoveStar($('#' + eID));
        }
        else
        {
            eID = "StarWhite" + id + _starPos;
            learn.MarkStar(true, $('#' + eID));
        }
        if (showPopup == true) {
            eID = "StarWhite" + id + _starPos;

            var upgradePopUp = document.createElement('div');
            upgradePopUp.className = "upgrade_popover_container";
            var p = document.createElement('p');
            p.innerHTML = oSite.LimitPopoverMessage;
            upgradePopUp.appendChild(p);
            if(oSite.AllowPurchase){
                var button = document.createElement('button');
                button.innerHTML = oSite.LimitPopoverButton;
                button.onmousedown = function () {
                    oUI.upgradeClicked = true;
                    window.onmouseup = function () {
                        oStuff.gaLog('Popups', 'Upgrade wordlist click', 'upgrade click');
                        window.open(oSite.PurchaseUrl, '_self');
                    }
                }
                upgradePopUp.appendChild(button);
            }

            $('#' + eID).popover({
                placement: 'bottom',
                trigger: 'focus',
                html: true,
                container: 'body',
                content: upgradePopUp
            });
            $('#' + eID).focus();
            $('#' + eID).on('hidden.bs.popover', function () {
                if (!oUI.upgradeClicked) {
                    oStuff.gaLog('Popups', 'Upgrade wordlist click', 'outside popup click');
                }
                $('#' + eID).popover('destroy');
            });
            oStuff.gaLog('Popups', 'Upgrade wordlist shown', oSite.PersonalListLimit);
        }

    },

    dummyFunc: function () {

    }
}



;
(function () {

    window['oLogin'] =
    {
        FBinit: function () {
            window.fbAsyncInit = function () {
                FB.init({
                    appId: oSite.appId,
                    xfbml: true,
                    version: 'v2.1'
                });
                FB.getLoginStatus(function (response) {
                    if (response.status === 'connected') {
                        
                    }
                    else {
                        var data = oUI.readCookie("UserLoginType");
                        if (data != null && data != "undefined" && data == "True") {
                            oUI.Logout();
                        }
                    }
                }, true);
            };
            
            (function (d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) { return; }
                js = d.createElement(s); js.id = id;
                js.src = "//connect.facebook.net/en_US/sdk.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
         
        },
        FbLogin: function ()
        {
            FB.login(function (response) {
                if (response) {
                    if (response.authResponse) {
                        if (response.status === 'connected') {
                            FB.api('/me', function (response) {
                                wordID = typeof wordID !== 'undefined' ? wordID : 0;
                                var Data = {
                                    "id": response.id,
                                    "email": response.email,
                                    "first_name": response.first_name,
                                    "last_name": response.last_name,
                                    "mID": wordID != "" ? wordID : 0,
                                    "IsAnonimousQuiz": oSite.IsAnonimousQuiz
                                }
                                localStorage["UserName"] = response.email;
                                dataRequest = "UserDetails=" + JSON.stringify(Data);
                                var destURL = oSite.CurrentSiteURL + "users/LoginFb";
                                ajaxHelper.AjaxReqest(dataRequest, destURL, 'post', false, oUI.OnPostLogin);
                            });
                        }
                    } else {
                        console.log("unsuccessful auth");
                    }
                }
            }, { scope: 'email' });
        },
        IsLoggedIn: function () {
            var result = false;
            var data = oUI.readCookie("UserSettings");
            if (data != null && data != "undefined" && data != "") {
                result = true;
            }
            return result;
        }
    }

})();;
