/*****************  BRIGHTCOVE VIDEO HOLDER *****************/
bcVideoHolderClass = function() {
	this.videoSet = {};
//	console_log("---- BCVIDEOHOLDER INIT ----");
};
bcVideoHolderClass.prototype.addVideo = function(videoID, bcVideoObj) {
	this.videoSet[videoID] = bcVideoObj;
//	console_log(" Adding video "+videoID);
};
bcVideoHolderClass.prototype.getVideo = function(videoID) {
	return(this.videoSet[videoID]);
};
bcVideoHolderClass.prototype.getVideoComponent = function (videoID, componentName) {
	var videoObj = this.videoSet[videoID];
	if (videoObj == null) {
		return(null);
	}
	if (componentName == "player") {
//		console_log(videoObj);
		var playerComponent = videoObj.getModule(APIModules.VIDEO_PLAYER);
		return(playerComponent);
	}
	return(null);
};
bcVideoHolderClass.prototype.dumpAllVideos = function() {
	// console_log(this.videoSet);
};
var bcVideoHolder = new bcVideoHolderClass(); // instantiate a singleton
// called when template loads, this function stores a reference to the player and modules.
// will be executed for each player that has been configured with API = yes
function onTemplateLoaded(experienceID) {
    console_log('called onTemplateLoaded');
	bcExp = brightcove.getExperience(experienceID);
	bcVideoHolder.addVideo(experienceID, bcExp);
    console_log('setting mouseover in otl');
    $('#feature li.current img').delay(2000).mouseover(function(){
        $(this).hide();
    });
}

// setup ul
var mpstart;
var fpnew;
var liwidth = 214; // 204px width plus 10px margin
var lilength = $('#feature li').length; // count total # of li's
var ulwidth = (liwidth * lilength)+525; // add 500 to give room for featured item to expand
var fuloffset;
$('#feature ul').css('width', ulwidth);
var pageWidth = $('body').width();
$('#feature li').hide();
var isAllowedAction = {
	prevNext: false
};
var isIE = false;
if (navigator) {
	if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") > -1) {
        console_log(navigator.userAgent);
		isIE = true;
	} 
}

function isAllowedPrevNext() {
    console_log('called isAllowedPrevNext');
	return(isAllowedAction.prevNext);
}
function releasePrevNext() {
    console_log('called releasePrevNext');
	isAllowedAction.prevNext = true;
}
function blockPrevNext() {
    console_log('called blockPrevNext');
	isAllowedAction.prevNext = false;
}

function featureFSControl() { // controls 660px+ feature behaviors
    console_log('called featureFSControl');
	
	//$('<img class="loading" src="/extension/adcouncil/design/adcouncil/images/loading.gif" alt="" />').appendTo('#feature'); // load in js so we're not fetching unneeded content
	featureLaunchCurrent = $('#feature li.current');
	viewMoreToggle(); // enable behavior for the view more button next to the featured slide
	$('#view-more').hide();

	balanceElements();

	// load the slideshow and initialize the functions
	$('#feature ul').css('height','0px').delay('300').animate({
		height:'156px' // grow the slideshow ul
	}, 400, function() {
		//$('.loading').fadeIn('fast').delay('500').fadeOut('fast'); // fade out the loading graphic
		$(this).find('li').delay('700').fadeIn('slow').each(function() {$('<span class="img-select"></span>').appendTo(this);}); // simple fix to keep images from being ged
		setTimeout("animateFeatureToCenter()",1000); // delay centering the current slide until the fadeIn is finished
		setTimeout("animateFeature(featureLaunchCurrent)", 1000); // add the little more delay before showing the current slide for sparkle
	});

	featureNavInit(); // add feature control next/prev arrows
	var featureTimout = 0;

	$("#feature li").stop().click(function(e) {
		if ($(this).hasClass('current')) {return;} // prevents feature from toggling when play button is clicked

        $('#feature li').removeClass('current');
        featureHide(); // close the current feature

        if (!$(e).hasClass("active")) { // make sure the active feature isn't retoggled
            $(this).addClass('current');
            verifyBCVideosAreLoaded();
            animateFeatureToCenter(); // center's the new slide
            animateFeature(this); // start the slide animation
        } else {
            // nothing
        }
    });
	//$("#fslideshow").fadeIn("slow");	
}

