var G_someLocale = null;
var G_bAutoInstall = false;
var G_bAutoLaunch = false;

var G_bSendADEInstalled = false;
var G_bSendSWFVersion = false;
var G_bSendButtonPush = false;  // if true, only call the JS function - contentURL would be ignored if used
var G_strBadFlashRedirectURL = null;

// ********************
// Global script variable to indicate installed state for Digital Editions
// 0-NOT installed 1-Installed
// ********************
var G_bSawADEInstalled = false;
var G_nADEInstalled = 0;
var G_bForce_nADEInstalled_zero = false;	// used during debug/demo modes

var G_bTEST_nADEInstalled_control = false;	// used during debug/demo modes

var	GD_at_setG_nADEInstalled = 0;

// ********************
// Global script variable to hold SWF Version
// ********************
var G_strSWFVersion = "";
var G_bUpdateSWFVersion = true;
var	GD_at_setG_strSWFVersion = 0;

// ********************
// Stub function provided to support operation
// independent of DigitalEditionsDetection.js
// ********************
//function ShowADE_DivLayer()
//{
	// Copy and enable this function into your
	// implementations not using DigitalEditionsDetection.js
//}


// ********************
// setG_nADEInstalled()
//
// Callback function for the ade_web_library.swf
// to indicate the installed state of Digital editions
//
// CONTROLLED BY: io_sendADEInstalled
//
// NOTE:
// if you are using the DigitalEditionsDetection.js file
// then you must disable the stub ShowADE_DivLayer() above
// to allow the Detection function to be called
// ********************
function setG_nADEInstalled (numberAsString)
{
	var nADEInstalled_current = G_nADEInstalled;

	GD_at_setG_nADEInstalled++;

	// ON MAC firefox, observed that the test control caused the
	// page to enter this function (call the SWF again?)
	// anyway, if control just pushed, ignore this hit
	if (G_bTEST_nADEInstalled_control)
	{
		G_bTEST_nADEInstalled_control = false;
	}
	else  // normal
	{
		var nResult = parseInt(numberAsString);
		if (!(nResult == Number.NaN))
		{
			if (G_bForce_nADEInstalled_zero)
			{
				G_nADEInstalled = 0;
			}
			else // normal case
			{
				G_nADEInstalled = nResult;
			}

			// If have not seen first report of installed state
			// OR State has changed, then wiggle the layers
			if (!G_bSawADEInstalled || (nADEInstalled_current != G_nADEInstalled))
			{
				ShowADE_DivLayer();
			}

			G_bSawADEInstalled = true;
		}
	}
}

// ********************
// setG_strSWFVersion()
//
// CONTROLLED BY: io_sendSWFVersion
//
// This is called when sendSWFVersion = "true"
//
// Callback function for the ade_web_library.swf
// to indicate the version of ade_web_library.swf
// ********************
function setG_strSWFVersion(strSWFVersion)
{
	GD_at_setG_strSWFVersion++;
	if (strSWFVersion)
	{
		// If have not seen this, then wiggle the layers and save
		if (strSWFVersion != G_strSWFVersion)
		{
			G_strSWFVersion = strSWFVersion;
			G_bUpdateSWFVersion = true;

			// also do this if needed - implement the stub somewhere
			ShowSWFVersion_DivLayer();
		}
	}
}

// ********************
// send_ADE_SWF_ButtonPush()
//
// CONTROLLED BY: io_sendButtonPush
//
// Callback function for the ade_web_library.swf
// when implementations set sendButtonPush = "true"
//
// NOTE: When io_sendButtonPush is true, then even if io_contentURL is set, it will not
// be sent to ADE after it is launched.  When io_sendButtonPush is true, all that happens
// after ADE is launched is that the JS Callback is made, and that is it.
//
// This callback indicates that ADE is installed, launched, and user pushed the button
// ********************
function send_ADE_SWF_ButtonPush()
{
	// you can add Script code here to call out to
	// other parts of your script to take action
	// Default is call to this stub API that you can move around where needed
	// and leave this JS file intact
	ADE_SWF_ButtonPush_action();
}

