//=======================================================
// Functions accessible from Flash ExternalInterface should not be in included .js as may not be initialized when Flash calls them!

// Must match IMM_ActionScript/common.as
var imm_success = 1;
var imm_failed = 2;
var imm_pending = 3;
var imm_abort = 4;
var imm_retry = 5;

function GetPageURL()
{
  var szURL = window.location.href;
  //alert(szURL);
  return(szURL);
}
      
function GetUniqueBrowserID()
  {
  var szTimestamp = GetBrowserTimestamp();
  //alert("application.rhtml => GetUniqueBrowserID()="+szTimestamp)
  return(szTimestamp);
  }

function ShowLogin()
{
  // Note: Flash object name will be imm_swf_name[_div_extn]
  var flashHeader = getMovieObj("imm_header");
  //alert("ShowLogin():"+flashHeader);
  // see flash.external.ExternalInterface.addCallback in Flash header.swf
  flashHeader.ShowLogin();
}

// Called by ExternalInterface to manage inter-swf communication
// Returns imm_success/failed/pending/retry
// Note: JS syntax errors may not show up but call can fail!
function SendCommand(szCallbackTarget, szTarget, szTargetFn, param1, param2, param3, param4, param5)
{
  var nRet = imm_failed;
  
  //alert("SendCommand("+szCallbackTarget+", "+szTarget+", "+szTargetFn+", "+param1+", "+param2+", "+param3+", "+param4+", "+param5+")");
  
  // Assume format 'obj_name'.'obj_name'_'this'
  var targetParts = szTarget.split(".");
 
  // First check target exists, loaded and initialized else retry
  var targetObj = getFlashMovieObject(targetParts[0]);
  //alert("Target="+szTarget+" => "+targetObj);
  if (!targetObj)
    {
    //alert("Target not loaded yet");
    return(imm_retry);
    }
  
  // Ping first so we can retry and trap other eval exceptions seperately and fail
  var szCommand = "getFlashMovieObject(\""+targetParts[0]+"\")";
  szCommand+="."+targetParts[1]+"(undefined, \"onActionInternal\", \"_ping\", undefined, undefined, undefined, undefined)";

  // Can throw exception here!
  try
    {
    nRet = eval(szCommand);
    }
  catch(szErr)
    {
    //alert("SendCommand ping failed:"+szCommand+" =>"+szErr);
    return(imm_retry);
    }

  // OK so object and callback are available
  // See flash.external.ExternalInterface.addCallback()
  szCommand = "getFlashMovieObject(\""+targetParts[0]+"\")";
  szCommand+="."+targetParts[1]+"(";
  szCommand+=addParam(szCallbackTarget, true);
  szCommand+=addParam(szTargetFn, true);
  szCommand+=addParam(param1, true);
  szCommand+=addParam(param2, true);
  szCommand+=addParam(param3, true);
  szCommand+=addParam(param4, true);
  szCommand+=addParam(param5);
  szCommand+=")";
  //alert(szCommand);
  
  // Can throw exception here!
  try
    {
    nRet = eval(szCommand);
    //alert(nRet);
    }
  catch(szErr)
    {
    alert("SendCommand error:"+szCommand+" =>"+szErr);
    }
  
  // Only a no response should trigger a retry!
  if (nRet != imm_success && nRet != imm_failed && nRet != imm_pending)
    nRet = imm_retry;

  return(nRet);
}

// Note: Make sure to escape '"' in params!
function addParam(szParam, bComma)
{
  // Quote of string
  if (szParam != undefined && typeof(szParam) == "string")
    szParam = "\""+szParam+"\"";  // Quote as string in eval()!
  
  if (bComma==true)
    szParam += ", ";

  return(szParam);
}

