if( typeof(jQuery) != 'function' ) document.write('<scr'+'ipt type="text/javascript" src="http://www.bhg.com/bhg/files/videoplayer/grab/ramp.jquery.js"></scr'+'ipt>');
if( !GRAB ) document.write('<scr'+'ipt type="text/javascript" src="http://vcl.grabnetworks.com/assets/scripts/core/libraries/com.grabnetworks.core.js"></scr'+'ipt>');
var _gpIsIe = /*@cc_on!@*/false;
var mdp = mdp || {app:{}};
mdp.endScript = mdp.endScript || null;
if( _gpIsIe && mdp.endScript ) document.write('<script type="text/javascript" src="'+mdp.endScript+'"></script>');
var GRAB = GRAB || null; /**** requires grab ****/



/*

mdp.GrabDataHandler = new mdp.app.GrabDataHandler( 'mdp.GrabDataHandler' );
mdp.loadPlaylistIntoGrab = function( obj ){

    console.log('\n\n     loadPlaylistIntoGrab');

    var s = encodeURIComponent( jQuery.json.serialize(obj.videos) );
    GRAB.mediaos.core.ui.component.list.draw.call(document.createElement('div'),s,'grab-vcl-list', 'meredith-interactive-vcl-player',obj.videos.length,'true','true','','my-vcl-list')
};

setTimeout(function(){/*console.log('load nav');mdp.GrabDataHandler.getVideosFromCatalogByVideoIds( 67, [4253468,4252946,4252946,4253232,4253313,4253314], 'mdp.loadPlaylistIntoGrab');},10000);


 */
