/**
*
* Postmedia Inline Ad PLayer
*
* @description this loads and displays the Postmedia Slice Player
*
* @class SliceLoader
* @namespace PmVids
* @Player v. 03-20-2015
*
*/
var PmVids = PmVids || {};
PmVids.Loader = PmVids.Loader || {};
jQuery.noConflict();
if (window.SliceBootloaderCount === undefined) {
    window.SliceBootloaderCount = 0;
}
if (window.SliceBootloaderJSLoaded === undefined) {
    window.SliceBootloaderJSLoaded = false;
}    
PmVids.Loader.SlicePlayer = (function ($) {
    var Config = {
        type: "PmSlice",
        name: "SlicePlayer",
        isProduction : "true",
        domain : "calgaryherald.com",
        adType: null,
        analytics : {          
            streamSenseBaseUrl : "http://b.scorecardresearch.com/p?c1=2&c2=16433038",
            dfpCmsId : "1141"
        },
        cat: {
            ck:"news",
            sck: "politics"
        },       
        assets : {
            "path": "http://app.canada.com/video/assets/",
            "core": [
                "//wurfl.io/wurfl.js",
                "http://app.canada.com/video/assets/js/pmvids-utils.js?03-20-2015",
                "http://app.canada.com/video/assets/js/pmvids-adserver.js?03-20-2015"
            ],
            "scripts": [                                
                "//imasdk.googleapis.com/js/sdkloader/ima3.js",
                "http://app.canada.com/video/assets/js/pmvids-sliceplayer.js?03-20-2015",
                "http://app.canada.com/video/assets/js/pmvids-slicepercent.js?03-20-2015"
            ],
            "flashScripts":[                
                "http://app.canada.com/video/assets/js/lib-swfobject.js",
                "http://app.canada.com/video/assets/js/pmvids-flash-sliceplayer.js?03-20-2015",
                "http://app.canada.com/video/assets/js/pmvids-slicepercent.js?03-20-2015"
            ]
        },
        player:{
            videoId:"",
        },
        slice: {
            id: "",
            target: "SlicePlayer",
            insertNode: "#SlicePlayer",
            parentNode: ".entry-content",
            parentContainer: "SlicePlayerParentContainer",
            pCount:"5",
            container:"SlicePlayerContentElement",
            mainContainer:"SlicePlayerMainContainer",
            isFlash: false
        },
        ad:{
            url: null,
            params: null,
            tag: null,
            width: null,
            height: null,
            size: "321x241",                        
            loc: "slice",
            container: "SlicePlayerAdContainer"
        },
        startTime: new Date()
    };
    
    function PreLoad(){
        BootLoader(Config.assets.core, function () {        
            PreLoadCheck();            
        });
    }
    function PreLoadCheck(){
        
        SetLogging();
        SetAdServer();        
        if (PlayAd() == true) {
            var insertNode = GetInsertDiv(".entry-content", 5);
            
            if (insertNode){
                SetIMASDKType();
                AddVideoPlayer(insertNode);
                Loader();
                Config.slice.insertNode = insertNode;
            }else{
                Log("PmSlice: No Suitable Target found on page.");
            }
        }
    }    
        
    function AddVideoPlayer(node) {
        $(node).before('
');
        Log("PmSlice: Video Construct on Page: " + PmVids.Utils.ReportTime("SlicePlayer"));
        SetPlayer();
    }
        
    function SetIMASDKType(){
        
        if(PmVids.Utils.IsNotIE()){
            //Use HTML5 IMA SDK                
        } else {
            //Use FLASH IMASDK
            Config.slice.isFlash = true;
            Log("PmSlice: IE Browser detected, using Flash version of IMA SDK");
        }
    }
    function SetLogging(){
        //Set Logging Level
        PmVids.Utils.SetIsProduction(true);
    }
    function SliceIt() {               
        
        PmVids.SlicePlayer.Init("SlicePlayer");
        ShowLogs();
    }   
    function PlayAd() {
        var playAd = false;
        //if($(".breadcrumb.sponsored").length == 0 && $("a.feature01").length == 0){
            if(!WURFL.is_mobile){                      
            
                if(PmVids.AdServer.configured != false){
                    if(PmVids.Utils.AreCookiesEnabled() === true){
                        if(!PmVids.Utils.GetCookie("slicePlayed")){     
                        
                            playAd = true;
                        }  else {                        
                            Log("PmSlice: User Quota exceeded for day.");
                        }                            
                    
                    }else{
                        Log("PmSlice: Cookies Diabled.");
                    }                
                     
                }
            }else {
                Log("PmSlice: Mobile Device Detected.");
            }
        //}else{
        //    Log("PmSlice: Sponsored content detected.");
        //}                 
        return playAd;
    } 
    function GetInsertDiv(parentNode, pMax){
        var insertNode = null, defaultNode = $("#SlicePlayer");
        if(defaultNode.length){
            insertNode = defaultNode;
            Log("PmSlice: InsertNode found at ID #SlicePlayer" );
        } else if(parentNode != "" && parentNode != null) {
            var pNode = $(parentNode);
            if(pNode.length){
                var paraInsertPoint =  $(pNode).find( 'p:eq(' + pMax + ')' );
                if(paraInsertPoint.length){
                    insertNode = paraInsertPoint;
                    Log("PmSlice: InsertNode found at paragraph " + pMax + " of .entry-content" );
                }
            }
        }
       
        return insertNode;
        
    }
    function SetPlayer(){
        //debugger;
        var vNode = $("#SlicePlayerMainContainer");
        var aNode = $("#SlicePlayerAdContainer");
        var w = vNode.parent().width(),
            h =  Math.floor((w/16)*9);
        
        vNode.css( 'width', w );
        vNode.css('height', h);
        aNode.css( 'width', w );
        aNode.css('height', h);
        Config.ad.width = w;	  
        Config.ad.height = h;
    }
    function SetAdServer(){
        var ad = PmVids.AdServer.GetVideoAd('SlicePlayer', Config);
        if(ad == undefined || ad == "" || ad == false || ad == null){
            
            PmVids.AdServer.configured = false;            
        } else {
            Config.ad.url = ad.url;
            Config.ad.params = ad.params;
            Config.ad.type = ad.type;
            Config.ad.tag = Config.ad.url + "&cust_params=" + Config.ad.params;
        }
    }
    function BootLoader(array, callback) {
        var loader = function ( url, callback ) {
            var head = document.getElementsByTagName("head")[0] || document.documentElement;
            var script = document.createElement("script");
            script.src = url;
	
            // Handle Script loading
            var done = false;
	
            // Attach handlers for all browsers
            script.onload = script.onreadystatechange = function() {
                if ( !done && (!this.readyState ||
                        this.readyState === "loaded" || this.readyState === "complete") ) {
                    done = true; 
                    if( typeof callback == 'function'){
                        callback();
                    }
	
                    // Handle memory leak in IE
                    script.onload = script.onreadystatechange = null;
                    if ( head && script.parentNode ) {
                        head.removeChild( script );
                    }
                }
            };
	
            // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
            // This arises when a base node is used (#2709 and #4378).
            head.insertBefore( script, head.firstChild );
        };
        (function () {
            if (array.length != 0) {
                loader(array.shift(), arguments.callee);
            } else {     
                callback && callback();
            }
        })();
    }
    function Loader() {
        window.SliceBootloaderCount++;
        
        //Check for IE - if true load flash player scripts
        var scripts = Config.assets.scripts;
        if(Config.slice.isFlash){
            scripts = Config.assets.flashScripts;
        }
        if(window.SliceBootloaderCount == 1) 
        {
            BootLoader(scripts, function () {
                window.SliceBootloaderJSLoaded = true;
                SliceIt();
            });
        }
        else
        {
            function LoopMe() {
                if(window.SliceBootloaderJSLoaded===false) { 
                    setTimeout(LoopMe, 10); //wait 10 milliseconds then recheck
                    return;
                }
                //console.log("[[[[[[[ Bootloader Not Needed ]]]]]]]");
                SliceIt();
            }
            LoopMe();
        }
    }
    function ShowLogs(){
        
        PmVids.Utils.SetIsProduction(true);
        Log("PmSlice: PM Slice Files Loaded" + PmVids.Utils.ReportTime("SlicePlayer"));
        
    }
    function Log(msg, type) {
        PmVids.Utils.Log(msg, type);
    }
    PreLoad();
    
        
    return {
        Config: Config
    }
})(jQuery);