//  ------------------------------
//  io_ADEVersion - (string - NUMBER)
//  This controls the Adobe Digital Editions version
//  that will be installed or launched by this SWF
//  Send the string version of a Number to control the version
//
//  '1' - DEPRECATED - ILLEGAL VALUE - System Requirements
//  '2' - Digital Editions 1.5 series - DEPRECATED - ILLEGAL VALUE - System Requirements
//  '3' - Digital Editions 1.7 series and greater BETA INSTALL
//  '4' - Digital Editions 1.7 series and greater
//
//  sending any other value chooses the 1.7 series (like "4")
//
//  AS of 04/15/2008, using '1' is no longer supported
//  if the value of '1' is supplied, then the badge will enter "system Requirements" state
//
//  AS of 10/20/2008, using '2' is no longer supported
//  if the value of '2' is supplied, then the badge will enter "system Requirements" state
//
//  ------------------------------
//  io_badgeJSLauncher - (true, false)
//  NOT USED by the Adobe Labs Library mode
//  true - if from ADEBadgeLauncher.js
//
//  ------------------------------
//	io_contentURL - (string)
//  NOT USED by the Adobe Labs Library mode
//  This parameter is used by ADEBadgeLauncher.js
//
//  How the ADE Launcher SWF handles this parameter is based on
//  the setting of io_doFulfillmentLink.
//
//  If io_doFulfillmentLink is false, then io_contentURL is
//  intended to be a URL path to an un-encrypted ePub or PDF Document.
//  io_contentURL will be sent to DE by the Launcher SWF and then
//  DE will download the file, add to the DE library, and open for reading
//
//  If io_doFulfillmentLink is true, then io_contentURL is
//  intended to be a GBLink fulfillment URL for Adobe Content Server DRM fulfillment
//  The launcher SWF will play the io_contentURL into the browser frame to
//  simulate a user clicking a GBLink URL href on a HTML page.  The target
//  ACS server will respond in the normal way with the ETD mime response to
//  be handed to DE by the browser.  DE will handle the ETD response as usual and
//  fulfill the ACS DRM protected content.
//
//  VERY IMPORTANT:
//  The io_contentURL must be escaped (js escape() function) to retain its integrity
//
//  USE fix_gblink_plus_characters() with ACS GBLink URL
//  There is a helper function named fix_gblink_plus_characters() in the ADE Launcher SDK
//  that is provided to perform the final fix for io_contentURL that is used with
//  io_doFulfillmentLink = true for GBLink URLs.  Please read the documentation and example
//  at fix_gblink_plus_characters() and in the ADE Launcher SDK examples
//
//  NOTE: When io_sendButtonPush is true, then even if io_contentURL is set, it will not
//  be sent to ADE after it is launched.  When io_sendButtonPush is true, all that happens
//  after ADE is launched is that the JS Callback is made, and that is it.
//
//  ------------------------------
//	io_autoInstall - (true, false)
//  true - If DE is not installed then install it. When installation of DE starts,
//  the the Adobe EULA always appears.  The user must click through the EULA to complete the install.
//  false - Take no special action to install DE
//
//  ------------------------------
//	io_autoLaunch - (true, false)
//  true - If DE is installed then launch it.  If DE not installed, do nothing special
//  false - Take no special action to launch DE
//
//  ------------------------------
//  io_MMredirectURL - (string)
//  This is a URL that is used if NO Flash Version is detected or the Flash Version
//  is too low to run the Launcher SWF.
//  This URL should go to a warning page that is maintained by the
//  partner that says something like
//
//  Can't see this content? To view this content, JavaScript must be enabled,
//  and you need the latest version of the Adobe Flash Player. Download the Flash Player now!
//
//  www.adobe.com/go/getflashplayer is the Adobe GO URL to provide a link for FlashPlayer
//
//  ------------------------------
//  io_doFulfillmentLink - (true, false)
//  true - submit "io_contentURL" parameter into browser (for ACS GBLink DRM fulfillment URL)
//  false - pass "io_contentURL" through LocalConnection into DE. DE will download the
//  content from the URL, add to the library, and then and open into reading mode
//
//  ------------------------------
//  io_sendADEInstalled - (true, false)
//  true - SWF performs call back into Jscript function setG_nADEInstalled() to indicate
//  installed state of DE.
//  false - DO NOT perform any JScript callback
//
//  ------------------------------
//  io_sendSWFVersion - (true, false)
//  true - SWF performs call back into Jscript function setG_strSWFVersion() to indicate
//  Version of the Adobe Digital Editions Launcher SWF
//  false - DO NOT perform any JScript callback
//
//  ------------------------------
//  io_sendButtonPush - (true, false)
//  true - SWF performs call back into Jscript function send_ADE_SWF_ButtonPush() to indicate
//  ADE is installed and the Button on the SWF is pushed
//  false - DO NOT perform any JScript callback
//
//  NOTE: When io_sendButtonPush is true, then even if io_contentURL is set, it will not
//  be sent to ADE after it is launched.  When io_sendButtonPush is true, all that happens
//  after ADE is launched is that the JS Callback is made, and that is it.
//
//  ------------------------------
//  io_debug_PlayerNotReady - (true, false)
//  Test-DEBUGGING option to simulate Bad Flash Version to run the SWF
//
//  ------------------------------
//  io_debug_BadOperatingSystem - (true, false)
//  Test-DEBUGGING option to simulate invalid Operating System
//
//  ------------------------------


