/*
--------------------------------------------------
	ContextualizeTitle Settings
--------------------------------------------------
*/
var titleSettings = {
	separator    : "Apex One Photo ",    // Text to insert between parts of title.
	maxLength    : -1,      // Limits length of title (-1 == no limit).
	doPhotos     : true,    // true == append photo captions
	doAlbums     : true,    // true == append album names
	doGalleries  : true,    // true == append gallery names
	stripSmugmug : true,    // true == remove " - powered by SmugMug" from title bar text
	inverse      : false,   // true == reverse order of home/gallery/album/photo
	siteTitle    : null     // null == use normal site title. "" == suppress site title. "Any Value" == replaces normal site title.
};

/*
--------------------------------------------------
	ContextualizeTitle Class
--------------------------------------------------
*/
function ContextualizeTitle ()
{
	var pieces = new TitlePieces();
	var newTitle = "";
	if (titleSettings.inverse)
	{
		newTitle = MakeTitleBackward();
	}
	else
	{
		newTitle = MakeTitleForward();
	}
	if (titleSettings.maxLength > -1)
	{
		newTitle = newTitle.substr(0, titleSettings.maxLength);
	}
	if (titleSettings.stripSmugmug == false)
	{
		newTitle += " - powered by SmugMug";
	}
	document.title = newTitle;

	// METHODS

	function MakeTitleBackward ()
	{
		var title = "";
		title += pieces.Photo
		if (title.length > 0
			&& pieces.Album.length > 0)
		{
			title += titleSettings.separator;
		}
		title += pieces.Album;
		if (title.length > 0
			&& pieces.Gallery.length > 0)
		{
			title += titleSettings.separator;
		}
		title += pieces.Gallery;
		if (title.length > 0
			&& pieces.Main.length > 0)
		{
			title += titleSettings.separator;
		}
		title += pieces.Main;
		return title;
	}

	function MakeTitleForward ()
	{
		var title = "";
		title += pieces.Main;
		if (title.length > 0
			&& pieces.Gallery.length > 0)
		{
			title += titleSettings.separator;
		}
		title += pieces.Gallery;
		if (title.length > 0
			&& pieces.Album.length > 0)
		{
			title += titleSettings.separator;
		}
		title += pieces.Album;
		if (title.length > 0
			&& pieces.Photo.length > 0)
		{
			title += titleSettings.separator;
		}
		title += pieces.Photo
		return title;
	}

	// CLASSES

	function TitlePieces ()
	{
		this.Main = GetMainTitle();
		this.Gallery = GetGalleryTitle();
		this.Album = GetAlbumTitle();
		this.Photo = GetPhotoTitle();

		function GetMainTitle ()
		{
			var value = titleSettings.siteTitle;
			if (value == null)
			{
				var index = document.title.indexOf("- powered by SmugMug");
				value = document.title.substr(0, index);
			}
			return value;
		}

		function GetGalleryTitle ()
		{
			var value = "";
			if (titleSettings.doGalleries)
			{
				var element = document.getElementById("galleryTitle");
				if (element)
				{
					value = GetTextContent(element);
					if (value.length > 0)
					{
						 // remove " galleries" from title
						var index = value.indexOf(" galleries");
						if (index > -1)
						{
							value = value.substr(0, index);
						}
					}
				}
			}
			return value;
		}

		function GetAlbumTitle ()
		{
			var value = "";
			if (titleSettings.doAlbums)
			{
				var element = document.getElementById("albumTitle");
				if (element)
				{
					value = GetTextContent(element);
				}
			}
			return value;
		}

		function GetPhotoTitle ()
		{
			var value = "";
			if (titleSettings.doPhotos)
			{
				var element = document.getElementById("caption_bottom");
				if (!element)
				{
					element = document.getElementById("caption_top");
				}
				if (element)
				{
					value = GetTextContent(element);
				}
			}
			return value;
		}

	}

} // end of ContextualTitle class

/*
--------------------------------------------------
	Utility Methods
--------------------------------------------------
*/

