if (typeof com == "undefined") { com={}; }
if (typeof com.digitaria == "undefined") { com.digitaria={}; }

com.digitaria.VideoPopup={
	/**
	 * Hide the lightbox, unbind the events, stop the swfobject.
	 * @returns {void}
	 * @param {event} e Event reference that triggered it.
	 * @see com.digitaria.VideoPopup.load (called by)
	 * @author Nick Davison
	 */
	hide: function(e) {
		// Stop eventexecution
		e.stop();
		// Hide the window
		com.digitaria.lightbox.hide();
		// Unbind the close button
		$('vid_pop_close').stopObserving('click', com.digitaria.VideoPopup.hide);
		// Remove the swfobject
		swfobject.removeSWF("vid_pop_holder");
		// Reneable the flashwall IF the function exists
		if (typeof enableFlashWall != "undefined") {
			enableFlashWall();
		}
	},
	
	/**
	 * Loads a url in via the lightbox and initializes it.
	 * <p>Check to see if the lightbox system is initialized. If not, attempt to initialize it.</p>
	 * <p>Load the url via the lightbox system. If there's an issue, tell the user. 
	 * If it's successful, get the flash properties from the #vid_pop_holder element.
	 * Bind the close button to cleanly close the player (see com.digitaria.VideoPopup.hide).
	 * Initialize the flash via swfobject.</p>
	 * @returns {void}
	 * @param {string} url The url to load.
	 * @see com.digitaria.VideoPopup.hide (calls)
	 * @see com.digitaria.VideoPopup.init (called by)
	 * @author Nick Davison
	 */
	load: function(url) {
		// If the lightbox isn't already initialized
		if (!document.getElementById('lightbox_holder')) {
			// If it hasn't been included, warn the user and bail
			if (typeof com.digitaria.lightbox=="undefined") {
				alert("Make sure you include com.digitaria.lightbox.js");
				return;
			}
			// Otherwise, initialize it.
			com.digitaria.lightbox.init();
		}
				
		// Ensure the width is correct (just incase anyone else has been using the lightbox)
		com.digitaria.lightbox.divWindow.style.width="632px";
		
		com.digitaria.lightbox.load({
			url: url,
			onSuccess: function(data) {
				// Get the dimensions for the player
				var w=$('vid_pop_holder').getWidth().toString();
				var h=$('vid_pop_holder').getHeight().toString();
				if (h<20) {
					h="345";
				}
				
				var swf=$('vid_pop_holder').getAttribute('rel');
				var xml=$('vid_pop_holder').getAttribute('rev');
				var chapter=null;
				
				// If the rel has a | separator
				if (swf.indexOf("|")!=-1) {
					// Split it to swf|chapter
					parts=swf.split("|");
					chapter=parts[1];
					swf=parts[0];
				}

				// Bind the close button
				$('vid_pop_close').observe('click', com.digitaria.VideoPopup.hide);

				// Initialize the flash player.
				var flashvars={
					xmlPath: xml,
					swfPath: 'http://'+(document.location.hostname == 'content.qualcomm.com' ? 'www.qualcomm.com' : document.location.hostname)+'/sites/all/themes/qualcomm/swfs',
					mode: 'modal'
				};
				var params={
					quality: 'high',
					wmode: 'transparent',
					salign: '',
					allowFullScreen: 'true',
					allowScriptAccess: 'sameDomain'
				};
				var attributes={};
				
				if (chapter!=null) {
					flashvars['chapter']=chapter;
				}
				swfobject.embedSWF(swf, "vid_pop_holder", w, h, "9.0.124", "", flashvars, params, attributes);
				
				var replacer=new com.qualcomm.Sifr.replacement();
			},
			onFailure: function() {
				alert("We are sorry. We were unable to load the video for you at this time.");
			}
		});
	},
	
	/**
	 * Scan the document (if no parentNode is passed, otherwise scan children of it) for all a.video_popup links.
	 * Bind each one so that they load their url via com.digitaria.VideoPopup.load().
	 * This will change all of those links to proper lightbox calls, handling all swf initialization, etc.
	 * @returns {void}
	 * @param {element} parentNode The root element to search under. (Defaults to body)
	 * @see com.digitaria.VideoPopup.load (calls)
	 * @author Nick Davison
	 */
	init: function(parentNode) {
		if ((typeof parentNode=="undefined") || (parentNode==null)) {
			parentNode=$$('body');
			parentNode=$(parentNode[0]);
		}
		parentNode.select('a.video_popup').each(function(el) {
			$(el).observe('click', function(e) {
				// Stop the regular event from firing
				e.stop();
				// Load the href in to the video popup, instead
				com.digitaria.VideoPopup.load(this.href);
			});
		});
	}
}

