/*jslint white: false, browser: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */

/*global videos,Translate,jsplayer,flowplayer,gadgets,setup_page,trans,pageTracker*/
var JSPlayer = function (video, lang) {
    // default video is "vid1"
    this.currentvid = video || "vid1";
    // default language is English
    this.lang = lang || "en";
};

/**
 * Set up the prototype for the video player
 */

(function (a) {
    a.prototype.SplashScreen = function () {
        return videos[this.currentvid]["splash"] + "_" + 
            this.lang + ".jpg";
    };
    
    a.prototype.TopBanner = function () {
        return "http://viral.s3.amazonaws.com/players/upintheair/PlayerTopBanner_" + 
                this.lang + ".jpg";
    };

    a.prototype.VideoFile = function () {
        var base = videos[this.currentvid]["url"],
            langext = this.lang;
        if (this.lang === "au") {
            langext = "en";
        }
        return base + "_" + langext + ".mov";
    };

    a.prototype.VideoTitle = function () {
        //TODO: get the correct video
        var title = videos[this.currentvid]["title"];
        return Translate(title,this.lang);
    };

    a.prototype.UniqueID = function () {
        return this.currentvid + "-" + this.lang;
    };

    a.prototype.EmbedCode = function () {
        var embed = "<iframe width=\\\"300\\\" height=\\\"250\\\" src=\\\"" +
                "http://syndication1.viraladnetwork.net/gadgetserver/gadgets/ifr?" +
                "up_lang=" + this.lang +
                "&up_vid=" + this.currentvid +
                "&url=http://viral.s3.amazonaws.com/players/upintheair/upintheairplayer.xml" +
                "\\\"> </iframe>";
        return escape(embed);
    };


    // Callbacks
    a.prototype.RecordViewStart = function () {
        if (!hasplayed) {
            _ADS_ReportInteraction();
            hasplayed = true;
        }
        try {
            pageTracker._trackPageview( this.UniqueID() + "-start" );
        } catch (e){}
    };

    a.prototype.RecordViewEnd = function () {
        try {
            pageTracker._trackPageview( this.UniqueID() + "-end" );
        } catch (e){}
    };

    a.prototype.PluginConfig = function () {
        return {
                 SharePanel:  { 
                    url: 'http://viral.s3.amazonaws.com/players/upintheair/shareoptions.swf',
                    top: '81px',
                    left: '0px',
                    height: "154px",
                    width: "300px",
                    twitterString: Translate("twitterString",this.lang),
                    urlToShare: 'http://www.theupintheairmovie.com/',
                    shareTitle: 'UpInTheAir',
                    display: "none",
                    emailText: Translate("emailText", this.lang),
                    embedText: Translate("embedText", this.lang),
                    trailerText: Translate("trailerText", this.lang),
                    musicVideoText: Translate("musicvideoText", this.lang),
                    embedCodeText: this.EmbedCode(),
                    copypasteText: Translate("copypasteText", this.lang),
                    visitsiteText: Translate("visitsiteText", this.lang),
                    movieUrl: Translate("movieUrl", this.lang),
                    tiptext1: Translate("title1", this.lang),
                    tiptext2: Translate("title2", this.lang),
                    tiptext3: Translate("title3", this.lang),
                    tiptext4: Translate("title4", this.lang),
                    facebookLink: Translate("facebookLink", this.lang),
                    emailCopy: Translate("emailCopy", this.lang)
                 },
                 controls: {
                    height:'24px',
                    time: false
                 },
                ReplayButton: {
                    url: 'http://viral.s3.amazonaws.com/players/upintheair/ReplayButton.swf',
                    top: '15%',
                    left: '50%'
                }
            };
    };

    // API-like functionality

    a.prototype.ShowShareScreen = function () {
        if (this.flowplayer === undefined) {
            this.StartVideo();
            // Give the browser time to respond to DOM changes
            // 
            //
            setTimeout("jsplayer.ShowShareScreen()", 1000);
            return;
        }
        this.flowplayer.pause();
        this.flowplayer.getPlugin("SharePanel").show();
        this.flowplayer.getPlugin("controls").fadeOut();
        this.flowplayer.getPlugin("ReplayButton").fadeIn();
    };

    a.prototype.ShowStartScreen = function () {
        var vp = document.getElementById("videoplayer");
        var image = "" +
            "<div class='splashscreen' style='background:transparent " + 
            "url(" + this.SplashScreen() + ") no-repeat scroll 0 0'>" +
            "<a href='#' " +
            "onclick='jsplayer.StartVideo();return false;'>" +
            "<span id='videotitle'>" +
            " </span></a></div>";
        document.getElementById("videoplayer").innerHTML = image;
        document.getElementById("videotitle").innerHTML = Translate("guideto", this.lang) +
            " " + this.VideoTitle();
    };

    /**
     * (Optional) vidid - switch to a different video
     */
    a.prototype.StartVideo = function (vidid) {
        if (vidid !== undefined) {
            this.currentvid = vidid;
        }
        try {
            document.getElementById("sharebuttontext").style.display = "block";
        }catch(e){}
        // make sure the javascript has loaded
        if (flowplayer === undefined) {
            setTimeout(jsplayer.StartVideo, 100);
            return;
            }
        this.flowplayer = flowplayer( 
         "videoplayer",
         "http://viral.s3.amazonaws.com/players/upintheair/flowplayer-3.1.1.swf",
         { 
         clip: { 
            url:this.VideoFile(),   
            onStart: function (clip) {
                jsplayer.RecordViewStart(); 
                this.getPlugin("play").hide();
                this.getPlugin("controls").fadeIn();
                this.getPlugin("SharePanel").hide();
                this.getPlugin("ReplayButton").hide();
            },
            onFinish:function(clip){
                jsplayer.RecordViewEnd();
                jsplayer.ShowShareScreen();
            },
            onResume:function(clip){
                this.getPlugin("play").hide();
                this.getPlugin("controls").fadeIn();
                this.getPlugin("SharePanel").hide();
                this.getPlugin("ReplayButton").hide();
            }
         },
         play: {replayLabel:""},
         screen: {
            top:"81px",
            height:"129px"
         },
         canvas:{
            background:"url(" + this.TopBanner() + ") no-repeat 0 0",
            backgroundGradient:[0.0]
         },
         plugins: this.PluginConfig()
     });
    };

}(JSPlayer));


