/**
 * This file handles the external Ad Integration with the Brightcove Player.
 *
 * @author Jesse Streb
 * @author Plastic
 */
var player = null;
var experience = null;
var adModule = null;
var videoPlayerModule;
var firstMediaBeginFired = false;

var socialModule = null;

/**
 * An event fired by the Brightcove Player.  Since we have a custom ad integration we register the correct ad formats.
 * @param {Object} message
 */
function onTemplateLoaded(pId){
	player = brightcove.getExperience(pId);
	
	/* BEGIN - added by chris bennett - july 8, 2010
	 * - creates a window-level variable for each API-enabled player so it can be accessed by other scripts (variable name is playerID - reference with: window[playerID])
	 */
	window[pId] = player;
	/* END - added by chris bennett - july 8, 2010 */
	
	BrightcoveTool.fillInAdsAfterBrightcove(pId);
	
	videoPlayerModule = player.getModule(APIModules.VIDEO_PLAYER);
	videoPlayerModule.addEventListener(BCMediaEvent.CHANGE, onMediaEvent);
	
	experience = player.getModule(APIModules.EXPERIENCE);

	experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	//experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);

	modCon = player.getModule(APIModules.CONTENT);
	modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad);

	//experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, updateTitles);
	//modCon.addEventListener(BCContentEvent.VIDEO_LOAD, updateTitles);

	socialModule = player.getModule(APIModules.SOCIAL);
}

function onMediaEvent(evt) {
    if ($("div.page-title h2.video")) {
        var curTitle = videoPlayerModule.getCurrentVideo().displayName;
        $("div.page-title h2.video").html(curTitle);
    }
}


function onVideoLoad(evt){
    var newUrl = BC_site_root + NextUp.getCurrentVideoURL();
    socialModule.setLink(newUrl);
}

function onTemplateReady(){
    try {
        //possibly old:
        //adModule.enableExternalAds(true);
        
        //rest:
        videoPlayerModule = player.getModule(APIModules.VIDEO_PLAYER);
        videoPlayerModule.addEventListener(BCMediaEvent.BEGIN, onMediaBegin);
        videoPlayerModule.addEventListener(BCMediaEvent.COMPLETE, onMediaComplete);
        
        if (typeof(BC_autoplay) != 'undefined' && BC_autoplay) {
            videoPlayerModule.play();
        }
        
        socialModule.setLink(BC_site_root + BC_currenturi + BC_video_sef);
    } 
    catch (e) {
        //gulp
    }
    
    
    //PLASTIC: old code??
    /*
    
     try
    
     {
    
     adModule.enableExternalAds(true);
    
     
    
     //videoPlayerModule = player.getModule(APIModules.VIDEO_PLAYER);
    
     videoPlayerModule.addEventListener(BCMediaEvent.BEGIN, onMediaBegin);
    
     videoPlayerModule.addEventListener(BCMediaEvent.COMPLETE, onMediaComplete);
    
     
    
     //VideoComments.init(experience.getExperienceURL(), videoPlayerModule.getCurrentVideo().id);
    
     //VideoComments.refresh();
    
     
    
     VideoRatings.init();
    
     VideoRatings.refresh();
    
     
    
     } catch (e)
    
     {
    
     //gulp
    
     }
    
     */
    
}

function onMediaBegin(pEvent){

    if (firstMediaBeginFired) {
        //console.log("FIRST MEDIA BEGIN FIRED");
        var currentVideo = videoPlayerModule.getCurrentVideo();
        var html = '';
        html += '<a href="' + SITE_ROOT + '">' + SITE_TITLE + '</a> &raquo; ';
        
        if (PLAYLIST_ID) {
            html += '<a href="' + SITE_ROOT + PLAYLIST_ID + '/' + PLAYLIST_SEF + '/">' + PLAYLIST_NAME + '</a> &raquo; ';
        }
        
        html += currentVideo.displayName
        
        jQuery("#Video-Content h2").html(html);
        
        VideoComments.refresh();
        VideoRatings.refresh();
        NextUp.updateSharingLinks();
        //VideoComments.showFormBox();
    }
    else {
        //console.log("WHO IS calling it?");
        firstMediaBeginFired = true;
        //VideoComments.showFormBox();
        
        VideoRatings.init();
        //VideoComments.init(experience.getExperienceURL(), videoPlayerModule.getCurrentVideo().id);
    }
    
    //PLASTIC: old code??
    /*
    
     if(firstMediaBeginFired)
    
     {
    
     //console.log("FIRST MEDIA BEGIN FIRED");
    
     var currentVideo = videoPlayerModule.getCurrentVideo();
    
     var html = '';
    
     html += '<a href="' + SITE_ROOT + '">' + SITE_TITLE + '</a> &raquo; ';
    
     
    
     if(PLAYLIST_ID)
    
     {
    
     html += '<a href="' + SITE_ROOT + PLAYLIST_ID + '/' + PLAYLIST_SEF + '/">' + PLAYLIST_NAME + '</a> &raquo; ';
    
     }
    
     
    
     html += currentVideo.displayName
    
     
    
     jQuery("#Video-Content h2").html(html);
    
     
    
     VideoComments.refresh();
    
     VideoRatings.refresh();
    
     NextUp.updateSharingLinks();
    
     //VideoComments.showFormBox();
    
     }
    
     else
    
     {
    
     //console.log("WHO IS calling it?");
    
     firstMediaBeginFired = true;
    
     //VideoComments.showFormBox();
    
     
    
     VideoRatings.init();
    
     //VideoComments.init(experience.getExperienceURL(), videoPlayerModule.getCurrentVideo().id);
    
     }
    
     */
    
}

