mok3_g_pageReady = false;
mok3_g_brokerHandshake = false;
mok3_g_componentsInitialized = false;
mok3_g_historyEvent = false;
mok3_g_currentTourpath = "";
mok3_g_currentPanoId = "";
mok3_g_flashOptions = "";
mok3_g_cbOptions = "";
mok3_g_disableStaticMap = false;
mok3_g_disableTourMap = false;
mok3_g_disableSiteList = false;
mok3_g_disablePanoviewer = false;
mok3_g_cachedDataFiles = 0;
mok3_g_componentsInteractive = 0;
mok3_g_showTourViewer = false;
mok3_g_firstTourLoad = true;
mok3_g_buildParameter = "";
mok3_g_showAngles = "false";
mok3_g_mapMsgCookie = "false";
mok3_g_panoMsgCookie = "true";
mok3_g_showViewerOverride = "false";
mok3_g_supertourViewerBgColor = "0xffffff";
mok3_g_weblinkWindow = null;
mok3_g_baseDebug = false;
mok3_g_viewerWmodeTransparent = false;

// Get the broker object
function mok3_getBroker(bNoFail)
{
	var broker = window.document.central_broker;
	if (broker == null)
		broker = document.getElementById( mok3_g_mainViewerName );
	if (broker == null && bNoFail == true)
		alert('mok3_getBroker() - Broker not found');
	return broker;
}



function mok3_customInit() {}

function mok3_baseInit(buildParameter, flashOptions, cbOptions, bUseShockwaveViewer, bDisableStaticMap, bDisableTourMap, bDisableSiteList, bDisablePanoviewer)
{
  mok3_g_buildParameter = buildParameter;
  mok3_g_flashOptions = flashOptions;
  mok3_g_cbOptions = cbOptions;
  mok3_g_disableStaticMap = bDisableStaticMap;
  mok3_g_disableTourMap = bDisableTourMap;
  mok3_g_disableSiteList = bDisableSiteList;
  mok3_g_disablePanoviewer = bDisablePanoviewer;


  // Upgrade flash if needed
  var minAcceptableVersion = 8;
  var bHasAcceptableVersion = mok3_hasAtLeastFlashVersion(minAcceptableVersion, 0, 0);
  if ( !bHasAcceptableVersion )
  {
    var bHasUpgradableVersion = mok3_hasAtLeastFlashVersion(6, 0, 65);
    if (bHasUpgradableVersion)
    {
      //alert('upgradable');
      // Show the flash installer
      mok3_embedFlashUpgrader();
			return;
    }
  }

  mok3_setLoadingState( 'page_initialized' );
	
  // Signal that the page is ready
  mok3_g_pageReady = true;
}

function mok3_getBuildParameter() { return mok3_g_buildParameter; }
function mok3_getFlashOptions() { return mok3_g_flashOptions; }
function mok3_getCbOptions() { return mok3_g_cbOptions; }
function mok3_staticMapDisabled() { return mok3_g_disableStaticMap; }
function mok3_tourMapDisabled() { return mok3_g_disableTourMap; }
function mok3_siteListDisabled() { return mok3_g_disableSiteList; }
function mok3_panoviewerDisabled() { return mok3_g_disablePanoviewer; }

function mok3_historyChange(newLocation, historyData)
{
  mok3_g_historyEvent = true;
  //mok3_loadTourFromHash();
	mok3_notifyHistoryChange();
}

// Called when central broker able to communicate with javascript
// Called when central broker able to communicate with javascript
function mok3_brokerHandshake()
{
  if (mok3_g_brokerHandshake == false &&
      mok3_g_pageReady == true)
  {
    mok3_g_brokerHandshake = true;
    // Tell the broker that the JS received the handshake call so the broker stops sending the handshake
    mok3_getBroker().js_brokerReadyHandshakeAck();
  }
}

