var flashPrefix = '/flash/';
var nonflashVideoContentPart1 = 'To see this video you need JavaScript enabled and the latest version of Flash.  You can also use a browser that supports H.264 HTML5 Video.';
var nonflashVideoContentPart2LinkText = 'Click here';
var nonflashVideoContentPart2LinkUrl = 'http://www.adobe.com/go/getflashplayer';
var nonflashVideoContentPart2Text = ' to go to the Adobe Flash download center.';

/***********************************************************************
playVideo initializes the SWFObject for video play and
sets up the parameters of the video, or falls back to
play the video using HTML5 for browsers that support that.
required:   videoURL
            params:
            videoURL
            lightbox/colorbox div id (defaults to "lbVideo")
            vidWidth
            vidHeight
            vidDuration (in seconds)

Needs the following Global Variables setup to function also:
    flashPrefix
    nonflashVideoContentPart1
    nonflashVideoContentPart2LinkText
    nonflashVideoContentPart2LinkUrl
    nonflashVideoContentPart2Text
***********************************************************************/
function playVideo(videoURL, lbid, vidWidth, vidHeight, vidDuration, playerURL, dontOpenInLightbox) {
	// SWFplayer and ContainerDiv sizes are dynamic based on vidWidth & vidHeight

    if (videoURL == "") { return false; }

	/*****************************************/
	/* IMPORTANT PARAMS TO CONFIGURE - START */
	/*****************************************/
    var flashVideoPlayerURL = playerURL;
    if (playerURL == null || playerURL == "") { flashVideoPlayerURL = flashPrefix + "FlashVideoPlayer_scale.swf"; }

	var videoURLForFlashPlayer = videoURL;

    var flash1_contentVersion = "9.0.115"; // Flash 9.0.115 or higher required for H.264 video codec support

	// Add 22px for the height of the control bar in the Flash player, edit if the control bar height changes in SWF
	var flashPlayerControlHeight = 22;


	// CHOOSE SOME DEFAULT HEIGHTS AND WIDTHS IF THEY ARE NOT EXPLICITLY DEFINED IN CALL TO playVideo
	var defaultVideoWidth = "532";
	var defaultVideoHeight = "420";
    /*****************************************/
	/* IMPORTANT PARAMS TO CONFIGURE - END */
	/*****************************************/

	// test function variables
	if (lbid == "") { lbid = "lbVideo"; }
	if (vidWidth == "") { vidWidth = defaultVideoWidth; }
	if (vidHeight == "") { vidHeight = defaultVideoHeight; }
	if (vidDuration == "") { vidDuration = "9999"; }
	if (playerURL == null || playerURL == "") { playerURL = flashPrefix + "FlashVideoPlayer_scale.swf"; }

    //Check if video is larger than the viewport, if so, resize video proportionally to fit
	var viewportY = $(window).height();
	var viewportX = $(window).width();
	var dimChanged = false;

	vidWidth = parseInt(vidWidth);
	vidHeight = parseInt(vidHeight);
	if (vidWidth + 20 > viewportX || vidHeight + 20 > viewportY) {
		dimChanged = true;
		var vidPorportions = vidWidth / vidHeight;
		var orgW = vidWidth;
		var orgH = vidHeight;
		if (vidHeight + 20 > viewportY) {
			vidHeight = viewportY * .75;
			vidWidth = orgW > orgH ? vidHeight * vidPorportions : vidHeight / vidPorportions;
			if (vidWidth + 20 > viewportX) {
				vidWidth = viewportX * .75;
				vidHeight = orgW > orgH ? vidWidth / vidPorportions : vidWidth * vidPorportions;
			}
		} else {
			vidWidth = viewportX * .75;
			vidHeight = orgW > orgH ? vidWidth / vidPorportions : vidWidth * vidPorportions;
			if (vidHeight + 20 > viewportY) {
				vidHeight = viewportY * .75;
				vidWidth = orgW > orgH ? vidHeight * vidPorportions : vidHeight / vidPorportions;
			}
		}
	}

    var playerWidth = parseInt(vidWidth);

	// Add the height of the control bar in the Flash player
	var playerHeight = parseInt(vidHeight) + flashPlayerControlHeight;

	// get div if exists, create if it doesn't
	var lightboxDiv = $("#" + lbid);
	if (lightboxDiv.length == 0) {
		lightboxDiv = createLBdiv(lbid, 'body');
	}

	if (!dontOpenInLightbox) {
	    if (!dimChanged) {
	        // open lightbox to display
	        // ScrollFreeze is used for Firefox only because it repositions the page to the top when
	        // overflow: hidden is applied to the HTML element
	        $.fn.colorbox({
	            innerWidth: playerWidth,
	            innerHeight: playerHeight,
	            inline: true,
	            href: "#" + lbid,
	            onOpen: function() { if ($.browser.mozilla) ScrollFreeze.on(); $('html').css({ overflow: 'hidden' }); }, //prevent scrolling
                onComplete: function() { // setup SWFObject
                    createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, flashVideoPlayerURL, playerWidth, playerHeight, lightboxDiv);
                },
	            onCleanup: function() { lightboxDiv.hide(); $('html').css({ overflow: 'auto' }); }, //re-enable scrolling
	            onClosed: function() { lightboxDiv.remove(); if ($.browser.mozilla) ScrollFreeze.off(); },
	            opacity: 0.5
	        });
	    } else {  // Don't disable scrolling if video had to be resized to fit
	        // open lightbox to display
	        $.fn.colorbox({
	            innerWidth: playerWidth,
	            innerHeight: playerHeight,
	            inline: true,
	            href: "#" + lbid,
	            onOpen: function() { },
                onComplete: function() { // setup SWFObject
                    createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, flashVideoPlayerURL, playerWidth, playerHeight, lightboxDiv);
                },
	            onCleanup: function() { lightboxDiv.hide(); },
	            onClosed: function() { lightboxDiv.remove(); },
	            opacity: 0.5
	        });
	    }
	} else {
        createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, flashVideoPlayerURL, playerWidth, playerHeight, lightboxDiv);
    }

    if (detectAndroid()) {
    	$("video").live("click", function() {
    		this.play();
    	});
    }  
}

