/**
 * Digital Sports Ventures Widget.
 */
var _gaq = _gaq || [];
var dsvWidget = (function()
{
    /**
     * Private variables.
     */
    var failedValidation = false;

    /**
     * Private Method to create the google analytics.
     * @param publisherAppId
     */
    function trackPlayer(publisherAppId)
    {
      _gaq.push(function()
      {
          var pageTracker = _gat._createTracker('UA-2526960-16', 'axnTracker');
          pageTracker._trackEvent('Loaded with URL - JS', publisherAppId, document.location.href);
      });
      (function()
      {
          var ga = document.createElement('script');
          ga.type = 'text/javascript';
          ga.async = true;
          ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
          var s = document.getElementsByTagName('script')[0];
          s.parentNode.insertBefore(ga, s);
      })();
    }

    /**
     * Tracks the Quancast.
     */
    function trackQuancast()
    {
        //- track the quancast js
        var _qevents = _qevents || [];

        (function() {
        var elem = document.createElement('script');
        elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js";
        elem.async = true;
        elem.type = "text/javascript";
        var scpt = document.getElementsByTagName('script')[0];
        scpt.parentNode.insertBefore(elem, scpt);
        })();

        _qevents.push({qacct:"p-14SzMBaE2cnRs"});

        //- append this blank image
        $DSV(document.body).append('<noscript><div style="display:none;"><img src="//pixel.quantserve.com/pixel/p-14SzMBaE2cnRs.gif" border="0" height="1" width="1" alt="Quantcast"/></div></noscript>');
    }

	/**
     * Private Method to load an external script.
     * @param script url
	 * @param call back method
     */
	function loadScript(url, callback)
	{
		var script = document.createElement("script")
		script.type = "text/javascript";

		if (script.readyState){  //IE
			script.onreadystatechange = function(){
				if (script.readyState == "loaded" ||
						script.readyState == "complete"){
					script.onreadystatechange = null;
					callback();
				}
			};
		} else {  //Others
			script.onload = function(){
				callback();
			};
		}

		script.src = url;

        var hasScriptAlready = false;
		var header = document.getElementsByTagName("head")[0];
        for(var i=0; i < header.childNodes.length;i++) {
            var node = header.childNodes[i];
            if(node.src && node.src.indexOf(url) > -1){
                hasScriptAlready = true;
            }
        }

        if(!hasScriptAlready){
            header.appendChild(script);
        }
        else {
            callback();
        }
	}

    /**
     * Loads the css for a given url.
     * @param url
     */
    function loadCss(url)
    {
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", url)
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }

	function loadAds(widgetType,publisherAppId,widgetId)
	{
		var zoneid = null;
		if( widgetType == 'video_bar' ) {
			zoneid = 14;
		}
		if( zoneid ) {
			var m3_u = (location.protocol=='https:'?'https://openx.test.athletixnation.com/www/delivery/ajs.php':'http://openx.test.athletixnation.com/www/delivery/ajs.php');
			var m3_r = Math.floor(Math.random()*99999999999);
			if (!document.MAX_used) document.MAX_used = ',';
			document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u);
			document.write ("?zoneid=" + zoneid);
			document.write ("&amp;publisherAppId=" + publisherAppId);
			document.write ("&amp;widgetId=" + widgetId);
			document.write ('&amp;cb=' + m3_r);
			if (document.MAX_used != ',') document.write ("&amp;exclude=" + document.MAX_used);
			document.write (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));
			document.write ("&amp;loc=" + escape(window.location));
			if (document.referrer) document.write ("&amp;referer=" + escape(document.referrer));
			if (document.context) document.write ("&context=" + escape(document.context));
			if (document.mmm_fo) document.write ("&amp;mmm_fo=1");
			document.write ("'><\/scr"+"ipt>");
		}
	}
	
    /**
     * Validates a property is on the specific type.
     */
    function validatePropertyExists(objectToEval, type)
    {
        if(objectToEval[type] == undefined || objectToEval[type] == null){
            alert('Property not set:' + type + ' and is required for Digital Sports Ventures widget to function.')
            failedValidation = true;
        }
    }

    return {
        
        /**
         * Public Method to create the widget.
         * @param widgetId
         * @param publisherAppId
         */
        init: function (paramObject)
        {
            validatePropertyExists(paramObject, "widgetId");
            validatePropertyExists(paramObject, "publisherAppId");
            validatePropertyExists(paramObject, "widgetType");

            //- Hack for widgets to fix the ? problem.
			if( paramObject['fullPageUrl'] ) {
				if( paramObject['fullPageUrl'].split('?').length <= 1 ) {
					paramObject['fullPageUrl'] += "?";
				}
			}

            //- Use applicationConstants values if set
			if( typeof applicationConstants == 'undefined' ) {
				paramObject['contextRoot'] = "http://ui.digitalsportsventures.com/";
				paramObject['uiContextRoot'] = "http://ui.digitalsportsventures.com/";
				paramObject['videoContextRoot'] = "http://player.athletixnation.com/";
				paramObject['apiUrl'] = "http://api.athletixnation.com/";
			}
			else {			
				paramObject['contextRoot'] = applicationConstants['contextRoot'];
				paramObject['uiContextRoot'] = applicationConstants['uiContextRoot'];
				paramObject['videoContextRoot'] = applicationConstants['videoContextRoot'];
				paramObject['apiUrl'] = applicationConstants['apiUrl'];
			}
			
            //- All params: widgetId, publisherAppId, fullPageUrl, tags, andTags, videoCount, widgetType, headerText, target
            //- Types of widget: horizontal_black_driver, horizontal_black_no_header_driver, horizontal_white_driver
            //- Types of widget cont.: vertical_black_driver, vertical_black_no_header_driver, vertical_white_driver, thumbnail_driver

            if(!failedValidation){
				loadAds( paramObject.widgetType, paramObject.publisherAppId, paramObject.widgetId );
                //Load required resources
                loadCss(paramObject['contextRoot'] + "css/dsv_" + paramObject.widgetType + ".css");
                loadScript(paramObject['uiContextRoot'] + 'js/jquery-1.5.1.custom.min.js', function(){
                    loadScript(paramObject['contextRoot'] + 'js/dsv_' + paramObject.widgetType + ( paramObject['debug'] ? '' : '.min') + '.js', function(){

                        //Ensure page is loaded completely, plugin is loaded, and jquery is loaded with our custom namespace
                        if(window.$DSV != undefined){
                            $DSV(document).ready(function(){
                                //Init the controller object
                                if($DSV()["dsv_" + paramObject.widgetType]){
                                    $DSV("div#" + (paramObject['target'] || 'dsv_' + paramObject.widgetType + "_" + paramObject.widgetId))["dsv_" + paramObject.widgetType](paramObject);
                                }
                            });
                        }
                    });
	                trackQuancast();
                });

                trackPlayer(paramObject.publisherAppId);
            }
        }
  };
})();