mdp.app.GrabDataHandler = function( ref ){
    var _ref, _nc, _errorCount, _videoCount, _callback, _videos, _timeout, _playlistTitleObj, _playlistReceived, _playlistTitleObjOrder, _videoPlaylistHash,_apiPath,_domain;

    function GrabDataHandler(){
        _ref = ref;
        _videos = [];
        _videoCount = _errorCount = 0;
        _callback = null;
        _timeout = 0;
        _playlistTitleObj = [];/* [{vi:393939, plTi:'playlist title'}]*/
        _playlistTitleObjOrder = [];
        _playlistReceived = false;
        _videoPlaylistHash = {};
	_nc = false;
	_domain = 'http://www.bhg.com';
	_apiPath= "/partners/grab/grabApi.jsp";
    }

	this.setDomain = function(s){
		_domain = s;
	}

	function getApiURL(){return _domain + _apiPath;}

    this.checkComplete = function(){
        if( _callback != null ){
            eval( _callback + '([' + _videos + ']);');
            /*
            console.log(_callback);
            */
            _videos = [];
            _videoCount = 0;
            _callback = null;
            _playlistTitleObj = [];
            _playlistReceived = false;
        }
    };

	this.nc = function(b){
		_nc = b;
	};

	function getNc(){
		return _nc;
	}

    /**
     *
     * @param pId Int
     * @param callback string
     * this is a hack - but it will get us the videos from a playlist
     */
    this.getVideosByPlaylistId = function( pId, callback ){
        /*
        console.log('getVideosByPlaylistId');
        */

        _callback = callback;
        jQuery.ajax({
           type: "GET",
           url: getApiURL(),
           dataType: "script",
           data: "action=titlesForPlaylist&actionId="+pId+"&callback="+ callback + (getNc() ? "&nc=true" : "")
         });
    };

    /**
     *
     * @param catId int
     * @param vidIdArray array of ints
     * @param callback string of function name
     */
    this.getVideosFromCatalogByVideoIds = function( catId, vidIdArray, callback ){
        var i = 0, vi, ci, s="";
        _videoCount = vidIdArray.length;
        _callback = callback;
        for( i=0; i<vidIdArray.length; i++){
            ci = catId;
            vi = vidIdArray[i];
            if( vidIdArray[i]['ci'] && vidIdArray[i]['vi'] ){
                ci = vidIdArray[i]['ci'];
                vi = vidIdArray[i]['vi'];
            }
			s+=','+vi+':'+ci;
        }
		jQuery.ajax({
		   type: "GET",
		   url: getApiURL(),
		   dataType: "script",
		   data: "action=titleList&actionId="+s.substr(1)+"&callback="+ callback + (getNc() ? "&nc=true" : "")
		 });
    };

    /**
     * Public interface for getPlaylistFromCatalogByVideoIds
     * @param catId int
     * @param vidIdArray array of ints
     * @param callback string of function name
     */
    this.getPlaylistFromCatalogByVideoIds = function( catId, vidIdArray, callback ){
        getPlaylistFromCatalogByVideoIds ( catId, vidIdArray, callback );
    };

    /**
     * Public interface for getPlaylistFromCatalogByVideoIds
     * @param catId int
     * @param vidIdArray array of ints
     * @param callback string of function name
     */
    this.getPlaylistData = function( obj ){
        /*
        console.log("getPlaylistData");
        console.log(obj);
        /**/
        _playlistTitleObj = obj;
        jQuery.ajax({
           type: "GET",
           url: getApiURL(),
           dataType: "script",
           data: "methodUrl=/playlists/"+obj.playlist.id+"/videos&limit="+obj.playlist.playlist_items_count+"&callback="+_ref + ".playlistResult" + (getNc() ? "&nc=true" : "")
         });
    };

    /**
     *
     * @param catId
     * @param vidIdArray
     * @param callback
     */
    var _leftOvers = {};
    function getPlaylistFromCatalogByVideoIds ( catId, vidIdArray, callback ){
        /*
        console.log("getPlaylistFromCatalogByVideoIds");
        /**/
        _playlistTitleObjOrder = [];
        var i = 0, vi, ci,s="";
        _videoCount = vidIdArray.length;
        _callback = callback;
        for( i=0; i<vidIdArray.length; i++){
            ci = catId;
            vi = vidIdArray[i];
            if( vidIdArray[i]['ci'] && vidIdArray[i]['vi'] ){
                ci = vidIdArray[i]['ci'];
                vi = vidIdArray[i]['vi'];
                _playlistTitleObjOrder.push({video:{id:vidIdArray[i]['vi'],catalog:{id:vidIdArray[i]['ci']}}});  
                _leftOvers[vidIdArray[i]['vi']] = false;
            } else {
                _playlistTitleObjOrder.push({video:{id:vidIdArray[i],catalog:{id:catId}}});
                _leftOvers[vidIdArray[i]] = false;
            }
			s+=','+vi+':'+ci;
        }
		jQuery.ajax({
		   type: "GET",
		   url: getApiURL(),
		   dataType: "script",
		   data: "action=titleList&actionId="+s.substr(1)+"&callback="+ callback + (getNc() ? "&nc=true" : "")
		 });
    }

    /**
     *
     * Used as a call back for getVideosByPlaylistId
     */
    this.playlistResult = function( obj ){
       /*
       console.log('playlistResult');
       console.log(obj);
       /**/
        _playlistTitleObjOrder = obj;
        var cat = obj[0].video.catalog.id;
        var arr = [];
        for( var i = 0; i<obj.length; i++ ) {
            arr.push({vi:obj[i].video.id,ci:obj[i].video.catalog.id});
        }
        getPlaylistFromCatalogByVideoIds(cat,arr,_callback);
    };

    /**
     *
     * Used as a call back for getVideosFromCatalogByVideoIds
     */
    this.videoIdResult = function( obj ){
        /*
        console.log('videoIdResult');
        /**/
        _videoCount--;
        _videos.push( obj.result );

        if( _videoCount == 0 ){
            clearTimeout( _timeout );
            eval( _callback + '([' + _videos + ']);');
            /*
            console.log(_callback);
            */
            _videos = [];
            _videoCount = 0;
            _callback = null;
        } else {
            clearTimeout( _timeout );
            _timeout = setTimeout(_ref+'.checkComplete();', 3000);
        }
    };

    /**
     *
     * Used as a call back for getPlaylistFromCatalogByVideoIds
     */
    this.playlistIdResult = function( obj ){

        /*console.log('playlistIdResult');
        /**/
        _videoCount--;
        if( !obj.error ){
            var newObj = obj;
                if( !_leftOvers[newObj.video.id] ) _leftOvers[newObj.video.id] = true;
                newObj.video['classification_id'] = null;
                /*newObj.video['embargo_date'] = '';*/
                newObj.video['source_name'] = newObj.video.provider.name;
                /*newObj.video['updated_at'] = '';*/
                /*newObj.video['duration'] = '';*/
                newObj.video['in_time'] = '';
                if( typeof( _playlistTitleObj ) == 'object' && typeof( _playlistTitleObj.playlist ) == 'object' && _playlistTitleObj.playlist['name'] != '' ){
                    newObj.video['playlist_name'] = _playlistTitleObj.playlist.name;
                } else {
                    newObj.video['playlist_name'] = '';
                }
                /*newObj.video['keywords'] = '';*/
                newObj.video['master_stream_uri'] = '';
                newObj.video['network_name'] = newObj.video.catalog.name;
                /*newObj.video['id'] = '';*/
                /*newObj.video['custom_fields'] = '';*/
                /*newObj.video['out_time'] = '';*/
                newObj.video['bookmarked'] = null;
                newObj.video['show_id'] = null;
                /*newObj.video['copyright'] = null;*/
                /*newObj.video['title'] = '';*/
                newObj.video['master_filmstrip_uri'] = '';
                newObj.video['distribution_id'] = newObj.video.id;
                /*newObj.video['participants'] = '';*/
                /*newObj.video['short_description'] = '';*/
                newObj.video['provider_name'] = newObj.video.provider.name;
                newObj.video['categorizations'] = null;
                newObj.video['status'] = null;
                newObj.video['source_icon'] = newObj.video.provider.small_logo;
                newObj.video['container_sequence'] = null;
                newObj.video['originated_at'] = '';
                newObj.video['provider_id'] = newObj.video.provider.id;
                /*newObj.video['container_id'] = '';*/
                /*newObj.video['is_available'] = true;*/
                /*newObj.video['classification_name'] = '';*/
                newObj.video['master_id'] = newObj.video.video_product_id;
                newObj.video['network_id'] = newObj.video.catalog.id;
                /*newObj.video['expiration_date'] = '';*/
                /*newObj.video['created_at'] = '';*/
                newObj.video['preview_url'] = newObj.video.media_assets[0].url;
                newObj.video['summary'] = '';
                newObj.video['thumbnail_url'] = newObj.video.media_assets[1].url;
                /*newObj.video['external_id'] = '';*/
                /*newObj.video['show_name'] = '';*/
                newObj.video['is_published'] = true;

                if(newObj.video.id) _videoPlaylistHash[ newObj.video.id ] = jQuery.json.serialize( newObj );

        } else {
            _errorCount++;
            /*console.log('   error');
            /**/
        }
            /*console.log('   _videoCount:' + _videoCount);
            /**/

            if( _videoCount == 0 ){
                cleanUpPlaylistOrder();
                clearTimeout( _timeout );
                eval( _callback + '([' + _videos + ']);');

                /*
                console.log(_callback);
                */
                _videos = [];
                _videoCount = 0;
                _callback = null;
            } else {
                clearTimeout( _timeout );
                _timeout = setTimeout(_ref+'.checkComplete();', 3000);
            }
    };

    function cleanUpPlaylistOrder(){
        /*
        console.log('cleanUpPlaylistOrder');
        console.log(_playlistTitleObjOrder.length - _errorCount);
        console.log(_videos);
        console.log(_playlistTitleObjOrder);
        /**/
        var n = _playlistTitleObjOrder.length,i=0,o=0;
        while( i<n ) {
            if( _leftOvers[_playlistTitleObjOrder[i].video.id] ) {
                _videos[o] = _videoPlaylistHash[_playlistTitleObjOrder[i].video.id];
                o++;
            }
            i++;

        }
        
        return;
    }

    GrabDataHandler();

};