/***********************************************************************
supports_html5_h264_video tests the browser to see if it can
play HTML5_h264 video natively
***********************************************************************/
function supports_html5_h264_video() {
    //if Android, return true
    if (detectAndroid()) return true;
    //if browser can't play video tag at all (IE), return false:
    if (!document.createElement('video').canPlayType) { return false; }
    //if it can, check for mp4 type:
    else {
        var v = document.createElement("video");
        return !!v.canPlayType('video/mp4');
    }
}


/***********************************************************************
createsLBdiv creates a div for the video to go into
params: id for the lightbox div, width of the video, where to append it
returns the jQuery div object
***********************************************************************/
function createLBdiv(lbid, appendIdent) {
	var lightboxDiv = $("<div></div>").attr({ id: lbid });

	//create noflash div and insert
	var noflashDiv = $("<div></div>").attr("id", lbid + "noflash").addClass("no-flash");
	var noflashP1 = $("<p></p>").text(nonflashVideoContentPart1).attr("style", "padding-top:30px");
	var noflashP2link = $("<a></a>").attr({ href: nonflashVideoContentPart2LinkUrl, target: "_blank" }).text(nonflashVideoContentPart2LinkText);
	var noflashP2 = $("<p></p>").text(nonflashVideoContentPart2Text);
	noflashP2.prepend(noflashP2link);
	noflashDiv.append(noflashP1).append(noflashP2);
	lightboxDiv.append(noflashDiv);

	//Insert lightboxDiv
	$(appendIdent).append(lightboxDiv);
	return lightboxDiv;
}

/***********************************************************************
createVideoObject creates either the SWFObject or Video tag as appropriate
params: flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight,
        vidDuration, playerWidth, playerHeight, lightboxDiv
***********************************************************************/
function createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, playerURL, playerWidth, playerHeight, lightboxDiv) {
    // setup SWFObject
	if (swfobject.hasFlashPlayerVersion(flash1_contentVersion)) {
		//EMBED SWFObject Flash Player
		var vidDiv = lbid + "noflash";
		var flashvars = {};
		flashvars.videoUrl = videoURL;
		flashvars.videoWidth = vidWidth;
		flashvars.videoHeight = vidHeight;
		flashvars.videoDuration = vidDuration;
		var flashparams = {};
		flashparams.menu = "false";
		flashparams.quality = "high";
		flashparams.wmode = "opaque";
		flashparams.bgcolor = "#3E3C3C";
		var flashattributes = {};

		swfobject.embedSWF(playerURL, vidDiv, playerWidth, playerHeight, flash1_contentVersion, null, flashvars, flashparams, flashattributes);

	} else if (supports_html5_h264_video()) {
		//EMBED HTML5 Video Player
		// NOTE that iPhone OS2 does not support HTML5 Video
		var videoattributes = {};
		videoattributes.src = videoURL;
        //if (detectAndroid() && videoURL.substring(0,3) == "../" && videoUrlPrefixForRelativeRootUsed) videoattributes.src = videoURL.substring(3);
		videoattributes.width = vidWidth;
		videoattributes.height = vidHeight;
		videoattributes.controls = "true";
		videoattributes.autoplay = "true";
		var video = $("<video></video>").attr(videoattributes);
		lightboxDiv.html('');
		lightboxDiv.append(video);
	}
}

/*********************************************************************************************
	ScrollFreeze stops the page from scrolling while on
	Originally downloaded from
	http://bytes.com/topic/javascript/answers/498334-document-body-scroll-does-not-work-firefox

	Usage: ScrollFreeze.on() , ScrollFreeze.off()
	NOTE: The X freeze is currently not enabled, the script only freezes the Y axis scrolling
*********************************************************************************************/
ScrollFreeze = {
	propFlag: true,
	Ydisp: 0,
	Xdisp: 0,
	on: function() {
		if (this.getProp())
			$(window).bind("scroll", function() { ScrollFreeze.setXY(); });
	},
	off: function() {
		$(window).unbind("scroll");
		if ($(window).scrollTop() != $(window).data("yOffset"))
			setTimeout(this.setXY, 5);
	},
	getProp: function() {
		this.Ydisp = $(window).scrollTop();
		$(window).data("yOffset", this.Ydisp);
		return this.propFlag;
	},
	setXY: function() {
		$(window).scrollTop($(window).data("yOffset"));
	}
}

/***********************************************************************
detectiOSDevice returns true if the device is an iOS device,
based on the user agent string, false if not
***********************************************************************/
function detectiOSDevice() {
    var iOSdevices = ['ipod','itouch','ipad','iphone'];
    var userAgent = navigator.userAgent.toLowerCase();
    for (var i = 0; i < iOSdevices.length; i++) {
        if (userAgent.indexOf(iOSdevices[i]) != -1) {
            return true;
        }
    }
    return false;
}

/***********************************************************************
detectAndroid returns true if the device is an Android device,
based on the user agent string, false if not
***********************************************************************/
function detectAndroid() {
    var Android = ['android'];
    var userAgent = navigator.userAgent.toLowerCase();
    for (var i = 0; i < Android.length; i++) {
        if (userAgent.indexOf(Android[i]) != -1) {
            return true;
        }
    }
    return false;
}
