/*
#rtslib.inc /rtslib/browser.js
#rtslib.inc /rtslib/basic.js
*/

// This file has tests. Please check that they are still up and running.
// Feel free to add more of them too, this module needs your love.
if (typeof RTS != 'object')
    RTS = {};
    
// Usually coming from rtslib.js but might be used in a standalone manner
if (typeof log === "undefined")
    var log = function() {};

RTS.player = {
    tsrboutique: "https://www.tsrboutique.ch/commande-emission-tsr.php",
    defaults: {
        swf: (!~document.location.href.search(/^https?:\/\/([^\/]*(ece[^.]*|www)\.)?tsr\.ch/) ? 'http://www.tsr.ch' : '') + 
             "/swf/player.swf?v=2010-05-03b",
        //debug: true,
        width: 640,
        height: 360,
        version: '10',
        wmode: 'transparent',
        expressInstall: '/flash/expressInstall.swf',
        AllowScriptAccess: 'always',
        AllowFullScreen: true
    },
    keys: {
        params: 'play,loop,menu,quality,scale,salign,wmode,bgColor,base,swLiveConnect,flashvars,devicefont,AllowScriptAccess,SeamlessTabbing,AllowFullScreen,AllowNetworking'.split(','),
        attribs: 'id,name,styleclass,align'.split(','),
        reserved: 'swf,id,width,height,expressInstall'.split(',')
    },
    hasBoutique: true,
    players: {},
    streams: {},
    host: "",

    init: function(videoPlays, videoHolders) {
        // Get the cache of media that were preloaded in page
        if (typeof mediaToAdd !== 'undefined') {
            for (var i in mediaToAdd) {
                this.addStream(mediaToAdd[i]);
            }
        }

        this.bindInit(null, videoPlays, videoHolders);
    },
    
    // see video.js
    //additionalPlayOps: function() {},
    //additionalClickOps: function() {},
    
    // Bind the code for the videos
    // If only the content of a container has to be parsed, use argument (useful for dynamically loaded content)
    bindInit: function(container, videoPlays, videoHolders) {
    
        // Disable video injection for iphone
        if (RTS.browser.iPhone){
            return;
        }
        
        // Bind code to every video-play links of the page
        $(videoPlays || $('a.video-play', container)).live('click', function(event) {

            // Ignore right clicks (jquery live bug)
            if (event.button) return;

            var lnk = $(this),
                // Get video target
                vTarget = lnk.attr('data-video-target') || 'video',
                // and ID from link attributes
                vId = lnk.attr('data-video-id'),
                // Get some info from link
                additionalInfo = {
                    'link-date': lnk.find('.date').text(),
                    'link-title': lnk.find('.title').text(),
                    'link-intro': lnk.find('.intro').text()
                };

            // Call the Ajax function
            RTS.player.playVideo(vId, vTarget, additionalInfo);

            return false;
        });

        // Play videos
        $(videoHolders || $('.video-player-holder', container)).each(function() {
            if (!this.id)
                this.id = "player"+new Date().valueOf()

            var vTarget = this.id,
                me = $(this);

            var initOption = {
                width: me.attr('data-video-width'),
                height: me.attr('data-video-height'),
                bigPlay: me.attr('data-video-bigplay')||true,
                bigPlayColor: me.attr('data-video-bigplaycolor')||"0xF20017",
                autoPlay: me.attr('data-video-autoplay')||false
                //autoPlay:false
            };

            initOption.debug = false;

            if (t = me.attr('data-video-image')) initOption.image = t;

            var vId = me.attr('data-video-id');

            RTS.player.playVideo(vId, vTarget, null, initOption);
        });

    },
    addStream: function(s) {
        this.streams[s.video_id] = s;

        if (this.current && typeof this.current.stream.video_id == 'undefined') {
            this.current.stream = this.streams[s.video_id];
        }
    },
    rebuildTargetName: function(p) {
        if (typeof(p) == 'object') {
            if (!p) return;
            if (!p.options) return;
            if (!p.options.target) return;

            //WITHOUTJQUERY
            if (!document.getElementById(p.options.target)) return;
            //if (!$('#'+p.options.target)[0]) return;
            if (p.options.target.indexOf('-') ==-1) return;

            var target = p.options.target;
            var reg = new RegExp("-","g");
            target = target.replace(reg,"_");

            //WITHOUTJQUERY
            document.getElementById(p.options.target).id = target;
            //$('#'+p.options.target)[0].id = target;
            p.options.target = target;
            p.options.name = target;
            p.options.id = target;
            p.attribs.name = target;
            p.attribs.id = target;
            p.vars.target = target;
        } else if (typeof(p) == 'string') {
            var reg = new RegExp("-","g");
            return p.replace(reg,"_");
        }
    },
    injectParentNode: function(p) {
        if (!p) return;
        if (!p.options) return;
        if (!p.options.target) return;
        //WITHOUTJQUERY
        if (!document.getElementById(p.options.target)) return;
        //if (!$('#'+p.options.target)[0]) return;


        //WITHOUTJQUERY
        var node = document.getElementById(p.options.target);
        //var node = $('#'+p.options.target)[0];
        if (!node.parentNode) return;

        var parent = node.parentNode;
        if (parent.className.indexOf('tsrplayer-parent')!=-1) return;

        var pClass = (node.className) ? ' '+node.className : '';
        var pStyle = (node.getAttribute('style')) ? node.getAttribute('style') : '';
        if (typeof(pStyle) =='object') pStyle = pStyle.cssText.toLowerCase();

        pStyle = pStyle.replace(/width *: *[a-zA-Z0-9]{0,} *;/,'')
                       .replace(/height *: *[a-zA-Z0-9]{0,} *;/,'');

        if(p.options.width == '100%' || p.options.height == '100%'){
            pStyle = pStyle+' width:100%;height:100%;';
        }

        var style = 'width:'+p.options.width+'px; height:'+p.options.height+'px; overflow:hidden;'+pStyle;
        if (style.indexOf('margin') ==-1) style += 'margin:auto;';
        
        var itm = $(document.createElement("div")).attr({
                "class": "tsrplayer-parent" + pClass,
                "style": style
            });


        parent.insertBefore(itm[0],node);
        //WITHOUTJQUERY
        parent.removeChild(document.getElementById(p.options.target));
        //parent.removeChild($('#'+p.options.target)[0]);
        itm[0].appendChild(node);
    },
    getPlayer: function(id) {
        var me = this;

        //id = me.rebuildTargetName(id);
        if (id && me.players[id]) {
            me.current = me.players[id];

            return me.current;
        }

        // default player
        var r = {
            options: {},
            stream: {},
            params: {},
            attribs: {},
            vars: {},
            stats: true,
            injected: false,
            inject: function(v) {
                if (!v) v = null;

                this.init();

                // options.target is required
                if (!this.options.target) {
                    log('You must provide a target to inject a player.');
                    return;
                }
                
                this.loadStream(v);

                if (this.stream && this.stream.media.length == 1 && this.stream.media[0].codec == 'h264') {
                        this.options.version = '9.0.115';
                }

                RTS.player.injectPlayer(this);

                this.injected = true;
            },
            play: function(vid) {
                if (!this.injected) {
                    if (this.injected) this.options.autoPlay = true;
                    this.inject(vid);
                    return;
                }
                //WITHOUTJQUERY
                if (document.getElementById(this.options.target).tagName.toLowerCase()!='object' &&
                    document.getElementById(this.options.target).tagName.toLowerCase()!='embed') {
                    if (this.injected) this.options.autoPlay = true;
                    this.inject(vid);
                    return;
                }

                var o = swfobject.getObjectById(this.options.target);

                if (vid)
                    this.loadStream(vid);

                //log("Load data in " + this.options.target);
                if(!o || typeof o.change != 'function')
                    return false;
                //log(this.stream);
                o.change({stream: this.stream, autoPlay: true});
            },
            isPlaying: function() {
                var o = swfobject.getObjectById(this.options.target);
                if(!o || typeof o.isVideoPlaying !== 'function')
                    return false;
                log(this.stream);
                return o.isVideoPlaying();
            },
            init: function(v) {
                // add default options
                for (var k in me.defaults) {
                    if (!this.options[k]) {
                        this.options[k] = RTS.player.defaults[k]
                    }
                }
                // id = name = target
                this.options.id = this.options.name = this.options.target = id;

                // set params, attribs and vars
                for (var k in this.options) {
                    if ($.inArray(k, RTS.player.keys.params) > -1) {
                        this.params[k] = this.options[k];
                    } else if ($.inArray(k, RTS.player.keys.attribs) > -1) {
                        this.attribs[k] = this.options[k];
                    } else if ($.inArray(k, RTS.player.keys.reserved) == -1) {
                        this.vars[k] = this.options[k];
                    }
                }
            },
            loadStream: function(id) {
                if (id && id in RTS.player.streams) {
                    this.stream = RTS.player.streams[id]
                }
            }
        };
        return r;
    },
    getStream: function(id) {
        var p = this.getPlayer(id);
        return p.stream;
    },
    sendToFriend: function(stream) {
		
        var send = $("#video-title .send");
        if(false && send.length) {
            send.click();
        } else if("lightbox" in RTS) {
			
            var a = $(document.createElement("a"));
			
            a.attr("data-width", 510)
             .attr("data-params", "format=lightbox&sendto=show&permalink="+encodeURIComponent(document.location.href))
             .attr("href", "?format=lightbox&sendto=show")
			 .attr("class", "send tsr-lightbox")
             .appendTo("body");

            RTS.lightbox.init(a);

            a.click();
        }
    },
    goShopping: function(stream) {
        var shopLink = $("#shopLink");
        if(shopLink.length) {
            shopLink.click();
        } else {
			if (!'shopParams' in stream) {
				log('shop error: no shopParams in stream');
				return false;
			}
            var shopParams = stream.shopParams,
                form = $(document.createElement("form")),
                input = document.createElement("input");

            for(var param in shopParams) {
                $(input.cloneNode(false)).attr("name", param)
                                         .attr("value", shopParams[param])
                                         .attr("type", "hidden")
                                         .appendTo(form);
            }
            form.attr("action", this.tsrboutique)
                .attr("method", "POST")
                .appendTo("body").submit();
        }
    },
    getRelated: function(stream) {
        if (!this.hasRelated(null))
            return [];
        log('get related videos: ' + RTS.player.related_videos.length);
        return RTS.player.related_videos;
    },
    hasRelated: function(stream) {
        if (typeof RTS.player.related_videos == 'undefined' || typeof RTS.player.related_videos.length == 'undefined')
            return false;
        return RTS.player.related_videos.length > 0;
    },
    hasShopping: function(stream) {
    	//log('has shopping call: ' + ('shopLink' in stream && stream.shopLink != ''));
        return 'shopLink' in stream && stream.shopLink != '';
    },
    hasMail: function(stream) {
        return "lightbox" in RTS;
    },
    // hook called by the Flash player (work in progress)
    playVideoFromAS: function(stream, target) {
        target = target || "mainPlayer";
        // Needs a way to know which is the current player
        if(document.getElementById(target) && "video_id" in stream) {
            // clear cache!
            delete this.streams[stream.video_id];
            this.playVideo(stream.video_id, target);
            return true
        } else {
            return false
        }
    },
    playVideoFromXobixId: function(xId, target) {
        var me = this;
        $.getJSON(this.host+'/?format=json/video&vid='+xId, function(data){
			var id = me.addData(data);
            // Once the stream is added, call playVideo again
            RTS.player.playVideo(id, target);
        });
    },
    /*
    playVideo:      play a video in the page, creates the player if needed (if initOption is given), and load info if needed
    vId:            the ID of the video to play, will load info in AJAX if not available
    vTarget:        the ID / target of the player
    additionalInfo: Additional fields to update in HTML elements when the video is played
    initOption:     to create the player (flash object), initialization options
    */
    playVideo: function(vId, vTarget, additionalInfo, initOption) {
        var me = this;

        if(arguments.length == 1) {
            // this is coming from the actual player (which should call playVideoFromAS)
            return
        }

        if(this.streams[vId]) {
            // Either take given size, or get the parent div's size
            var target = $("#"+vTarget),targetTagName="",w,h,v,c,t;

            if(!target.length)
                target = $("#"+vTarget.replace(/-/g, "_"));
            
            if(!target.length) {
                log("no target found: "+vTarget);
                return
            }

            w = $('#'+vTarget).width();
            h = w / (16/9);

            // 100%, DO NOT WANT!
            if (initOption) {
                if (initOption.width == '100%') initOption.width = null;
                if (initOption.height == '100%') initOption.height = null;

                if (initOption.width) w = initOption.width;
                if (initOption.height) h = initOption.height;
            }

            // Check if player is initalized already
            // TODO: there should be a cleaner way to do this.
            target.each(function(){
                targetTagName = this.tagName.toLowerCase()
            });

            // if (targetTagName != 'object') alert('player '+vTarget+' doesn\'t exist, create one without options.');

            // Play right away if no initOption
            if (!initOption && targetTagName == 'object') {
                RTS.player.playStream(target[0].id, vId);

            // if there is initOption, initlialize the player and inject the video
            } else {
                var p = RTS.player.getPlayer(target[0].id);
                p.options.width = w;
                p.options.height = h;
                p.options.autoPlay = true;
                if (initOption) {
                    
                    p.options.bigPlay = initOption.bigPlay;
                    p.options.bigPlayColor = '0xF20017';
                    p.options.autoPlay = initOption.autoPlay;
                }

                //p.options.debug = true;
                p.inject(vId);
            }

            // Get other info from the XML and insert them into elements with the
            // corresponding class that are in the same container as the player
            v = this.streams[vId];
            c = $('#'+vTarget+'-info');
            for (t in v)
                $('.'+t, c).html(v[t]);

            if (additionalInfo) {
                for(var k in additionalInfo) {
                    $('.'+k, c).html(additionalInfo[k])
                }
            }
            
            t = $(this);
            t.triggerHandler("additionalClickOps", [vId]);
            t.triggerHandler("additionalPlayOps", [v]);
			
							if(c.css('display') == 'none'){
								c.css('display','block');
							}
			
			
        // If video is not loaded, do an AJAX request to load it, then call playVideo again
        } else {
            $.getJSON(this.host+'/?format=json/video&id='+vId, function(data){
				var id = me.addData(data);
                // Once the stream is added, call playVideo again
                if (vId == id)
                    RTS.player.playVideo(vId, vTarget, additionalInfo, initOption);
                else 
                    log('Video ID does not match, play aborted!');    
            });
        }
    },
    addData: function(data) {
        if(!data || !("video" in data) || !("JSONinfo" in data.video)) {
            return false;
        }

        // Get the JSON code of the video object
        var info = data.video.JSONinfo;
        
        RTS.player.related_videos = info.related;

        // Add the stream
        RTS.player.addStream(info);
        
        return info.video_id;
    },
    jsReady: function() {
        return true;
    },
    injectPlayer: function(p) {
        this.rebuildTargetName(p);
        this.injectParentNode(p);
        
        this.players[p.options.target] = p;
        this.current = null;

        swfobject.embedSWF(p.options.swf, p.options.target,
                           p.options.width, p.options.height,
                           p.options.version, p.options.expressInstall,
                           p.vars, p.params, p.attribs);
    },
    playStream: function(pid, vid) {
        pid = this.rebuildTargetName(pid);
        if (!pid || pid && !this.players[pid] ||
            !vid || vid && !this.streams[vid]) return;

        this.getPlayer(pid).play(vid);
    },
    setVolume: function(v) {
        RTS.basic.setCookie('tsrPlayerVolume', v, 60*60*24*365, '/', 'tsr.ch', '');
    },
    getVolume: function() {
        return RTS.basic.getCookie('tsrPlayerVolume');
    },
    setQuality: function(v) {
        RTS.basic.setCookie('tsrPlayerQuality', v, 60*60*24*365, '/', 'tsr.ch', '');
    },
    getQuality: function() {
        var v = RTS.basic.getCookie('tsrPlayerQuality');
        return v;
    },
    stats: {
        currentStream: '',
        currentMedia: null,
        statString: '',
        renommage: '',
        bcVideoId: '0-0',
        format: '',
        wsInfo: {},
        defaults: {
            /* Page */
            compte: 'tsr',
            target: 'embedVideo',
            pageGroup: 'tsrvideo.ch',
            pageName: '',
            frame: 'NOPV',
            parametre: '',
            extranet: '',
            roi: '',
            profil:''
        },
        addDefaultValues: function() {
            for (var k in this.defaults) {
                if (!this.wsInfo[k]) {
                    this.wsInfo[k] = this.defaults[k];
                }
            }
        },
        
        // Main function, with 2 params (player target AND media id)
        register: function(pid, stream) {
            // verifs
            if(!pid) return false;
            if (typeof stream != 'object' || !stream) return false;

            var p = RTS.player.getPlayer(pid);
            if (!p.stats) {
                log('stats is false, ignore');
                return false;
            }
            // Get Player Infos
            this.wsInfo.target = pid;
            this.currentStream = stream;


            // Launch
            this.addDefaultValues();
            if (this.parse()) this.doStats();
            else log('parsing is false, no stats');
        },
        doStats: function() {
            var o = this.wsInfo;

            if (!this.hasVideoStats()) {
                log('#error# player.doStats cannot work: statistique.js?video=1 is not defined');
                return false;
            }

            log("doStats: wysistat("+[o.compte,o.frame,o.parametre,o.extranet,
                                      o.renommage,o.roi,o.profil,o.statString].join(", ")+");");
            if(typeof wysistat !== "undefined")
                wysistat(o.compte, o.frame, o.parametre, o.extranet,
                         o.renommage, o.roi, o.profil, o.statString)
        },
        hasVideoStats: function() {
            var scripts = $.makeArray(document.getElementsByTagName('script'));
            for (var k in scripts) {
                var s = scripts[k].src;
                if (typeof s != 'undefined' && s.indexOf('statistique.js?video=1') != -1) {
                    return true;
                }
            }
            return false;
        },
        parseDate: function(dateTimeSolr) {
            if (!dateTimeSolr) return;
            dateTimeSolr = dateTimeSolr.split('T');
            var aDate = dateTimeSolr.shift().split('-');
            return aDate[2] + aDate[1] + aDate[0];
        },
        removeSpecialChars : function(s) {
            s = s || "";
            var acS = {
                a:/[áàâä]/gi,
                c:/ç/gi,
                e:/[èéêë]/gi,
                i:/[íìîï]/gi,
                o:/[óòôö]/gi,
                oe:/œ/gi,
                u:/[úùûü]/gi,
                y:/[ýÿ]/gi,
                '-':/[\/|]/gi
            };
            for (var l in acS) {
                s = s.replace(acS[l], l);
            }
            return s;
        },
        getFormatByMimeType:function (f) {
            return "WS_VIDEOTYPE_FLASH";
        },
        parse: function() {
            var s = this.currentStream,
                wi = this.wsInfo;
            wi.duration = parseInt(s.duration, 10);
            wi.broadcast_date = this.parseDate(s.broadcast_date);
            wi.title = this.removeSpecialChars(s.title);
            wi.program = this.removeSpecialChars(s.xobix_program_name);
            wi.pageGroup = s.pageGroup ? s.pageGroup : this.defaults.pageGroup;
            wi.renommage = !s.pageNathis ? wi.pageGroup : wi.pageGroup + ';' + s.pageNathis;
            wi.format = s.codec;
            wi.bcVideoId = (s.xobix_broadcast_id || s.video_id) + '-' + s.video_id;
            wi.bitrate = s.bitrate;
            wi.statString = [wi.target,wi.title,wi.program,wi.broadcast_date,
                             wi.format,wi.duration,wi.bitrate,wi.bcVideoId].join("|");
            return !!(wi.title || s.video_id)
        }
    }
};

// Backward compatibility
if(typeof TSR === "undefined") var TSR = {};
TSR.player = RTS.player;