/**
 * Translation object
 */

trans = {
   share: {
       en: "SHARE / MORE CLIPS",
       de: "WEITEREMPFEHLEN / MEHR CLIPS",
       fr: "PARTAGER / Plus d\'extraits",
       it: "Condividi /  Altre clip",
       es: "COMPARTIR / MÁS CLIPS"
   },
   guideto: {
       en: "Ryan Bingham\'s Guide to",
       de: "Ryan Binghams",
       fr: "Le Guide de Ryan Bingham",
       it: "La Guida di Ryan Bingham Sul",
       es: "Guía de Ryan Bingham para"
   },
   title1: {
       en: "Travel ",
       de: "Reiseratgeber ",
       fr: "Voyages ",
       it: " Viaggiare  ",
       es: "viajar "
   },
   title2: {
       en: "Work",
       de: "Arbeitsratgeber ",
       fr: "Travail ",
       it: " Lavoro ",
       es: "trabajar "
   },
   title3: {
       en: "Sex",
       de: "Sexratgeber ",
       fr: "Sexe ",
       it: " Sesso ",
       es: "el sexo "
   },
   title4: {
       en: "Love",
       de: "Liebesratgeber ",
       fr: "Amour ",
       it: "lamore ",
       es: "Amar "
   },
   musicvideoText: {
       en: "Music Video",
       de: "Musikvideo",
       fr: "Extrait ",
       it: "Video Musicale ",
       es: "video musical "
   },
   embedText: {
       en: "Embed",
       de: "Embed ",
       fr: "Embed ",
       it: "Embed ",
       es: "incrustar "
   },
   emailText: {
       en: "Email",
       de: "Email ",
       fr: "Email ",
       it: "Email ",
       es: "Correo "
   },
   trailerText: {
       en: "Trailer",
       de: "Trailer ",
       fr: "BA ",
       it: "Trailer ",
       es: "Trailer "
   },
   copypasteText: {
       en: "Copy and paste this code:",
       de: "Diesen Code kopieren und einfügen",
       fr: "Copier et coller ce code",
       it: "Copia ed incolla questo codice",
       es: "copia y pega este código"
   },
   visitsiteText: {
       en: "Visit Site",
       de: "Seite besuchen",
       fr: "Site officiel",
       it: "Vai al sito",
       es: "Visita la web"
   },
   movieUrl: {
       en: "http://www.theupintheairmovie.com/intl/uk/",
       de: "http://www.up-in-the-air.de",
       fr: "http://www.intheair-lefilm.fr",
       it: "http://www.tralenuvole-ilfilm.it",
       es: "http://www.upintheair.es",
       au: "http://www.theupintheairmovie.com/intl/au/"
   },
   facebookLink: {
        en: "http://www.facebook.com/UpInTheAirFilm",
        de: "http://www.facebook.com/UpInTheAir.de",
        fr: "http://www.facebook.com/pages/In-The-Air/136619754682",
        it: "http://www.facebook.com/pages/Tra-le-nuvole/150647933052",
        es: "http://www.facebook.com/upintheairespana",
        au: "http://www.facebook.com/ParamountPicturesAU"
   },
   emailCopy: {
        en: "Hello!\nI just saw some great footage from Up In The Air, the new George Clooney Film. Head to www.theupintheairmovie.com/intl/uk/ for more details about the film!",
        de: "Hi! Ich habe gerade super Filmausschnitte von UP IN THE AIR – dem neuen George Clooney Film – gesehen. Gehe einfach auf www.up-in-the-air.de  für mehr Informationen!",
        fr: "Hello! Je viens juste de voir des super extraits du film \"In the air\" avec george Clooney. Visite le site officiel http://www.intheair.fr pour en savoir plus sur le film !",
        it: "Ciao! Ho appena  visto degli splendidi contenuti di Tra le nuvole, il nuovo film con George  Clooney. Vai su www.tralenuvole-ilfilm.it   per  altri dettagli sul film",
        es: "¡Hola! Acabo de ver un magnífico clip de Up in The Air, la nueva película de George Clooney. Visita http://www.upintheair.es para obtener más detalles sobre la película"
   },
    twitterString: {
        en: "just saw new great footage from Up In The Air www.upintheairtweets.co.uk #uita",
        de: "Ich habe gerade super Filmausschnitte von UP IN THE AIR gesehen. http://www.upintheairtweets.de  #UITAde", 
        fr: "viens de découvrir des nouveaux extraits du film \"In the air\" http://www.intheairtweets.com/  #intheair",
        it: "appena visto degli splendidi contenuti da Tra le nuvole  http://www.tralenuvoletweets.it  #TLN",
        es: "Acabo de ver un magnífico clip de Up in The Air www.upintheairtweets.es  #UITAes",
        au: "just saw new great footage from Up In The Air http://www.upintheairtweets.com.au #UITAau"
    }
};