function onHeaderTrackScore(gameID, level, score, other, sig)
{
  // Note: Flash object name will be div_movie_extn
  var flashHeader = getFlashMovieObject("imm_header");
  //alert("onHeaderTrackScore():"+flashHeader+", "+sig);
  // see ExternalInterface.addCallback in Flash header.swf
  flashHeader.onHeaderTrackScore(gameID, level, score, other, sig);
}

function onHeaderAction(szAction, bIgnoreBackProcessing, param1, param2, param3)
{
  // Note: Flash object name will be div_movie_extn
  var flashHeader = getFlashMovieObject("imm_header");
  //alert("onHeaderAction():"+flashHeader+", "+szAction);
  // see ExternalInterface.addCallback in Flash header.swf
  flashHeader.onHeaderAction(szAction, bIgnoreBackProcessing, param1, param2, param3);
}

// If called from clicked link should work through popup blockers but from events (onunload...) will fail
function popupWindow(url, name, width, height)
{
 var popup_win;
 if (navigator.appVersion.indexOf('4') != -1)
   {
   // Vars for centering the new window on Version 4 Browsers
   xTop = screen.width/2 - (width/2);
   yTop = screen.height/2 - (height/2);

   popup_win = window.open(url, name, 'height='+height+',width='+width+',scrollbars=1,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=' + xTop + ',top=' + yTop + '');
   }
 else
   {
   popup_win = window.open(url, name, 'height='+height+',width='+width+',scrollbars=1,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=150,top=200');
   }
 
 // Set focus
 if (popup_win)
   popup_win.focus();
 
 return("popupWindow()");
}

// Assumes:
// 1. IFRAME has name/id set to szFrameID
// 2. IFRAME src contains a div with id=szDivID i.e. <div id="szDivID" style="position:absolute;cursor:default">
// Note: Does not seem to be an easy standard way to make content non-selectable!
function IFrameScroll(szFrameID, szDivID, nPercent)
{
  //alert("IFrameScroll("+szFrameID+", "+szDivID+", "+nPercent+")");
  var iframewindow = getIFrameWindow(szFrameID);
  var nFrameHeight = iFrameHeight(iframewindow);
  var divobj = getElementObj(szDivID, iframewindow);
  var nContentHeight = divobj.offsetHeight;
  
  var nScrollDelta = nContentHeight - nFrameHeight;
  
  if (nScrollDelta < 0)
    nScrollDelta = 0;
    
  var nScrollPixels = -nScrollDelta * nPercent / 100;
  //alert("Scroll to="+nScrollPixels);
  
  // Firefox requires "px"
  divobj.style.top=nScrollPixels+"px";
}

// May need to poll if loading page
// page length in pixels or -1 if loading
function isScrollable(szFrameID, szDivID)
{
  if (bIsLoading)
    return(-1);
    
  return(nContentHeight);
}

function GetIFRAMEContent(szURL, szFrameID)
{
  bIsLoading = true;
  //alert("GetIFRAMEContent("+szIFrameName+", "+szURL+")");

  var iframeobj = document.all ? eval("document.all."+szFrameID) : document.getElementById(szFrameID); 

  //alert("IFRAME="+iframeobj);
  iframeobj.src = szURL; 
}

function getElementObj(szID, win)
{
  var obj;

  //alert("getElementObj("+szID+", "+win+")");

  if (win == undefined)
    win = window;

  obj = win.document.all ? eval("win.document.all."+szID) : win.document.getElementById(szID);

  return(obj);
}

function getIFrameWindow(szFrameID)
{
  var iframeobj = getElementObj(szFrameID);
  return(iframeobj.contentWindow);
}

// IFRAME should have: onload='NotifyFrameLoaded("szFrameID", "szDivID")'
// IFRAME onLoad() appears to fire BEFORE page src property is updated. Using setTimeout() processes all events first
var bIsLoading = true;
var bScrollable = false;
var nContentHeight = 0;
function NotifyFrameLoaded(szFrameID, szDivID)
{
  setTimeout("NotifyLoaded('"+szFrameID+"', '"+szDivID+"')", 100);
}