// ********************
//  ADEBadgeLauncherInstance()
//
//  Launcher construction function
//
//  Places an instance of ade_web_library.swf (<object> tag with <embed> element)
//  into a <div> section on HTML Page.  The id of the <div> section as well as the desired id
//  for the <object> tag are passed in.
//
//  In addition, the parameters to control the behavior of the SWF are passed in
//
//  HTML Section params:
//  =========================
//	HTMLdivID  - id of the <div> which will hold the SWF
//  HTMLobjectID - desired ID for the HTML <object> that contains the SWF (may be null - default is ADEBadgeLauncherInstance)
//
//  Flash SWF parameters (FlashVars):
//  =========================
//  See the flashvars documentation just above
//
// NOTE: on 04/17/08, the (3) buttonLabel params were removed
// buttonLabelNotRequirements, buttonLabelNot, buttonLabelInst
// ********************
function ADEBadgeLauncherInstance(HTMLdivID, HTMLobjectID,
contentURL,		    // MUST BE escaped
doFulfillmentLink,	// controls use of contentURL
autoInstall,
autoLaunch,
badFlashRedirectURL,
sendADEInstalled,
sendSWFVersion,
sendButtonPush)
{

	if (!HTMLobjectID)
		HTMLobjectID = 'ADEBadgeLauncherInstance';

	// These params are script-provided, or finalized by this script
	// See io_ADEVersion documentation, above
	var ADEVersion = "4"; // "4" is ADE 1.7 or greater - "3" is ADE 1.7 Beta or greater
	var badgeJSLauncher = "true";	// ALWAYS true from here

	var userAgent = navigator.userAgent;

	var locale = "";
	if (G_someLocale)
		locale = G_someLocale;

	var bEscape = true;
	var finalBadFlashRedirectURL = getFinalBadFlashRedirectURL(badFlashRedirectURL, bEscape);

	// sum up the variables to be passed into the SWF
	// NOTE: on 04/17/08, the following (4) params were removed from the SWF
	// badgeImagePath, buttonLabelNotRequirements, buttonLabelNot, buttonLabelInst
	var strFlashVars = 'ADEVersion=' + ADEVersion +
					'&badgeJSLauncher=' + badgeJSLauncher +
//					'&debug_PlayerNotReady=' + debug_PlayerNotReady +
//					'&debug_BadOperatingSystem=' + debug_BadOperatingSystem +
					'&userAgent=' + userAgent +
					'&locale=' + locale +
					'&MMredirectURL=' + finalBadFlashRedirectURL +
					'&contentURL=' + contentURL +	// MUST BE escaped
					'&autoInstall=' + autoInstall +
					'&autoLaunch=' + autoLaunch +
					'&doFulfillmentLink=' + doFulfillmentLink +   // controls use of contentURL
					'&sendADEInstalled=' + sendADEInstalled +
					'&sendSWFVersion=' + sendSWFVersion +
					'&sendButtonPush=' + sendButtonPush;

	// size of the SWF.  This size is specified in the .FLA Flash design file
	// NOTE leading & trailing space is required to be built into this string
	//	var swfSize = ' width="225" height="170" ';	// This was the Beta3 Launcher
	var swfSize = ' width="315" height="220" ';		// This is the Ver 1.0 Launcher (june, 2007)

	// color, quality - declared 1 place
	var qualityValue = '"high"';
	var bgColorValue = '"#ffffff"';

	// path to the SWF just in case its not in same folder/place as this file
	// for example a relatitive path to the swf that is one directory higher might be
	// var swfPath = '"../parentpath/ade_web_library.swf"';
	var swfPath = '"/ade/ade_web_library.swf"';

	// Create object/embed tag for ade_web_library.swf
	var swf  = '<object id="' + HTMLobjectID + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + swfSize + 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
		swf += '<param name="movie" value=' + swfPath + ' />';
		swf += '<param name="quality" value=' + qualityValue + ' />';
		swf += '<param name="bgcolor" value=' + bgColorValue + ' />';
		swf += '<param name="allowscriptaccess" value="samedomain" />';
		swf += '<param name="flashVars" value="' + strFlashVars + '" />';
		swf += '<embed type="application/x-shockwave-flash" src=' + swfPath + swfSize + 'id="' + HTMLobjectID + '" name="' + HTMLobjectID + '"allowscriptaccess="samedomain" flashVars="' + strFlashVars + '" swLiveConnect="true" quality=' + qualityValue + ' bgcolor=' + bgColorValue + 'align="" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>';
		swf += '</object>';

	// Now place the SWF object/embed tag into the HTML at the divID
	var element = document.getElementById (HTMLdivID);
	element.innerHTML = swf;

	// kick in the pants to be sure to display
	element.style.display = "block";
}