/**
 * Fire video popups from the Wireless Lifestyle flash wall.
 * @returns {void}
 * @param {number} elementID Key for which video to play
 */
function playModalVideo( elementID ) {
	/**************************************************** 
	Array of video id's mapped to corresponding elements
	in the flash module. Module ID's represent the following
	wall items and are mapped to the corresponding keyed index
	in the videoIDArray:
	
	0. Introduction Video
	1. Asset Tracking
	2. Digital Home
	3. Digital Home Away from Home
	4. Global Mobile Internet at the Airport
	5. Global Mobile Internet on Campus
	6. Global Roaming
	7. Locate Friends
	8. Location Finder
	9. Mobile Gaming
	10. Mobile Health
	11. Mobile Payment for Concert Tickets
	12. Mobile Payment for Transportation
	13. Mobile Payment at Flower Vendor
	14. Mobile Tagging
	15. Mobile TV
	16. Personalized UI
	17. Points of Interest
	******************************************************/
	// http://www.qualcomm.com/partials/video/nid
	var videoIDArray = [
		"http://www.qualcomm.com/partials/video/49", 
		"http://www.qualcomm.com/partials/video/51", 
		"http://www.qualcomm.com/partials/video/62", 
		"http://www.qualcomm.com/partials/video/54", 
		"http://www.qualcomm.com/partials/video/52", 
		"http://www.qualcomm.com/partials/video/64", 
		"http://www.qualcomm.com/partials/video/59", 
		"http://www.qualcomm.com/partials/video/63", 
		"http://www.qualcomm.com/partials/video/53", 
		"http://www.qualcomm.com/partials/video/66", 
		"http://www.qualcomm.com/partials/video/50", 
		"http://www.qualcomm.com/partials/video/65", 
		"http://www.qualcomm.com/partials/video/57", 
		"http://www.qualcomm.com/partials/video/55", 
		"http://www.qualcomm.com/partials/video/61", 
		"http://www.qualcomm.com/partials/video/58", 
		"http://www.qualcomm.com/partials/video/56", 
		"http://www.qualcomm.com/partials/video/60"
	];
	com.digitaria.VideoPopup.load(videoIDArray[elementID]);
}

// ------------------
// EI INIT & JS -> AS3
// ------------------

if (typeof initEi == "undefined") {
	function initEi(id) {
	    /*used to initialize ei calls, blank for a reason*/
        jQuery.get('/popularity/video?type=denominator&nid=' + id);
        // url is GET /fivestar/vote/node/51/vote/80?token=3baefea978650f45604434a73199ee77
        // return fivestar token - set in partial
        return rating_token;
	}
}

if (typeof getFlashMovie == "undefined") {
	function getFlashMovie(movieName) {
	  var isIE = navigator.appName.indexOf("Microsoft") != -1;
	  return (isIE) ? window[movieName] : document[movieName];
	}
}

if (typeof jsSend == "undefined") {
	function jsSend(movieName, func, data) {
		getFlashMovie(movieName).eiJSSender(func, data);
	}
}

/*
AS3 callable function list & arguments:
	function name sent as string
	arguments sent as comma delineated values

		func:seekVideo
		arg:Number(targetTime)
			- can be used to seek video to chapter time in seconds, int or float ok
*/

