﻿///<reference path="~/static/scripts/Jquery.IntelliSense.js" />
///<reference path="~/static/Main.js" />

function isArray(obj) {
    return obj.constructor == Array;
}
function logFunc(funcName,args)
{
    var s = "Function:"+funcName +"(";
    for(i=0;i<args.length;i++)
    {
        s += args[i] + ",";
    }
    return s+=") Time :" + new Date().getTime() + "\n";
}
function logVar(FuncName, varName, arg) {
    return "Func:" + FuncName + " var " + varName + " = " + arg + "\n";
}
function logError(_action,_type,_message)
{
    return "Action:" + _action + " Name:" + _type  + " Message: " + _message;
}
function saveLog(str, output) {
    $.post("/a7Admin/chillzone.ashx", { "log": "true", "str": str, "output": output },
    function() {
            window.open("/a7Admin/chillzone.ashx?output=readlastlog", "PlayerLog");
    });
}
////Players constructor
var Players=[];
if(!sStaticURL){sStaticURL='/';}
if(!View.PlayerSize) View.PlayerSize = {width:319,height:239};
Players.New = function(video, TVZone, size, uimode) {
if (!TVZone)
{ TVZone = [-2, -2] /*230*/; }
else if (!isArray(TVZone))
{ TVZone = [TVZone, TVZone]; } 
    if (!size) size = View.PlayerSize;
    var id = Players.length;
    var p = new Player(id, video, size,({zones:TVZone}), false, uimode);
    Players.push(p);
    p.TVZone = TVZone;
    p.fA = Player.prototype.fA;
    return p;
}

//Player Object
function Player(id,video,size,params,DontWriteCSS,mp_uimode)
{
    this.video = video;
	this.size = size;
	this.id=id;
	this.AdIn = false;
	this.log = "";
	var sPlayer = '<div style=color:white;>It is not possible to play the video <a style=color:white href='+video.url+'>You can try to Open it in an external player</a>';
	var sl=this.CheckSL();
	var uimode='full';
	if (!!params.zones) {
	    this.TVZone = params.zones;
	}
	var _url = this.ManageUrl(this.video.url);
	if(!!mp_uimode)
	{
    	uimode=mp_uimode;
    }
  
			

	if (!$.browser.msie&&!sl)
		{this.Silverlight=true; this.html = "<div style=direction:ltr;background-color:black;height:"+(size.height-20)+"px;padding:10px;color:white;width:"+(size.width-40)+"px>You need the Silverlight plugin for Firefox.<br><a href=\"http://go.microsoft.com/fwlink/?LinkID=124807\" style=color:white>Click here to install it</a></div>"; this.Writed=DoNothing; return false;}
		else if (!$.browser.msie && sl)
		//   else if (sl)
		///static/images/objects/a7player.xap?v=2
		{
		    sPlayer = '<object type="application/x-silverlight-2" id="Player' + id + '" src="images/objects/a7player.xap" \
		style=width:' + (size.width - 20) + 'px;height:' + size.height + 'px">\
		<param name="MinRuntimeVersion" value="2.0.31005.0" />\
		<param name="Source" value="/static/images/objects/a7player.xap" />\
		<param name="autoUpgrade" value="true" />\
		<param name="initParams" \
                value="url='+ _url+'"/>\
		<a href="http://go2.microsoft.com/fwlink/?LinkID=114576&amp;v=2.0"><img src="http://go2.microsoft.com/fwlink/?LinkID=108181" alt="Get Microsoft Silverlight" style="border-width:0;" /></a></object>'; this.Silverlight = true }
	else if ($.browser.msie) { 
	sPlayer = '<object id="Player' + id + '" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" style="width:' + (size.width - 20) + 'px;height:' + (size.height + 65) + 'px;margin-top:-18px;" class="objectplayer">\
		<param name="stretchToFit" value="true" />\
		<param name="uimode" value="'+uimode+'" />\
		<param name="autoSize" value="false" />\
		<param name="autoStart" value="false" />';

		sPlayer +='<param name="URL" value="' + _url + '" />';

		sPlayer+='</object>\
		<script for="Player' + id + '" event="playStateChange">Players['+id+ '].Changed();</script>'; }
	
	this.html = this.GraphIt(sPlayer);
	if(DontWriteCSS){this.WriteCSS=false;}
		//this.ActiveUrl = _url; this.UrlSetted = true;
this.log += logVar("SETTED:::",'', _url);
	}