function GetPhotoCaption()
{
	var caption = "";
	var photoTitle = document.getElementById("caption_bottom");
	if(!photoTitle)
	{
		photoTitle = document.getElementById("caption_top");
	}
	if(photoTitle)
	{
		caption = GetTextContent(photoTitle);
	}
	return caption;
}

function GetTextContent(node)
{
	var text = "";
	if(node)
	{
		if(node.children)
		{
			text = GetTextContent(node.firstChild);
		}
		else
		{
			if(node.nodeValue)
			{
				text = node.nodeValue; // IE
			}
			else
			{
				text = node.textContent; // mozilla
			}
		}
	}
	text = Trim(text);
	return text;
}

function Trim(text)
{
	var regexp = /^\s+|\s+$/g;
	text = text.replace(regexp, "");
	return text;
}

function IsHomePage()
{
	var isHomePage = false;
	// test for the "homepage" class name in the <BODY> tag
	var classStr = document.body.className;
	if (classStr && (classStr.indexOf("homepage") != -1))
	{
		isHomePage = true;
	}
	return isHomePage;
}

function doOnLoad() {
  if (window.AlbumID && (window.AlbumID == "1842382")) //
  removeLinkFromImg();
}

function removeLinkFromImg()

{

    var links = document.getElementsByTagName("A");

    for (var i = 0; i < links.length; i++)

    {

        var link = links[i];

        var divElm = link.parentNode;

        if (!divElm)

            continue;

        divElm = divElm.parentNode;

        if (!divElm)

            continue;

        if (divElm.className.indexOf("photo")<0)

            continue;

        link.href = "javascript:void(0);";

    }

} 

//------------------------------------------------------------------------------------------
// Stretchy Slideshow code
//
// See http://www.dgrin.com/showthread.php?t=141047 for documentation on parameters.

//------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------
// Flash detection code
//
// We've change the name of the base object to avoid conflicting with anyone
// else.
//------------------------------------------------------------------------------------------