function videoAnalyticsLog(msg) {
	if (typeof console != "undefined") {
		if (typeof console.debug != "undefined") {
			console.debug(msg);
		}
	}
}

// --------------------
// MODAL VIEW FUNCTIONS
// --------------------

function modalReciever(arg1, arg2) //number or arguments to be determined later 
{
	videoAnalyticsLog("modalReciever - arg1: "+arg1+" arg2:"+arg2);
}

// -------------------
// ANALYTICS FUNCTIONS
// -------------------

function wrapperTrackPercentPlay(url, time, duration, percent, id) {
	videoAnalyticsLog("trackPercentPlay - url: "+url+" time:"+time+" duration:"+duration+" percent:"+percent);
    jQuery.get('/popularity/video?type=numerator&nid=' + id);
	if (typeof trackPercentPlay!="undefined") {
		trackPercentPlay(url, time, duration, percent);
	}
	// Do local code here
}

function wrapperTrackVideoPlay(url, time, duration) {
	videoAnalyticsLog("trackVideoPlay - url: "+url+" time:"+time+" duration: "+duration);
	if (typeof trackVideoPlay!="undefined") {
		trackVideoPlay(url, time, duration);
	}
	// Do local code here
}

function wrapperTrackVideoPause(url, time, duration) {
	videoAnalyticsLog("trackVideoPause - url: "+url+" time:"+time+" duration: "+duration);
	if (typeof trackVideoPause!="undefined") {
		trackVideoPause(url, time, duration);
	}
	// Do local code here
}

function wrapperTrackVideoStop(url, time, duration) {
	videoAnalyticsLog("trackVideoStop - url: "+url+" time:"+time+" duration: "+duration);
	if (typeof trackVideoStop!="undefined") {
		trackVideoStop(url, time, duration);
	}
	// Do local code here
}

function wrapperTrackLinkClick(source, mode) {
	videoAnalyticsLog("trackVideoStop - source: "+source+" mode:"+mode);
	if (typeof trackLinkClick!="undefined") {
		trackLinkClick(source, mode);
	}
	// Do local code here
}

/* Recently Viewed Handling */

function pushRecentlyViewedVideo(options) {
	if (typeof CookieJar != "undefined") {
		var cookie_name = 'qc_video_wall_rv';
		var jar = new CookieJar({expires:3600*10000,path:'/'});
		var recentlyViewed = jar.get(cookie_name);
		if (!recentlyViewed) {
			recentlyViewed = new Array();
		}
		var exists = false;
        // normalize url
        var match = /$(.*)\?/.exec(options['url']);
        if (match) {
            options['url'] = match[1];
        }
		for (i = 0; i < recentlyViewed.length; i++) {
			if (options['url'] == recentlyViewed[i]['url']) {
				exists = true;
				break;
			}
		}
		if (!exists) {
			recentlyViewed.unshift(options);
			if (recentlyViewed.length >= 5) {
				recentlyViewed = recentlyViewed.slice(0, 5);
			}
			jar.put(cookie_name, recentlyViewed);
			initRecentlyViewedVideos();
		}
	}
}

function initRecentlyViewedVideos() {
	if (document.getElementById('vc_navigator_recent')) {
        var cookie_name = 'qc_video_wall_rv';
        var jar = new CookieJar();
        var recentlyViewed = jar.get(cookie_name);
        if (recentlyViewed) {
            var html = [];
            html.push('<ul>');
            html.push('<li class="vc_title" id="recently_viewed_title">Recently Viewed</li>');
            for (var i = 0; i < recentlyViewed.length; i++) {
                html.push(createRecentlyViewedVideoDisplay(recentlyViewed[i]));
            }
            html.push('</ul>');
            $('vc_navigator_recent').innerHTML = html.join("\n");
        }
    }
}

function createRecentlyViewedVideoDisplay(options) {
    return '<li class="option"><a href="' + options['url'] + '" class="vc_play_hover_small" title="' + options['title'] + '"><img src="' + options['thumb'] + '" width="50" height="28" alt="' + options['title'] + '" /></a></li>';
}