/**
 *
 * Put the following into a second file
    mdp.gp = new mdp.app.GrabPlayer( "mdp.gp" );
    var template = '<div id="grab-vcl-broadcast"><div id="grab-vcl-broadcast-main">[PLAYER]<div id="grab-vcl-broadcast-main-extras"><div id="grab-vcl-broadcast-videos">[PLAYLIST]</div><div id="grab-vcl-broadcast-guide">[GUIDE]</div></div></div><div id="grab-vcl-broadcast-sidebar"><div id="grab-vcl-meta"><h4 id="grab-vcl-meta-videoTitle"></h4><p id="grab-vcl-meta-videoSummary"></p></div><div id="grab-vcl-companion_300x250"></div><div id="grab-vcl-search-block"><h4>Search</h4>[SEARCH]</div></div></div>';
    var config = {
                    player   : {width:300,height:250},
                    list     : {display:true,howManyToDisplay:10},
                    guide    : {display:true,guideId:38,listId:158368},
                    search   : {display:true,howManyToDisplay:10},
                    title    : 'videoTitle-div',
                    desc     : 'videoSummary-div',
                    random   : false,
                    template : template,
                    apikey   : null
                 };
    document.write( mdp.gp.initGrabPlayer( config ) );

 */

mdp.app.GrabPlayer = function( ref ){
    /**** vars ****/
    var _is_listLoaded, _is_playerLoaded, _registeredPlayer, _registeredList, _videoLoaded, _initialVideoLoaded, _initialListLoaded;
    var _ref, _loadingAnimationWrapper, _loadingAnimationElement;
    var _playerName, _playerDivId, _playlistName, _playlistDivId, _channelsName, _channelsDivId, _searchDivId;
    var _playlistTitleId, _playlistKeywordsId;
    var _videoHeadlineId, _videoSummaryId, _videoDescriptionId, _videoPubdateId, _videoThumbnailId, _videoPreviewImageId;
    var _ak,_op, _currentVideoSeconds, _callbacks, _random, _firstload,_obj, _loadVideoId;
    var _ad_kw, _ad_frmt, _ad_sb, _ad_comp_ad, _currentAsset;
    var _omnitureObject, _omnitureSet, _videoPlayerName, _isOmnitureAvailable;
    var _poll, _autoLoadFirstVideo;
    /**** constructor ****/
    function GrabPlayer(){
        _ref = ref;
        _playerDivId = "grab-vcl-flash";
        _playerName = "meredith-interactive-vcl-player";
        _playlistDivId = "grab-vcl-list";
        _playlistName = "my-vcl-list";
        _channelsName = "grab-vcl-channels";
        _loadVideoId = _videoLoaded = _is_listLoaded = _is_playerLoaded = _initialVideoLoaded = _initialListLoaded = false;
        _registeredPlayer = _registeredList = _loadingAnimationWrapper = _loadingAnimationElement = undefined;
        _obj = _playlistTitleId = _playlistKeywordsId = _currentAsset = _channelsDivId = _searchDivId = null;
        _videoHeadlineId = _videoSummaryId = _videoDescriptionId = _videoPubdateId = _videoThumbnailId = _videoPreviewImageId = null;
        _ak = 'fb6c5973e905d7480d925f640ec6bf54';
        _op = '';
        _callbacks = [];
        _firstload = true;

		_autoLoadFirstVideo = true; /* loads the first video in a playlist */

		_autoLoadFirstVideo = true; /* loads the first video in a playlist */

        /* advertising */
        _ad_kw = 'na';
        _ad_frmt = 'na';
        _ad_sb = 'bhg';
        _ad_adType = 'n';

        /* omniture */
        _videoPlayerName = 'grabplayer';
        _poll = -1;
        _isOmnitureAvailable = false;
        _omnitureSet = false;
        _omnitureObject = {};
        _startPoll();

GRAB.mediaos.servers.vcl.domain = null;
        GRAB.mediaos.core.ui.component.player.draw = function(_asset, _class, _playerId, _skinId, _target, _remote_address, _server_name, _communityShortUrl, _engine, _videoObject, _customizations, _relatedAssets, _options){

            var
                swf_url = undefined,
                videoObject = eval( "(" + unescape(_videoObject) + ")" ).video,
                customizations = _customizations,
                autoplay = undefined, mdp_i;

            /* Begin VCL advertising object parsing. */
            try {
                var adVariableGroupRef = '';
                for (var ad_unit_index in _options.view.player.options.advertising.units){
                        var ad_unit = _options.view.player.options.advertising.units[ad_unit_index];
                    for(var ad_variable_group_index in ad_unit.variableGroups){
                        /* if - check to see if this is in our array */
                        if(ad_variable_group_index < ad_unit.variableGroups.length){
                        var ad_variable_group = ad_unit.variableGroups[ad_variable_group_index];
                            adVariableGroupRef += ad_variable_group.name + "={";
                            for (var ad_variable_group_var_index in ad_variable_group.variables){
                                /* if - check to see if this is in our array */
                                if(ad_variable_group_var_index < ad_variable_group.variables.length){
                                    var adVariableGroupVar = ad_variable_group.variables[ad_variable_group_var_index];
                                        adVariableGroupRef += "'" + adVariableGroupVar.name + "':'" + adVariableGroupVar.value + "'";
                                        adVariableGroupRef = adVariableGroupRef.replace( "''", "','" ); // insert a separator when there are multiple key/vals present
                                } /* end if - check to see if this is in our array */
                            }
                            adVariableGroupRef += '}' + '&';
                        }
                        /* end if - check to see if this is in our array */
                    }
                }
            } catch (e) {
                var adVariableGroupRef = '';
            }

            try {
                var zoneId = _options.view.player.options.advertising.units[0].zone_id;

                if (zoneId != ''){
                    var ad_zone_ref = 'companion_zone_id=' + _options.view.player.options.advertising.units[0].zone_id + '&';
                } else{
                    var ad_zone_ref = '';
                }
            } catch (e) {
                var ad_zone_ref = ''
            }

            /* End VCL advertising object parsing. */

            try {
                autoplay = ( _options.view.player.options.autoplay == 'on' ) ? true : false;
                swf_url = 'http://'+ GRAB.mediaos.servers.cube.domain +'/swf/cube.swf?'+ad_zone_ref+adVariableGroupRef+'resourceDNS=player.grabnetworks.com&autoplay='+ autoplay +'&jskey=' + _skinId + '&namespace=GRAB.mediaos.core.ui.events&eventhandler=flashExternal&playerid=' + _playerId + '&remoteaddr=' + _remote_address + '&servername=' + _server_name+ '';
            } catch ( error ) {
                autoplay = false;
                // we exclude the overridden parameter 'autoplay' altogether so that the player ignores it
                swf_url = 'http://'+ GRAB.mediaos.servers.cube.domain +'/swf/cube.swf?'+ad_zone_ref+adVariableGroupRef+'resourceDNS=player.grabnetworks.com&jskey=' + _skinId + '&namespace=GRAB.mediaos.core.ui.events&eventhandler=flashExternal&playerid=' + _playerId + '&remoteaddr=' + _remote_address + '&servername=' + _server_name+ '';
            }

            // if we detect related assets then draw the list
            if ( _relatedAssets ) {
                var div = document.createElement('div');

                div.className = 'related-list';
                div.setAttribute('class','related-list');
                GRAB.mediaos.core.ui.component.list.draw.call( div, _relatedAssets, _target, _playerId, 5 );
            }

            switch(_engine) {
                case 'gmos':
                    var player__ = this;
                    this.setAttribute('name', _playerId);
                    this.name = _playerId;
                    this.setAttribute('id', _playerId);
                    this.id = _playerId;
                    this.setAttribute('width', _options.view.player.width);
                    this.width=_options.view.player.width;
                    this.setAttribute('height', _options.view.player.height );
                    this.height=_options.view.player.height;

                    this.setAttribute('type','application/x-shockwave-flash');
                    this.setAttribute('className', 'grab-video-engine');
                    this.setAttribute('class', 'grab-video-engine');
                    this.data = swf_url;
                    this.setAttribute('data', swf_url);

                    this.movie = swf_url;
                    var param_movie = document.createElement('param');
                    param_movie.setAttribute('name','movie');
                    param_movie.setAttribute('value',swf_url);
                    this.appendChild(param_movie);

                    this.src = swf_url;
                    var param_src = document.createElement('param');
                    param_src.setAttribute('name','src');
                    param_src.setAttribute('value',swf_url);
                    this.appendChild(param_src);

                    this.allowScriptAccess = 'always';
                    var param_scriptaccess = document.createElement('param');
                    param_scriptaccess.setAttribute('name','allowScriptAccess');
                    param_scriptaccess.setAttribute('value','always');
                    this.appendChild(param_scriptaccess);

                    this.base = '.';
                    var param_base = document.createElement('param');
                    param_base.setAttribute('name', "base");
                    param_base.setAttribute('value','.');
                    this.appendChild(param_base);

                    this.wmode = 'transparent';
                    var param_wmode = document.createElement('param');
                    param_wmode.setAttribute('name', "wmode");
                    param_wmode.setAttribute('value','transparent');
                    this.appendChild(param_wmode);

                    this.allowFullScreen = 'true';
                    var param_fullscreen = document.createElement('param');
                    param_fullscreen.setAttribute('name', "allowFullScreen");
                    param_fullscreen.setAttribute('value','true');
                    this.appendChild(param_fullscreen);

                    this.scale = 'default';
                    var param_scale = document.createElement('param');
                    param_scale.setAttribute('name', "scale");
                    param_scale.setAttribute('value','default');
                    this.appendChild(param_scale);
                    break;
                case 'osmf':
                    this.setAttribute('name', _playerId);
                    this.setAttribute('id', _playerId);
                    this.setAttribute('width', _options.view.player.width);
                    this.setAttribute('height',_options.view.player.height);
                    this.setAttribute('allowFullScreen', 'true');
                    this.setAttribute('type','application/x-shockwave-flash');
                    this.setAttribute('class', 'grab-video-engine');
                    this.setAttribute('data','http://'+ GRAB.mediaos.servers.vcl.domain +'/assets/dino/flash/osmf_player.swf?namespace=GRAB.mediaos.core.ui.events&eventhandler=flashExternal&playerid=' + _playerId + '&remoteaddr=' + _remote_address + '&servername=' + _server_name+ '');

                    var param_movie = document.createElement('param');
                    param_movie.setAttribute('name','movie');
                    param_movie.setAttribute('value','http://'+ GRAB.mediaos.servera.vcl.domain +'/assets/dino/flash/osmf_player.swf?namespace=GRAB.mediaos.core.ui.events&eventhandler=flashExternal&playerid=' + _playerId + '&remoteaddr=' + _remote_address + '&servername=' + _server_name+ '');
                    this.appendChild(param_movie);

                    var param_src = document.createElement('param');
                    param_src.setAttribute('name','src');
                    param_src.setAttribute('value','http://'+ GRAB.mediaos.servers.vcl.domain +'/assets/dino/flash/osmf_player.swf?namespace=GRAB.mediaos.core.ui.events&eventhandler=flashExternal&playerid=' + _playerId + '&remoteaddr=' + _remote_address + '&servername=' + _server_name+ '');
                    this.appendChild(param_src);

                    var param_scriptaccess = document.createElement('param');
                    param_scriptaccess.setAttribute('name','AllowScriptAccess');
                    param_scriptaccess.setAttribute('value','always');
                    this.appendChild(param_scriptaccess);

                    var param_base = document.createElement('param');
                    param_base.setAttribute('name', "base");
                    param_base.setAttribute('value','http://'+ GRAB.mediaos.servers.vcl.domain +'/assets/dino/flash/');
                    this.appendChild(param_base);

                    var param_wmode = document.createElement('param');
                    param_wmode.setAttribute('name', "wmode");
                    param_wmode.setAttribute('value','transparent');
                    this.appendChild(param_wmode);

                    var param_fullscreen = document.createElement('param');
                    param_fullscreen.setAttribute('name', "allowFullScreen");
                    param_fullscreen.setAttribute('value','true');
                    this.appendChild(param_fullscreen);

                    var param_scale = document.createElement('param');
                    param_scale.setAttribute('name', "scale");
                    param_scale.setAttribute('value','default');
                    this.appendChild(param_scale);
                    break;
                case 'html5':
                    // to be implemented
                    break;
                default:
                    //
                    break;
            }

            this["_type"] = {
                _class: "player",
                _spec: _class,
                _engine: _engine
            };

            /* Auto Target */

            // find the currently executing script element
            //var currScriptElement = document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
            var currScriptElement = document.getElementById('grab-vcl-video-player-script');

            // find that scripts parent element
            var currScriptParent = currScriptElement.parentNode;

            // create a container to size the player properly
            var containerElement = document.createElement('DIV');
            containerElement.style.position = 'relative';
            containerElement.style.top = 0;
            containerElement.style.left = 0;
            containerElement.style.width = _options.view.player.width + 'px';
            containerElement.style.height = _options.view.player.height + 'px';

            currScriptParent.insertBefore( containerElement, currScriptElement );

            // add the new DIV into that parent element
            var targetElement = document.createElement('DIV');
            targetElement.id = _options.target.id;
            targetElement.className = _options.target.classReference;

            containerElement.appendChild( targetElement );

            // add the Flash object element to the target
            targetElement.appendChild( this );

            /* End Auto Target */
            this["_states"] = {};

            // begin register autoplay reactor
            this._states['autoplay'] = autoplay;
            // end register autoplay reactor

            // tell the player to initially load an asset or remain blank
            try {
                this._states['loadByDefault'] = ( _options.view.player.options.loadByDefault == 'true' ) ? true : false;
            } catch (e) {}

            // tell the player to initially load an associated list's first asset
            try {
                this._states['loadFirstListItem'] = ( _options.view.player.options.loadFirstListItem == 'true' ) ? true : false;
            } catch (e) {}

            try {
                // clean the ad variable group value to format it back to proper JSON
                this._states['advertising'] = {};
                this._states['advertising']['variables'] = {};
                this._states['advertising']['variables']['static'] = ( adVariableGroupRef.length > 1 ) ? adVariableGroupRef.substring( adVariableGroupRef.indexOf( '{' ), adVariableGroupRef.lastIndexOf( '&' ) ) : null;
            } catch(e) {}

            GRAB.mediaos.core.registry.utils.register(this);
            var playerResetSuccessful = GRAB.mediaos.core.ui.component.player.reset.call(this, videoObject, _communityShortUrl);

            GRAB.mediaos.core.ui.component.player.controls.draw(_target, this);
            GRAB.mediaos.plugins.analytics.google.trackEvent('VCL', 'INIT', 'PLAYER', 1, 'sender', 'draw');
        };

        /* hack into grab to get the current seconds */
        var updateMethodHack = GRAB.mediaos.core.ui.events._updateTime;
        GRAB.mediaos.core.ui.events._updateTime = function( _playerId, _secs ){
            _currentVideoSeconds = _secs;
            updateMethodHack( _playerId, _secs );
        };

        /* hack into grab to get the first video object */
        var initialVideoDataHack = GRAB.mediaos.core.ui.component.player.draw;
        GRAB.mediaos.core.ui.component.player.draw = function( _asset, _class, _playerId, _skinId, _target, _remote_address, _server_name, _communityShortUrl, _engine, _videoObject, _customizations, _relatedAssets, _options ) {
            _currentAsset = eval( "(" + unescape(_videoObject) + ")" ).video;
            initialVideoDataHack.call( this, _asset, _class, _playerId, _skinId, _target, _remote_address, _server_name, _communityShortUrl, _engine, _videoObject, _customizations, _relatedAssets, _options );
        };

        /**/
    }

    /**** public ****/
    this.initGrabPlayer = function( obj ) {
        var player, playlist, guide, search;
            player = playlist = guide = search = '';

        _obj = obj;

        if( typeof( obj['apikey'] ) === 'string' ) _ak =obj['apikey'];

        if( typeof( obj['random'] ) === true ) _random =true;

        if( typeof( obj['player'] ) === 'object' ){
            if( obj['player'] ){
                player += '\n';
                player += '<div id="grab-vcl-flash">';
                /*"advertising": {"units": [{"delivery": "inline", "zone_id": "test-companion", "variableGroups": [{"variables": [{"name": "grab", "value": "networks"}], "name": "custom_ad_keyvals"}]}]}, "autoplay":"off"*/
                var playerCode = '<scr'+'ipt id="grab-vcl-video-player-script" type="text/javascript" src=\'http://vcl.grabnetworks.com/mediaos/vcl/component/player.js?options={"key":"' + _ak + '","target":{"id":"grab-vcl-flash-player", "classReference":"grab-single-asset"},"view":{"player":{"id":"meredith-interactive-vcl-player",      '+( obj['player']['videoId'] ? '"asset":"' + obj['player']['videoId'] + '", ' : '' )+'           "type":"single-asset","width":"' + ( obj['player']['width'] ? obj['player']['width'] : '604' ) + '","height":"' + ( obj['player']['height'] ? obj['player']['height'] : '341' ) + '","engine":{"name":"gmos"},"options":{'+( obj['player']['videoId'] ? '' : ' "loadByDefault":"false", ' )+' "advertising": {"units": [{"delivery": "inline", "zone_id": "banner300x250", "variableGroups": [{"variables": [' + ( _ad_frmt != '' && _ad_frmt!= null ? '{"name": "frmt", "value": "' + _ad_frmt + '"},' : '' ) + ( _ad_kw != '' && _ad_kw != null ? '{"name": "kw", "value": "'+_ad_kw+'"},' : '' ) +(_ad_sb!='' && _ad_sb != null ? '{"name": "sb", "value": "'+_ad_sb+'"},':'')+ (_ad_adType!='' && _ad_adType != null ? '{"name": "c", "value": "'+_ad_adType+'"}':'')+'], "name": "custom_ad_keyvals"}]}]}, "autoplay":"off"}}}}\'></scr'+'ipt>';
                player += playerCode;
                player += '</div>';

                if( config['player']['videoId'] ) _loadVideoId = true;
            }
        }

        player += '\n<div id="grab-vcl-list" style="display:none;"><div id="my-vcl-list"></div></div>';

        if( typeof( obj['search'] ) === 'object' ){
            if( obj['search'] ){
                search += '\n';
                search += '<div id="grab-vcl-search">';
                search += '  <scr'+'ipt type="text/javascript" src=\'http://vcl.grabnetworks.com/mediaos/vcl/component/search.js?options={"key":"' + _ak + '","view":{"search":{"sender":"grab-vcl-search"    ,"count":"' + ( obj['search']['howManyToDisplay'] ? obj['search']['howManyToDisplay'] : '10' ) + '" }},"target":"my-vcl-list"}\'></scr'+'ipt>';
                search += '</div>';
            }
        }

        _videoHeadlineId        = obj['title'] || _videoHeadlineId;
        _videoSummaryId         = obj['summary'] || _videoSummaryId;
        _videoDescriptionId     = obj['desc'] || _videoDescriptionId;
        _videoPubdateId         = obj['pubDateId'] || _videoPubdateId;
        _videoThumbnailId       = obj['videoThumbnailId'] || _videoThumbnailId;
        _videoPreviewImageId    = obj['videoPreviewImageId'] || _videoPreviewImageId;

        _playlistTitleId        = obj['playlistTitleId'] || _playlistTitleId;
        _playlistKeywordsId     = obj['playlistKeywordsId'] || _playlistKeywordsId;

        if( obj['template'] ){
            _op = obj['template'];
            _op = _op.replace( '[PLAYER]', player );
            _op = _op.replace( '[PLAYLIST]', playlist );
            _op = _op.replace( '[GUIDE]', guide );
            _op = _op.replace( '[SEARCH]', search );
        } else {
            _op = player + playlist + guide + search;
        }

        return _op;
    };

    this.setAdParams = function( sb, kw, frmt, adType ){
        _ad_kw = kw || _ad_kw;
        _ad_frmt = frmt || _ad_frmt;
        _ad_sb = sb || _ad_sb;
        _ad_adType = adType || _ad_adType;

        /* for adap */
        _ad_adType == 'none' ? _ad_adType = 'n' : _ad_adType;
        _ad_adType == 'both' ? _ad_adType = 'b' : _ad_adType;
        _ad_adType == 'post' ? _ad_adType = 'o' : _ad_adType;
        _ad_adType == 'pre' ? _ad_adType = 'p' : _ad_adType;
    };

    this.videoPlayerName = function( videoPlayerName ){
        _videoPlayerName = videoPlayerName;
    };

    this.loadAsset = function( asset ) {
        _loadAsset( asset );
    };

    this.playerName = function( playerName ) {
        _playerName = playerName;
    };

    this.playlistName = function( playlistName ) {
        _playlistName = playlistName;
    };

    this.setAutoLoadFirstVideo = function(b) {
        _autoLoadFirstVideo = b;
    };

    this.getFirstListItem = function() {
        _getFirstListItem();
    };

    this.handlePlayerLoadComplete = function( ) {
        _handlePlayerLoadComplete( );
    };

    this.handleVideoLoadComplete = function( ){
        _handleVideoLoadComplete( );
    };

    this.handleListLoadComplete = function( ){
        _handleListLoadComplete( );
    };

    this.handleVideoPlaybackComplete = function( ){
        _handleVideoPlaybackComplete( );
    };

    this.handleVideoPlay = function( ){
        _handleVideoPlay( );
    };

    this.handleVideoPause = function( ){
        _handleVideoPause( );
    };

    this.handlePrerollAdBegin = function( ){
        _handlePrerollAdBegin( );
    };

    this.handlePrerollAdEnd = function( ){
        _handlePrerollAdEnd( );
    };

    this.addCallback = function( name, callback ){
        _callbacks[ name ] = callback;
    };

    this.loadVideo = function(){
        _loadVideo( );
    };

    this.currentAsset = function(){
        return _currentAsset;
    };

    this.playVideo = function(){
        GRAB.mediaos.core.ui.component.player.play.call( _registeredPlayer );
    };

    this.pauseVideo = function(){
        GRAB.mediaos.core.ui.component.player.pause.call( _registeredPlayer );
    };

    this.setVolume = function( n ){
        _registeredPlayer.setVolume( n );
    };

    this.registerReactors = function(){
        /* Playlist Events */
        GRAB.mediaos.core.ui.component.list.reactor.register(  _playlistDivId, 'onListLoadComplete', eval( _ref + ".handleListLoadComplete"), _playlistName );
        /* Playlist metadata */
        if( _playlistKeywordsId ) GRAB.mediaos.core.ui.component.player.reactor.register( _playlistKeywordsId, 'onListLoadComplete', 'printKeywords' );
        if( _playlistTitleId ) GRAB.mediaos.core.ui.component.player.reactor.register( _playlistTitleId, 'onListLoadComplete', 'printPlaylistName' );
        /* Player Events */
        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onPlayerLoadComplete', eval( _ref + ".handlePlayerLoadComplete") );
        /* Video Events */
        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onVideoLoadComplete', eval( _ref + ".handleVideoLoadComplete") );
        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onVideoPlay', eval( _ref + ".handleVideoPlay") );
        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onVideoPause', eval( _ref + ".handleVideoPause") );
        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onVideoPlaybackComplete', eval( _ref + ".handleVideoPlaybackComplete") );

        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onPrerollAdBegin', eval( _ref + ".handlePrerollAdBegin") );
        GRAB.mediaos.core.ui.component.player.reactor.register( _playerDivId, 'onPrerollAdComplete', eval( _ref + ".handlePrerollAdEnd") );

        /* video Metadata */
        if( _videoHeadlineId )      GRAB.mediaos.core.ui.component.player.reactor.register( _videoHeadlineId, 'onVideoLoadComplete', 'printHeadline' );
        if( _videoSummaryId )       GRAB.mediaos.core.ui.component.player.reactor.register( _videoSummaryId, 'onVideoLoadComplete', 'printSummary' );
        if( _videoDescriptionId )   GRAB.mediaos.core.ui.component.player.reactor.register( _videoDescriptionId, 'onVideoLoadComplete', 'printDescription' );
        if( _videoPubdateId )       GRAB.mediaos.core.ui.component.player.reactor.register( _videoPubdateId, 'onVideoLoadComplete', 'printPubdate' );
        if( _videoThumbnailId )     GRAB.mediaos.core.ui.component.player.reactor.register( _videoThumbnailId, 'onVideoLoadComplete', 'loadThumbnail' );
        if( _videoPreviewImageId )  GRAB.mediaos.core.ui.component.player.reactor.register( _videoPreviewImageId, 'onVideoLoadComplete', 'loadPreviewImage' );

    };


    /**** private  ****/
    function _getFirstListItem() {
        return _registeredList.children[0].children[0]._metadata;
    }

    function _getAutoLoadFirstVideo(){
	return _autoLoadFirstVideo;
    }

    function _getRandomListItem() {
        var len = _registeredList.children[0].length;
        var rand = Math.floor( Math.random * len );
        return _registeredList.children[0].children[0]._metadata;
    }

    function _loadAsset( asset ) {
        /*
        console.log("_loadAsset");
        /**/
        _currentAsset = asset;
        /**/
        try {
            _loadingAnimationElement = document.createElement("div");
            if( _loadingAnimationElement ){
                _loadingAnimationElement.id = "grab-playlist-loading-animation";
                _loadingAnimationWrapper = document.getElementById("grab-vcl-player");
                _loadingAnimationWrapper.appendChild( _loadingAnimationElement );
            }
        } catch (e) {}

        GRAB.mediaos.core.ui.component.player.video.load.call( _registeredPlayer, asset );
    }

    function _handleVideoLoadComplete( ) {
        /*
        console.log("_handleVideoLoadComplete");
        /**/
        _videoLoaded = true;
        _setOmniture( );
        if ( _initialVideoLoaded ) {
            if ( _registeredPlayer["_states"].loaded ) {
                GRAB.mediaos.core.ui.component.player.play.call( _registeredPlayer );
            }
        } else {
            _initialVideoLoaded = true;
        }

        if( _callbacks[ 'onVideoLoaded' ] ) eval( _callbacks[ 'onVideoLoaded' ] + '();');

        try { _loadingAnimationWrapper.removeChild( _loadingAnimationElement ) } catch(e) {};
    }

    function _handleListLoadComplete( ) {
        /*console.log("_handleListLoadComplete");
        /**/
        /* apparently there should only be one list -- this removes the first one if there are 2 */
        if ( GRAB.mediaos.core.registry.components.lists.length > 1 ) GRAB.mediaos.core.registry.components.lists.shift();

        _registeredList     = GRAB.mediaos.core.registry.components.lists[0];
        _is_listLoaded      = true;
        var command = '';
        if( _getAutoLoadFirstVideo() ) command += ' ' + _ref + '.loadVideo( ); ';
        if( _callbacks[ 'onListLoaded' ]) command += ' ' + _callbacks[ 'onListLoaded' ] + '();';
        eval( command );

    }

    function _handlePlayerLoadComplete(){
        /*console.log("_handlePlayerLoadComplete");
        /**/

        _is_playerLoaded = true;
        _registeredPlayer   = GRAB.mediaos.core.registry.utils.findInRegistry( { "_type":"player", "name":_playerName} );

        if( _callbacks[ 'onPlayerLoaded' ] ) eval( _callbacks[ 'onPlayerLoaded' ] + '();');
        if( _getAutoLoadFirstVideo() ) _loadVideo( );
    }

    function _handleVideoPlay(){
        /*console.log("_handleVideoPlay");
        /**/
        if( _callbacks[ 'onVideoPlay' ] ) eval( _callbacks[ 'onVideoPlay' ] + '();');
    }

    function _handleVideoPause( ) {
        /*console.log("_handleVideoPause");
        /**/
        if( _callbacks[ 'onVideoPause' ] ) eval( _callbacks[ 'onVideoPause' ] + '();');
    }

    function _handlePrerollAdBegin( ) {
        /*console.log("_handlePrerollAdBegin");
        /**/
        if( _callbacks[ 'onPrerollAdBegin' ] ) eval( _callbacks[ 'onPrerollAdBegin' ] + '();');
    }

    function _handlePrerollAdEnd( ) {
        /*console.log("_handlePrerollAdEnd");
        /**/
        if( _callbacks[ 'onPrerollAdEnd' ] ) eval( _callbacks[ 'onPrerollAdEnd' ] + '();');
    }

    function _handleVideoPlaybackComplete( ) {
        /*console.log("_handleVideoPlaybackComplete");
        /**/
        _endOmniture();
        if( _callbacks[ 'onVideoComplete' ] ) eval( _callbacks[ 'onVideoComplete' ] + '();');
    }

    function _loadVideo( ){
        /*
        console.log("_loadVideo:" );
        console.log("--");
        console.log("   _onPlayerLoaded:->_is_playerLoaded:" + _is_playerLoaded );
        console.log("   _onPlayerLoaded:->_is_listLoaded:" + _is_listLoaded );
        /**/

        if ( _is_playerLoaded && _is_listLoaded ) {
            var firstListItem = _getFirstListItem();
            if ( !_initialListLoaded && _registeredPlayer["_states"].loadFirstListItem ) {
                /* check if list and player are loaded */
                if( !_loadVideoId ) _loadAsset( firstListItem );
                _initialListLoaded = true;
            }
        }
    }

    this.checkForOmniture = function(){
        return _checkForOmniture();
    };

    this.getOmnitureObject = function(){
        return _omnitureObject;
    };

    /* video tracking */
    function _checkForOmniture(){
        /*console.log('checkForOmniture');
/**/
        _isOmnitureAvailable = typeof(s) === 'object' ? typeof(s.Media) === 'object' /*true*/ : false;
        /*console.log( '_isOmnitureAvailable:' + _isOmnitureAvailable );
/**/
        if( _isOmnitureAvailable ) _endPoll();
        return _isOmnitureAvailable;
    }

    function _beginOmniture(){
        if( _isOmnitureAvailable ){
            if( s && s.Media ){
                s.Media.open( _omnitureObject.mediaName,
                              _omnitureObject.mediaLength,
                              _omnitureObject.mediaPlayerName );
                s.Media.play( _omnitureObject.mediaName, 0 );
            } else {
                _isOmnitureAvailable = false;
            }
        }
        return;
    }

    function _endOmniture( ){

        if( _isOmnitureAvailable ){
            if( s && s.Media ){
                s.Media.stop( _omnitureObject.mediaName, _currentVideoSeconds );
                s.Media.close( _omnitureObject.mediaName );
            } else {
                _isOmnitureAvailable = false;
            }
        }
        return;
    }

    function _setOmniture( ){
        if( _videoLoaded && _isOmnitureAvailable ){
            _omnitureObject.available = _isOmnitureAvailable;
            _omnitureObject.mediaName = _currentAsset.title;
            _omnitureObject.mediaLength = _currentAsset.duration / 1000;
            _omnitureObject.mediaPlayerName = _videoPlayerName;
            _omnitureSet = true;
            _beginOmniture();
            return;
        }
    }

    function _startPoll(){
        /* poll for items from  */
         _poll = setInterval( _ref + '.checkForOmniture();', 500 );
        if( typeof(jQuery) == 'function' ){
            jQuery(window).load(function(){
                _endPoll();
            });
        }
    }

    function _endPoll(){
        /* poll for items from  */
        clearInterval( _poll );
        /* this is called after omniture is found and after the video is loaded */
        _setOmniture( );
    }

    /**** init ****/
    GrabPlayer();
};
