var _initialWidth = 0;
var _initialHeight = 0;

var _flashProxy = null;

function DetectFinale()
{
	// Check for plugin
	if (!detectFinaleViewer(null, false)) 
	{
		var div1 = document.getElementById('fvDownload');
		if (div1) div1.style.display = '';

		return;
	}

	var div2 = document.getElementById('fvWrapper');
	if (div2) div2.style.display = '';
}

function ViewerLoadedSmall() 
{	
	// Load saved settings
	LoadSettings();
	
	// Create Flash communication proxy
	var uid = new Date().getTime();
	_flashProxy = new FlashProxy(uid, "http://www.finalemusic.com/viewer/controls/JavaScriptFlashGateway.swf");
	
	// Set up Finale interface	
	var tag = new FlashTag("http://www.finalemusic.com/viewer/controls/InterfaceSmall.swf", 440, 45);
	tag.setFlashvars('lcId=' + uid);
	document.getElementById('interfaceDiv').innerHTML = tag.toString();

}

function ViewerLoaded() 
{	
	// Load saved settings
	LoadSettings();
	
	// Create Flash communication proxy
	var uid = new Date().getTime();
	_flashProxy = new FlashProxy(uid, "http://www.finalemusic.com/viewer/controls/JavaScriptFlashGateway.swf");
	
	// Set up Finale interface	
	var tag = new FlashTag("http://www.finalemusic.com/viewer/controls/Interface.swf", 586, 60);
	tag.setFlashvars('lcId=' + uid);
	document.getElementById('interfaceDiv').innerHTML = tag.toString();
}

function ControllerLoaded()
{
	_flashProxy.call("setup", 
		document.finaleViewer.Volume,		// Volume
		100,					// Tempo
		document.finaleViewer.minMeasure,	// Minimum Measure
		document.finaleViewer.maxMeasure,	// Maximum Measure
		document.finaleViewer.Measure		// Measure
	);		
}

function StopPlayBack()
{
	if (!document.finaleViewer)
		return;

	if (document.finaleViewer.isPlaying == 1)
		document.finaleViewer.PlayPause();
} 

function PlayTick()
{
	_flashProxy.call("playTick", 
		document.finaleViewer.isPlaying,	// Is Playing?
		document.finaleViewer.Measure		// Measure
	);	
}

function FitWidth()
{
	document.finaleViewer.SetViewAsPage(true);
}

function FitHeight()
{
	document.finaleViewer.SetViewAsPage(false);
}

function PlayPause()
{
	document.finaleViewer.PlayPause();	
}

function ChangeKey()
{
	document.finaleViewer.ChangeKey();
}

function AboutBox()
{
	document.finaleViewer.AboutBox();
}

function PrintView()
{
	document.finaleViewer.PrintView('TEST', true);
}

function SetVolume(val)
{
	document.finaleViewer.Volume = val;
}

function SetTempo(val)
{
	document.finaleViewer.Tempo = val;
}

function SetMeasure(val)
{
	document.finaleViewer.Measure = val;
}

function SaveSettings()
{
	var productID = getParam("itemId"); 
	var cookieval = "S" + document.finaleViewer.soloIndex;
	cookieval = cookieval + ",O" + document.finaleViewer.octaveIndex;
	cookieval = cookieval + ",T" + document.finaleViewer.transposeIndex;
	createCookie("productSettings_" + productID, cookieval, 30);
}

function LoadSettings()
{
	var productID = getParam("itemId");
	var cookieval = readCookie("productSettings_" + productID);

	if (cookieval != null)
	{
		var start = cookieval.indexOf(",");
		var soloIndex = cookieval.substr(1, start-1);
		cookieval = cookieval.substr(start+1);

		start = cookieval.indexOf(",");
		var octaveIndex = cookieval.substr(1, start-1);
		cookieval = cookieval.substr(start+1);	
		
		var transposeIndex = cookieval.substr(1, cookieval.length);
		
		document.finaleViewer.SetChangeKey(soloIndex, octaveIndex, transposeIndex);
	}
}

// QUERY STRING

function getParam(name)
{
  //alert(location);
  var start=location.search.indexOf("?"+name+"=");
  if (start<0) start=location.search.indexOf("&"+name+"=");
  if (start<0) return '';
  start += name.length+2;
  var end=location.search.indexOf("&",start)-1;
  if (end<0) end=location.search.length;
  var result=location.search.substring(start,end);
  var result='';
  for(var i=start;i<=end;i++) {
    var c=location.search.charAt(i);
    result=result+(c=='+'?' ':c);
  }
  return unescape(result);
}

// COOKIE MANAGEMENT