if (typeof deconceptTemp == "undefined") var deconceptTemp = new Object();
if (typeof deconceptTemp.util == "undefined") deconceptTemp.util = new Object();
if (typeof deconceptTemp.SWFObjectUtil == "undefined") deconceptTemp.SWFObjectUtil = new Object();
deconceptTemp.SWFObjectUtil.getPlayerVersion = function () {
  var PlayerVersion = new deconceptTemp.PlayerVersion([0, 0, 0]);
  if (navigator.plugins && navigator.mimeTypes.length) {
      var x = navigator.plugins["Shockwave Flash"];
      if (x && x.description) {
          PlayerVersion = new deconceptTemp.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
      }
  } else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0) {
      var axo = 1;
      var counter = 3;
      while (axo) {
          try {
              counter++;
              axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + counter);
              PlayerVersion = new deconceptTemp.PlayerVersion([counter, 0, 0]);
          } catch(e) {
              axo = null;
          }
      }
  } else {
      try {
          var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
      } catch(e) {
          try {
              var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
              PlayerVersion = new deconceptTemp.PlayerVersion([6, 0, 21]);
              axo.AllowScriptAccess = "always";
          } catch(e) {
              if (PlayerVersion.major == 6) {
                  return PlayerVersion;
              }
          }
          try {
              axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
          } catch(e) {}
      }
      if (axo != null) {
          PlayerVersion = new deconceptTemp.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
      }
  }
  return PlayerVersion;
}
deconceptTemp.PlayerVersion = function (arrVersion) {
  this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
  this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
  this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconceptTemp.PlayerVersion.prototype.versionIsValid = function (fv) {
  if (this.major < fv.major) return false;
  if (this.major > fv.major) return true;
  if (this.minor < fv.minor) return false;
  if (this.minor > fv.minor) return true;
  if (this.rev < fv.rev) return false;
  return true;
}



//------------------------------------------------------------------------------------------
// InsertStretchySlideshow
//
// This creates a stretchy slideshow that will size itself to the screen size.
//
// See http://www.dgrin.com/showthread.php?t=141047 for documentation on parameters.
//------------------------------------------------------------------------------------------

function InsertStretchySlideshow(parms)
{
  var slideshowInserted = false;

  // copy all attributes from src object to dest object
  // this is a shallow copy so if attributes are objects or arrays themselves, we are not doing a deep copy (thus they will be references)
  function CopyObj(dest, src)
  {
      for (var i in src)
      {
          dest[i] = src[i];
      }
  }

  // functions to determine element height and width across multiple browsers
  function GetElementWidth(whichElem)
  {
      var elem = YD.get(whichElem);
      if (!elem) return 0;
      if (typeof elem.clip !== "undefined")
      {
          return elem.clip.width;
      }
      else
      {
          if (elem.style.pixelWidth)
          {
              return elem.style.pixelWidth;
          }
          else
          {
              return elem.offsetWidth;
          }
      }
  }

  function GetElementHeight(whichElem)
  {
      var elem = YD.get(whichElem);
      if (!elem) return 0;
      if (typeof elem.clip !== "undefined")
      {
          return elem.clip.height;
      }
      else
      {
          if (elem.style.pixelHeight)
          {
              return elem.style.pixelHeight;
          }
          else
          {
              return elem.offsetHeight;
          }
      }
  }

  function DebugOut(e)
  {
      if (window.console) console.log(e);
  }

  function HandleResize()
  {
      if (!slideshowInserted) return;        // if we haven't put the slideshow object in yet, then don't try to talk to the flash object yet

      try
      {
          // make sure slideshow has been loaded before we call this
          var ssContainer = YD.get("ssLocalContainer");
          if (!ssContainer || !ssContainer.stretchySlideShowLoaded)
          {
              setTimeout(HandleResize, 10);        // keep calling until we're successful
              return;
          }

          var newSize = CalcAndSetSize();

          // set the slideshow to the right size and clear the cache here to get it to take the new size
          var ssObj = YD.get("stretchySSID");
          YD.setStyle(ssObj, "height", newSize.height + "px");
          YD.setStyle(ssObj, "width", newSize.width + "px");
          // DebugOut('Before call ssObj.extHookHandler({cmd: "clearCache"})');
          ssObj.extHookHandler({cmd: "clearCache"});
          // DebugOut('After call ssObj.extHookHandler({cmd: "clearCache"})');
      } catch (e) {DebugOut(e);}
  }

  function MakeSlideshowHTML(w, h, params)
  {
      params.name = "stretchySSID";
      params.allowedDomain = document.location.hostname;
      params.type = "gallery";
      params.transparent = "true";
      var args = "";
      for (var i in params) {
          args += i + "=" + params[i] + "&amp;";
      }
      var html = "";
      // because we need a DOM ID on the object, we can't do both object and embed and have it work right (conflicting IDs)
      // if it's navigator compatible, then just do the embed tag
      if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length)
      {
          // just embed tag
          html += '<embed id="stretchySSID" src="/ria/ShizamSlides-' + SM.appVersion['ShizamSlides'] + '.swf"';
          html += ' flashVars="' + args + '" wmode="transparent"';
          html += ' width="' + w + '" height="' + h + '"';
          html += ' type="application/x-shockwave-flash" allowScriptAccess="always" allowNetworking="all"/>';
          return(html);
      }
      else
      {
          // must be IE, just use the object tag
          html += '<object id="stretchySSID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" align="middle">';
          html += '<param name="movie" value="/ria/ShizamSlides-' + SM.appVersion['ShizamSlides'] + '.swf?' + args + '" />';
          html += '<param name="wmode" value="transparent"/>';
          html += '</object>';
          return(html);
      }
  }

  function CalcAndSetSize()
  {
      // use the width of our container as a starting point
      var ssWidth, ssHeight, viewWidth, viewHeight;
      var ssLocalContainer = YD.get("ssLocalContainer");

      // calc the desired height
      viewHeight = YD.getViewportHeight();
      var ssYPos = YD.getY(ssLocalContainer);

      // figure out if the homePageTools are there yet (probably aren't) and account for their eventual height
      // this is only an approximation and only affects the site when loggedIn
      if (YD.hasClass(document.body, "homepage") && YD.hasClass(document.body, "loggedIn"))
      {
          var homepageToolsHeight = GetElementHeight("homepageTools");
          if (homepageToolsHeight < 20)
          {
              homepageToolsHeight = 49;            // this is the approx height (measured in Firefox)
          }
          viewHeight -= homepageToolsHeight;        // account for the space that the homepage tools will take after they are added
      }

      // adjust height based on passed in parameters and our current position
      viewHeight -= localParms.extraH;                        // sutract out any extraH that was specified
      viewHeight -= ssYPos;                                // subtract out our starting y position so we just fill up the rest of the screen
      viewHeight = Math.min(viewHeight, localParms.maxH);    // don't start with more than maxH
      viewHeight = Math.max(viewHeight, localParms.minH);    // don't start with less than minH
      ssHeight = viewHeight;                                // go with this full height for now

      // set the actual height now so that a scroll bar will appear if required before we calc the width
      YD.setStyle(ssLocalContainer, "height", ssHeight + "px");

      // calc the desired width
      viewWidth = GetElementWidth(ssLocalContainer);
      if (viewWidth == 0)
      {
          viewWidth = YD.getViewportWidth() - 50;        // show something if we don't have a valid width
      }

      // if extra width padding is specified, take that out of the viewing area width
      viewWidth -= localParms.extraW;
      viewWidth = Math.min(viewWidth, localParms.maxW);    // don't start with more than maxW
      viewWidth = Math.max(viewWidth, localParms.minW);    // don't start with less than minW
      ssWidth = viewWidth;                                    // go with this full width for now

      // if constraining the aspect ratio, then find out what fits
      if (localParms.aspectHeightConstrain)
      {
          // now calc the size if we are constrained by width
          var ssHeightTest = parseInt(Math.round((ssWidth * localParms.aspectHeight) / localParms.aspectWidth, 10));

          // if the full height isn't needed, then go with only what is needed
          if (ssHeightTest < viewHeight)
          {
              ssHeight = ssHeightTest;
              YD.setStyle(ssLocalContainer, "height", ssHeight + "px");    // set the new height
              // Note: it is slightly possible that a scrollbar would have disappeared here (when we shortened the page), throwing our width calc off a little bit
              // not sure what we can do about that or that it's really a problem
          }
      }
      // return our results
      var ssSize = new Object;
      ssSize.width = ssWidth;
      ssSize.height = ssHeight;
      return(ssSize);
  }

  function CalcStandardSizeToFit(h, w)
  {
      var sizeTable = ["X3", "X2", "XL", "L", "M", "S", "Th", "Ti"];
      var widthTable = [1600, 1280, 1024, 800, 600, 400, 150, 100];
      var heightTable = [1200, 960, 768, 600, 450, 300, 150, 100];

      for (var i = 0; i < widthTable.length; i++)
      {
          if ((w > widthTable[i]) && (h > heightTable[i]))
          {
              return(sizeTable[i]);
          }
      }
      return("Ti");        // as small as we have
  }

  function AddSlideshowNow()
  {
      var ssSize = CalcAndSetSize();

      // now that we know the size, see if we should autoscale the splash image
      // http://jfriend.smugmug.com/photos/625569049_csHXe-L-3.jpg
      if (localParms.autoScaleSplash)
      {
          // get the base value of the URL
          var re = /(^.*?)(-[a-zA-Z0-9]{1,2})(-\d+){0,1}(.\w{3,})$/
          // matches[0] = whole string
          // matches[1] = first part of the string before the -X2
          // matches[2] = -X2
          // matches[3] = -2 (might be undefined)
          // matches[4] = .jpg
          var matches = re.exec(localParms.splash);
          if (matches && (matches.length >= 5))
          {
              var extension = matches[4];                        // get extension
              var version = matches[3] ? matches[3] : "";        // get version number if present
              localParms.splash = matches[1] + "-" + CalcStandardSizeToFit(ssSize.height, ssSize.width) + version + extension;
          }
      }

      // now make a clean version of the parms that doesn't have all our extra ones in it
      var cleanParms = new Object;
      for (var i in localParms)
      {
          // only copy over the params that are not our params (the ones not in our defaults table)
          if (typeof(defaultParms[i]) == "undefined")
          {
              cleanParms[i] = localParms[i];
          }
      }

      var containerObj = YD.get("ssLocalContainer");
      containerObj.innerHTML = MakeSlideshowHTML(ssSize.width, ssSize.height, cleanParms);
      slideshowInserted = true;        // now it's OK to talk to the flash object
  }

  // Here's where the actual execution of this function starts.  Everything before this was local function definitions
  var flashVersion = deconceptTemp.SWFObjectUtil.getPlayerVersion();
  var requiredVersion = new deconceptTemp.PlayerVersion([9,0,0]);
  if (!flashVersion.versionIsValid(requiredVersion))
  {
      if (parms.flashRequiredImageURL)
      {
          document.write('<div id="ssNoFlashDiv" style="text-align: center; vertical-align: middle; margin: 0 auto;"><img src=' + parms.flashRequiredImageURL + '" border="0" /></div>');
      }
      else
      {
          var noFlashHTML = 'You need the latest version of Adobe Flash Player to view the show! <a href="http://www.adobe.com/go/getflashplayer">Get it here</a>!';
          if (parms.flashRequiredHTML)
          {
              noFlashHTML = parms.flashRequiredHTML;
          }
          document.write('<div id="ssNoFlashDiv" style="text-align: center; vertical-align: middle; margin: 0 auto;">' + noFlashHTML + '</div>');
      }
      return;
  }

  // Set some default parameters if they don't already exist in the passed in parameter object.
  // We must list all possible parameters here with a default value because this list is also used
  // to strip out our extra parameters before passing the parms to the slideshow.
  var localParms = new Object;
  var defaultParms =
  {
      minW: 100,
      minH: 100,
      maxW: 5000,
      maxH: 5000,
      extraH: 10,
      extraW: 0,
      aspectWidth: 600,
      aspectHeight: 400,
      aspectHeightConstrain: "false",
      resize: "true",
      flashRequiredImageURL: "",
      flashRequiredHTML: "",
      autoScaleSplash: "false"
  };

  CopyObj(localParms, defaultParms);    // initialize with defaults
  CopyObj(localParms, parms);            // copy over the passed in parms (replacing default ones )

  // condition the input values (all numbers converted to real numbers, all booleans to real booleans, etc...
  // At this point, everyone of our defaultParms is present because we copied it in
  // so we cycle through the defaultParms list looking for each of those values in the localParms
  // and then fix it up if it needs fixing
  for (var i in defaultParms)
  {
      // Now make sure all the numeric parameters that are passed in as strings are converted to numbers
      if ((typeof(defaultParms[i]) == "number") && (typeof(localParms[i]) == "string"))
      {
          localParms[i] = parseInt(localParms[i]);
      }
      // convert all our vars to actual boolean true/false rather than strings
      if (localParms[i] == "true")
      {
          localParms[i] = true;
      }
      else if (localParms[i] == "false")
      {
          localParms[i] = false;
      }
  }

  // make sure that if we are constraining the aspect ratio that they have also passed in the aspect width and height
  if (localParms.aspectHeightConstrain)
  {
      if (!localParms.aspectWidth || !localParms.aspectHeight)
      {
          localParms.aspectHeightConstrain = false;        // turn constrain off because no height and width
      }
  }

  // make sure we aren't trying to auto scale when there is no splash image
  if (localParms.autoScaleSplash && !localParms.splash)
  {
      localParms.autoScaleSplash = false;        // turn it off, as both must be supplied
  }

  // if we are resizing, then set up a resize monitor
  if (localParms.resize)
  {
      YE.on(window, 'resize', HandleResize);
  }

  // add these additional parameters so our callback function can be hooked up
  localParms.eventHandler = "StretchySlideshowEventHandler";
  localParms.elementID = "ssLocalContainer";

  // put our place holder div into place
  document.write('<div id="ssLocalContainer" style="text-align: center; margin: 0 auto; height: auto; width: auto;"></div>');

  // wait until the document is laid out before we can actually measure the space available and insert the slideshow
  YE.onDOMReady(AddSlideshowNow);
}