function mok3_loadTourFromHash()
{
	if ( mok3_g_baseDebug )
		$( 'debug' ).innerHTML += mok3_functionToString( mok3_loadTourFromHash ) + '<br/>';

  //if (!mok3_g_componentsInitialized)
  //  return;
  
  // Set the scratchpad cookie if needed
  var scratchpad_id = mok3_getUrlParameter('scratchpad_id');
  if (scratchpad_id != '' &&
      mok3_getCookie('scratchpad_id') != scratchpad_id)
  {
    expiration_date_ms = Date.parse("12/31/9999 11:59:59 PM");
    var expiration_date = new Date();
    expiration_date.setTime(expiration_date_ms);
    mok3_setCookie('scratchpad_id', scratchpad_id, expiration_date, '/');
  }
  
  // Load tour based on url
  var tourPath = mok3_getUrlParameter('tour_path');
  var panoramaId = mok3_getUrlParameter('panorama_id');
  var phi = mok3_getUrlParameter('viewer_phi');
  var theta = mok3_getUrlParameter('viewer_theta');
  var siteType = mok3_getUrlParameter('site_type');
  var walkType = mok3_getUrlParameter('walk_type');
  var walkId = mok3_getUrlParameter('walk_id');

  mok3_loadTourInternal(tourPath, panoramaId, phi, theta, siteType, walkType, walkId);
	mok3_customLoad();
}

// Use this from HTML
function mok3_loadTour(tourPath, panoramaId, phi, theta, siteType, walkType, walkId)
{
	if ( mok3_g_baseDebug )
		$( 'debug' ).innerHTML += mok3_functionToString( mok3_loadTour ) + '<br/>';
  //mok3_stats("evt_slink?from=html");
  mok3_loadTourInternal(tourPath, panoramaId, phi, theta, siteType, walkType, walkId);
	//mok3_customLoad();
}

/// if inPausedState if true, then the viewer will be in a paused state
/// otherwise it is in a stopped state.
function mok3_loadExperience( expPath, expId, inPausedState )
{
  if (expPath == "" || expId == "") 
    return;

	if ( typeof inPausedState == "undefined" )
		inPausedState = false;
	var b = mok3_getBroker();
  if ( b != null)
	{
    b.js_loadExperience( expPath + 'experiences.ex', expId, inPausedState );
		return true;
	}
	return false;
}

function mok3_playNext()
{
      mok3_playExperience(data.defaultPath, data.defaultExperience);
}

function mok3_panolink(panoId, bPause, phi, theta)
{
  if (mok3_getBroker() != null)
    mok3_getBroker().js_panolink( panoId, bPause, phi, theta );
}

function mok3_playExperience( expPath, expId )
{
  if (expPath == "" || expId == "") 
    return;
	var b = mok3_getBroker();   
  if ( b != null)
	{
    b.js_playExperience( expPath + 'experiences.ex', expId );
		return true;
	}
	return false;
}

function mok3_pauseExperience()
{
	var b = mok3_getBroker();
	if ( b != null )
	{
		b.js_pauseExperience();
		return true;
	}
	return false;
}


// Use this for programmatic calls
function mok3_loadTourInternal(tourPath, panoramaId, phi, theta, siteType )
{
	if ( mok3_g_baseDebug )
		$( 'debug' ).innerHTML += mok3_functionToString( mok3_loadTourInternal ) + '<br/>';
  if (tourPath == "")
	{
		alert( 'no initial tour' );
		return;
	}

  if (mok3_getBroker() != null)
	{
    mok3_getBroker().js_loadTour(tourPath, panoramaId, phi, theta, siteType );
	}
}


function mok3_updateAddressBar(tour_path, panorama_id, phi, theta)
{
  newHash = mok3_makeHash(tour_path, panorama_id, phi, theta) + mok3_addToHashForUpdateAddressBar();
  if (mok3_g_historyEvent == true)
    mok3_g_historyEvent = false;
  else
  {
    // Don't add a history event if this is the first load
    if (mok3_g_firstTourLoad)
      mok3_g_firstTourLoad = false;
    else
      dhtmlHistory.add(newHash, null);
  }
  mok3_refreshTitleBar();
  mok3_g_currentTourpath = tour_path;
	mok3_g_currentPanoId = panorama_id;
}

function mok3_getCurrentTourpath()
{
  return mok3_g_currentTourpath;
}

function mok3_getCurrentPanoId()
{
	return mok3_g_currentPanoId;
}

function mok3_makeHash(tour_path, panorama_id, phi, theta)
{
  var hash = '';
  hash += '#tour_path=' + escape(tour_path);
  if (panorama_id != 'undefined' &&
      panorama_id != 'null' &&
      panorama_id != null &&
      panorama_id != '')
    hash += '&panorama_id=' + escape(panorama_id);
  if (phi != 'undefined' &&
      phi != 'null' &&
      phi != null &&
      phi != '')
    hash += '&viewer_phi=' + escape(phi);
  if (theta != 'undefined' &&
      theta != 'null' &&
      theta != null &&
      theta != '')
    hash += '&viewer_theta=' + escape(theta);
    
  scratchpad_id = mok3_getCookie('scratchpad_id');
  if (scratchpad_id != null)
    hash += '&scratchpad_id=' + escape(scratchpad_id);
      
  return hash;
}