function verifyBCVideosAreLoaded($obj){
    $obj = $("#feature li.current");
    console_log($obj);
    // load the BC video
    var currentBcVideoHTML = $obj.children('div.feature-media').children('div.bc-holder').html();
    console_log('Checking BC Video, Current BC HTML = ' + $.trim(currentBcVideoHTML));
    if (!$.trim(currentBcVideoHTML)){
        console_log("No Content, Reloading BC Video");
        var bcID = $obj.children('div.feature-media').children('div.bc-holder').attr('bcid');
        $obj.children('div.feature-media').children('div.bc-holder').load("/layout/set/ajax/content/view/hp/" + bcID, function() { brightcove.createExperiences(); fadeInVideo(); });
    } else {
        console_log("Had Content No BC Reload Necessary");
    }
}

/*
 * function featureNavInit
 *
 *  Set up the next/prev controls for the piece
 *
 */
function featureNavInit() {
    console_log('called featureNavInit');
	$('<a class="next">Next</a> <a class="prev">Previous</a>').appendTo('#feature');
	$('.next').click(function() {
		if (isAllowedPrevNext()) {
			blockPrevNext();
			$('#feature .current').next().each(function() {
				$('#feature .current').removeClass('current');
	    		featureHide(); // close the current feature
			    $(this).addClass('current');
			    animateFeatureToCenter('next'); // centers the new slide
			    animateFeature(this); // start the slide animation
			});
		} else {
//			console_log("blocked next.");
		}
	});
	$('.prev').click(function() {
		if (isAllowedPrevNext()) {
			blockPrevNext();
            thing = $('#feature .current').prev();
			$('#feature .current').prev().each(function() {
				$('#feature .current').removeClass('current');
	    		featureHide(); // close the current feature
			    $(this).addClass('current');
			    animateFeatureToCenter('prev'); // center's the new slide
			    animateFeature(this); // start the slide animation
			});
		} else {
//			console_log("blocked prev.");
		}
	});
}


/*
 * function calculateFeatureOffset
 *
 *  Calculate the amount that the feature needs to be shifted to be centered
 * 
 */
function calculateFeatureOffset(indexOffset){
    console_log('called calculateFeatureOffset');
	var featureContainerCenter = ($('#feature').width())/2; // 760-1200p
    var featureStripWidth = $('#feature ul').width(); // approx 1900px
	
	var pageWidth = $('body').width();
	if (pageWidth < '660') {
		var featureCurrentWidth = pageWidth/2;
	} else {
		var featureCurrentWidth = '380'; // used to offset the main feature
	}

    var featureCurrentIndexRaw = $('#feature .current').index();
    var featureCurrentIndex = featureCurrentIndexRaw;// + indexOffset;
	var featureLocationCurrent = featureCurrentIndex * 214; // 214 is 1/2 width of full-size feature content
    var featureLocationNew = (featureContainerCenter - featureLocationCurrent)-featureCurrentWidth; 
	return featureLocationNew;
}

/*
 * function animateFeatureToCenter
 *
 *  Animante the selected element to the center
 */
function animateFeatureToCenter(direction) {
    console_log('called animateFeatureToCenter');
    var featureLocationNew = calculateFeatureOffset(1);
    $('#feature ul').animate({
        left: featureLocationNew
    }, 600, 'swing');
}

/*
 * function featureResizeCenter
 *
 *  Animate the 0th element to the center
 *
 */
function featureResizeCenter() {
	console_log('called featureResizeCenter');
  var featureLocationNew = calculateFeatureOffset(0);
      $('#feature ul').css({
        left: featureLocationNew
    });
}


/*
 *
 * function balanceElements()
 *
 *  This balances the elements around the current selected element by
 *  moving the dom elements with jquery
 *
 */