// unfortunately, this has to be a globally scoped identifier
function StretchySlideshowEventHandler(elem, argObj)
{
  try
  {
      var str = "";
      if (argObj)
      {
          for (var i in argObj)
          {
              str += ", argObj[" + i + "] = " + argObj[i];
          }
      }

      if (argObj.type == "slideshowLoaded")
      {
          YD.get(elem).stretchySlideShowLoaded = true;
      }
  }
  catch (e) {if (window.console) console.log(e);}
}

//------------------------------------------------------------------------------------------
// End of Stretchy Slideshow code
//------------------------------------------------------------------------------------------

var Ll = new Array();
Ll[0] = "http://www.smugmug.com/photos/random.mg?AlbumID=4734709&AlbumKey=6qXp6&Size=75x75";

var P = new Array();
P[0] = "http://www.smugmug.com/photos/random.mg?AlbumID=5087841&AlbumKey=HSztF&Size=127.5x75";

var Lr = new Array();
Lr[0] = "http://www.smugmug.com/photos/random.mg?AlbumID=6706217&AlbumKey=iD82F&Size=75x75";

function choosePhoto(parray)
{
  inx = Math.floor(Math.random()*parray.length);
  img = parray[inx];
  document.write('<img border="2" src="' + img + '"/>');
}