// ********************
// SetADEBadgeLauncherLocale()
// hardcode a Locale to use
// ********************
function SetADEBadgeLauncherLocale(theirLocale)
{
	G_someLocale = theirLocale;
}





// ********************
// getFinalBadFlashRedirectURL()
//
// Utility function to escape the URL.
// If not provided, use current window with params added (?flash=bad")
// ********************
function getFinalBadFlashRedirectURL(badFlashRedirectURL, bEscape)
{
	var scriptBadFlashRedirectURL = null;
	var finalBadFlashRedirectURL = null;
	if  (badFlashRedirectURL)
	{
		scriptBadFlashRedirectURL = badFlashRedirectURL;
	}
	else	// nothing special provided, use current window.
	{
		scriptBadFlashRedirectURL = window.location;

		// Modify to add any special URL parameters here
		scriptBadFlashRedirectURL += "?flash=bad"
	}

	if (bEscape)
	{
		finalBadFlashRedirectURL = escape(scriptBadFlashRedirectURL);
	}
	else
	{
		finalBadFlashRedirectURL = scriptBadFlashRedirectURL;
	}

	return finalBadFlashRedirectURL;
}

function fix_gblink_plus_characters (escapedContentURL) // CHANGE "+" to escaped plus "%2B"
{
	var fixedURL = "";
	var strFind = "+";
	var lenFind = strFind.length;
	var strReplace = "%2B"; // ASCII + is 0x2B

	var iNext = 0;
	var iStart = escapedContentURL.indexOf ("gbauthdate", 1);
	if (iStart > 0)
	{
		iStart = escapedContentURL.indexOf (strFind, iStart);
	}

	while (iStart > 0)
	{
		fixedURL += escapedContentURL.substring (iNext, iStart);
		fixedURL += strReplace;
		iNext = iStart + lenFind;
		iStart = escapedContentURL.indexOf (strFind, iNext);
	}

	if (iNext > 0)
		fixedURL += escapedContentURL.substring (iNext);
	else // never found anything to replace
		fixedURL = escapedContentURL;

	return fixedURL;
}