function createCookie(name,value,days)
{
 if (days)
 {
  var date = new Date();
  date.setTime(date.getTime()+(days*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();
 }
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++)
 {
  var c = ca[i];
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
 return null;
}

function eraseCookie(name)
{
 createCookie(name,"",-1);
}

// VIEWPORT

function getViewPortWidth()
{
	return (window.innerWidth || document.body.clientWidth || documemt.documentElement.offsetWidth || 0);
}

function getViewPortHeight()
{
	return (window.innerHeight || document.body.clientHeight || documemt.documentElement.offsetHeight || 0);
}


// PLUGIN DETECTION
//
// Copyright © 2000 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.
// initialize global variables
var detectableWithVB = false;
var pluginFound = false;


function goURL(daURL) {
    // if the browser can do it, use replace to preserve back button
    window.location.replace(daURL);
    return;
}

function redirectCheck(pluginFound, redirectURL, redirectIfFound) {
    // check for redirection
    if( redirectURL && ((pluginFound && redirectIfFound) || 
	(!pluginFound && !redirectIfFound)) ) {
	// go away
	goURL(redirectURL);
	return pluginFound;
    } else {
	// stay here and return result of plugin detection
	return pluginFound;
    }	
}

function canDetectPlugins() {
    if( detectableWithVB || (navigator.plugins && navigator.plugins.length > 0) ) {
	return true;
    } else {
	return false;
    }
}

function detectFinaleViewer(redirectURL, redirectIfFound) { 
    pluginFound = detectPlugin('Finale Viewer'); 
    // if not found, try to detect with VisualBasic
    if(!pluginFound)
    {
        pluginFound = detectGeckoActiveXControl('FINALEVIEWER.FinaleViewerCtrl.1');
    }
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('FINALEVIEWER.FinaleViewerCtrl.1');
    }
    // check for redirection
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectGeckoActiveXControl(controlName)
{
    try
    {
        var o = new GeckoActiveXObject('FINALEVIEWER.FinaleViewerCtrl.1');
	if (o)
            return true;
    }
    catch (e) { }

    return false;
}

function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = detectPlugin.arguments;
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
	var pluginsArrayLength = navigator.plugins.length;
	// for each plugin...
	for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    // loop through all desired names and check each against the current plugin name
	    var numFound = 0;
	    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
		// if desired plugin name is found in either plugin name or description
		if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) || 
		    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    // this name was found
		    numFound++;
		}   
	    }
	    // now that we have checked all the required names against this one plugin,
	    // if the number we found matches the total number provided then we were successful
	    if(numFound == daPlugins.length) {
		pluginFound = true;
		// if we've found the plugin, we can stop looking through at the rest of the plugins
		break;
	    }
	}
    }
    return pluginFound;
} // detectPlugin


// Here we write out the VBScript block for MSIE Windows
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
    document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('\'and the following function handles QuickTime');
    document.writeln('Function detectQuickTimeActiveXControl()');
    document.writeln('  on error resume next');
    document.writeln('  detectQuickTimeActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('    detectQuickTimeActiveXControl = False');
    document.writeln('    hasQuickTimeChecker = false');
    document.writeln('    Set hasQuickTimeChecker = CreateObject("QuickTimeCheckObject.QuickTimeCheck.1")');
    document.writeln('    If IsObject(hasQuickTimeChecker) Then');
    document.writeln('      If hasQuickTimeChecker.IsQuickTimeAvailable(0) Then ');
    document.writeln('        detectQuickTimeActiveXControl = True');
    document.writeln('      End If');
    document.writeln('    End If');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('</scr' + 'ipt>');
}


// ActiveX workaround stuff below this point.
// Added by Paul Eiche 12/7/06.
// Based off workaround for Scorch files.

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.

function Finale_RunContent()
{
  var ret = Finale_GetArgs(arguments);
  Finale_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function Finale_GetArgs(args)
{
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i = 0; i < args.length; i = i + 2)
  {
    var currArg = args[i].toLowerCase();    

    switch (currArg) {

      case "type":
        ret.objAttrs[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "classid":
        ret.objAttrs[args[i]] = args[i + 1];
        break;
      case "id":
        ret.objAttrs[args[i]] = args[i + 1];
        break;
      case "width":
        ret.objAttrs[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "height":
        ret.objAttrs[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "codebase":
        ret.objAttrs[args[i]] = args[i + 1];
        break;
      case "lockserverURL":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "action":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "prodId":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "transactionId":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "vendorArg00":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "vendorArg01":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "vendorArg02":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "vendorArg03":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "vendorArg04":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      case "vendorArg05":
        ret.params[args[i]] = args[i + 1];
        ret.embedAttrs[args[i]] = args[i + 1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i + 1];
    }
  }
  return ret;
}

function Finale_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += ' VIEWASTEXT >';
  
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" />';
  
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

