function RedirectionMobile() {
    if (IsMobilePhone()) {
        if (window.location.toString().indexOf('iphonewww=0') < 0) {


            if (GetCookie("iphonewww") != "1") {
                SetCookieDays("iphonewww", "0", 1);

                var mobURL = GetMobileURL();

                if (mobURL.indexOf("nomobileredirect") < 0)
                    window.location = mobURL;
            }
        }
        else {
            SetCookieDays("iphonewww", "1", 1);
        }
    }
}

function GetMobileURL(oneUrl) {

    var retVal = "https://m.one.co.il/Mobile";
    var mDomain = "https://m.one.co.il/Mobile";

    var url = oneUrl || window.location.toString().toLowerCase();

    console.log("ONE Redirect: Original URL: " + url);

    // Article
    if (url.toLowerCase().indexOf("/article/") > -1) {
        return url.replace(/http:\/\/.*[.]{0,1}one.co.il\/article\//ig, mDomain + "/Article/");
    }

    // VOD
    if (url.toLowerCase().indexOf("/vod/") > -1) {
        return url.replace(/http:\/\/.*[.]{0,1}one.co.il\/vod\//ig, mDomain + "/VOD/");
    }

    

    if (url.toLowerCase().indexOf("\/video\/first.aspx") > -1) {
        var retval = url.replace(/\/cat\//ig, "/");
        retval = retval.replace(/first\.aspx/ig, "default.aspx");

        console.log("ONE Redirect: VOD first replace: " + retVal);

        retval = retval.replace(/http:\/\/.*[.]{0,1}one.co.il\/cat\/video\//ig, mDomain + "/video/");

        console.log("ONE Redirect: VOD second replace: " + retVal);

        return retval;
    }

    


    if (url.toLowerCase().indexOf("/glitches/") > -1) {
        return mDomain + "/Glitches/Glitches.aspx";
    }

    if (url.toLowerCase().indexOf("/glitch/") > -1) {

        var myregexp = /\/glitch\/([\d]+)\//i;
        var match = myregexp.exec(url);
        result = (match != null) ? match[1] : "";

        return mDomain + "/Glitches/Glitch.aspx?id=" + result;
    }

    if (url.toLowerCase().indexOf("oppinion/") > -1) {
        var myregexp = /\/oppinion\/([\d]+)\/([\d]+)/i;
        var match = myregexp.exec(url);
        result = (match != null) ? match[2] : "";

        return mDomain + "/Articles/Article.aspx?id=" + result;
    }

    // Leagues
    if (url.toLowerCase().indexOf("league/") > -1) {
        return url.replace(/http:\/\/.*[.]{0,1}one.co.il\/league\//ig, mDomain + "/League/");
    }



    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    // 
    // OLD
    //
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////


    // Glitches

    //retVal = getMobileSuffix(retVal, url, /.*?article.*?\/([\d]+)\.html/ig, "Articles/Article.aspx?id=$1");
    //retVal = getMobileSuffix(retVal, url, /.*?Article(.*)?\/([\d]+)\.html[?]*(.+)*/ig, "Article/$1/$2.html?$3");

    // League news
    retVal = getMobileSuffix(retVal, url, /.*League\/Current\/([\d]+),([\d]+),([\d]+),([\d]+)\/.+/ig, "Articles/articles.aspx??title=1&c=$1&t=$2");
    // Live
    retVal = getMobileSuffix(retVal, url, /.*\/live\/.*/ig, "Live/Live.aspx");

    //retVal = getMobileSuffix(retVal, url, /.*?article.aspx\?id=([\d]+)/ig, "Articles/Article.aspx?id=$1");
    retVal = getMobileSuffix(retVal, url, /.*?oppinion.*?\/([\d]+)\.html/ig, "Articles/Article.aspx?id=$1");
    //retVal = getMobileSuffix(retVal, url, /.*InsideArticle\.aspx\?id=([\d]+).*/ig, "Articles/Article.aspx?id=$1");
    retVal = getMobileSuffix(retVal, url, /.*PersonalColumn\.aspx\?id=([\d]+).*/ig, "Articles/Article.aspx?id=$1");
    retVal = getMobileSuffix(retVal, url, /.*7,801,0,0.*/ig, "Articles/articles.aspx?t=801&title=1");


    retVal = getMobileSuffix(retVal, url, /.*\/winner\/.*/ig, "winner/winner.aspx");

    retVal = getMobileSuffix(retVal, url, /.*\/cat\/video\/[?first.aspx?c=]*([\d]+)/ig, "video/default.aspx?cat=$1");
    retVal = getMobileSuffix(retVal, url, /.*\/cat\/video[\/]*$/ig, "video/default.aspx");

    retVal = getMobileSuffix(retVal, url, /.*Team\/Current.*\/.*?,([\d]+),([\d]+).*/ig, "Leagues/Team.aspx?tid=$2");
    retVal = getMobileSuffix(retVal, url, /.*Player\/Current.*\/.*?([\d]+),([\d]+),([\d]+),([\d]+).*/ig, "general/player.aspx?pid=$4&tid=$3");

    if (
            url.indexOf("preview.aspx") > -1 ||
            url.indexOf("playbyplay.aspx") > -1 ||
            url.indexOf("bestof.aspx") > -1 ||
            url.indexOf("isf.one.co.il") > -1 ||
            url.indexOf("isa.one.co.il") > -1 ||
            url.indexOf("ibba.one.co.il") > -1 ||
            url.indexOf("olympic.one.co.il") > -1 ||
            url.indexOf("bestof.aspx") > -1 ||

            url.indexOf("mmm") > -1 ||
            url.indexOf("tools") > -1 ||
            url.indexOf("boffice") > -1

            ||

            (
                (url.toLowerCase().indexOf("sites.one.co.il") > -1 || url.toLowerCase().indexOf("extra.one.co.il") > -1

                )
                &&
                (url.toLowerCase().indexOf("tableid=100") < 0 && url.toLowerCase().indexOf("t=100") < 0)
            )
        )
        return url + "&nomobileredirect=1";

    return retVal + (GetQueryString("app") == "1" || GetQueryString("amp;app") == "1" ? "&app=1" : "");
}

function getMobileSuffix(retVal, url, regex, template) {
    if (retVal == "https://m.one.co.il/Mobile/") {
        if (url.match(regex)) {
            retVal += url.replace(regex, template);
        }
    }
    return retVal;
}


///
/// Mobile Section
///
function DeviceSelect() {
    if (navigator.userAgent.match(/Android/i)) { return "android" }
    else if (navigator.userAgent.match(/BlackBerry/i)) { return "blackberry" }
    else if (navigator.userAgent.match(/iPhone/i)) { return "iphone" }
    else if (navigator.userAgent.match(/iPad/i)) { return "ipad" }
    else if (navigator.userAgent.match(/iPod/i)) { return "ipod" }
    else if (navigator.userAgent.match(/IEMobile/i)) { return "iemobile" }
    else if (navigator.userAgent.match(/Macintosh/i)) { return "macintosh" }
    else { return "PC" }
}

function IsIphone() {
    return DeviceSelect() == "iphone" ? true : false;
}

function IsIpad() {
    return DeviceSelect() == "ipad" ? true : false;
}

function IsAndroid() {
    return DeviceSelect() == "android" ? true : false;
}

function IsMobilePhone() {
    return IsIphone() || IsAndroid() ? true : false;
}var isChrome = navigator.userAgent.indexOf('Chrome') > -1;
var isExplorer = navigator.userAgent.indexOf('MSIE') > -1;
var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
var isSafari = navigator.userAgent.indexOf("Safari") > -1;
var isOpera = navigator.userAgent.toLowerCase().indexOf("op") > -1;
if ((isChrome) && (isSafari)) { isSafari = false; }
if ((isChrome) && (isOpera)) { isChrome = false; }

function log(text)
{
    console.log("ONE_dev: " + text);
}

function logone(text) {
    console.log("ONE_dev: " + text);
}

function GetQueryString(variable) {

    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable)
            return pair[1];
    }

    return "";
}

//
// IP && CuntryLookUp
// http://www.west-wind.com/WebLog/posts/107136.aspx
//
function GetClientIP() {
    var isNeedRegetIPData = false;
    if (GetCookie("IPClientIP"))
        IP = GetCookie("IPClientIP");
    else
        isNeedRegetIPData = true;

    if (GetCookie("IPIsIsrael"))
        IsIsrael = (GetCookie("IPIsIsrael").toString().toLowerCase() == "true") ? true : false;
    else
        isNeedRegetIPData = true;

    if (isNeedRegetIPData)
        document.write('<script src="https://svc.one.co.il/SetIPData"></script>');

}

function SetIPData(Result) {
    logone("Im in SetIPData");
    logone("IP is " + Result.IP);
    IsIsrael = (Result.IsIsrael.toLowerCase() === "true") ? true : false;
    IP = Result.IP;

    SetCookieDays("IPClientIP", IP, 30);
    SetCookieDays("IPIsIsrael", IsIsrael, 30);
}

// Open centered popup
// return reference to new opened window
function OpenWindow(url, name, wwidth, wheight, isResizable, isMenu, isToolbar, isStatusbar, isLocation, isScroll) {
    var xpos = GetWindowWidth() / 2 - wwidth / 2;
    var ypos = GetWindowHeight() / 2 - wheight / 2;
    var params = "";
    params += "menubar=" + (isMenu ? 1 : 0) + ","
    params += "status=" + (isStatusbar ? 1 : 0) + ","
    params += "toolbar=" + (isToolbar ? 1 : 0) + ","
    params += "location=" + (isLocation ? 1 : 0) + ","
    params += "resizable=" + (isResizable ? 1 : 0) + ","
    params += "scrollbars=" + (isScroll ? 1 : 0) + ","
    params += "left=" + xpos + ","
    params += "top=" + ypos + ","
    params += "width=" + wwidth + ","
    params += "height=" + wheight;

    if (name.toLowerCase().indexOf("http://") > -1) {
        var t = name;
        name = url;
        url = t;
    }
    var wopen = window.open(url, name, params);

    return wopen;
}

function GetWindowWidth() {
    return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
}

function GetWindowHeight() {
    return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
}




/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 * http://blog.stevenlevithan.com/archives/date-time-format
 */

/*
d           Day of the month as digits; no leading zero for single-digit days. 
dd          Day of the month as digits; leading zero for single-digit days. 
ddd         Day of the week as a three-letter abbreviation. 
dddd        Day of the week as its full name. 
m           Month as digits; no leading zero for single-digit months. 
mm          Month as digits; leading zero for single-digit months. 
mmm         Month as a three-letter abbreviation. 
mmmm        Month as its full name. 
yy          Year as last two digits; leading zero for years less than 10. 
yyyy        Year represented by four digits. 
h           Hours; no leading zero for single-digit hours (12-hour clock). 
hh          Hours; leading zero for single-digit hours (12-hour clock). 
H           Hours; no leading zero for single-digit hours (24-hour clock). 
HH          Hours; leading zero for single-digit hours (24-hour clock). 
M           Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months. 
MM          Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months. 
s           Seconds; no leading zero for single-digit seconds. 
ss          Seconds; leading zero for single-digit seconds. 
l or L      Milliseconds. l gives 3 digits. L gives 2 digits. 
t           Lowercase, single-character time marker string: a or p. No equivalent in CF. 
tt          Lowercase, two-character time marker string: am or pm. No equivalent in CF. 
T           Uppercase, single-character time marker string: A or P. Uppercase T unlike CF's t to allow for user-specified casing. 
TT          Uppercase, two-character time marker string: AM or PM. Uppercase TT unlike CF's tt to allow for user-specified casing. 
Z           US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500 No equivalent in CF. 
o           GMT/UTC timezone offset, e.g. -0500 or +0230. No equivalent in CF. 
S           The date's ordinal suffix (st, nd, rd, or th). Works well with d. No equivalent in CF. 
'…' or "…"  Literal character sequence. Surrounding quotes are removed. No equivalent in CF. 
UTC:        Must be the first four characters of the mask. Converts the date from local time to UTC/GMT/Zulu time before applying the mask. The "UTC:" prefix is removed.
            No equivalent in CF. 

And here are the named masks provided by default (you can easily change these or add your own):

Name Mask Example 
default                 ddd mmm dd yyyy HH:MM:ss        Sat Jun 09 2007 17:46:21 
shortDate               m/d/yy                          6/9/07 
mediumDate              mmm d, yyyy                     Jun 9, 2007 
longDate                mmmm d, yyyy                    June 9, 2007 
fullDate                dddd, mmmm d, yyyy              Saturday, June 9, 2007 
shortTime               h:MM TT                         5:46 PM 
mediumTime              h:MM:ss TT                      5:46:21 PM 
longTime                h:MM:ss TT Z                    5:46:21 PM EST 
isoDate                 yyyy-mm-dd                      2007-06-09 
isoTime                 HH:MM:ss                        17:46:21 
isoDateTime             yyyy-mm-dd'T'HH:MM:ss           2007-06-09T17:46:21 
isoUtcDateTime          UTC:yyyy-mm-dd'T'HH:MM:ss'Z'    2007-06-09T22:46:21Z 


HOW TO USE:

1.  Stand alone function : 
    var now = new Date();
    dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

2.  Extensions method
    var now = new Date();
    now.Formst("h:MM:ss");

*/
var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date();
        if (isNaN(date)) throw new SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.Format = function (mask, utc) {
    return dateFormat(this, mask, utc);
}
/*

SECTIONS
  0. Universal document.ready for both platforms
  1. Marking session
  2. Voting
  3. Video
  4. Count views

*/

var IsIsrael = true;

$j(document).ready(function () {

    $j("iframe[src*='youtube']").wrap("<div class='embed-container'></div>");
});


function DoSearch(query) {
    document.location = "/Cat/General/SearchResults.aspx?oneSearchtype=1&isSearchInOne=true&q=" + escape(query);
}

/* ------------------------------------------------------
    #1
    MARKING SESSION
*/
function MarkSessionDay(pageType) {
    if (pageType == undefined)
        pageType = "";

    SetSessionNumber(pageType);

    if (GetSessionNumber(pageType) < 2) {
        SetCookieDays("sessionmark" + pageType, "1", 1);
    }
}

function GetSessionNumber(pageType) {
    if (pageType == undefined)
        pageType = "";

    var sessionNumber = GetCookie("sessionnum" + pageType);
    if (sessionNumber < 1 || sessionNumber == null)
        sessionNumber = SetSessionNumber(pageType);

    return sessionNumber;
}

function SetSessionNumber(pageType) {
    if (pageType == undefined)
        pageType = "";

    var sessionNumber = GetCookie("sessionnum" + pageType);

    if (sessionNumber < 1 || sessionNumber == null) {
        sessionNumber = 1;
    }
    else {
        sessionNumber++;
    }

    SetCookieDays("sessionnum" + pageType, sessionNumber, 1);

    return sessionNumber;
}
/*
    MARKING SESSION END
---------------------------------------------------------*/











/*---------------------------------------------------------
    #2
    VOTING
*/
function VoteInit(refId) {
    if (GetCookie("vote" + refId) == 1)
        VoteAlready(refId);
    else
        $j('.btnVoting th').bind("click", function () { VoteMain(refId); });
}

function VoteViewResults(refID) {
    var url = "/Cat/Vote/ViewVotePopUp.aspx?refid=" + refID;
    OpenWindow(url, "vote", 770, 620, false, false, false, false, false, false)
}

function VoteMain(refID) {
    var val = $j('input[name=voteAnswer]:checked').val();
    if (val == undefined) { alert("אנא בחר תשובה על מנת להשתתף במשאל"); return false; }

    var voteUrl = "http://" + serviceHost + "/Cat/General/Counter.aspx?type=7&id=" + refID + "&an=" + val;
    var imgVote = new Image(); imgVote.src = voteUrl;
    SetCookieDays("vote" + refID, "1", 7);
    VoteAlready(refID);
    VoteViewResults(refID)
}

function SetVote(refID, voteType) {
    var val = $j('input[name=Vote' + refID + ']:checked').val();
    if (val == undefined) { alert("אנא בחר תשובה על מנת להשתתף במשאל"); return false; }

    var voteUrl = "http://" + serviceHost + "/Cat/General/Counter.aspx?type=7&id=" + refID + "&an=" + val;
    var imgVote = new Image();
    var timeout = (voteType) ? 10 : 1000;
    imgVote.onerror = function () { window.setTimeout("UpdateVote(" + refID + "," + voteType + ")", timeout); }
    imgVote.onload = function () { window.setTimeout("UpdateVote(" + refID + "," + voteType + ")", timeout); }
    imgVote.src = voteUrl;

    var titleSelector = "";
    var descriptionSelector = "";
    var pictureSelector = "";

    switch (voteType) {
        case 0: //main page vote
            titleSelector = ".oneMainVote .question";
            descriptionSelector = "label[for='rbAnswer" + refID + "_" + val + "']";
            pictureSelector = ".oneMainVote img";
            break;
        case 1: //article vote
            titleSelector = ".ArticleVoteQuestion span";
            descriptionSelector = "label[for='rbAnswer" + refID + "_" + val + "']";
            pictureSelector = ".ArticleVoteQuestion img[id$='imgImage']";
            break;
        case 2: //votes page vote
            titleSelector = "#vote" + refID + " .BigVoteQuestion span";
            descriptionSelector = "label[for='rbAnswer" + refID + "_" + val + "']";
            pictureSelector = "#vote" + refID + " .BigVoteRight img[id$='imgImage']";
            break;
        case 3: //ExtraONE
            break;
    }

    if (window.FBSocialReader != undefined) {
        FBSocialReader.Post('ONE גם אתם מוזמנים להצביע בסקר של אתר',
                         $j(titleSelector).text(), "אני הצבעתי: " + $j(descriptionSelector).text(), 'https://www.one.co.il/Cat/Vote/Votes.aspx',
                        $j(pictureSelector).attr("src"),
                        [{ 'name': 'בואו להצביע', 'link': 'https://www.one.co.il/Cat/Vote/Votes.aspx' }]);
    }
    SetCookieDays("vote" + refID, "1", 7);
}

function UpdateVote(refID, voteType) {
    switch (voteType) {
        case 0: //main page vote
            window.location.href = "/Cat/Vote/Votes.aspx";
            break;
        case 1: //article vote
            $j("#vote").load("/Cat/Vote/ShowVote.aspx?vId=" + refID + "&showType=1&bz=" + Math.ceil(Math.random() * 1000) + " #vote>div");
            ResizeVoteIframe();
            break;
        case 2: //votes page vote
            $j("#vote" + refID).load("/Cat/Vote/ShowVote.aspx?vId=" + refID + "&showType=2&bz=" + Math.ceil(Math.random() * 1000) + " #vote>table");
            break;
        case 3: //ExtraONE
            $j("#vote" + refID).load("/General/ShowVote.aspx?vId=" + refID + "&bz=" + Math.ceil(Math.random() * 1000) + " #vote" + refID + " >*");
            break;
    }
}

function ResizeVoteIframe(refID) {
    if ($j(".divArticleVote").length > 0)
        $j(parent.document.getElementById("ifVote" + refID)).height($j(".divArticleVote").height());
}

function VoteAlready(refID) {
    $j('input[name=voteAnswer]').attr("disabled", "1");

    $j('.btnVoting th').html("לתוצאות").bind("click", function () { VoteViewResults(refID); });
    if (refID == 1328) {
        $j('.btnVoting th').html("תוצאות הסקר").prepend("<div class='h20'></div>");
        $j('.btnVoting').css({ "float": "left" });
    }
}

/*
    END VOTING
---------------------------------------------------------*/









/*---------------------------------------------------------
    #3
    VIDEO
*/

/// objVideo - json version of instance ContentItems.Video
///
/// Function builds clip object for FlowPlayer
function GetFPSources(objVideo) {
    var clip = {

        title: objVideo.Title,

        sources: [
            {
                src: objVideo.URLStreamSD, type: objVideo.MIMEType
            }],

        vodQualities:
        {
            qualities: [
                { label: '1080p', src: objVideo.URLStreamHD, type: objVideo.MIMEType },
                { label: '360p', src: objVideo.URLStreamSD, type: objVideo.MIMEType },
            ],
            defaultQuality: "360p"
        }
    };


    if (IsIphone() || IsAndroid() || IsIpad()) {
        clip.sources = [
            {
                src: objVideo.URLStreamMobile, type: objVideo.MIMEType
            }
        ];

        clip.vodQualities = null;
    }

    return clip;
}

/// Get JSON of related videos
/// JSON in ContentITem.Video format
function GetRelatedVideoss(playerName, vid, categoryVOD) {
    var url = "/cat/video/VideoSearch.aspx?type=1&cat=" + categoryVOD + "&videoid=" + vid;

    $j.ajax(url).done(function (result) {

        var arrRelated = JSON.parse(result);

        flowplayer($j("#" + playerName)).conf.related = arrRelated;

        var relContainer = $j("#" + playerName + " div.fp-related-videos");
        relContainer.html("");

        $j.each(arrRelated, function (i, obj) {
            if (i < 6)
            {
                relContainer.append("<a class=\"item\" href='javascript:" + playerName + "PlayRelated(" + i + ");'>"
                    + "<img src=\"https://images.one.co.il/images/video/segment377x285/" + obj.ImageFile + "\" />"
                    + "<span>" + obj.Title + "</span>"
                    + "</a>");
            }
        });

        $j("#" + playerName + " div.fp-related-videos a.item:first").css("border", "solid 1px white");

        relContainer.append("<progress class=\"progressbar\" value=\"0\" max=\"6\"></progress>");
    })
}

/*
    END VIDEO
---------------------------------------------------------*/





/* ------------------------------------------------------
    #4
    COUNT VIEWS
*/

function CountViews(type, id) {

    var url = "https://counter.one.co.il/Views/Counter/" + type + "/" + id + "/" + Math.random().toString().split(".")[1];

    logone("View count: " + id + ":" + type);

    new Image().src = url;
}

function CountArticleView(id) {
    CountViews("Article", id);
}

function CountGlitchView(id) {
    CountViews("Glitch", id);
}

function CountVideoView(id) {
    CountViews("Video", id);
}

/*
    END COUNT VIEWS
---------------------------------------------------------*///////////////////////////////////////////////////
//
//
// SCROLL DOWN TO GET ORIGINAL DFP HELPERS
//
//
//////////////////////////////////////////////////
function PrepareAdsElementsForResponsiveDesign() {
    // We add special css class for Sided Towers containers.
    // 'Cos DFP takes time to render banners need to wait numbers of seconds
    // 'Cos DFP can render into containers different sized ads we need add css class that will be trigger for differenr Media Query rule
    setTimeout(function () {
        if ($j("#adLeftTower").width() > 165)
            $j("#adLeftTower").addClass("adTowerWide");

        if ($j("#adRightTower").width() > 165)
            $j("#adRightTower").addClass("adTowerWide");
    }, 3000);
};

/*
 * USING OF ZEDO IS DEPRECATED
 *
 */
function ImpressionCount(id) {
    return;
    //var zzp = new Image();
    //zzp.src = "http://l4.zedo.com/log/p.gif?a=" + id + ";c=455000000;x=5632;n=455;e=i;i=0;s=0;z=" + Math.random();
}

function ImpressionCountDFP(id, iu) {
    var zzp = new Image();
    zzp.src = "http://pubads.g.doubleclick.net/gampad/clk?id=" + id + "&iu=" + iu;
}















//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// ORIGIAL DFP HELPERS
// 
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//
//
// POP UNDER
//
//
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////


// pop under V4.5
// In chrome open the pop under as pop-up in a new window ( using classic new window function).
// test on chrome  44.0.2403.125 m
// date: 03/08/2015



if (typeof tmo_util != "object") {
    tmo_util = {};
};
if (typeof tmo_prop != "object") {
    tmo_prop = {};
};

tmo_prop.IE = (navigator.userAgent.indexOf("MSIE") >= 0) ? true : false;
if (navigator.userAgent.indexOf(".NET4.0E; .NET4.0C;") >= 0) { tmo_prop.IE = true }
tmo_util.stlPopUnder = function (adcode, specification, Targetwindow, pop, ife, Height, Width) {
    tmo_prop.TM_PopUnder = "off";
    tmo_prop.TM_PopUnderData = adcode
    tmo_prop.TM_PopUnderHeight = Height;
    tmo_prop.TM_PopUnderWidth = Width;
    tmo_prop.TM_Targetwindow = Targetwindow
    tmo_prop.TM_PopUnderSpecification = specification
    top.isPopDone_ = false;
    window.TM_openWin = function () {
        if (tmo_prop.TM_PopUnder == "off") {
            tmo_prop.TM_PopUnder = "on"
            myWindow = window.open('', tmo_prop.TM_Targetwindow, tmo_prop.TM_PopUnderSpecification);
            myWindow.document.write('<html><head><title>&nbsp;Advertisement</title></head><body marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>' + tmo_prop.TM_PopUnderData + '</body></html>');
            if (!tmo_prop.IE) {
                myWindow.window.open('about:blank').close();
            }
            if (pop = "Pop-under") {
                myWindow.blur();
                window.focus();
            }
        }
    }
    if (!tmo_prop.IE) {
        document.addEventListener("click", window.TM_openWin, false);
    }
    if (!tmo_prop.IE) {
        document.addEventListener("mouseup", function () {
            if (top.isPopDone_)
                return;
            var rand = Math.random();
            var a = document.createElement("a");
            a.href = "data:text/html," + unescape('%3Cscript%3E') + "window.close();" + unescape('%3C/script%3E'),
			document.getElementsByTagName("body")[0].appendChild(a);
            var e = document.createEvent("MouseEvents");
            e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
            a.dispatchEvent(e);
            a.parentNode.removeChild(a);
            window.open("about:blank", "_tab" + rand.toString()).close();
            top.isPopDone_ = true;
        }, false);
    } else {
        setTimeout(window.TM_openWin, 250);
    }
}

var tm = {
    tm_pop: function (l, x) {
        var p = x.cap || 1;
        var k = x.wait || 4;
        var j = x.cookie || "__.tm";
        var y = x.width;
        var e = x.height;
        var x = "";
        var m = {
            tm_initializefun: function () {
                this.ua.tm_initializefun()
            },
            ua: {
                tm_initializefun: function () {
                    this.browser = this.tm_Stringsearchfun(this.list_browser) || "unknown";
                    this.version = this.tm_Versionsearchfun(navigator.userAgent) || this.tm_Versionsearchfun(navigator.appVersion) || "unknown";
                    this.os = this.tm_Stringsearchfun(this.list_os) || "unknown";
                    if (this.browser == "Chrome" || this.browser == "chrome") {
                        y = y || window.innerWidth;
                        e = e || window.innerHeight
                    } else if (this.browser == "Explorer" || this.browser == "explorer") {
                        y = y || window.innerWidth;
                        e = e || window.innerHeight
                    } else {
                        y = y || screen.width;
                        e = e || screen.height
                    }
                    x = "width=" + y + ",height=" + e + ",resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,scrollbars=yes,top=0,left=0"
                },
                list_browser: [{
                    str: navigator.userAgent,
                    subStr: "Chrome",
                    id: "Chrome"
                }, {
                    str: navigator.userAgent,
                    subStr: "OmniWeb",
                    versionSearch: "OmniWeb/",
                    id: "OmniWeb"
                }, {
                    str: navigator.vendor,
                    subStr: "Apple",
                    id: "Safari",
                    versionSearch: "Version"
                }, {
                    prop: window.opera,
                    id: "Opera",
                    versionSearch: "Version"
                }, {
                    str: navigator.vendor,
                    subStr: "iCab",
                    id: "iCab"
                }, {
                    str: navigator.vendor,
                    subStr: "KDE",
                    id: "Konqueror"
                }, {
                    str: navigator.userAgent,
                    subStr: "Firefox",
                    id: "Firefox"
                }, {
                    str: navigator.vendor,
                    subStr: "Camino",
                    id: "Camino"
                }, {
                    str: navigator.userAgent,
                    subStr: "Netscape",
                    id: "Netscape"
                }, {
                    str: navigator.userAgent,
                    subStr: "MSIE",
                    id: "Explorer",
                    versionSearch: "MSIE"
                }, {
                    str: navigator.userAgent,
                    subStr: "Gecko",
                    id: "Mozilla",
                    versionSearch: "rv"
                }, {
                    str: navigator.userAgent,
                    subStr: "Mozilla",
                    id: "Netscape",
                    versionSearch: "Mozilla"
                }
                ],
                list_os: [{
                    str: navigator.platform,
                    subStr: "Win",
                    id: "Windows"
                }, {
                    str: navigator.platform,
                    subStr: "Mac",
                    id: "Mac"
                }, {
                    str: navigator.userAgent,
                    subStr: "iPhone",
                    id: "iPhone/iPod"
                }, {
                    str: navigator.platform,
                    subStr: "Linux",
                    id: "Linux"
                }
                ],
                tm_Stringsearchfun: function (l) {
                    for (var x = 0; x < l.length; x++) {
                        var p = l[x].str;
                        var k = l[x].prop;
                        this.versionSearchString = l[x].versionSearch || l[x].id;
                        if (p) {
                            if (p.indexOf(l[x].subStr) != -1) {
                                return l[x].id
                            }
                        } else {
                            if (k) {
                                return l[x].id
                            }
                        }
                    }
                },
                tm_Versionsearchfun: function (l) {
                    var x = l.indexOf(this.versionSearchString);
                    if (x == -1) {
                        return
                    }
                    return parseFloat(l.substr(x + this.versionSearchString.length + 1))
                }
            },
            cookie: {
                tm_get: function (l, x) {
                    var p = new Date;
                    p.setTime(p.getTime());
                    var k = (new Date(p.getTime() + 1e3 * 60 * 60 * x)).toGMTString();
                    var j = document.cookie.split(";");
                    var y = "";
                    var e = "";
                    var m = [0, k];
                    for (var a = 0; a < j.length; a++) {
                        y = j[a].split("=");
                        e = y[0].replace(/^\s+|\s+$/g, "");
                        if (e == l) {
                            b_cookie_found = true;
                            if (y.length > 1) {
                                m = unescape(y[1]).split("|");
                                if (m.length == 1) {
                                    m[1] = k
                                }
                            }
                            return m
                        }
                        y = null;
                        e = ""
                    }
                    return m
                },
                tm_set: function (l, x, p) {
                    document.cookie = l + "=" + escape(x + "|" + p) + ";expires=" + p + ";path=/"
                }
            },
            listener: {
                tm_addfun: function (l, x, p) {
                    var k = "on" + x;
                    if (typeof l.addEventListener != "undefined") {
                        l.addEventListener(x, p, arguments.callee)
                    }
                    else {
                        if (typeof l.attachEvent != "undefined") { l.attachEvent(k, p) }
                        else {
                            if (typeof l[k] != "function") { l[k] = p }
                            else { var j = l[k]; l["old_" + k] = j; l[k] = function () { j(); return p() } }
                        }
                    }
                },
                tm_removefun: function (l, x, p) {
                    var k = "on" + x;
                    if (typeof l.removeEventListener != "undefined") {
                        l.removeEventListener(x, p, false)
                    } else {
                        if (typeof l.detachEvent != "undefined") {
                            l.detachEvent(k, p)
                        } else {
                            if (typeof l["old_" + k] != "function") {
                                l[k] = null
                            } else {
                                l[k] = l["old_" + k]
                            }
                        }
                    }
                }
            },
            format: {},
            random: function () {
                return Math.floor(Math.random() * 1000001)
            }
        };
        m.tm_initializefun();
        m.format.popunder = {
            settings: {
                url: l,
                times: p,
                hours: k,
                cookie: j
            },
            config: x,
            isBinded: false,
            isTriggered: false,
            tm_initializefun: function () {
                var l = m.cookie.tm_get(m.format.popunder.settings.cookie, m.format.popunder.settings.hours);
                this.cookie = {};
                this.cookie.times = !isNaN(Number(l[0])) ? Number(l[0]) : 0;
                this.cookie.expires = !isNaN(Date.parse(l[1])) ? l[1] : (new Date).toGMTString();
                if (document.readyState == "complete") {
                    setTimeout(m.format.popunder.bind, 1)
                } else {
                    m.listener.tm_addfun(document, "DOMContentLoaded", function () {
                        m.listener.tm_removefun(document, "DOMContentLoaded");
                        m.format.popunder.bind()
                    });
                    m.listener.tm_addfun(document, "onreadystatechange", function () {
                        if (document.readyState == "complete") {
                            m.listener.tm_removefun(document, "onreadystatechange");
                            m.format.popunder.bind()
                        }
                    });
                    m.listener.tm_addfun(window, "load", m.format.popunder.bind)
                }
            },
            bind: function () {
                if (m.format.popunder.isBinded) {
                    return
                }
                m.format.popunder.isBinded = true;
                if (m.format.popunder.cookie.times >= m.format.popunder.settings.times) {
                    return
                }
                var l = {};
                for (var x in m.format.popunder.binders) {
                    //console.log("x="+x)
                    var p = m.format.popunder.binders[x];
                    var k = x.split("");
                    var j = "",
					y = "";
                    var e = 1,
					a;
                    for (var f = 0; f < k.length; f++) {
                        var ll = k[f];
                        if (ll.match(/[a-z0-9]/) == null) {
                            continue
                        }
                        a = ll.search(/[a-z]/) == 0;
                        if (a) {
                            if (a != e) {
                                l[j][y] = p;
                                j = ll
                            } else {
                                j += ll
                            }
                        } else {
                            if (a != e || parseInt(f) + 1 == k.length) {
                                if (a != e) {
                                    if (typeof l[j] != "object") {
                                        l[j] = {}

                                    }
                                    y = ll
                                }
                                if (parseInt(f) + 1 == k.length) {
                                    l[j][a == e ? y + ll : y] = p
                                }
                            } else {
                                y += ll
                            }
                        }
                        e = a
                    }
                }
                var c = l[m.ua.browser.toLowerCase()] || l.all;
                var h = Object.keys(c);
                h.sort();
                for (var p = 0; p < h.length; p++) {
                    var y = h[p];
                    if (m.ua.version <= y) {
                        break
                    }
                }
                c[y]()
            },
            binders: {
                chrome: function () {
                    //console.log("%%")
                },
                chrome37: function () {
                    m.listener.tm_addfun(document, "mousedown", m.format.popunder.triggers.tm_anchor_trigg)
                },
                chrome30: function () {
                    m.listener.tm_addfun(document, "click", m.ua.os == "Windows" ? m.format.popunder.triggers.tm_fullscreen_trigg : m.format.popunder.triggers.tm_triple_trigg)
                },
                chrome28: function () {
                    m.listener.tm_addfun(document, "click", m.format.popunder.triggers.tm_triple_trigg)
                },
                firefox12_chrome21: function () {
                    m.listener.tm_addfun(document, "click", m.format.popunder.triggers.tm_double_trigg)
                },
                explorer0: function () {
                    m.listener.tm_addfun(document, "click", m.format.popunder.triggers.tm_singledelay)
                },
                all0: function () {
                    m.listener.tm_addfun(document, "click", m.format.popunder.triggers.tm_single)
                }
            },
            triggers: {
                tm_fullscreen_trigg: function () {
                    m.listener.tm_removefun(document, "click", m.format.popunder.triggers.tm_fullscreen_trigg);
                    if (!m.format.popunder.tm_register_trigg()) {
                        return
                    }
                    document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                    window.open(m.format.popunder.settings.url, "pu_" + m.random(), m.format.popunder.config);
                    document.webkitCancelFullScreen()
                },
                tm_triple_trigg: function () {
                    m.listener.tm_removefun(document, "click", m.format.popunder.triggers.tm_triple_trigg);
                    if (!m.format.popunder.tm_register_trigg()) {
                        return
                    }
                    window.open("javascript:window.focus()", "_self");
                    var l = window.open("about:blank", "pu_" + m.random(), m.format.popunder.config);
                    var x = document.createElement("a");
                    x.setAttribute("href", "data:text/html,<scr" + "ipt>window.close();</scr" + "ipt>");
                    x.style.display = "none";
                    document.body.appendChild(x);
                    var p = document.createEvent("MouseEvents");
                    p.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
                    x.dispatchEvent(p);
                    document.body.removeChild(x);
                    l.document.open().write("<scr" + 'ipt type="text/javascript">window.location="' + m.format.popunder.settings.url + '";</scr' + "ipt>");
                    l.document.close()
                },
                tm_anchor_trigg: function () {
                    m.listener.tm_removefun(document, "mousedown", m.format.popunder.triggers.tm_triple_trigg);
                    if (!m.format.popunder.tm_register_trigg()) {
                        return
                    }
                    var anchor = document.createElement("A");
                    //anchor.href =  m.format.popunder.settings.url;
                    //document.body.appendChild (anchor);
                    var l = window.open(m.format.popunder.settings.url, "pu_" + m.random(), m.format.popunder.config);
                    var e = document.createEvent("MouseEvents");
                    e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
                    anchor.dispatchEvent(e);
                    anchor.parentNode.removeChild(anchor);

                },

                tm_double_trigg: function (l) {
                    m.listener.tm_removefun(document, "click", m.format.popunder.triggers.tm_double_trigg);
                    if (!m.format.popunder.tm_register_trigg() && l != "i") {
                        return
                    }
                    var x = window.open(m.format.popunder.settings.url, "pu_" + m.random(), m.format.popunder.config);
                    if (x) {
                        x.blur();
                        try {
                            var p = x.window.open("about:blank");
                            p.close()
                        } catch (k) { }
                        if (m.ua.browser == "Firefox")
                            window.showModalDialog("javascript:window.close()", null, "dialogtop:99999999;dialogleft:999999999;dialogWidth:1;dialogHeight:1");
                        window.focus()
                    }
                },
                tm_singledelay: function () {
                    m.listener.tm_removefun(document, "click", m.format.popunder.triggers.tm_singledelay);
                    if (!m.format.popunder.tm_register_trigg())
                        return;
                    var l = window.open(m.format.popunder.settings.url, "pu_" + m.random(), m.format.popunder.config);
                    window.setTimeout(window.focus, 750);
                    window.setTimeout(window.focus, 850);
                    if (l)
                        l.blur()
                },
                tm_single: function (l) {
                    m.listener.tm_removefun(document, "click", m.format.popunder.triggers.tm_single);
                    if (!m.format.popunder.tm_register_trigg() && l != "i") {
                        return
                    }
                    var x = window.open(m.format.popunder.settings.url, "pu_" + m.random(), m.format.popunder.config);
                    if (x) {
                        x.blur();
                        window.focus()
                    }
                }
            },
            tm_register_trigg: function () {
                if (m.format.popunder.isTriggered) {
                    return false
                }
                m.format.popunder.isTriggered = true;
                if (m.format.popunder.settings.hours > 0) {
                    m.cookie.tm_set(m.format.popunder.settings.cookie, ++m.format.popunder.cookie.times, m.format.popunder.cookie.expires)
                }
                return true
            }
        };
        m.format.popunder.tm_initializefun();
        if (!Object.keys) {
            Object.keys = function () {
                var l = Object.prototype.hasOwnProperty,
				x = !{
				    toString: null
				}
				.propertyIsEnumerable("toString"),
				p = ["toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor"],
				k = p.length;
                return function (j) {
                    if (typeof j !== "object" && typeof j !== "function" || j === null)
                        throw new TypeError("Object.keys called on non-object");
                    var y = [];
                    for (var e in j) {
                        if (l.call(j, e)) {
                            y.push(e)
                        }
                    }
                    if (x) {
                        for (var m = 0; m < k; m++) {
                            if (l.call(j, p[m]))
                                y.push(p[m])
                        }
                    }
                    return y
                }
            }
			()
        }
    }
}

/*
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//
//
// END OF POP UNDER
//
//
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
*/function IsCookieEnabled() {
    document.cookie = "Enabled=true";
    var cookieValid = document.cookie;

    // if retrieving the VALUE we just set actually works
    // then we know cookies enabled
    if (cookieValid.indexOf("Enabled=true") != -1)
        return true;
    else
        return false;
}

function SetCookieDays(name, value, days)        { SetCookieByTime(name, value, 1000 * 60 * 60 * 24 * days); }
function SetCookieHours(name, value, hours)      { SetCookieByTime(name, value, 1000 * 60 * 60 * hours); }
function SetCookieMinutes(name, value, minutes)  { SetCookieByTime(name, value, 1000 * 60 * minutes); }
function SetCookieByTime(name, value, expires) {
    var expdate = new Date();
    expdate.setTime(eval(expdate.getTime() + (expires)));
    document.cookie = name + "=" + escape(value) + ";expires=" + expdate.toGMTString() + ";path=/";//+ ";domain=one.co.il;path=/" ;
}

function GetCookie(name) {
    var dcookie = document.cookie;
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;

    while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
        if (dcookie.substring(cbegin, vbegin) == cname) {
            var vend = dcookie.indexOf(";", vbegin);
            if (vend == -1)
                vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
        }

        cbegin = dcookie.indexOf(" ", cbegin) + 1;
        if (cbegin == 0)
            break;
    }

    return null;
}/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Comments v3
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var refToMainReplyBox = null;
var refToCurrentReplyBox = null;

var objCommentRater;

var commentBoxTemplate = "";

function ReplyToThis(parentID, id) {

    $j("div.one-comments-reply-to-this").html("");

    var options =
        {
            'id': id,
            'parentID': parentID,
            'elementID': oneItemid,
            'type': oneContentType,
            'platform': onePlatform
        };

    refToCurrentReplyBox = new CommentBox(options);
    refToCurrentReplyBox.Show();
}

var CommentBox = function (options) {
    this.init(options);
}

jQuery.extend(CommentBox.prototype, {

    init: function (options) {

        this.id = options.id;
        this.parentContainer = "#one-comments-reply-box" + (this.id === 0 ? "" : this.id) + " ";
        this.parentCommentID = options.parentID;

        this.contentElementID = options.elementID;
        this.contentType = options.type;
        this.platform = options.platform;
    },

    CommenterTeamChanged: function (team_id) {

        this.SetSignatureSelect(team_id);
    },

    SetSignatureSelect: function (team_id) {

        var sigSelector = $j(this.parentContainer + "select.one-reply-signature");

        $j(sigSelector).html("<option value='0'>בחר דגל</option>");

        $j(this.parentContainer + "img.one-reply-signature-image").hide();

        var isTeamHaveSignatures = false;

        $j.each(signatures.Rows, function (i, sig) {

            if ( sig.Team_Id == team_id ) {

                isTeamHaveSignatures = true;
                $j(sigSelector).append("<option value='" + sig.Id + "'>" + sig.Description + "</option>");

            }
        });

        //dont show flag row if this team doesnt have signatures
        if (isTeamHaveSignatures)
            $j(this.parentContainer + "select.one-reply-signature").show();
    },

    SignatureChanged: function (sigId) {
        var fileName = "";

        $j.each(signatures.Rows, function (i, sig) {
            if (sig.Id == sigId) {

                fileName = this.platform == 0 ?
                    "https://images.one.co.il/images/comments/signatures/" + sig.FileName :
                    "https://images.one.co.il/images/comments/signatures/mobile/" + sig.FileName_Mobile;

                return;
            }
        });

        if (fileName.length > 1)
            $j(this.parentContainer + "img.one-reply-signature-image").attr("src", fileName.toLowerCase()).show();
        else
            $j(this.parentContainer + "img.one-reply-signature-image").hide();
    },

    SubmitComment: function () {

        if ($j(this.parentContainer + "input.one-reply-name").val().trim().length < 2) {
            alert("לא ניתן לשלוח תגובה ללא שם");
            return false;
        }

        if ($j(this.parentContainer + "textarea.one-reply-text").val().trim().length < 2) {
            alert("לא ניתן לשלוח תגובה ללא תוכן");
            return false;
        }

        var commentData = {
            commentID: this.id,
            type: this.contentType,
            elementID: this.contentElementID,
            parentID: this.parentCommentID,
            platform: this.platform,
            ip: IP,

            name: $j(this.parentContainer + "input.one-reply-name").val(),
            team: $j(this.parentContainer + "select.one-reply-team").val(),
            signature: $j(this.parentContainer + "select.one-reply-signature").val() == null ? 0 : $j(this.parentContainer + "select.one-reply-signature").val(),
            text: $j(this.parentContainer + "textarea.one-reply-text").val()
        };

        jQuery.ajax({
            url: commentsServer + '/AddComment',
            type: "POST",
            dataType: "json",
            data: "{'data': '" + JSON.stringify(commentData) + "'}",

            contentType: "application/json; charset=utf-8"
        })
            .always(function (data) {

                var response = JSON.parse(data.d);

                if (response.Result) {
                    $j("#one-comments-reply-box" + response.CommentID + " div.one-reply-result").show();

                    $j("#one-comments-reply-box" + response.CommentID + " input, #one-comments-reply-box" + response.CommentID + " select, #one-comments-reply-box" + response.CommentID + " textarea").prop("disabled", true);

                    setTimeout(function () {
                        $j("#one-comments-reply-box" + response.CommentID + " div.one-reply-result").hide()

                        $j("#one-comments-reply-box" + response.CommentID + " input, #one-comments-reply-box" + response.CommentID + " select, #one-comments-reply-box" + response.CommentID + " textarea").prop("disabled", false);

                        $j("#one-comments-reply-box" + response.CommentID + " input[type='text'], #one-comments-reply-box" + response.CommentID + " textarea").val("");
                        $j("#one-comments-reply-box" + response.CommentID + " select").val(0).trigger("change");

                        if (response.CommentID > 0) {
                            $j("#one-comments-reply-box" + response.CommentID).html("");
                        }
                    }, 3000);


                }
            });
    },

    Show: function () {

        $j(this.parentContainer).html(commentBoxTemplate);
    }
});


function ShowMoreComments(num) {

    

    $j(".show-more-comments").blur();

    numberOfShowedComments += num;


    $j(".one-comment").each(function (i, obj) {

        if (i >= numberOfShowedComments)
            return;

        var cid = $j(obj).data("comment-id");

        $j("div[class*='comment-id-" + cid + "']").show();
        $j("div[class*='comment-id-" + cid + "']").next().show();

    });

    if (numberOfShowedComments > numberOfComments) {
        $j(".show-more-comments").hide();
        return;
    }
}















var CommentRating = function (elementType, elementID) {
    this.init(elementType, elementID);
}

jQuery.extend(CommentRating.prototype, {

    init: function (elementType, elementID) {

        this.objectName = "commentRating" + elementType + "" + elementID;

        var coo = GetCookie(this.objectName);

        this.data = (coo == null) ? {} : JSON.parse(coo);
    },

    Rate: function (newVote, id) {

        var jVote = {
            'id': id,
            'isAddPositive': false,
            'isSubPositive': false,
            'isAddNegative': false,
            'isSubNegative': false,
            'point': 0
        }

        var currentVote = this.data.hasOwnProperty(id) ? this.data[id] : 0;

        if (currentVote == 0) {
            jVote.point = newVote;
            if (newVote > 0) {
                jVote.isAddPositive = true;

                this.AddPoint("#thumb-positive-" + jVote.id, 1);
            }
            if (newVote < 0) {
                jVote.isAddNegative = true;

                this.AddPoint("#thumb-negative-" + jVote.id, 1);
            }
        }

        if (newVote == -1 && currentVote == -1) {
            jVote.point = 0;
            jVote.isSubNegative = true;

            this.AddPoint("#thumb-negative-" + jVote.id, -1);
        }

        if (newVote == 1 && currentVote == 1) {
            jVote.point = 0;
            jVote.isSubPositive = true;

            this.AddPoint("#thumb-positive-" + jVote.id, -1);
        }

        if (newVote == 1 && currentVote == -1) {
            jVote.point = newVote;
            jVote.isSubNegative = true;
            jVote.isAddPositive = true;

            this.AddPoint("#thumb-positive-" + jVote.id, 1);
            this.AddPoint("#thumb-negative-" + jVote.id, -1);
        }

        if (newVote == -1 && currentVote == 1) {
            jVote.point = newVote;
            jVote.isSubPositive = true;
            jVote.isAddNegative = true;

            this.AddPoint("#thumb-positive-" + jVote.id, -1);
            this.AddPoint("#thumb-negative-" + jVote.id, 1);
        }



        this.data[id] = jVote.point;

        jQuery.ajax({
            url: commentsServer + '/Rate',
            type: "POST",
            dataType: "json",
            data: "{'data': '" + JSON.stringify(jVote) + "'}",

            contentType: "application/json; charset=utf-8"
        })

        this.UpdateUI(false);

        this.Save();
    },

    UpdateUI: function (isUpdatePoints) {
        jQuery.each(this.data, function (key, value) {

            $j("#icon-negative-" + key).attr("src", imgThumbDownWhite);
            $j("#icon-positive-" + key).attr("src", imgThumbUpWhite);

            if (value === -1) {

                $j("#icon-negative-" + key).attr("src", imgThumbDownBlack);

                if (isUpdatePoints)
                    objCommentRater.AddPoint("#thumb-negative-" + key, 1);
            }
            if (value == 1) {

                $j("#icon-positive-" + key).attr("src", imgThumbUpBlack);

                if (isUpdatePoints)
                    objCommentRater.AddPoint("#thumb-positive-" + key, 1);
            }
        });
    },

    AddPoint: function (id, val) {

        var obj = $j(id);

        var points = parseInt(obj.data("points"), 10);

        points += val;

        obj.data("points", points).html(points);
    },

    Save: function () {
        SetCookieDays(this.objectName, JSON.stringify(this.data), 365);
    }
});



/**
 * jQuery custom selectboxes
 * 
 * Copyright (c) 2008 Krzysztof Suszyֵ„ski (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * http://info.wsisiz.edu.pl/~suszynsk/jQuery/demos/jquery-selectbox/
 *
 * @version 0.6.1
 * @category visual
 * @package jquery
 * @subpakage ui.selectbox
 * @author Krzysztof Suszyֵ„ski <k.suszynski@wit.edu.pl>
**/
jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
		className: 'jquery-selectbox',
		animationSpeed: "normal",
		listboxMaxSize: 10,
		replaceInvisible: false,
		onCurrentFocus: null,
		onShowList:null,
		onHideList:null,
		onItemClick:null
	};
	var commonClass = 'jquery-custom-selectboxes-replaced';
	var listOpen = false;
	var lastGroup = "";
	var showList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideDown(settings.animationSpeed, function(){
			listOpen = true;
		});
		selectbox.addClass('selecthover');
		jQuery(document).bind('click', onBlurList);
		if (settings.onShowList != null)
		    settings.onShowList();
		return listObj;
	}
	var hideList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideUp(settings.animationSpeed, function(){
			listOpen = false;
			jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
		});
		jQuery(document).unbind('click', onBlurList);
		if (settings.onHideList != null)
		    settings.onHideList();
		return listObj;
	}
	var onBlurList = function(e) {
		var trgt = e.target;
		var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
			hideList( jQuery('.' + commonClass + '-list') );
		}
		return false;
	}
	
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	return this.each(function() {
		var _this = jQuery(this);
		if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
			return;
		var replacement = jQuery(
			'<div class="' + settings.className + ' ' + commonClass + '">' +
				'<div class="' + settings.className + '-moreButton" />' +
				'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
				'<span class="' + settings.className + '-currentItem" />' +
			'</div>'
		);
		
		jQuery('option',_this).each(function(k,v){
			
			var v = jQuery(v);
			
			var listElement =  jQuery('<span class="' + settings.className + '-item value-'+v.val()+' item-'+k+'">' + v.text() + '</span>');	
			listElement.click(function(){
				var thisListElement = jQuery(this);
				var thisReplacment = thisListElement.parents('.'+settings.className);
				var thisIndex = thisListElement[0].className.split(' ');
				if (settings.onItemClick != null)
				    settings.onItemClick(v.val(), v.text());
				for( k1 in thisIndex ) {
					if(/^item-[0-9]+$/.test(thisIndex[k1])) {
						thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
						break;
					}
				
				};
				var thisValue = thisListElement[0].className.split(' ');
				for( k1 in thisValue ) {
					if(/^value-.+$/.test(thisValue[k1])) {
						thisValue = thisValue[k1].replace('value-','');
						break;
					}
				};
				thisReplacment
					.find('.' + settings.className + '-currentItem')
					.text(thisListElement.text());
				thisReplacment
					.find('select')
					.val(thisValue)
					.triggerHandler('change');
				var thisSublist = thisReplacment.find('.' + settings.className + '-list');
				if(thisSublist.filter(":visible").length > 0) {
					hideList( thisSublist );
				}else{
					showList( thisSublist );
				}
			}).bind('mouseenter',function(){
			    if (settings.onCurrentFocus != null)
			        settings.onCurrentFocus(v.val());   
				jQuery(this).addClass('listelementhover');
			}).bind('mouseleave',function(){
				jQuery(this).removeClass('listelementhover');
			});
			
			/* OPTGROUP SUPPORT */
			if(($j(v)[0].parentNode.tagName=="OPTGROUP") &&($j(v)[0].parentNode.label!=lastGroup))
			{
			    var grp = $j(v)[0].parentNode;
			    lastGroup = $j(grp).attr("label");
			    var grpElement = jQuery('<span class="' + settings.className + '-opt">' + lastGroup + '</span>');	
			    jQuery('.' + settings.className + '-list', replacement).append(grpElement);
			}
			
			jQuery('.' + settings.className + '-list', replacement).append(listElement);
			if(v.filter(':selected').length > 0) {
				jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
			}
		});
		replacement.find('.' + settings.className + '-moreButton').click(function(){
			var thisMoreButton = jQuery(this);
			var otherLists = jQuery('.' + settings.className + '-list')
				.not(thisMoreButton.siblings('.' + settings.className + '-list'));
			hideList( otherLists );
			var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
			if(thisList.filter(":visible").length > 0) {
				hideList( thisList );
			}else{
				showList( thisList );
			}
		}).bind('mouseenter',function(){
			jQuery(this).addClass('morebuttonhover');
		}).bind('mouseleave',function(){
			jQuery(this).removeClass('morebuttonhover');
		});
		_this.hide().replaceWith(replacement).appendTo(replacement);
		var thisListBox = replacement.find('.' + settings.className + '-list');
		var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
		if(thisListBoxSize > settings.listboxMaxSize)
			thisListBoxSize = settings.listboxMaxSize;
		if(thisListBoxSize == 0)
			thisListBoxSize = 1;	
		var thisListBoxWidth = Math.round(_this.width() + 5);

        /*
		if (jQuery.browser.safari)
			thisListBoxWidth = thisListBoxWidth * 0.94;
        */
		/*replacement.css('width', thisListBoxWidth + 'px');*/
		
		///////////////////////////////////
		////  PATH BY DROR 11/11/2009  ////
		///////////////////////////////////
		if(thisListBoxSize == settings.listboxMaxSize)
		    thisListBox.css({
			    /*width: Math.round(thisListBoxWidth-5) + 'px',*/
			    height: thisListBoxSize + 'em'
		    });
		else
		{
		    thisListBox.css({
			    /*width: Math.round(thisListBoxWidth-5) + 'px',*/
			    height: parseInt(thisListBoxSize*15) + 'px'
		    });
		}
		    
	});
}
jQuery.fn.unselectbox = function(){
	var commonClass = 'jquery-custom-selectboxes-replaced';
	return this.each(function() {
		var selectToRemove = jQuery(this).parent().filter('.' + commonClass);
		selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
}/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jֳ¶rn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(8($){j e={},9,m,B,A=$.2u.2g&&/29\\s(5\\.5|6\\.)/.1M(1H.2t),M=12;$.k={w:12,1h:{Z:25,r:12,1d:19,X:"",G:15,E:15,16:"k"},2s:8(){$.k.w=!$.k.w}};$.N.1v({k:8(a){a=$.1v({},$.k.1h,a);1q(a);g 2.F(8(){$.1j(2,"k",a);2.11=e.3.n("1g");2.13=2.m;$(2).24("m");2.22=""}).21(1e).1U(q).1S(q)},H:A?8(){g 2.F(8(){j b=$(2).n(\'Y\');4(b.1J(/^o\\(["\']?(.*\\.1I)["\']?\\)$/i)){b=1F.$1;$(2).n({\'Y\':\'1D\',\'1B\':"2r:2q.2m.2l(2j=19, 2i=2h, 1p=\'"+b+"\')"}).F(8(){j a=$(2).n(\'1o\');4(a!=\'2f\'&&a!=\'1u\')$(2).n(\'1o\',\'1u\')})}})}:8(){g 2},1l:A?8(){g 2.F(8(){$(2).n({\'1B\':\'\',Y:\'\'})})}:8(){g 2},1x:8(){g 2.F(8(){$(2)[$(2).D()?"l":"q"]()})},o:8(){g 2.1k(\'28\')||2.1k(\'1p\')}});8 1q(a){4(e.3)g;e.3=$(\'<t 16="\'+a.16+\'"><10></10><t 1i="f"></t><t 1i="o"></t></t>\').27(K.f).q();4($.N.L)e.3.L();e.m=$(\'10\',e.3);e.f=$(\'t.f\',e.3);e.o=$(\'t.o\',e.3)}8 7(a){g $.1j(a,"k")}8 1f(a){4(7(2).Z)B=26(l,7(2).Z);p l();M=!!7(2).M;$(K.f).23(\'W\',u);u(a)}8 1e(){4($.k.w||2==9||(!2.13&&!7(2).U))g;9=2;m=2.13;4(7(2).U){e.m.q();j a=7(2).U.1Z(2);4(a.1Y||a.1V){e.f.1c().T(a)}p{e.f.D(a)}e.f.l()}p 4(7(2).18){j b=m.1T(7(2).18);e.m.D(b.1R()).l();e.f.1c();1Q(j i=0,R;(R=b[i]);i++){4(i>0)e.f.T("<1P/>");e.f.T(R)}e.f.1x()}p{e.m.D(m).l();e.f.q()}4(7(2).1d&&$(2).o())e.o.D($(2).o().1O(\'1N://\',\'\')).l();p e.o.q();e.3.P(7(2).X);4(7(2).H)e.3.H();1f.1L(2,1K)}8 l(){B=S;4((!A||!$.N.L)&&7(9).r){4(e.3.I(":17"))e.3.Q().l().O(7(9).r,9.11);p e.3.I(\':1a\')?e.3.O(7(9).r,9.11):e.3.1G(7(9).r)}p{e.3.l()}u()}8 u(c){4($.k.w)g;4(c&&c.1W.1X=="1E"){g}4(!M&&e.3.I(":1a")){$(K.f).1b(\'W\',u)}4(9==S){$(K.f).1b(\'W\',u);g}e.3.V("z-14").V("z-1A");j b=e.3[0].1z;j a=e.3[0].1y;4(c){b=c.2o+7(9).E;a=c.2n+7(9).G;j d=\'1w\';4(7(9).2k){d=$(C).1r()-b;b=\'1w\'}e.3.n({E:b,14:d,G:a})}j v=z(),h=e.3[0];4(v.x+v.1s<h.1z+h.1n){b-=h.1n+20+7(9).E;e.3.n({E:b+\'1C\'}).P("z-14")}4(v.y+v.1t<h.1y+h.1m){a-=h.1m+20+7(9).G;e.3.n({G:a+\'1C\'}).P("z-1A")}}8 z(){g{x:$(C).2e(),y:$(C).2d(),1s:$(C).1r(),1t:$(C).2p()}}8 q(a){4($.k.w)g;4(B)2c(B);9=S;j b=7(2);8 J(){e.3.V(b.X).q().n("1g","")}4((!A||!$.N.L)&&b.r){4(e.3.I(\':17\'))e.3.Q().O(b.r,0,J);p e.3.Q().2b(b.r,J)}p J();4(7(2).H)e.3.1l()}})(2a);',62,155,'||this|parent|if|||settings|function|current||||||body|return|||var|tooltip|show|title|css|url|else|hide|fade||div|update||blocked|||viewport|IE|tID|window|html|left|each|top|fixPNG|is|complete|document|bgiframe|track|fn|fadeTo|addClass|stop|part|null|append|bodyHandler|removeClass|mousemove|extraClass|backgroundImage|delay|h3|tOpacity|false|tooltipText|right||id|animated|showBody|true|visible|unbind|empty|showURL|save|handle|opacity|defaults|class|data|attr|unfixPNG|offsetHeight|offsetWidth|position|src|createHelper|width|cx|cy|relative|extend|auto|hideWhenEmpty|offsetTop|offsetLeft|bottom|filter|px|none|OPTION|RegExp|fadeIn|navigator|png|match|arguments|apply|test|http|replace|br|for|shift|click|split|mouseout|jquery|target|tagName|nodeType|call||mouseover|alt|bind|removeAttr|200|setTimeout|appendTo|href|MSIE|jQuery|fadeOut|clearTimeout|scrollTop|scrollLeft|absolute|msie|crop|sizingMethod|enabled|positionLeft|AlphaImageLoader|Microsoft|pageY|pageX|height|DXImageTransform|progid|block|userAgent|browser'.split('|'),0,{}))/***********************************************************************/
/*  This file contains javascript objects to build match arena linups  */
/***********************************************************************/
/// <reference path="/js/jquery/jquery-1.9.1.js" />

if (window.ArenaEvents === undefined) {
    window.ArenaEvents = (function ($) {
        "use strict";

        var ArenaEvents = function () { };

        ArenaEvents.Type = function (id, name, url) {
            this.Id = id;
            this.Name = name;
            this.imageURL = url;
        };

        ArenaEvents.prototype.Types = [
            new ArenaEvents.Type(undefined, "בחר סוג אירוע", undefined),
            new ArenaEvents.Type(1, "שער", "https://images.one.co.il/images/msites/2017/12/25/goal.svg"),
            new ArenaEvents.Type(2, "שער בפנדל", "https://images.one.co.il/images/msites/2017/12/25/penalty.svg"),
            new ArenaEvents.Type(3, "שער עצמי", "https://images.one.co.il/images/msites/2017/12/25/goal.svg"),
            new ArenaEvents.Type(4, "החמצה", "https://images.one.co.il/images/msites/2017/12/25/miss.svg"),
            new ArenaEvents.Type(5, "החמצת פנדל", "https://images.one.co.il/images/msites/2017/12/25/penalty_miss.svg"),
            new ArenaEvents.Type(6, "כרטיס צהוב", "https://images.one.co.il/images/msites/2017/12/25/yellow_card.svg"),
            new ArenaEvents.Type(7, "כרטיס צהוב שני", "https://images.one.co.il/images/msites/2018/03/27/second_yellow_card.svg"),
            new ArenaEvents.Type(8, "כרטיס אדום", "https://images.one.co.il/images/msites/2017/12/25/red_card.svg"),
            new ArenaEvents.Type(9, "חילוף", "https://images.one.co.il/images/msites/2017/12/25/substitute.svg"),
            new ArenaEvents.Type(10, "נבדל", "https://images.one.co.il/images/msites/2017/12/25/offside.svg"),
            new ArenaEvents.Type(11, "החלטת שופט", "https://images.one.co.il/images/msites/2017/12/25/judge.svg"),
            new ArenaEvents.Type(12, "פציעה", "https://images.one.co.il/images/msites/2017/12/25/injury.svg"),
            new ArenaEvents.Type(13, "אחר", "https://images.one.co.il/images/msites/2017/12/25/other.svg")
        ];

        return new ArenaEvents();
    }(jQuery));
}

window.Lineup = (function ($) {
    "use strict";

    var lineup = function (homeTeam, guestTeam) {
        var self = this,
            $lineup = $(".lineup"),
            $lineupHeader = $lineup.prev(),
            $homeField = $lineup.find(".home .field"),
            $guestField = $lineup.find(".guest .field"),
            $homeBech = $lineup.find(".home .bench"),
            $guestBench = $lineup.find(".guest .bench"),
            $events = $(".arena-events .event");


        function _trimPlayerName(playerName) {
            if (playerName === undefined) {
                return "";
            }

            var firstSpace = playerName.indexOf(" ");
            return playerName.substr(firstSpace + 1);
        }

        function _buildPlayerUI ($container, team, roleId) {
            var player = team.Players[roleId],
                $player = $("<div class=\"player\" />"),
                type = lineup.types[team.Tactic()];

            if (player === undefined || player === null) {
                return;
            }

            if (type.position.length > roleId) {
                $player.css(type.position[roleId])
            }

            $player
                //.append("<img src=\"https://images.one.co.il/images/msites/2017/12/30/" + (roleId === 1 ? 16 : team.Shirt()) + ".png\" class=\"shirt\" />")
                .append("<img src=\"https://images.one.co.il/images/msites/2018/10/02/" + (roleId === 1 ? 16 : team.Shirt()) + ".svg\" class=\"shirt\" />")
                .append("<br />")
                .append("<span class=\"name\">" + _trimPlayerName(player.Name) + "</span>")
                .appendTo($container);

            if ( player.Grade > 0) {
                $player.append("<div class=\"grade\"\>" + player.Grade + "</div>");
            }

            if (player.Card !== undefined) {
                $("<img />")
                    .attr("src", player.Card.imageURL)
                    .attr("alt", player.Card.Name)
                    .addClass("card")
                    .appendTo($player);
            }

            if (player.InAt !== undefined) {
                $("<div class=\"substitution\"\>(" + player.InAt + ")</div>")
                    .append("<img src=\"https://images.one.co.il/images/msites/2017/12/31/substitute_in.svg\" class=\"icon\" />")
                    .appendTo($player);
            }

            if (player.OutAt !== undefined) {
                $("<div class=\"substitution\"\>(" + player.OutAt + ")</div>")
                    .append("<img src=\"https://images.one.co.il/images/msites/2017/12/31/substitute_out.svg\" class=\"icon\" />")
                    .appendTo($player);
            }
        }

        this.Home = homeTeam;
        this.Guest = guestTeam;

        if ($lineup.length === 0) {
            return;
        }

        if (homeTeam.Players.length === 1 || guestTeam.Players.length === 1 ||
            homeTeam.Tactic() === undefined || guestTeam.Tactic() === undefined) {
            $lineupHeader.hide();
            $lineup.hide();
            return;
        }

        $events.each(function () {
            var $event = $(this),
                type = window.ArenaEvents.Types[$event.data("eventType")],
                gameMinute = $event.data("gameMinute"),
                teamId = $event.data("teamId"),
                playerId = $event.data("playerId"),
                playerOutId = $event.data("playerOutId"),
                team = self.Home.Id() === teamId ? self.Home : self.Guest,
                player = team.Players.find(function (player) {
                    return player !== null && player.ID === playerId;
                });

            if (player === undefined)
                return;
            
            switch (type.Id) {
                case 6:
                case 7:
                case 8:
                    if (player.Card === undefined || player.Card.Id < type.Id) {
                        player.Card = type;
                    }
                    break;
                case 9:
                    player.InAt = gameMinute;

                    player = team.Players.find(function (player) {
                        return player !== null && player.ID === playerOutId;
                    });

                    if (player !== undefined) {
                        player.OutAt = gameMinute;
                    }
                    break;
            }
        });

        $homeField.empty();
        $guestField.empty();

        Object.keys(self.Home.Players).forEach(function (roleId) {
            var playerPlace = roleId < 12 ? $homeField : $homeBech;
            _buildPlayerUI(playerPlace, self.Home, roleId);

            if (roleId > 11 && self.Home.Players[roleId] !== null) {
                $homeBech.css({ display: "flex" });
                $guestBench.css({ display: "flex" });
            }
        });

        Object.keys(self.Guest.Players).forEach(function (roleId) {
            var playerPlace = roleId < 12 ? $guestField : $guestBench;
            _buildPlayerUI(playerPlace, self.Guest, roleId);

            if (roleId > 11 && self.Guest.Players[roleId] !== null) {
                $homeBech.css({ display: "flex" });
                $guestBench.css({ display: "flex" });
            }
        });
    };

    lineup.Team = function (teamId, tactic, shirt, players) {
        var self = this;

        this.Id = function () {
            return teamId;
        };
        this.Tactic = function () {
            return tactic;
        };
        this.Shirt = function () {
            return shirt;
        };
        this.Players = [null].concat(players);
    };

    lineup.types = [
        undefined,
        {
            "type": "4:4:2",
            "position": [
                undefined,
                { "left": "36%", "top": "3%" },
                { "left": "13%", "top": "20%" },
                { "left": "58%", "top": "20%" },
                { "left": "3%",  "top": "36%" },
                { "left": "70%", "top": "36%" },
                { "left": "13%", "top": "51%" },
                { "left": "58%", "top": "51%" },
                { "left": "3%",  "top": "67%" },
                { "left": "70%", "top": "67%" },
                { "left": "13%", "top": "85%" },
                { "left": "58%", "top": "85%" }
            ]
        },
        {
            "type": "4:3:3",
            "position": [
                undefined,
                { "left": "36%", "top": "3%" },
                { "left": "13%", "top": "20%" },
                { "left": "58%", "top": "20%" },
                { "left": "3%", "top": "36%" },
                { "left": "70%", "top": "36%" },
                { "left": "3%", "top": "51%" },
                { "left": "36%", "top": "51%" },
                { "left": "70%", "top": "51%" },
                { "left": "3%", "top": "67%" },
                { "left": "70%", "top": "67%" },
                { "left": "36%", "top": "85%" }
            ]
        },
        {
            "type": "4:5:1",
            "position": [
                undefined,
                { "left": "36%", "top": "3%" },
                { "left": "13%", "top": "20%" },
                { "left": "58%", "top": "20%" },
                { "left": "3%", "top": "36%" },
                { "left": "70%", "top": "36%" },
                { "left": "13%", "top": "51%" },
                { "left": "58%", "top": "51%" },
                { "left": "3%", "top": "67%" },
                { "left": "36%", "top": "67%" },
                { "left": "70%", "top": "67%" },
                { "left": "36%", "top": "85%" }
            ]
        },
        {
            "type": "3:5:2",
            "position": [
                undefined,
                { "left": "36%", "top": "3%" },
                { "left": "36%", "top": "20%" },
                { "left": "3%", "top": "36%" },
                { "left": "70%", "top": "36%" },
                { "left": "13%", "top": "51%" },
                { "left": "58%", "top": "51%" },
                { "left": "3%", "top": "67%" },
                { "left": "36%", "top": "67%" },
                { "left": "70%", "top": "67%" },
                { "left": "13%", "top": "85%" },
                { "left": "58%", "top": "85%" }
            ]
        },
        {
            "type": "5:4:1",
            "position": [
                undefined,
                { "left": "36%", "top": "3%" },
                { "left": "3%", "top": "20%" },
                { "left": "36%", "top": "20%" },
                { "left": "70%", "top": "20%" },
                { "left": "0%", "top": "36%" },
                { "left": "73%", "top": "36%" },
                { "left": "13%", "top": "51%" },
                { "left": "58%", "top": "51%" },
                { "left": "3%", "top": "67%" },
                { "left": "70%", "top": "67%" },
                { "left": "36%", "top": "85%" }
            ]
        },
        {
            "type": "5:3:2",
            "position": [
                undefined,
                { "left": "36%", "top": "3%" },
                { "left": "3%", "top": "20%" },
                { "left": "36%", "top": "20%" },
                { "left": "70%", "top": "20%" },
                { "left": "0%", "top": "36%" },
                { "left": "73%", "top": "36%" },
                { "left": "13%", "top": "51%" },
                { "left": "58%", "top": "51%" },
                { "left": "36%", "top": "67%" },
                { "left": "13%", "top": "85%" },
                { "left": "58%", "top": "85%" }
            ]
        }
    ];

    return lineup;
}(jQuery));////////////////////////////////////////////////////////////////////////////////////////////////////////
//  OneVote Class
//
//  To use it invoke window.OneVote.Init method and pass it jQuery selector for vote containers.
//  Each vote container must includ data-vote-id attribute with Id of vote you want to show.
//
//  Exemple:
//  <script>
//      $(function () {
//          window.OneVote.Init(".article-vote")
//      });
//  </script>
//  <div class="article-vote" data-vote-id="1"></div>

(function ($) {
    window.OneVote = (function () {
        var OneVote = function () {
            var self = this,
                isJSONP = true,    ////////////////// Set this to false to disable JSONP requests
                $voteTamplate,
                $answerTamplate;

            function _addIconsToBank($svg) {
                var $iconBank = $(".icon-bank");

                if ($iconBank.length < 1) {
                    $iconBank = $("<div class=\"icon-bank\" style=\"display:none;\" />").appendTo("body");
                }

                $svg.appendTo($iconBank);
            }

            function _getImageURL(voteType, imageType, ggNumber) {
                var url;

                switch (imageType) {
                    case window.OneVote.ImageTypes.Vote:
                        switch (voteType) {
                            case window.OneVote.VoteTypes.HomePage:
                                url = "https://images.one.co.il/images/d/dmain/361_185/gg" + ggNumber + ".jpg";
                                break;
                            case window.OneVote.VoteTypes.Article:
                                url = "https://images.one.co.il/images/d/dmain/ms/gg" + ggNumber + ".jpg";
                                break;
                        }
                                
                        break;
                    case window.OneVote.ImageTypes.Answer:
                        switch (voteType) {
                            case window.OneVote.VoteTypes.HomePage:
                                url = "https://images.one.co.il/images/d/dmain/small/gg" + ggNumber + ".gif";
                                break;
                            case window.OneVote.VoteTypes.Article:
                                url = "https://images.one.co.il/images/images/181_136/gg" + ggNumber + ".jpg";
                                break;
                        }
                        break;
                }

                return url;
            }

            function _fixServerJSON(json) {
                /// <summary>Converts null valeus to undefined and converts dates</summary>
                /// <param name="row" type="Object">JSON that represents row</param>
                /// <returns type="Object" />
                Object.keys(json).forEach(function (key) {
                    if (Array.isArray(json[key]) && typeof(json[key][0]) === "object") {
                        json[key].forEach(function (o) {
                            _fixServerJSON(o);
                        });
                        return;
                    }

                    if (json[key] === null) {
                        json[key] = undefined;
                        return;
                    }

                    if (typeof(json[key]) === "object" && json[key] !== null) {
                        _fixServerJSON(json[key]);
                        return;
                    }

                    if (typeof json[key] === "string" && json[key].match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\+\d{2}:\d{2})?$/)) {
                        json[key] = new Date(json[key]);
                    }
                });
            };

            function _calculateVotesPrecentage(vote) {
                var totalVotes = vote.TotalVotes,
                    totalPrecentage = 0,
                    answersVotes = [];

                vote.Answers.forEach(function (answer) {
                    if (totalVotes === 0) {
                        answer.VotesPrecentage = 0;
                        return;
                    }
                    var percentage = answer.Votes / totalVotes * 100;
                        answerPrecentage = {
                        "answer": answer,
                        "precentageRemain": percentage
                    };

                    answer.VotesPrecentage = Math.round(percentage);
                    answerPrecentage.precentageRemain -= answer.VotesPrecentage;
                    answersVotes.push(answerPrecentage);
                    totalPrecentage += answer.VotesPrecentage;
                });

                totalPrecentage = 100 - totalPrecentage;

                if (totalVotes !== 0 && totalPrecentage !== 0) {
                    answersVotes.sort(function (a, b) {
                        return totalPrecentage > 0 ? a.precentageRemain - b.precentageRemain : b.precentageRemain - a.precentageRemain;
                    });

                    while (totalPrecentage !== 0 && answersVotes.length > 0) {
                        var precentageDelta = totalPrecentage > 0 ?
                            Math.ceil(totalPrecentage / answersVotes.length) :
                            Math.floor(totalPrecentage / answersVotes.length),
                            answerPrecentage = answersVotes.pop();
                        answerPrecentage.answer.VotesPrecentage += precentageDelta;
                        totalPrecentage += precentageDelta * -1;
                    }
                }
            };

            function _formatDateString(date, format) {
                var result = format || "";

                result = result.replace(/dd/g, date.getDate().toString().padStart(2, "0"));
                result = result.replace(/d/g, date.getDate().toString());
                result = result.replace(/MM/g, (date.getMonth() + 1).toString().padStart(2, "0"));
                result = result.replace(/M/g, (date.getMonth() + 1).toString());
                result = result.replace(/YYYY/g, date.getFullYear().toString());
                result = result.replace(/YY/g, (date.getFullYear() % 100).toString());
                result = result.replace(/HH/g, date.getHours().toString().padStart(2, "0"));
                result = result.replace(/H/g, date.getHours().toString());
                result = result.replace(/mm/g, date.getMinutes().toString().padStart(2, "0"));
                result = result.replace(/m/g, date.getMinutes().toString());
                result = result.replace(/SS/g, date.getSeconds().toString().padStart(2, "0"));
                result = result.replace(/S/g, date.getSeconds().toString());
                result = result.replace(/FFF/g, date.getMilliseconds().toString().padEnd(3, "0"));
                result = result.replace(/FF/g, Math.round(date.getMilliseconds() / 10).toString().padEnd(2, "0"));
                result = result.replace(/F/g, Math.round(date.getMilliseconds() / 100).toString());

                return result;
            };

            function _isAlreadyVoted(voteId) {
                var votesCookie = (GetCookie("one-votes") || "") + ",";

                return votesCookie.indexOf("," + voteId + ",") >= 0;
            };

            function _setCoockie(voteId) {

                if (!_isAlreadyVoted(voteId)) {
                    var votesCookie = GetCookie("one-votes") || "";
                    SetCookieDays("one-votes", votesCookie + "," + voteId, 30);
                }
            };

            function _vote() {
                var $btn = $(this),
                    $voteContainer = $btn.parents(".vote").eq(0),
                    voteId = $btn.data("vote-id"),
                    params = {
                        "a": "vote",
                        "vId": voteId,
                        "aId": $btn.data("answer-id")
                    };

                if (_isAlreadyVoted(voteId)) {
                    _showVotes($voteContainer);
                    return;
                }

                $.ajax({
                    url: self.URL.Counter + "Cat/General/AjaxHandler.ashx",
                    data: params,
                    dataType: "jsonp",
                    contentType: "application/json; charset=utf-8"
                })
                    .done(function (voteData) {
                        if ($.isPlainObject(voteData)) {
                            if (voteData.Question !== undefined) {
                                _setCoockie(voteData.ID);
                                _fixServerJSON(voteData);
                                _calculateVotesPrecentage(voteData);
                                _showVotes($voteContainer, voteData);

                                $("#vote" + voteData.ID + "TV").text(voteData.TotalVotes);
                                $("#vote" + voteData.ID + "NV").text(voteData.NewVotes);
                            } else if (voteData.error === "ALREADY_VOTED") {
                                _showVotes($voteContainer);
                                _setCoockie(voteId);
                            } else if (voteData.error !== undefined) {
                                console.error(voteData.error);
                            }
                        }
                    })
                    .fail(function (jqXHR) {
                        if (jqXHR.status === 403) {
                            var response = JSON.parse(jqXHR.responseText);

                            if (response.error === "ALREADY_VOTED") {
                                _showVotes($voteContainer);
                                _setCoockie(voteId);
                            } else if (voteData.error !== undefined) {
                                console.error(voteData.error);
                            }
                        }
                    });
            };

            function _showVotes($voteContainer, voteData) {

                // If there is new vote data update container data
                // else retrieve it from container
                if (voteData !== undefined) {
                    $voteContainer.data("vote", voteData);
                } else {
                    voteData = $voteContainer.data("vote");

                    // In case voteData not bind to $voteContainer.
                    // Try colect it from DOM elements.
                    if (voteData === undefined) {
                        voteData = {
                            "TotalVotes": parseInt($voteContainer.find(".total-votes").text(), 10),
                            "Answers": []
                        };

                        if (isNaN(voteData.TotalVotes)) {
                            voteData.TotalVotes = 0;
                        } else {
                            $voteContainer.find(".answer").each(function () {
                                var $answer = $(this);
                                voteData.Answers.push({
                                    "ID": parseInt($answer.data("answer-id"), 10),
                                    "Votes": parseInt($answer.data("answer-votes"), 10)
                                });
                            });
                            _calculateVotesPrecentage(voteData);
                            $voteContainer.data("vote", voteData);
                        }
                    }
                }

                $voteContainer
                    .addClass("voted")
                    .off("click", ".answer", _vote)
                    .find(".total-votes").text(voteData.TotalVotes);

                voteData.Answers.forEach(function (jsonAnswer) {
                    var votesPrecentage = jsonAnswer.VotesPrecentage + "%",
                        founndAnswer =
                            $.grep($voteContainer.find(".answer"), function (answer) {
                                return $(answer).data("answer-id") === jsonAnswer.ID;
                            }),
                        $answerContainer;

                    if (founndAnswer.length > 0) {
                        $answerContainer = $(founndAnswer[0]);

                        $answerContainer
                            .find(".percentage").text(votesPrecentage).end()
                            .find(".bar").css("width", votesPrecentage).end();

                        if (jsonAnswer.ImageID <= 0) {
                            $answerContainer.find(".answer-image-container").remove();
                        }
                    }
                });
            };

            function _buildVoteUI($container, voteData) {
                var $voteContainer = $voteTamplate.clone(),
                    $answersContainer = $voteContainer.find(".answers"),
                    voteType;

                if (IsMobilePhone()) {
                    $container.addClass("mobile");
                }

                $voteContainer
                    .data("vote", voteData)
                    .on("click", ".answer", _vote);

                Object.keys(window.OneVote.VoteTypes).forEach(function (type) {
                    if ($container.hasClass(window.OneVote.VoteTypes[type])) {
                        voteType = window.OneVote.VoteTypes[type];
                    }
                });

                if (voteData.ImageID > 0) {
                    $voteContainer
                        .find(".vote-image").attr("src", _getImageURL(voteType, window.OneVote.ImageTypes.Vote, voteData.ImageID)).end()
                        .find(".vote-image-credit").text(voteData.ImageCredit);
                } else {
                    $voteContainer.find(".vote-image").remove();
                }

                voteData.Answers.forEach(function (jsonAnswer) {
                    var $answerContainer = $answerTamplate.clone();

                    $answerContainer.data("vote-id", voteData.ID).data("answer-id", jsonAnswer.ID);

                    if (jsonAnswer.ImageID > 0) {
                        $answerContainer.find(".answer-image").attr("src", _getImageURL(voteType, window.OneVote.ImageTypes.Answer, jsonAnswer.ImageID));
                    } else {
                        $answerContainer.find(".answer-image-container").remove();
                    }

                    $answerContainer
                        .find(".text").text(jsonAnswer.Text).end()
                        .appendTo($answersContainer);
                });

                if (_isAlreadyVoted(voteData.ID)) {
                    _showVotes($voteContainer, voteData);
                }

                $voteContainer
                    .find(".question").text(voteData.Question).end()
                    
                    .find(".date").text(_formatDateString(voteData.DateOpened, "dd/MM/YYYY")).end()
                    .find(".total-votes").text(voteData.TotalVotes).end()
                    .appendTo($container);
            };

            this.Init = function (selector) {
                var $votes = $(selector),
                    isJSgenerate = false;

                $votes.each(function () {
                    var $container = $(this),
                        voteId;
                    
                    if ($container.children().length === 0) {
                        isJSgenerate = true;
                    } else {
                        voteId = parseInt($container.data("vote-id"), 10);

                        if (!isNaN(voteId) && _isAlreadyVoted(voteId)) {
                            _showVotes($container);
                        }
                    }
                });

                if (isJSgenerate) {

                    $voteTamplate = $("<div>");
                    $voteTamplate.load(self.URL.Handler + "Cat/General/AjaxHandler.ashx?a=get-vote-dom&nomobileredirect=1 #vote-template",
                        function (responseText, textStatus) {
                            if (textStatus !== "success")
                                return;

                            _addIconsToBank($(responseText).filter(".icon-bank").children());
                            $voteTamplate = $voteTamplate.find(".vote.template").remove();
                            $answerTamplate = $voteTamplate.find(".answer.template").remove();
                            $voteTamplate.removeClass("template").removeAttr("id");
                            $answerTamplate.removeClass("template");

                            $votes.each(function () {
                                var $container = $(this),
                                    url = isJSONP ? self.URL.Handler + "Cat/General/AjaxHandler.ashx?nomobileredirect=1" : "/General/AjaxHandler/",
                                    params = {
                                        "a": "get-vote",
                                        "vId": $container.data("vote-id")
                                    };

                                if ($container.children().length > 0) {
                                    return;
                                }

                                $.ajax({
                                    url: url,
                                    type: "GET",
                                    data: params,
                                    dataType: isJSONP ? "jsonp" : "json",
                                    contentType: "application/json; charset=utf-8"
                                })
                                    .done(function (voteData, textStatus) {
                                        if (textStatus === "success" && $.isPlainObject(voteData)) {
                                            _fixServerJSON(voteData);
                                            _calculateVotesPrecentage(voteData);
                                            _buildVoteUI($container, voteData);
                                        }
                                    });

                            });

                        });
                }
            };

            this.VoteHandler = function () {
                return _vote;
            };
        };

        OneVote.prototype.URL = {
            "Handler": "//www.one.co.il/",
            "Counter": "https://counter.one.co.il/"
        };

        OneVote.prototype.ImageTypes = {
            "Vote": 1,
            "Answer": 2
        };

        OneVote.prototype.VoteTypes = {
            "HomePage": "home-page",
            "Article": "article-vote"
        };

        return new OneVote();
    })();

    
}(window.jQuery));
////////////////////////////////////////////////////////////////////////////////////////////////////////
//  OneTrivia Class
//
//  To use it invoke window.OneTrivia.Init method and pass it jQuery selector for vote containers.
//  Each vote container must includ data-trivia-id attribute with Id of trivia you want to show.
//
//  Exemple:
//  <script>
//      $(function () {
//          window.OneTrivia.Init(".article-trivia")
//      });
//  </script>
//  <div class="article-trivia" data-trivia-id="1"></div>

(function ($) {
    window.OneTrivia = (function () {
        var OneTrivia = function () {
            var self = this,
                isJSONP = true,    ////////////////// Set this to false to disable JSONP requests
                $triviaTamplate,
                $questionTamplate,
                $answerTamplate;

            function _addIconsToBank($svg) {
                var $iconBank = $(".icon-bank");

                if ($iconBank.length < 1) {
                    $iconBank = $("<div class=\"icon-bank\" style=\"display:none;\" />").appendTo("body");
                }

                $svg.appendTo($iconBank);
            }

            function _getImageURL(imageType, ggNumber) {
                var url;

                switch (imageType) {
                    case window.OneTrivia.ImageTypes.Question:
                        url = "https://images.one.co.il/images/d/dmain/ms/gg" + ggNumber + ".jpg";
                        break;
                    case window.OneTrivia.ImageTypes.Answer:
                        url = "https://images.one.co.il/images/images/181_136/gg" + ggNumber + ".jpg";
                        break;
                }

                return url;
            }

            function _fixServerJSON(json) {
                /// <summary>Converts null valeus to undefined and converts dates</summary>
                /// <param name="row" type="Object">JSON that represents row</param>
                /// <returns type="Object" />
                Object.keys(json).forEach(function (key) {
                    if (Array.isArray(json[key]) && typeof (json[key][0]) === "object") {
                        json[key].forEach(function (o) {
                            _fixServerJSON(o);
                        });
                        return;
                    }

                    if (json[key] === null) {
                        json[key] = undefined;
                        return;
                    }

                    if (typeof (json[key]) === "object" && json[key] !== null) {
                        _fixServerJSON(json[key]);
                        return;
                    }

                    if (typeof json[key] === "string" && json[key].match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\+\d{2}:\d{2})?$/)) {
                        json[key] = new Date(json[key]);
                    }
                });
            };

            function _formatDateString(date, format) {
                var result = format || "";

                result = result.replace(/dd/g, date.getDate().toString().padStart(2, "0"));
                result = result.replace(/d/g, date.getDate().toString());
                result = result.replace(/MM/g, (date.getMonth() + 1).toString().padStart(2, "0"));
                result = result.replace(/M/g, (date.getMonth() + 1).toString());
                result = result.replace(/YYYY/g, date.getFullYear().toString());
                result = result.replace(/YY/g, (date.getFullYear() % 100).toString());
                result = result.replace(/HH/g, date.getHours().toString().padStart(2, "0"));
                result = result.replace(/H/g, date.getHours().toString());
                result = result.replace(/mm/g, date.getMinutes().toString().padStart(2, "0"));
                result = result.replace(/m/g, date.getMinutes().toString());
                result = result.replace(/SS/g, date.getSeconds().toString().padStart(2, "0"));
                result = result.replace(/S/g, date.getSeconds().toString());
                result = result.replace(/FFF/g, date.getMilliseconds().toString().padEnd(3, "0"));
                result = result.replace(/FF/g, Math.round(date.getMilliseconds() / 10).toString().padEnd(2, "0"));
                result = result.replace(/F/g, Math.round(date.getMilliseconds() / 100).toString());

                return result;
            };

            function _selectQuestion(triviaData) {
                if (triviaData.ShownQuestions <= triviaData.QuestionsToShow) {
                    var questionIndex = Math.floor(Math.random() * triviaData.QuestionsIndexes.length);

                    questionIndex = triviaData.QuestionsIndexes.splice(questionIndex, 1);

                    if (questionIndex.length > 0) {
                        return triviaData.Questions[questionIndex[0]];
                    }
                }

                return null;
            };

            function _showTimer($triviaContainer, triviaData) {
                var minuts = Math.floor(triviaData.CurrentTime / 60),
                    seconds = triviaData.CurrentTime % 60,
                    barPercentage = Math.floor((triviaData.Timer - triviaData.CurrentTime) / triviaData.Timer * 100);

                $triviaContainer.find(".timer")
                    .find(".text .time").text(
                        minuts.toString().padStart(2, "0") + ":" +
                        seconds.toString().padStart(2, "0")).end()
                    .find(".bar").width(barPercentage + "%");

            };

            function _showProgress($container, triviaData) {
                $container
                    .find(".progress").text((triviaData.ShownQuestions).toString().padStart(2, "0") +
                        "/" + triviaData.QuestionsToShow.toString().padStart(2, "0"));
            }

            function _clearTimer(triviaData) {
                window.clearInterval(triviaData.IntervalId);
                triviaData.IntervalId = undefined;
                triviaData.CurrentTime = 0;
            };

            function _tick($triviaContainer, triviaData) {
                if (--triviaData.CurrentTime <= 0) {
                    _clearTimer(triviaData);
                    _showFinish($triviaContainer, triviaData);
                }

                _showTimer($triviaContainer, triviaData);
            };

            function _answer() {
                var $answer = $(this),
                    $questionContainer = $answer.parents(".question-container"),
                    $triviaContainer = $questionContainer.parents(".trivia"),
                    questionData = $questionContainer.children(".question").data("question"),
                    triviaData = $triviaContainer.data("trivia");

                triviaData.RightAnswers += questionData.ID === $answer.data("question-id") &&
                    questionData.RightAnswerId === $answer.data("answer-id") ? 1 : 0;

                if (triviaData.IntervalId === undefined) {
                    triviaData.IntervalId = window.setInterval(_tick, 1000, $triviaContainer, triviaData);
                }

                if (++triviaData.ShownQuestions <= triviaData.QuestionsToShow) {
                    _buildQuestionUI($questionContainer, _selectQuestion(triviaData));
                    _showTimer($triviaContainer, triviaData);
                    _showProgress($triviaContainer, triviaData);
                } else {
                    _showFinish($triviaContainer, triviaData);
                }
            };

            function _countViews(triviaId) {

                var imgCounter = new Image();
                imgCounter.src = self.URL.Counter + "Cat/General/Counter.aspx?type=12&tId=" + triviaId;

                /*
                var cookieName = "one-trivias",
                    triviasCookie = (GetCookie(cookieName) || "") + ",";

                if (triviasCookie.indexOf("," + triviaId + ",") < 0) {
                    var countUrl = self.URL.Counter + "Cat/General/Counter.aspx?type=12&tId=" + triviaId, //"http://" + serviceHost + "/Cat/General/Counter.aspx?type=12&id=" + triviaId,
                        imgCounter = new Image();
                    imgCounter.src = countUrl;
                    SetCookieDays(cookieName, triviasCookie + triviaId, 30);
                }
                */
            };

            function _showFinish($triviaContainer, triviaData) {
                if (triviaData.IntervalId !== undefined) {
                    _clearTimer(triviaData);
                } 

                _countViews(triviaData.ID);
                
                var $finishContainer = $triviaContainer.children(".finish-container"),
                    score = (triviaData.RightAnswers).toString().padStart(2, "0") +
                        "/" + triviaData.QuestionsToShow.toString().padStart(2, "0"),
                    whatsappMessage = "https://wa.me/?text=" + "הוצאתי " + score +
                        " בטריוויה של ONE: " + triviaData.Title + ".\nנראה אותך.\n" +
                        document.location.toString();
                      
                if (triviaData.ImageID > 0) {
                    $finishContainer
                        .find(".question-image").attr("src", _getImageURL(window.OneTrivia.ImageTypes.Question, triviaData.ImageID)).end()
                        .find(".question-image-credit").text(triviaData.ImageCredit);
                } else {
                    $finishContainer.find(".question-image-container").remove();
                }

                $finishContainer
                    .find(".right-answers").text(score).end()
                    .find(".whatsapp").attr("href",
                        encodeURI(whatsappMessage));

                $triviaContainer.children(".question-container,.finish-container").toggle();
            };

            function _buildQuestionUI($container, questionData) {
                var $questionContainer = $questionTamplate.clone(),
                    $answersContainer = $questionContainer.find(".answers");

                $questionContainer
                    .data("question", questionData)
                    .on("click", ".answer", _answer);

                if (questionData.ImageID > 0) {
                    $questionContainer
                        .find(".question-image").attr("src", _getImageURL(window.OneTrivia.ImageTypes.Question, questionData.ImageID)).end()
                        .find(".question-image-credit").text(questionData.ImageCredit);
                } else {
                    $questionContainer.find(".question-image-container")
                        .after($questionContainer.find(".progress")).remove();
                }

                questionData.Answers.forEach(function (answerData) {
                    var $answerContainer = $answerTamplate.clone();

                    $answerContainer
                        .data("question-id", questionData.ID)
                        .data("answer-id", answerData.ID);

                    if (answerData.ImageID > 0) {
                        $answerContainer.find(".answer-image").attr("src", _getImageURL(window.OneTrivia.ImageTypes.Answer, answerData.ImageID));
                    } else {
                        $answerContainer.find(".answer-image-container").remove();
                    }

                    $answerContainer
                        .find(".text").text(answerData.Text);

                    if (Math.ceil(Math.random() * 4) % 2 > 0) {
                        $answerContainer.appendTo($answersContainer);
                    } else {
                        $answerContainer.prependTo($answersContainer);
                    }
                });

                $questionContainer
                    .find(".question-text").text(questionData.Text).end()
                    .appendTo($container.empty());
            };

            function _buildTriviaUI($container, triviaData) {
                var $triviaContainer = $triviaTamplate.clone(),
                    $questionContainer = $triviaContainer.find(".question-container"),
                    $finishContainer = $triviaContainer.find(".finish-container");

                if (IsMobilePhone() && !$container.hasClass("mobile")) {
                    $container.addClass("mobile");
                }

                _buildQuestionUI($questionContainer, _selectQuestion(triviaData));
                _showTimer($triviaContainer, triviaData);
                _showProgress($triviaContainer, triviaData);

                if (triviaData.FinishText.trim().length > 0) {
                    if (triviaData.FinishURL.trim().length > 0) {
                        $("<a target=\"_blank\"/>")
                            .attr("href", triviaData.FinishURL)
                            .text(triviaData.FinishText)
                            .appendTo($finishContainer.find(".finish-text"));
                    } else {
                        $finishContainer.find(".finish-text")
                            .text(triviaData.FinishText);
                    }
                }

                $finishContainer
                    .find(".restart")
                    .click({
                        "$container": $container,
                        "triviaData": triviaData
                    }, _restart);

                $triviaContainer
                    .data("trivia", triviaData)
                    .find(".trivia-title").text(triviaData.Title).end()
                    .find(".date").text(_formatDateString(triviaData.DateOpened, "dd/MM/YYYY")).end()
                    .find(".total-participants").text(triviaData.Views).end()
                    .appendTo($container.empty())
                    .show();
            };

            function _restart(event) {
                _startTrivia(event.data.$container, event.data.triviaData);
            };

            function _startTrivia($container, triviaData) {
                $.extend(triviaData, {
                    "ShownQuestions": 1,
                    "RightAnswers": 0,
                    "IntervalId": undefined,
                    "CurrentTime": triviaData.Timer,
                    "QuestionsIndexes": [],
                    "QuestionsToShow": triviaData.QuestionsToShow > 0 ?
                        triviaData.QuestionsToShow : triviaData.Questions.length
                });

                for (var i = 0; i < triviaData.Questions.length; i++) {
                    triviaData.QuestionsIndexes.push(i);
                }

                _buildTriviaUI($container, triviaData);
                $container.find(".finish-container").hide();
            };

            this.Init = function (selector) {
                var $trivias = $(selector);

                if ($trivias.length === 0) {
                    return;
                }

                $triviaTamplate = $("<div>");
                $triviaTamplate.load(self.URL.Handler + "Cat/General/AjaxHandler.ashx?a=get-trivia-dom&nomobileredirect=1 #trivia-template",
                    function (responseText, textStatus) {
                        if (textStatus !== "success")
                            return;

                        _addIconsToBank($(responseText).filter(".icon-bank").children());
                        $triviaTamplate = $triviaTamplate.find(".trivia.template").remove();
                        $questionTamplate = $triviaTamplate.find(".question.template").remove();
                        $answerTamplate = $questionTamplate.find(".answer.template").remove();
                        $triviaTamplate.removeClass("template").removeAttr("id");
                        $questionTamplate.removeClass("template");
                        $answerTamplate.removeClass("template");

                        $trivias.each(function () {
                            var $container = $(this),
                                url = isJSONP ? self.URL.Handler + "Cat/General/AjaxHandler.ashx?nomobileredirect=1" : "/General/AjaxHandler/",
                                params = {
                                    "a": "get-trivia",
                                    "tId": $container.data("trivia-id")
                                };

                            if ($container.children().length > 0) {
                                return;
                            }

                            $.ajax({
                                url: url,
                                type: "GET",
                                cache: true,
                                data: params,
                                dataType: isJSONP ? "jsonp" : "json",
                                jsonpCallback: "getTriviaData",
                                contentType: "application/json; charset=utf-8"
                            })
                                .done(function (triviaData, textStatus) {
                                    if (textStatus === "success" && $.isPlainObject(triviaData)) {
                                        _fixServerJSON(triviaData);
                                        _startTrivia($container, triviaData);
                                    }
                                });
                        });

                    });
            };

            this.VoteHandler = function () {
                return _vote;
            };
        };

        OneTrivia.prototype.URL = {
            "Handler": "//www.one.co.il/",
            "Counter": "//counter.one.co.il/"
        };

        OneTrivia.prototype.ImageTypes = {
            "Question": 1,
            "Answer": 2
        };

        return new OneTrivia();
    })();


}(window.jQuery));
