/**
 * Controller Script for Clip Detail Page
 * @requires jQuery, C4.OO, $.poshTabsLite, $.history, $.outerHtml, $.contractor
 */
 
/*global c4props, document, jQuery, s_account, swfRoot, swfobject */
 
// Implied global
var C4 = C4 || {};

// Episode Detail Page
C4.Controller = (function clipDetailControllerInit($){

    // Constant
    var _ESCAPECHARACTER = '@%_#',

    /**
     * Events Singleton
     */
    Events = {
        ClipDetail: {
            toggleClipInfo: function toggleClipInfo() {
                $(this)
					.find('.playClip, h4')
						.toggle();
                this.guidance.toggle();
            }
        }
    },
    /**
     * Views Singleton
     */
    Views = {
        Clip: {
            buildClipData: function buildClipData($clip){
                return {
                    title: $.trim($clip.find('h3').text()),
                    referenceId: $clip.find('h3').metadata().referenceId,
                    guidance: $.trim($clip.find('.guidance').text()),
                    img: {
                        src: $clip.find('h3').metadata().imgSrc,
                        alt: $clip.find('h3').metadata().imgAlt
                    },
                    img_lrg: {
                        src: $clip.find('h3').metadata().img_lrgSrc,
                        alt: $clip.find('h3').metadata().img_lrgAlt
                    },
                    synopsis: $.trim($clip.find('.synopsis').text()),
                    type: $clip.find('.clipType').text(),
                    duration: $.trim($clip.find('.duration').text()),
                    url: $clip.find('h3').metadata().url,
                    episode: $.trim($clip.find('.episode').text()),
					rating: $clip.find('h3').metadata().rating
                };
            },
            /**
             * Function to serialise brandData to JSON and embed flash into page
             */
            initialiseClipFlash: function initialiseClipFlash(clipData, relatedClipData) {
			var PARAMS = {
	                    salign: "top",
	                    allowFullScreen: "true",
	                    bgcolor: "#FFFFFF",
	                    allowScriptAccess: "always",
                        wmode: "opaque"
                        
	                },
					ATTRIBUTES = {
	                    id: "clipsPlayer"
	                },
					flashvars = {
	                    strQuotesEscapeChar: _ESCAPECHARACTER,
						brandTitle: encodeURIComponent($('#PrimaryContent').find('h1').find('span').text()),
	                    clip: encodeURIComponent($.toJSON(clipData)),
	                    relatedClips: encodeURIComponent("[" + relatedClipData.toString() + "]"),
	                    primaryColor: $.getCssFromClass('flashPrimaryColor', 'color', true),
	                    secondaryColor: $.getCssFromClass('flashSecondaryColor', 'color', true),
	                    invertSkin: $('body').hasClass('invert-skin')
	                };
					flashvars.pinRequestCallback = "C4.PinController.doPinChecks";
					
					swfobject.embedSWF(swfRoot + "asset/flash/swf/clipdetail.swf", "flashContainer", 625, 374, "9.0.115", swfRoot + "asset/flash/swf/expressInstall.swf", flashvars, PARAMS, ATTRIBUTES);
					C4.PinController.setFlashPlayer("clipsPlayer");
            },
            getRelatedClipData: function getRelatedClipData(){
                // Has to be object with nested array for flashvar formatting
                var relatedClipData = [];
                $('#relatedClips')
					.find('li')
						.each(function(){				
                    		relatedClipData.push( $.toJSON( Views.Clip.buildClipData($(this)) ) );
                		});
                return relatedClipData;
            },
            getClipData: function getClipData() {
                return Views.Clip.buildClipData($('#clipInfo'));
            },
			/**
				* Function to remove POSH after Flash is initialised
			*/
            amendClipPOSH: function amendClipDetailPOSH(clipData){
				$("#flashClipWrapper").addClass("flashEnabled");
				// on -page image doesn't exist anymore NCB-2347
				$(document.createElement('img')).attr("src",clipData.img_lrg.src).attr("alt",clipData.img_lrg.alt).appendTo('#flashContainer');
				$('#relatedClips').appendTo('#flashContainer');
				$('#flashClipWrapper').before($('#clipInfo h2')).before('<div class="accessibility">Flash content: <a href="#ClipDetailMainContent">skip to accessible alternative</a></div>');	
            }
        },
        /**
         * Query DOM for Clip data, embed flash and clean-up
         */
        enhanceClip: function enhanceClip(){
			// Remove no-js message
			$('#flashClipWrapper p.noscript').remove();
			// Default Message
			$('#flashContainer').prepend('<p class="info">For more content and an enhanced view of this page <a href="http://get.adobe.com/flashplayer/">click here to install or upgrade Flash</a>. </p>');
				
			var clipData = Views.Clip.getClipData(); // fetch data for swf and non-flash content
			// Inject Flash
			Views.Clip.initialiseClipFlash(clipData, Views.Clip.getRelatedClipData());
			// Hide non-flash content off-screen
			if (swfobject.hasFlashPlayerVersion("9.0.115")) {
				Views.Clip.amendClipPOSH(clipData);
			}else{
				$('#flashClipWrapper').before($('#clipInfo h2'));
			}
        },
        /** 
         * Attach event handlers to Clip List
         */
        enhanceClipList: function enhanceClipList(){
        	//for IE6 as css rollovers are not supported 
			if($.browser.msie && $.browser.version == 6) {	
				$('#clipsList li .guidance').css('display','none');				
				$('#clipsList li').hover(
					function() {
						$(this).find('span').hide();						
						$(this).find('.playClip').show();												
						$(this).find('.overlayBar').hide();																	
						$(this).find('.guidance').css({'position':'absolute',
						                                'left':'0',
						                                'top':'56px',
						                                'width':'392px',
						                                'margin-top':'5px',
						                                'height':'20px'}).show();
						if($(this).find('.guidance').length == 1) {													
							$('div#clipContainer ul.jumpPoints').css('margin-top','26px');
						}
						else {
							$('div#clipContainer ul.jumpPoints').css('margin-top','0');
						}
					}, 
					function() {
						$(this).find('span').show();											
						$(this).find('.playClip').hide();						
						$(this).find('.overlayBar').show();						
						$(this).find('.guidance').hide();
						$('div#clipContainer ul.jumpPoints').css('margin-top','0');					
					}
				);
			}
			/* For all other browsers, set position of guidance bar on clip roll-over */
			else {
				$('#clipsList li .guidance').css({'width':'392px'});
				$('#clipsList li').hover(					
					function() {
						if(!$(this).is(':first-child')) {
							// calculate negative margin			
							$this = $(this);												
							/* Calculate left position of guidance giving negative margin */
							var guidanceLeft = $this.offset().left;
							var ulLeft = $('ul#clipsList').offset().left;
							var marginLeft = (guidanceLeft - ulLeft) * -1;
							/* apply relative negative margin on guidance */
							$(this).find('.guidance').css('margin-left',marginLeft);
						}
					},
					function() {}
				);
			}		
        }
        
    };
    
    // Public init method
    return {
        init: function brandClipDetailController(){
            // Check Dependencies
            C4.OO.insistRequired({
                object: $,
                names: ["history", "poshTabsLite", "outerHtml", "metadata", "setadata", "toJSON"]
            }, {
                object: swfobject,
                names: ["embedSWF"]
            }, {
                object: C4.Brand.Views,
                names: ["buildPocketsAndTabs", "enhanceQuickLinks"]
            });
            // sIFR
            //$.c4font('h1');
            // Initialise Local Views
            Views.enhanceClip();
            Views.enhanceClipList();
			C4.Brand.Views.enhanceRelatedLinksList();
            // Initialise Global Views
			C4.Brand.Views.enhanceQuickLinks();
            C4.Brand.Views.buildPocketsAndTabs();
            C4.Brand.Views.enhanceSponsorship();
            C4.Brand.Views.enhanceBrandPageAds();
            C4.Brand.Views.enhanceComments();
            C4.Brand.Views.enhanceCommentsIE();
            C4.Brand.Views.enhanceJumpPointLinks();
        },
        // pseudo-private getters & setters
		// Return omniture vars for flash
		_getOmnitureVars: function getOmnitureVars(){
            return "s_prop22=" + c4props('vertical') + "|s_account=" + s_account + "|mypage="+document.location.href;
        },
        _set$: function(obj){
            $ = obj;
        },
        _get$: function(){
            return $;
        },
        _setViews: function(obj){
            Views = obj;
        },
        _getViews: function(){
            return Views;
        },
		_setEvents: function(obj){
            Events = obj;
        },
        _getEvents: function(){
            return Events;
        },
        _reset: (function(){
            var ref$ = $, refViews = Views, refEvents = Events;
            return function(){
                $ = ref$;
                Views = refViews;
				Events = refEvents;
            };
        })()
    };
})(jQuery);