function mok3_setLoadingState( state, flashPlayerId )
{
  var sInit = "Loading your destination.";
  var sLoading = "You will arrive at your destination momentarily.";
  
	if ( mok3_g_baseDebug )
		$( 'debug' ).innerHTML += state + '<br/>';
		
  switch(state)
  {
    case "page_initialized":
//      mok3_setMode("loading");
      //mok3_setLoadingContent(0, "");
      mok3_embedSupertourViewer();
      break;
      
    case "broker_initialized":
      //mok3_setLoadingContent(100, "");
      //mok3_loadTourFromHash();
      mok3_playExperience(data.defaultPath, data.defaultExperience);
			if ( typeof flashPlayerId != "undefined" && flashPlayerId == mok3_g_mainViewerName )
			{
				mok3_stats("evt_player_ready");
			}
      break;   

		default:
      alert('unexpected loading state: ' + state); 
  }
}

// Handle all the FSCommand messages in a Flash movie.
function central_broker_DoFSCommand(command, args)
{
	alert( mok3_functionToString( central_broker_DoFSCommand ));
  setTimeout(command, 0);
}

function mok3_setBrokerVariable(variable, value)
{
	alert( mok3_functionToString( mok3_setBrokerVariable ));
  var broker = mok3_getBroker();

  // from http://www.mustardlab.com/developer/flash/jscommunication/
  // -----------------------------------------------------------
  // Detection snippet from http://www.dithered.com/javascript/browser_detect/index.html
  // -----------------------------------------------------------
  var ua        = navigator.userAgent.toLowerCase(); 
  var is_pc_ie  = ( /*(ua.indexOf('msie') != -1 ) &&*/ ( ua.indexOf('win') != -1 ) && ( ua.indexOf('opera') == -1 ) && ( ua.indexOf('webtv') == -1 ) );

  /* -----------------------------------------------------------
  variable: variable to set on broker
  value: value to set broker variable to
  ----------------------------------------------------------- */
  if(is_pc_ie)
  {
	  broker.SetVariable(variable,value);
  }
  else
  {
    var divcontainer;
    // JSReady, LoadTour each have their own div element to house their gateway swf for sending variables to the broker
    // Search variables shared the same div element to house their gateway swf for communicating with the broker
    // This is to stay within the limitation on objects using local connections (seems to be maximum 8 components)
    if (variable.indexOf('Search') != -1)
    {
      divcontainer = "setBrokerVariables_containerSearch";
    }
    else
    {
    divcontainer = "setBrokerVariables_container"+variable;
	  }
	  var connectStr = "broker" + mok3_gConnectId;
	  if(!document.getElementById(divcontainer))
	  {
		  var divholder = document.createElement("div");
		  divholder.id = divcontainer;
		  document.body.appendChild(divholder);
	  }
	  document.getElementById(divcontainer).innerHTML = "";
	  // embed tag is no longer supported in safari as of 2.0
	  //var divinfo = "<embed src='gateway.swf' FlashVars='lc="+connectStr+"&variable="+escape(variable)+"&val="+escape(value)+"' width='0' height='0' type='application/x-shockwave-flash'></embed>";
	  // use object tag with data instead
 	  var divinfo  = "<object type=\"application/x-shockwave-flash\" data=\"_gateway.swf?lc="+connectStr+"&variable="+escape(variable)+"&val="+escape(value)+"\" width=\"0\" height=\"0\">";
        divinfo += "<param name=\"movie\" value=\"_gateway.swf?lc="+connectStr+"&variable="+escape(variable)+"&val="+escape(value)+"\"/></object>";
	  document.getElementById(divcontainer).innerHTML = divinfo;
  }
}

function mok3_embedFlashUpgrader()
{
   var so = new SWFObject("_upgrader.swf" + mok3_getBuildParameter(), "detectiontest", "215", "138", "6.0.65", "#3A6EA5");
   so.addParam("wmode", "transparent");
   so.addParam("allowScriptAccess", "true");
   so.addParam("loop", "false");
   so.addVariable("MMdoctitle", document.title);
   so.addVariable("MMredirectURL", window.location.href);
   so.addVariable("MMplayerType", (navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length) ? "PlugIn" : "ActiveX");
   so.write("flash_upgrader_container");
}