/* ======two homepages====== */
function hasPath(sPath)
{
re = new RegExp("\/" + sPath + "(\/|$)");
return re.test(window.location)
}

/* ======flash slideshow====== */
function createSWF( w, h, params) {
var args = "";
for (var i in params) {
   args += i + "=" + params[i] + "&amp;";
}
document.writeln('<object width="100%" height="100%" align="middle">'+
'<param name="movie" value="http://www.smugmug.com/ria/ShizamSlides-2007091201.swf?'+args+'"/>'+
'<param name="wmode" value="transparent" />'+
'<embed src="http://www.smugmug.com/ria/ShizamSlides-2007091201.swf?'+args+'" wmode="transparent" width="' + w + '" height="' + h + '" type="application/x-shockwave-flash" allowScriptAccess="always" allowNetworking="all"/></object>');
return 1;
}

rightClickWarning = "© All photos are property of Apex One Photo. All rights reserved. Unauthorized use is prohibited.";

document.title = "Apex One Photo";
function RelevantTitle()
{
 var baseTitle = "Apex One Photo";
 var separator = " - ";
 var albumTitle = document.getElementById("albumTitle");
 var galleryTitle = document.getElementById("galleryTitle");
 if( albumTitle && albumTitle.textContent )
    document.title = baseTitle + separator + albumTitle.textContent;
 else if( galleryTitle && galleryTitle.textContent )
 {
    var galleryTitleText = galleryTitle.textContent;
    // Strip " sub-categories" off the end of the category text
    var finalPositionCategory = galleryTitleText.SEARCH(" sub-categories");
    if( finalPositionCategory >= 0 )
       galleryTitleText = galleryTitleText.substr( 0, finalPositionCategory );
    else
    {
       // Strip " galleries" off the end of the category/sub-category text
       var finalPositionSubCategory = galleryTitleText.search(" galleries");
       if( finalPositionSubCategory >= 0 )
          galleryTitleText = galleryTitleText.substr( 0, finalPositionSubCategory );
    }
    document.title = baseTitle + separator + galleryTitleText;
 }
 else // Not Gallery, Category, or Subcategory
 {
    // Set title on homepage
    document.title = baseTitle;
 }
}