// Do NOT call directly => see NotifyFrameLoaded()
// Note: szDivID is scrollable div within src loaded by IFRAME!
function NotifyLoaded(szFrameID, szDivID)
{
  //alert("NotifyLoaded("+szFrameID+", "+szDivID+")");
  bIsLoading = false;
  
  var iframeobj = getElementObj(szFrameID);
  var iframewindow = getIFrameWindow(szFrameID);
  var nFrameHeight = iFrameHeight(iframewindow);
  var divobj = getElementObj(szDivID, iframewindow);
  nContentHeight = divobj.offsetHeight;
  
  bScrollable = nContentHeight > nFrameHeight ? true : false;
  
  // Notify header that frame content changed
  var szBlogURL = iframeobj.src;
  //alert("IFRAME src="+szBlogURL);
  onHeaderAction("broadcast", true, "refresh_blog_section", szBlogURL);
}

function iFrameHeight(win)
{
  var nHeight = 0;
  
  // Non-IE
  if (typeof(win.innerWidth) == 'number')
    nHeight = win.innerHeight;
  // IE 6+ in 'standards compliant mode'
  else if (win.document.documentElement && win.document.documentElement.clientHeight)
    nHeight = win.document.documentElement.clientHeight;
  // IE 4 compatible
  else if (win.document.body && win.document.body.clientHeight)
    nHeight = win.document.body.clientHeight;

  return(nHeight);
}

//=======================================================

onresize=PositionCurtains;

function PositionCurtains()
{
  //alert("onresize");
  
  //document.getElementById("curtains").width = GetWidth();
  document.getElementById("curtain_spacer").width = GetWidth();
}

function GetWidth()
  {
  var myWidth=0, myHeight=0;
  if (typeof(window.innerWidth) == 'number')
    {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
    }
  else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
    }
  else if(document.body && (document.body.clientWidth || document.body.clientHeight))
    {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
    }
    
  var width = 984 - 2 * 219;

  // Extend up to 2 * 219 pixels
  if (myWidth > 984)
    {
    width = myWidth - 2 * 219;
    }
    
  if (width > 984 + 2 * 219)
    {
    width = 984 + 2 * 219;
    }
    
  return(width);
}

function GetContent(szController, szPartial)
{
  //alert("Ajax.Updater: GetContent("+szController+", "+szPartial+")");

  // Google Analytics
  urchinTracker("/"+szController+"/"+szPartial);
  
  // Rails prototype.js
  // JavaScript will ALWAYS get stripped. If evalScripts:true script is parsed and EVALUATED before being stripped!
  // See more details at: http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxUpdater
  // Note : Updater is very picky about what it parses (and evaluates) without errors (onException:reportException seems to give FireFox issues)!
  // Evaluation or html syntax errors may not give JavaScript warnings but disable page/other script on page
  // Note: Had issues in some browsers caching page i.e. Click Gallery and get signup page, login and click Gallery and still get cached signup page!
	var no_cache = GetUniqueTimestamp();
	var url = '/'+szController+'/'+szPartial+'?'+no_cache;
	var pars = "";
	var AjaxObj = new Ajax.Updater({success: 'ajax_content'}, url, {method:'get', parameters:pars, onFailure:reportError, asynchronous:true, evalScripts:true});

	function reportError(XMLHttpRequest, Object)
  	{
    var szErrMsg = "Could not get content from server. (AJAX.Updater="+Object+")";
		alert(szErrMsg);
    
    var flashHeader = getFlashMovieObject("imm_header");
    //alert("ShowError():"+flashHeader);
    // see flash.external.ExternalInterface.addCallback in Flash header.swf
    flashHeader.ShowError(szErrMsg);
	  }
}

var jsReady = false;
function isJSReady()
{
  return(jsReady);
}

function init()
{
  //alert("init()");
  jsReady = true;
  PositionCurtains();
}