function mok3_setSupertourViewerBackgroundColor( color )
{ mok3_g_supertourViewerBgColor = color; }
function mok3_getSupertourViewerBackgroundColor() { return mok3_g_supertourViewerBgColor; }

function mok3_embedSupertourViewer(options)
{
	var so = new SWFObject( '_supertour_viewer.swf' + mok3_getBuildParameter(), "central_broker", "100%", "100%", "8" );
  so.addParam( 'allowScriptAccess', 'sameDomain' );
	so.addParam( 'menu', 'false' );
	//so.addParam( 'swliveconnect', 'true' );
	if ( mok3_g_viewerWmodeTransparent )
		so.addParam( 'wmode', 'transparent' );
	
  if (options == null)
    options = mok3_getCbOptions();
	options = options.split( '&amp;' );
	for ( var i = 0; i < options.length; ++i )
	{
		var a = options[i].indexOf( '=' );
		if ( a > 0 )
		{
			var s = options[i].substring( 0, a );
			var t = options[i].substring( a + 1, options[i].length );
			so.addVariable( s, t );
//			alert( s + "\n" + t );
		}
	}
	so.addVariable( 'BGCOLOR', mok3_getSupertourViewerBackgroundColor());
  so.addVariable( 'showAngles', mok3_g_showAngles );
  so.addVariable( 'hideMapMsg', mok3_g_mapMsgCookie );
  so.addVariable( 'showPanoMsg', mok3_g_panoMsgCookie );
  //so.addVariable( 'tourSiteId', mok3_g_siteId );
  so.addVariable( 'showViewerOverride', mok3_g_showViewerOverride );

	so.write( 'supertour_viewer_container' );
}

function mok3_showTourViewer(bShow)
{
  mok3_g_showTourViewer = bShow;
}


/*
function mok3_setLoadingContent(percent, message)
{
  mok3_setIdWidth("loading_bar_fill", 200 * percent * 0.01);
  mok3_replaceIdContents("loading_message", message + "<br />" + percent + "% complete.");
}
*/

function mok3_initLayout( startMode )
{
  if ( startMode == null )
    startMode = 'flash_upgrade';
  mok3_setMode( startMode );
}

function mok3_showViewer( show, flashObjId )
{
  var bShow = show == "true";
	
	if (mok3_g_showTourViewer == bShow)
		return;

	if ( mok3_getBroker() != null)
		mok3_getBroker().js_showViewer(bShow);

	mok3_g_showTourViewer = bShow;
}

function mok3_flashUpgradeResult(result)
{
  switch (result)
  {
    case "success":
      mok3_stats("evt_flash_upgrade_success");
      window.opener = self;
      window.close();
      break;
      
     case "cancelled":
      mok3_stats("evt_flash_upgrade_cancelled");
      break;
      
    case "error":
      mok3_stats("evt_flash_upgrade_error");
      break;  
  }
}

function mok3_updateLocation(tourPath)
{
  // updates ui links based on where we are
  if (mok3_g_gsTourPath != null && mok3_g_gsTourPath == tourPath)
  {
    mok3_showShowInMapLink();
  }
  else
  {
    mok3_hideShowInMapLink();
  }
}

function mok3_openWeblink(url, target)
{
  try
  {
	  if (mok3_g_weblinkWindow == null || mok3_g_weblinkWindow.closed)
	  {
		  mok3_g_weblinkWindow = window.open( url, target);
	  }
	  else
	  {
		  mok3_g_weblinkWindow.location = url;
    }
    if (mok3_g_weblinkWindow != null)
  	  mok3_g_weblinkWindow.focus();
  	else
  	  alert("Unable to open the link.  Are you using a popup blocker?");
	}
	catch (err)
	{
	  //alert('Caught exception. \nName: ' + err.name + "\nMessage: " + err.message + "\nDesc: " + err.description);
	}
}

function mok3_stats( evt )
{
  sPage = "/" + evt;
  
  // Generate google analytics event
  if (typeof (urchinTracker) == 'function')
    urchinTracker(sPage);
}

/////// CSS!!
// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var 
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
	return h.className;
}();