function Translate(id,lang) {
    // default english
    lang = lang || "en";
    var res = trans[id][lang];
    if (lang == "au" && res === undefined) {
        res = trans[id]["en"];
    }
    if (res != undefined) {
        return res;
    }
    else {
        //Fall back to English - saves space
        return trans[id]["en"];
    }
};

videos = {
    "vid1":   {
        id:"vid1",
        title:"title1",
        splash:"http://viral.s3.amazonaws.com/players/upintheair/PlayerStart1",
        url: "http://viral.s3.amazonaws.com/players/upintheair/travel"
    },
    "vid2":     {
        id:"vid2",
        title:"title2",
        splash:"http://viral.s3.amazonaws.com/players/upintheair/PlayerStart2",
        url: "http://viral.s3.amazonaws.com/players/upintheair/work"
    },
    "vid3":     {
        id:"vid3",
        title:"title3",
        splash:"http://viral.s3.amazonaws.com/players/upintheair/PlayerStart3",
        url: "http://viral.s3.amazonaws.com/players/upintheair/sex"
    },
    "vid4":     {
        id:"vid4",
        title:"title4",
        splash:"http://viral.s3.amazonaws.com/players/upintheair/PlayerStart4",
        url: "http://viral.s3.amazonaws.com/players/upintheair/love"
    },
    musicvid:   {
        id:"musicvid",
        title:"musicvidtitle",
        splash:"",
        url: "http://viral.s3.amazonaws.com/players/upintheair/music"
    },
    trailer:    {
        id:"trailer",
        title:"trailertitle",
        splash:"",
        url: "http://viral.s3.amazonaws.com/players/upintheair/trailer"
    }
};

function setupGA(){
    // Keep Trying to call the initial google analytics code
    try {
        pageTracker = _gat._getTracker("UA-4398741-4");
        pageTracker._trackPageview(jsplayer.UniqueID() + "_load");
    } catch (e) {
        setTimeout(setupGA,100);
    }
}

// ON-LOAD
// post-load the flowplayer-like api
gadgets.util.registerOnLoadHandler( function(){
    setup_page();
    var s = document.createElement('script');
    s.type='text/javascript';
    s.src ='http://viral.s3.amazonaws.com/players/upintheair/flowplayer-3.1.1.min.js';
    document.getElementsByTagName('head')[0].appendChild(s);

    var g  = document.createElement('script');
    g.type = 'text/javascript';
    g.src  = 'http://www.google-analytics.com/ga.js';
    document.getElementsByTagName('head')[0].appendChild(g);
    // Keep trying to load the page
    setTimeout(setupGA,100);

    try{
        document.getElementById("sharebuttontext").style.display = "none";
    }
    catch(e){}
});