function GetImage(imageid,width,height,engfilesystem)
{
    this.log += logFunc("GetImage", arguments);
    if(imageid==0){return '/static/images/objects/emptyad.gif'}
    if (engfilesystem)
        return "/static/pictures/resized/319-239/" + Math.floor(imageid / 1000) + "/" + imageid + ".jpg";
    else
        return "http://a7.org/Resizer.ashx?source=news&image=" + imageid + "&a=400&b=275";
}
//------------------------------------------Start Player prototype------------------------------------------//
Player.prototype = { Volume: 100, Silverlight: false, lastState: -1, IsWrited: false, IsSLLoaded: false, currImageClickUrl: "",
    WriteCSS: true,
    //--------- visual view of the player GraphIt---------------///
    GraphIt: function(playerobj) {
        this.log += logFunc("GraphIt", arguments);
        var sImg = "<img id=imgVideo" + this.id + " style=position:Absolute; src='" + GetImage(this.video.image, (this.size.width - 20), this.size.height) + "' />";
        var sHTML = [];
        sHTML.push('<div class=VVideo style=width:' + this.size.width + 'px;><div class=VVideoT></div><div id=divVideoBG' + this.id + ' style="margin:0 10px;width:' + (this.size.width - 20) + 'px;height:' + this.size.height + 'px;direction:ltr;overflow:hidden;cursor:pointer;" onclick=Players[' + this.id + '].Play()>' + sImg + '<img class=VidLargePlay id=VidLargePlay' + this.id + ' style=position:absolute;top:' + (this.size.height - 74) / 2 + 'px;left:' + (this.size.width - 84) / 2 + 'px src=' + sStaticURL + 'images/objects/play.png>' + playerobj + '<div class=VideoLoadingOut style=top:' + ((this.size.height / 2) + 60) + 'px dir=rtl> <span style=display:none id=divLoading' + this.id + '>Loading...</span></div></div><div onmouseup=Players[' + this.id + '].ChangePos(($.getMouseCoordsWithinEvent(arguments[0]).x/this.offsetWidth)*100) class=VPos><div id=VideoPosition' + this.id + '></div></div>');
        sHTML.push('<div class=VLine style="background-position:' + (this.size.width / 2 - 20) + 'px -79px">\
	<div onclick=Players[' + this.id + '].ChangeVolume(($.getMouseCoordsWithinEvent(arguments[0]).x/this.offsetWidth)*100) onmousedown=this.move=1;t=this;this.onclick.call();u=arguments[0]; onmouseup=this.move=0;clearTimeout(window.volto); onmousemove=if(this.move)Players[' + this.id + '].ChangeVolume(($.getMouseCoordsWithinEvent(arguments[0]).x/this.offsetWidth)*100)  onmousedown=this.move=1 onmouseout=setTimeout("this.move=0;",100); class=VVol><div class=Line></div><span id=spnVolume' + this.id + '></span>&nbsp;</div>\
	<span class="VMute" id="VMute' + this.id + '" onclick="Players[' + this.id + '].Mute()"></span>\
	<span class="VButton VPlay" id=VPlay' + this.id + ' onclick="Players[' + this.id + '].VPlayPause();"><span></span></span><span class="VButton VStop" onclick="Players[' + this.id + '].Command(\'Stop\');"><span></span></span><span class="VButton VFS" onclick="Players[' + this.id + '].FullScreen()"><span></span></span>\
	</div> <div class=VText ><span class=VMarker id=VMarker' + this.id + '></span><div id=divVidTitle' + this.id + '>' + this.video.title + '</div><img src="/static/images/objects/emptyad.gif" class="playerAdImage" id="playerAdImage' + this.id + '" onclick="Players[' + this.id + '].ImageClicked();" src=""/></div> </div>')
        return sHTML.string();
    },
    //-----------------end of Graphit ---------------------- //
    ShowVolume: function(value) {
        this.log += logFunc("ShowVolume", arguments);
        _('spnVolume' + this.id).style.left = ((value - 6) / 2) + "px";
    },
    ShowMute: function(IsMute) {
        this.log += logFunc("ShowMute", arguments);
        _("VMute" + this.id).style.backgroundPosition = '0 -' + (IsMute ? 10 : 23) + 'px';
    },
    ShowPauseButton: function(state) {
        this.log += logFunc("ShowPauseButton", arguments);
        $("#VPlay" + this.id + " span").css("backgroundPosition", "-" + (state ? 110 : 2) + "px -43px");
    },
    ShowPosition: function(posString) {
        this.log += logFunc("ShowPosition", arguments);
        _("VMarker" + this.id).innerHTML = posString;
    },
    ShowTitle: function(text) {
        this.log += logFunc("ShowTitle", arguments);
        _("divVidTitle" + this.id).innerHTML = text;
    },
    ShowWaitingImage: function(src) {
        this.log += logFunc("ShowWaitingImage", arguments);
        _("imgVideo" + this.id).src = src;
    },
    ShowPositionBar: function(value) {
        this.log += logFunc("ShowPositionBar", arguments);
        _("VideoPosition" + this.id).style.width = (value / 100) * (this.size.width - 20) + "px";
    },
    CheckSL: function(version) {
        this.log += logFunc("CheckSL", arguments);
        try {
            var control = null;
            try {
                control = new ActiveXObject('AgControl.AgControl');
                if (version == null) return true;
                control = null;
            }
            catch (e) {
                if (navigator.plugins["Silverlight Plug-In"]) return true;
            }
        }
        catch (e) {
            return false;
        }
    },
    Command: function(command) {
        this.log += logFunc("Command", arguments);
        var p = _("Player" + this.id);
        if (this.Silverlight) {
            try {
                eval("document.getElementById('Player" + this.id + "').Content.p." + command + '()');
            }
            catch (e) {
                this.log += logError("command","silverlightException","this is silverlight not recognized exception");
            }
        }
        else
            eval("p.controls." + command + "()");
    },
    Play: function() {
        this.log += logFunc("Play", arguments);
        this.log += logVar("Play", "activeUrl", this.UrlSetted);
        //        alert("play \n" + this.log);
        if (!this.UrlSetted)
            this.SetURL(this.ActiveUrl);
        //   $("#imgVideo" + this.id + ",#VidLargePlay" + this.id).hide();
        $("#imgVideo" + this.id).hide();
        $("#Player" + this.id).css("visibility", "");
        this.ShowPauseButton(false);
        this.Command("Play");
    },
    Stop: function() {
        this.log += logFunc("Stop", arguments);
        this.ShowPauseButton(false);
        this.Command("Stop");
    },
    Mute: function() {
        this.log += logFunc("Mute", arguments);
        this.IsMute = !this.IsMute;
        var p = _("Player" + this.id);
        if (this.Silverlight) {
            p.Content.p.Mute(this.IsMute);
        }
        else {
            p.settings.mute = p.settings.mute == true ? false : true;
        }
        this.ShowMute(this.IsMute);
    },
    VPlayPause: function() {
        arguments[arguments.length] = (this.playState);
        this.log += logFunc("VPlayPause", arguments);
        if (this.playState == 3) {//3=playing
            this.ShowPauseButton(false);
            this.Command("Pause");
        }
        else {
            this.Play();
        }
        if (this.AdIn)
            ExectueUrl(this.a.logurl);
    },
    UpdateMP: function() {
        arguments[arguments.length] = (this.playState);
        this.log += logFunc("UpdateMp", arguments);
        var MP = _('Player' + this.id), x, iPos, sPos, playState;
        if (this.Silverlight) {
            if (!this.IsSLLoaded) {
               // alert("problem")
                return false;
            }
            var o = MP.Content.p;
            playState = o.PlayState();
            sPos = o.PositionString().split(",");
            iPos = o.PositionInt();
            sPos = View.AddZero(sPos[0]) + ":" + View.AddZero(sPos[1]) + "/" + View.AddZero(sPos[2]) + ":" + View.AddZero(sPos[3])
        }
        else {
            sPos = (MP.currentMedia ? MP.currentMedia.durationString + " / " : "") + MP.controls.currentPositionString; playState = MP.playState; iPos = (MP.currentMedia ? Math.floor((MP.controls.currentPosition / MP.currentMedia.duration) * 100 + 0.999999999) + 1 : 0);
        }
        if (playState == 2 || playState == 3) {//2=Paused ,3=Playing
            if (!this.Silverlight && !isNaN(iPos) && iPos != Infinity && MP.currentMedia.duration || iPos > 0) {
                this.ShowPositionBar(iPos);
            }
        }
        this.playState = playState;
        this.ShowPauseButton(playState == 3);
        this.ShowPosition(sPos);
    },
    ChangePos: function(value) {
        arguments[arguments.length] = (this.AdIn);
        this.log += logFunc("ChangePos", arguments);
        if (this.AdIn)
            return false;
        MP = _("Player" + this.id);
        if (!this.Silverlight) {
            MP.controls.currentPosition = MP.currentMedia.duration * (value / 100);
        }
        else MP.Content.p.SetPosition(value);
    },
    ChangeVolume: function(value) {
        this.log += logFunc("ChangeVolume", arguments);
        if (value < 10 || !value)
            return;
        value += 5;
        if (value > 100)
            value = 100;
        this.Volume = value;
        if (this.Silverlight)
            _('Player' + this.id).Content.p.SetVolume(value);
        else
            _('Player' + this.id).settings.volume = this.Volume;
        this.ShowVolume(value);
    },
    UpdateImageClickUrl: function(url) {
        this.log += logFunc("UpdateImageClickUrl", arguments);
        this.currImageClickUrl = url;
    },
    ImageClicked: function() {
        this.log += logFunc("ImageClicked", arguments);
        if (this.currImageClickUrl != '') {
            this.Clicked(this.currImageClickUrl);
        }
    },
    UpdateImageAd: function(imagename) {
        this.log += logFunc("UpdateImageAd", arguments);
        var AdImage = _("playerAdImage" + this.id), p = _('Player' + this.id);
        if (AdImage != null) {
            AdImage.src = 'http://194.90.181.246/banners-en-new/' + imagename;
        }
    },
    FullScreen: function() {
        this.log += logFunc("FullScreen", arguments);
        var MP = _("Player" + this.id);
        if (MP.playState == 3 || MP.playState == 2 || MP.playState == 6)//3=Playing , 2= Paused, 6= Buffering
            MP.fullScreen = true;
    },
    IsLoad: function() {
        var arguments = [];
        arguments[0] = (this.playState);
        arguments[1] = (this.id);
        this.log += logFunc("IsLoad", arguments);
        var p = _('Player' + this.id), load = $('#divLoading' + this.id), other = $("#imgVideo" + this.id + ', #VidLargePlay' + this.id);
        if (this.playState) {
            if ((this.playState > 1 || (!this.Silverlight && this.playState == 0)) && this.playState < 5) {//0=Undefined,ps<5=Undefined,Stopped,Pauded,Playing,ScanForward
                load.hide();
                p.style.visibility = this.size.height ? '' : 'hidden';
            }
            else {
                if (this.Silverlight && this.playState != 5 && this.playState != 0 || !this.Silverlight && this.playState != 1 && this.playState != 8 && this.playState != 10)//5=ScanReverse,0=Undefined,1=Stopped,8=MediaEnded,10=ready
                    load.show();
                else
                    load.hide();
                other.show();
                p.style.visibility = 'hidden';
            }
        }
        else {
            load.hide();
            other.show();
            p.style.visibility = 'hidden';
        }
        p.style.height = this.size.height + (this.Silverlight ? 0 : 65) + "px";
        p.style.width = (this.size.width - 20) + "px";
    },
    WriteCSS: function() {
        this.log += logFunc("WriteCss", arguments);
        var headID = document.getElementsByTagName("head")[0];
        var cssNode = document.createElement('link');
        cssNode.type = 'text/css';
        cssNode.rel = 'stylesheet';
        cssNode.href = '/static/slplayer.css';
        cssNode.media = 'screen';
        cssNode.id = 'player_css';
        headID.appendChild(cssNode);
    },
    onWrited: DoNothing,
    onMediaEnded: DoNothing,
    Writed: function() {
        this.log += logFunc("Writed", arguments);
        if (this.WriteCSS) {
            if (_('player_css') != null) { }
            else {
                this.WriteCSS();
            }
        }
        if (this.Silverlight)
            this.IsSLLoad();
        else
            this.Writed2();

    },
    IsSLLoad: function(count) {
        this.log += logFunc("IsSLLoad", arguments);
        if (!count) count = 0;
        if (this.IsWrited === true) {
            this.log += logVar("IsSLLoad", "IsWritted", "IsWritted === true");
            return false;
        }
        try {
            var t = this;
            this.log += logVar("IsSLLoad", "try", "true");
            o = _('Player' + t.id).Content.p.SetVolume(1);
            this.Writed2();
        }
        catch (e) {
            this.log += logError("IsSLLoad", "error", e.name + ":" + e.message);
            this.log += logVar("IsSLLoad", 'count', count);
            this.log += logVar("IsSLLoad", 'id', t.id);
            if (count < 3) {
                count += 1;
                setTimeout("Players[" + this.id + "].IsSLLoad(" + count + ")", 500); //set video 
            } else {
                this.Writed2();
            }
        }
    },
    Writed2: function() {
        //alert("time0");
        this.log += logFunc("Writed2", arguments);
        this.ChangeVolume(this.Volume);
        this.SetVideo(this.video);
        this.IsLoad();
        var t = this;
        this.IsWrited = true;
        //alert("time0.5");
        if (this.Silverlight) {
            jQuery(document).ready(function() { $(".VButton.VFS").hide(); });
        }
        else {
            //  alert(this.TVZone[0])
            if (this.TVZone[0] > 0)
                this.Click = function() {
                    if (Players[this.id].AdIn) {
                        x = window.open(Players[this.id].a.link);
                        if (!x)
                            location.href = Players[this.id].a.link;
                    }
                }
            if (this.TVZone[0] > 0) {
                document.write('<scr' + 'ipt type="text/javascript" for="Player' + this.id + '" event="Click"> var p=_("Player' + this.id + '");for(var  i=0;i<p.currentMedia.attributeCount;i++){var s=p.currentMedia.getAttributeName(i);if(s=="AdUrl") {s=p.currentMedia.getItemInfo(s);Players[' + this.id + '].Clicked(s);break;}}</scr' + 'ipt>')
            }

        }

        this.onWrited();
    },
    Clicked: function(url) {
        this.log += logFunc("Clicked", arguments);
        var a = window.open(url, "icvtAD");
        if (!a)
            location.href = url;
    },
    RemoveTimeFromUrlForEqual: function(url) {
        this.log += logFunc("RemoveTimeFromUrlForEqual", arguments);
        var testurl = url;
        var iTimeIndex = url.indexOf("time");
        if (iTimeIndex > -1) {
            testurl = testurl.substring(0, iTimeIndex);
            var temphalf = url.substring(iTimeIndex);
            var iAmpIndex = temphalf.indexOf('&');
            testurl += temphalf.substring(iAmpIndex);
        }
        return testurl;
    },
    SetURL: function(origurl, notplay) {
        this.log += logFunc("SetURL", arguments);
        this.log += logVar("SetUrl", "id", this.id);
        this.log += logVar("SetUrl", "playerstate", this.playerState);
        this.log += logVar("SetUrl", "url", origurl);
        var url = this.ManageUrl(origurl);

        if (!this.UrlSetted || this.RemoveTimeFromUrlForEqual(url) != this.RemoveTimeFromUrlForEqual(this.ActiveUrl)) {
            this.log += logVar("SetUrl", "CURRENT_NOT_EQUAL", origurl);
            this.ActiveUrl = url; this.UrlSetted = 0;
            if (notplay) return false;
            if (this.Silverlight) {
                try {
                    _('Player' + this.id).Content.p.SetUrl(url);
                }
                catch (error) {
                    // alert("set Url error no id \n" + this.log);
                }

            }
            else _('Player' + this.id).URL = url;
            this.UrlSetted = true;
        }
        else {
            this.log += logVar("SetUrl", "CURRENT_EQUAL", origurl);
        }

    },
    fA: function(a) {
        this.log += logFunc("fA", arguments);
        if (a.url) { this.SetURL(a.url); this.a = a; this.AdIn = true; }
        else { this.SetURL(this.video.url); this.AdIn = false; }
    },
    _media_ended: function() {
        this.log += logFunc("media_ended", arguments);
        this.onMediaEnded();
        this.AdIn = false;
    },
    ReplaceUrl: function(id) {
        this.log += logFunc("ReplaceUrl", arguments);
        try {
            this.IsLoad()
        }
        catch (e) { }
        p = _("Player" + this.id);
        if (this.AdIn) {
            this.AdIn = false;
            this.SetVideo(this.video);
        }
    },
    Changed: function() {
        arguments[arguments.length] = (this.playState);
        arguments[arguments.length] = (this.lastState);
        this.log += logFunc("Changed", arguments);
        this.log += logVar("Changed", "id", this.id);
        p = _("Player" + this.id);
        if (p.Silverlight) { }
        else {
            if (p.playState == 8) {//8=MediaEnded
                this._media_ended();
            }
            else if ((p.lastState == 9) && p.playState == 3) {//9=preparing new media, 3= paused
                var nextAdTest = false;
                for (var i = 0; i < p.currentMedia.attributeCount; i++) {
                    var s = p.currentMedia.getAttributeName(i);
                    if (s == "AdLog") {
                        nextAdTest = true;
                        s = p.currentMedia.getItemInfo(s);
                        ExectueUrl(s);
                    }
                    else if (s == "imageName") {
                        nextAdTest = true;
                        s = p.currentMedia.getItemInfo(s);
                        this.UpdateImageAd(s);
                    }
                    else if (s == "AdUrl") {
                        nextAdTest = true;
                        s = p.currentMedia.getItemInfo(s);
                        this.UpdateImageClickUrl(s);
                    }
                }
                this.AdIn = nextAdTest;
            }
        }
        p.lastState = p.playState;
    },
    ManageUrl: function(origurl) {
        this.log += logFunc("ManageUrl", arguments);
        var url = '';
        if (!this.AdIn && (this.TVZone[0] > 0 || this.TVZone[1] > 0)) {
            url = '/tv/fullscreen2.aspx?time=' + new Date().getTime() + '&zones=' + this.TVZone[0] + ',' +
            this.TVZone[1];
            if (!!origurl && origurl != "") {
                url += '&file=' + origurl;
            }
        }
        else {
            url = origurl;
        }

        if (url.indexOf(":") == -1 && url.indexOf(".aspx") == -1)
            url = "mms://media.israelnn.com/inntv-eng/" + url;

        return url;
    },
    SetVideo: function(video, notplay) {
        this.log += logFunc("SetVideo", arguments);
        this.video = video;
        this.ShowTitle(video.title);
        this.ShowWaitingImage(GetImage(video.image, (this.size.width - 20), this.size.height, false));
        var url = '';
        //        if (!this.AdIn && (this.TVZone[0] > 0 || this.TVZone[1] > 0)) {
        //            url = '/tv/fullscreen2.aspx?time=' + new Date().getTime() + '&zones=' + this.TVZone[0] + ',' +
        //            this.TVZone[1];
        //            if (!!this.video.url) {
        //                url += '&file=' + this.video.url;
        //            }
        //        }
        //        else {
        url = this.video.url;
        //        }
        this.SetURL(url, notplay);
    },
    Dispose: function() {
        this.log += logFunc("Dispose", arguments);
        Players.remove(this.id);
    }
}
//------------------------------------------end of player object--------------------------------------------//
function CheckPState()
{
    this.log += logFunc("CheckPState", arguments);
	var played=false;
	for (var i=0;i<Players.length;i++)
	  if (Players[i]&&Players[i].Writed) {
	    var player = _("Player"+i), p = Players[i], playState;
        try
        {
	       p.UpdateMP();
	    }
	    catch (e){
	       this.log += logError("CheckPState",e.name,e.message);
        }
	    if(p.Silverlight) {}
		if (p.playState==8||(p.playState==4&&p.lastState==3)) {p.ReplaceUrl()}
		if(p.lastState*1 != p.playState*1) {

        p.lastState = p.playState;

}
		p.IsLoad()
		
		if (p.playState>1&&p.playState<8) played=true;
	}
	setTimeout(CheckPState,played?200:1500);
}
setTimeout(CheckPState,1500);
$(document).ready(function () {$('.VVideo').disableSelection();})