function balanceElements() {

    // skew is where the selected element should appear relative to the center of the list
    // -1 would move the element to the left one of center, causing there to be more elements
    // on the right by one
    var skew = -1;

    // calc the real middle of the list, subtract one to make 0-based to match the index.
	var trueMiddle = Math.ceil($("#feature li").length / 2) - 1;

    // grab the index of the current selected element (this is already updated as it runs post-animation)
	var current = $('#feature li.current').index();

    // find how many elements we need to shift to get current to the correct place
    // +/- value determines which direction
	var distToTrueMiddle = trueMiddle-current;

    // calculate if we need to append or prepend the items we move
    var action = distToTrueMiddle < 0 ? 'append':'prepend';
    
    // now that we have a action that determines direction, add the skew and lose any - value we may have
    var shiftAmt = Math.abs(distToTrueMiddle + skew);

    console_log('current was '+current+' centered would be '+trueMiddle+' the diff is '+distToTrueMiddle+' so action is now '+action+' '+shiftAmt+' elements');
   
    // move the elements
    for(i = 0; i<shiftAmt; i++){
        if(action == 'prepend'){
            console_log('prepending one');
            $('#feature li:first').before($('#feature li:last'));
        }else{
            console_log('appending one');
            $('#feature li:last').after($('#feature li:first'));
        }
    }
}

/*
 *
 * function animateFeature
 *
 *  This animates the selected feature, calling animateDrawer as appropriate
 *
 */
function animateFeature(e) {
    console_log('called animateFeature');
    verifyBCVideosAreLoaded();
    $('#feature li.current img').show();
	$("#fslideshow li.current > h2").slideUp();
	$(e).find('.description').hide();

	// animate the feature sliding into place
	$(e).delay('400').animate({
		top: '-40px',
		marginBottom:'-40px',
		height: '240px',
		width: '427px'
	}, 400, function() {
		    adjustVideo($(e), 'restore');
		$(e).addClass('active');
		
        // if wide enough to matter, slide out the drawer
		pageWidth = $(document).width();
		if (pageWidth > '600') {
            animateDrawer($(e), 'open');
		}
        releasePrevNext();
    });
}


function adjustVideo($obj, direction){
    console_log('called adjustVideo');
    if(!direction) direction = 'restore';
    if(direction == 'restore'){
        $('#feature li.current img').show();
        if(isIE == true){
            console_log('thought was IE, setting mouseover in adjustVideo');
            $('#feature li.current img').mouseover(function(){
                $(this).fadeOut();
            });
        }
    }else{
        $('#feature li.active img').show();
		var $playerHolder = $('#feature li.active .bc-holder'); // get the div handle
		var playerId = "myExperience_"+$playerHolder.attr('bcid')+"_"+$playerHolder.attr('holderid');
		var playerComponent = $('#'+playerId);
		if (playerComponent != null) {
			playerComponent.stop();
		}
    }
}

function animateDrawer($obj, direction){
    console_log('called animateDrawer');
    if(!direction) direction = 'open';
    if(direction == 'open'){
        $obj.addClass('active2');
        $obj.animate({
            width: '640px'
        }, 300, function() {
            $(this).find('.description').show();
            $("#fslideshow li.current > h2").show();
            $(this).find('.img-select').fadeOut();
            $('#view-more').delay('300').fadeIn();
            balanceElements();
            featureResizeCenter();
        });
    }else{
        $obj.find('h2').hide();
        //console_log($('#feature li').length);
        $obj.animate({
            top: '0',
            width: '204',
            height: '156'
        }, 300, function() {
            $obj.find('.img-select').fadeIn();
            $obj.find('h2').slideDown();
        });
        $obj.removeClass('active').removeClass('active2');
    }
}

function featureHide() { // hide the current feature
    console_log('called featureHide');
	// hide the view more pulldown menu, unrelated to actual features
	$('#view-more ul').slideUp();
	$('#view-more h3').removeClass('active');
	$('#view-more').hide();
    $obj = $('#feature li.active');
    console_log($obj);


    // get video and stop it
    $('#feature li.active div.feature-media img').show();
    console_log($('#feature li.active div.feature-media img').unbind('mouseover'));
	// then deal with the feature
	if ($('#feature li').hasClass('active')) {
        $(this).css('width', '420');
    }
	// before animating, in IE, show image, hide and "unload" video
    adjustVideo('', 'unload');
	// then remove all signs that this is active, and animate down to inactive size
    animateDrawer($obj, 'close');
}

function viewMoreToggle() {
	console_log('called viewMoreToggle');
	$('#view-more ul').slideUp();
	$('#view-more h3').click(function() {
	    if ($(this).hasClass('active')) {
	        $(this).removeClass('active');
			$('#view-more ul').slideUp('fast');
	    } else {
	        $(this).addClass('active');
	        $('#view-more ul').slideDown('fast');
		}
	});
}

function console_log(msg){
    //console.log(msg);
}