function onMediaComplete(pEvent){
	if ($('.top-story') != null) {
		$('.top-story').trigger('onMediaComplete');
	}
	
	var videoID = NextUp.getNextVideo();
	BC_autoplay = true;
	if (videoID) {
		//VideoComments.init(NextUp.getCurrentVideoURL(), videoID);
		videoPlayerModule.loadVideo(videoID);
	}
  
    //PLASTIC: old code??
    /*
    
     var videoID = NextUp.getNextVideo();
    
     if(videoID)
    
     {
    
     //VideoComments.init(NextUp.getCurrentVideoURL(), videoID);
    
     videoPlayerModule.loadVideo(videoID);
    
     }
    
     */
    
}

var VideoComments = {
    experienceURL: null,
    videoID: null,
    leaveCommentInterval: null,
    leaveCommentCounter: 0,
    
    init: function(pExperienceURL, pVideoID){
        this.experienceURL = pExperienceURL;
        this.videoID = pVideoID;
    },
    
    showFormBox: function(){
    
        //jQuery("div.js-commentControl a").click();
        //VideoComments.leaveCommentCounter = 0;
        //VideoComments.leaveCommentInterval = setInterval(VideoComments.checkForLeaveCommentLink, 500);
        setTimeout("VideoComments.checkForLeaveCommentLink()", 500);
    },
    
    checkForLeaveCommentLink: function(){
        ////console.log("checking for class");
        if (jQuery("div.js-LeaveComment").hasClass("hideMe")) {
            //console.log("has class");
            if (VideoComments.leaveCommentCounter >= 2) {
                //console.log("has had class long enough showing it and stopping");
                $JCA['0'].ShowCommentDialog();
                VideoComments.leaveCommentCounter = 0;
                //jQuery("div.js-commentControl a:first").click();
            }
            else {
                //console.log("checking from counter else");
                setTimeout("VideoComments.checkForLeaveCommentLink()", 500);
            }
            VideoComments.leaveCommentCounter++;
        }
        else {
            //console.log("adding class");
            jQuery("div.js-LeaveComment").addClass("hideMe");
            VideoComments.leaveCommentCounter = 0;
            //console.log("Calling from add else");
            setTimeout("VideoComments.checkForLeaveCommentLink()", 500);
        }
    },
    
    getRootDomain: function(pURL){
        var urlSplit = pURL.split("/");
        
        for (var i = 0; i < urlSplit.length; i++) {
            var urlSection = urlSplit[i];
            if (urlSection.length > 3 && urlSection !== "http:") {
                return urlSplit[i];
                break;
            }
        }
        return;
    },
    
    getURLPath: function(pURL){
        var urlSplit = pURL.split("/");
        var newURL = "";
        
        if (pURL.indexOf("http://") !== -1) {
            for (var i = 3; i < urlSplit.length; i++) {
                newURL += "/" + urlSplit[i];
            }
        }
        else {
            for (var i = 0; i < urlSplit.length; i++) {
                newURL += "/" + urlSplit[i];
            }
        }
        
        return newURL;
    },
    
    refresh: function(){
        //var path = VideoComments.getURLPath(this.experienceURL);
        var path = "/" + this.videoID;
        ////console.log("PATH: "+path);
        ////console.log("PERMALINK: "+VideoComments.getRootDomain(this.experienceURL));
        
        var test = $JCA['0'];
        
        $JCA['0'].config.path = path;
        $JCA['0'].setPath(path);
        $JCA['0'].config.permalink = VideoComments.getRootDomain(this.experienceURL);
        $JCA['0'].jspg.invalidate();
        //$JCA['0'].config.
        //$JCA['0'].ShowCommentDialog();
        $JCA['0'].rerender();
        
        this.showFormBox();
    }
}

var VideoRatings = {
    init: function(){
        jQuery("div.js-ratingWrapper div").each(function(pItem){
            if (jQuery(this).width() == 15 && jQuery(this).height() == 15) //removes that annoying info button
            {
                jQuery(this).remove();
            }
            
            if (jQuery(this).css("left") == "85px" && jQuery(this).css("top") == "-4px") //removes the "add a comment to your rating" box
            {
                jQuery(this).remove();
            }
        });
    },
    
    refresh: function(){
        var path = VideoComments.getURLPath(VideoComments.experienceURL);
        
        $JRA['0'].config.path = path;
        $JRA['0'].setPath(path);
        $JRA['0'].config.permalink = VideoComments.getRootDomain(VideoComments.experienceURL);
        $JRA['0'].rerender();
    }
}


/************************************************************************************
 * Functions to handle the custom ad integration
 ************************************************************************************/
function onExternalAd(pXML){

    //PLASTIC: old code??
    /*
     try {
     var externalAd = new External_Ad(pXML.ad);
     var ad = externalAd.getVideoAd();
     adModule.showAd(externalAd.getVideoAd());
     document.getElementById('CityTv-HeaderBanner').innerHTML = externalAd.getCollapsedAd();
     document.getElementById('CityTv-SquareBanner').innerHTML = externalAd.getExpandedAd();
     } catch (e) {
     adModule.resumeAfterExternalAd();
     }
     */
}


