//Change "Featured Galleries" to "Recent Galleries Added" - COMMENTED OUT
//YE.onAvailable('featuredTitle', function() {this.innerHTML = 'Recent //Galleries Added'});

//STOP FILMSTRIP FROM MOVING
filmstripMove = 0;

//MAKE FILMSTRIP GO OTHER DIRECTION
rightMoves = -5;
leftMoves = 5;

//Make Smugmug link a referral
function AddReferralCode() {
var links = this.getElementsByTagName("A");
if (links && (links.length != 0)) {
var smugLink = links.item(0);
smugLink.href = "http://www.smugmug.com/?referrer=TDXs85P2GErBQ";
}
}
YE.onAvailable('footer', AddReferralCode);

//Make photobar pop out to right of photo instead of over it
SM.PhotoBar.config.position = 'right';


//Make 'second' home page - for featured or recent galleries
function hasPath(sPath)
{
re = new RegExp("\/" + sPath + "(\/|$)");
return re.test(window.location)
}



/*=========================*/
/*== SLIDE SHOW          ==*/
/*== version 0.58        ==*/
/*== Updated 15 Mar 2007 ==*/
/*=========================*/
var SLIDE_SHOW = 0;
var RANDOM_PHOTO = 1;
var slideshowContainer;
var sSlide;
var sCaption;
var ssSlides;
var ssSlideTotal;
var ssSlideTimer;
var ssOldSlide;
var ssFadeTimer;
var ssFade;
var ssTimerId;
var blank;


function PrepSlideEnvironment() {
  tmpCookie = getCookie("Template");

  blank = new Image();
  blank.src = "/img/spacer.gif";

  if (typeof(slideshowType) == "undefined" || (slideshowType != SLIDE_SHOW && slideshowType != RANDOM_PHOTO)) {
    slideshowType = SLIDE_SHOW;
  }

  if (slideshowType == RANDOM_PHOTO) {
    randomSlides = true;
  }

  if (typeof(slideshowContainerId) == "undefined") {
    return false;
  } else if (typeof(slideshowContainerId) == "string") {
    slideshowContainer = YD.get(slideshowContainerId);
  }

  if (!slideshowContainer) {
    return false;
  }

  if (typeof(slideshowUrl) == "undefined" || typeof(slideshowUrl) != "string") {
    return false;
  } else {
    slideshowUrl =  /(?:http:\/\/[^\/]+)?(\/\S+)/.exec(slideshowUrl)[1];
  }

  if (/\/gallery\/[0-9]+/.test(slideshowUrl)) {
    slideSourceIsGallery = true;
  } else {
    slideSourceIsGallery = false;
  }

  if (typeof(slideHeight) == "undefined" || isNaN(slideHeight)) {
    slideHeight = "200";
  }

  if (typeof(slideWidth) == "undefined" || isNaN(slideWidth)) {
    slideWidth = "300";
  }

  if (typeof(photoHeight) == "undefined" || isNaN(photoHeight)) {
    photoHeight = slideHeight;
  }

  if (typeof(photoWidth) == "undefined" || isNaN(photoWidth)) {
    photoWidth = slideWidth;
  }

  if (typeof(slideDuration) == "undefined" || isNaN(slideDuration)) {
    slideDuration = 3;
  }

  if (typeof(firstSlideUrl) == "undefined" || typeof(firstSlideUrl) != "string") {
    firstSlideUrl = blank.src;
  }

  if (typeof(showSlideTransition) == "undefined" || typeof(showSlideTransition) != "boolean") {
    showSlideTransition = true;
  }
   
  if (typeof(resizeToPhoto) == "undefined" || typeof(resizeToPhoto) != "boolean") {
    resizeToPhoto = true;
  }

  if (typeof(quickStart) == "undefined" || typeof(quickStart) != "boolean") {
    quickStart = true;
  }

  if (typeof(randomSlides) == "undefined" || typeof(randomSlides) != "boolean") {
    randomSlides = false;
  }

  if (typeof(slideControls) == "undefined" || typeof(slideControls) != "boolean") {
    slideControls = false;
  }

  if (typeof(slideCaptions) == "undefined" || typeof(slideCaptions) != "boolean") {
    slideCaptions = false;
  }

  if (typeof(slidesClickable) == "undefined" || typeof(slidesClickable) != "boolean") {
    slidesClickable = false;
  }

  return true;
}


function loadSlideshow() {
  if (!PrepSlideEnvironment()) {
    return false;
  }

  slideshowContainer.innerHTML = '<img src="http://www.smugmug.com/img/spacer.gif" alt="" id="ssSlide" height="' + slideHeight + '" width="' + slideWidth + '" style="opacity: .99; background-image: url(' + firstSlideUrl + '); background-repeat: no-repeat; background-position: center;" />';

  if (slideCaptions) {
    slideshowContainer.innerHTML += '<div id="ssCaption"></div>';
  }

  if (slideControls) {
    slideshowContainer.innerHTML += '<div id="ssControl"><a title="Previous Slide" id="ssPrev" class="ssBtn" href="javascript: void(0);" onclick="prevSlide();"><img src="/img/spacer.gif" border="0" /></a><a title="Pause Slideshow" id="ssPause" class="ssBtn" href="javascript: void(0);" onclick="pauseSlideshow();"><img src="/img/spacer.gif" border="0" /></a><a title="Resume Slideshow" id="ssPlay" class="ssBtn" href="javascript: void(0);" onclick="resumeSlideshow();"><img src="/img/spacer.gif" border="0" /></a><a title="Next Slide" id="ssNext" class="ssBtn" href="javascript: void(0);" onclick="nextSlide();"><img src="/img/spacer.gif" border="0" /></a></div>';
  }

  sSlide = YD.get('ssSlide');
  sCaption = YD.get('ssCaption');

  if (slidesClickable) {
    sSlide.style.cursor = 'pointer';
  
    if (firstSlideUrl != blank.src) {
      ssAddSlideClick(slideshowUrl);
    }
  }

  ssSlides = [];
  ssSlideTotal = 0;
  ssSlideTimer = 0;
  ssOldSlide = 0;
  ssFadeTimer = 100;
  ssFade = "out";  

  if (slideSourceIsGallery) {
    ajax_query(slideshowHandler, '/photos/sspopup.mg?AlbumID=' + /\/gallery\/([0-9]+)/.exec(slideshowUrl)[1], null, true);
  } else {
    var postArray = [];
    postArray['TemplateID'] = '8';
    postArray['origin'] = slideshowUrl;
    ajax_query(slideshowHandler, '/homepage/templatechange.mg', postArray, true);
  }
}


function slideshowHandler(response)
{
  if (!slideSourceIsGallery) {
    if (tmpCookie && tmpCookie != "") {
      setCookie('Template', tmpCookie, 30, '/', /(?:http[s]?:\/\/)?(?:\w+\.)?(\S+[^\/])/.exec(location.href)[1]);
    } else {
      deleteCookie("Template", "/", /(?:http[s]?:\/\/)?(?:\w+\.)?(\S+[^\/])/.exec(location.href)[1]);
    }
  }

  var re = /imageID\[\d+\] = "\d+";/g;
  var re2 = /width\[\d+\] = "\d+";/g;
  var re3 = /height\[\d+\] = "\d+";/g;
  var re4 = /caption\[\d+\] = ".*";/g;

  s = response.match(re); 
  w = response.match(re2);
  h = response.match(re3);
  c = response.match(re4);

  var oSlide;

  for (i = 0; i < s.length; i++) {
    oSlide = {};

    temp = s[i].split(/"/);
    oSlide.ImageId = temp[1];
    oSlide.File = 'http://upload.smugmug.com/photos/toolthumbs.mg?ImageID=' + temp[1] + '&tool=slideshowXL&winHeight=' + photoHeight + '&winWidth=' + photoWidth;
    oSlide.Gallery = slideshowUrl + '/1/' + oSlide.ImageId;

    temp = h[i].split(/"/);
    oSlide.Height = temp[1];

    temp = w[i].split(/"/);
    oSlide.Width = temp[1];

    temp = c[i].split(/"/);
    oSlide.Caption = temp[1];

    oSlide.Loaded = false;
 
    if ((oSlide.Width > photoWidth) || (oSlide.Height > photoHeight)) {
      if (oSlide.Width >= oSlide.Height) {
         oSlide.Height = Math.round((oSlide.Height / oSlide.Width) * photoWidth);
         oSlide.Width = photoWidth;
      } else {
        oSlide.Width = Math.round((oSlide.Width / oSlide.Height) * photoHeight);
        oSlide.Height = photoHeight;
      }
    }

    ssSlideTotal = ssSlides.push(oSlide);
  }

  ssSlideTotal -= 1;

  if (randomSlides) {
    ssSlides.shift();
    ssSlides.shuffle();
    ssSlides.unshift(0);
  }

  if (quickStart) {
    ssSlideTimer = (slideDuration * 1000);
  }

  ssPrepSlide(1);
  window.setTimeout("ssPrepSlide(2);", 0);
  window.setTimeout("ssPrepSlide(ssSlideTotal);", 0);

  if (slideshowType == SLIDE_SHOW) {
    ssPlaySlideshow();
  } else {
    ssSlideSwap(1);
  }
}


function ssPauseSlideshow()
{
  window.clearTimeout(ssTimerId);
  ssTimerId = null;
}


function ssResumeSlideshow()
{
  if (!ssTimerId) {
    ssTimerId = window.setTimeout("ssPlaySlideshow()", 10);
  }
}


function ssPrepSlide(prep)
{
  if (ssSlides[prep].Loaded == false) {
    ssSlides[prep].Image = new Image();
    ssSlides[prep].Image.src = ssSlides[prep].File;
    ssSlides[prep].Loaded = true;
  }   
}


function ssMoveSlide(i) {
  ssSlideTimer = 0;
  ssFadeTimer = 100;
  ssTransition(ssFadeTimer);
  ssFade = "out";
  ssSlideSwap(i);                       
}


function ssPlaySlideshow()
{
  if (ssSlideTimer >= (slideDuration * 1000))
  {                
    if (ssFade == 'out') {
      ssTransition(ssFadeTimer -= 10);
    }
 
    if (ssFadeTimer == 0) {
      ssSlideSwap(1);
      ssFade = 'in';
    }
 
    if (ssFade == 'in') {
      ssTransition(ssFadeTimer += 10);
    }
 
    if (ssFadeTimer == 100) {
      ssSlideTimer = 0;
      ssFade = 'out';
    }
  } else {
    ssSlideTimer += 10;
  }
 
  ssTimerId = window.setTimeout("ssPlaySlideshow()", 10);
}


function ssTransition(opacity)
{
  if (showSlideTransition)
  {
    if (opacity != 100) {
      YD.setStyle(sSlide, 'opacity', (opacity / 100));
    } else {
      YD.setStyle(sSlide, 'opacity', '.99'); // to prevent flashing in mozilla browsers
    }
 
    // only affects Win IE
    YD.setStyle(sSlide, 'filter', 'alpha(opacity=' + opacity + ')');

    if (sCaption) {
      YD.setStyle(sCaption, 'opacity', sSlide.style.opacity);
      YD.setStyle(sCaption, 'filter', sSlide.style.filter);
    }
  }
}


function ssSlideSwap(i)
{
  var newSlide = ssOldSlide + i;
 
  if (newSlide > ssSlideTotal)
    newSlide = 1;
 
  if (newSlide < 1)
    newSlide = ssSlideTotal;
 
  if (ssSlides[newSlide].Loaded != false)
  {
    document.images['ssSlide'].src = blank.src;
    YD.setStyle(sSlide, 'backgroundImage', 'url(' + ssSlides[newSlide].File + ')');

    if (resizeToPhoto)
    {
      document.images['ssSlide'].height = ssSlides[newSlide].Height;
      document.images['ssSlide'].width = ssSlides[newSlide].Width;
    }

    if (slidesClickable) {
      ssAddSlideClick(ssSlides[newSlide].Gallery);
    }
    
    if (slideCaptions) {
      YD.get('ssCaption').innerHTML = ssSlides[newSlide].Caption;
    }

    ssPrepSlide(newSlide < ssSlideTotal ? newSlide + i : 1);
    ssOldSlide = newSlide;
  } else {
    ssPrepSlide(newSlide);
    ssSlideSwap(i);
  }
}


function ssAddSlideClick(sUrl) {
  YE.purgeElement(sSlide, false, 'click');
  YE.addListener(sSlide, 'click', function() {
	location.href = sUrl;
  })
}


Array.prototype.shuffle = function()
{
  var len = this.length;
  var rand, temp, i;

  for (i = 0; i < len; i++)
  {
    rand = Math.floor(Math.random()*len);
    temp = this[i];
    this[i] = this[rand];
    this[rand] = temp;
  }
}


function pauseSlideshow()
{
  YD.setStyle('ssPause', 'display', 'none');
  YD.setStyle('ssPlay', 'display', 'inline');
  ssPauseSlideshow();
}


function resumeSlideshow()
{
  YD.setStyle('ssPause', 'display', 'inline');
  YD.setStyle('ssPlay', 'display', 'none');
  ssResumeSlideshow();
}


function prevSlide()
{
  pauseSlideshow();
  ssMoveSlide(-1);
}


function nextSlide()
{
  pauseSlideshow();
  ssMoveSlide(1);
}


function getCookie(name) {
  var start = document.cookie.indexOf(name + "=");
  var len = start + name.length + 1;
  
  if ((!start) && (name != document.cookie.substring(0, name.length))) {
    return null;
  }

  if (start == -1) {
    return null;
  }

  var end = document.cookie.indexOf(";", len);

  if (end == -1) {
    end = document.cookie.length;
  }

  return unescape(document.cookie.substring(len, end));
}


function setCookie(name, value, expires, path, domain, secure) {
  var today = new Date();
  today.setTime( today.getTime() );

  if (expires) {
    expires = expires * 1000 * 60 * 60 * 24;
  }

  var expires_date = new Date(today.getTime() + (expires));

  document.cookie = name + '='+escape(value) +
    ((expires) ? ';expires=' + expires_date.toGMTString() : '') +
    ((path) ? ';path=' + path : '') +
    ((domain) ? ';domain=' + domain : '') +
    ((secure) ? ';secure' : '');
}


function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
  }
}


// RECENT GALLERIES HACK

// This hack replaces your Featured Galleries with Recent Galleries as determined by the RSS feed.
//
// RSS parsing code from Paul Sobocinski found here:
// http://www.xml.com/pub/a/2006/09/13/rss-and-ajax-a-simple-news-reader.html?page=5

// NOTE: You must have one gallery set to featured, as a placeholder to make the Featured Box show up
// This placeholder gallery will not show up once the hack is in place.

// Rename Featured Galleries to Recent Galleries
YE.onContentReady('featuredTitle', function() {this.innerHTML='Recently Updated Galleries'});

// Specify how many recent galleries you'd like to see
var rsscount = 6 ;

// Specify your RSS feed for Recent Galleries (replace XXXXXX with your site name)
// ImageCount needs to be "padded" if you have a lot of private galleries mixed in with your public 
// galleries.  If you are not seeing 6 (or however many) recent galleries, try increasing ImageCount

var rssurl = "http://www.adamfarber.com/hack/feed.mg?Type=nickname&Data=afarber&format=rss200&ImageCount=10";

// Added a line to the doOnLoad function that is also used by the removeLinkFromImg() function and others.  
// So you may only need to append the if//getRSS clause below.

function doOnLoad() {
  if (YD.hasClass(document.body, "homepage")) //
     getRSS();
}

//OBJECTS

//objects inside the RSS2Item object
function RSS2Enclosure(encElement)
{
	if (encElement == null)
	{
		this.url = null;
		this.length = null;
		this.type = null;
	}
	else
	{
		this.url = encElement.getAttribute("url");
		this.length = encElement.getAttribute("length");
		this.type = encElement.getAttribute("type");
	}
}

function RSS2Guid(guidElement)
{
	if (guidElement == null)
	{
		this.isPermaLink = null;
		this.value = null;
	}
	else
	{
		this.isPermaLink = guidElement.getAttribute("isPermaLink");
		this.value = guidElement.childNodes[0].nodeValue;
	}
}

function RSS2Source(souElement)
{
	if (souElement == null)
	{
		this.url = null;
		this.value = null;
	}
	else
	{
		this.url = souElement.getAttribute("url");
		this.value = souElement.childNodes[0].nodeValue;
	}
}

//object containing the RSS 2.0 item
function RSS2Item(itemxml)
{
	//required
	this.title;
	this.link;
	this.description;

	//optional vars
	this.author;
	this.comments;
	this.pubDate;

	//optional objects
	// this.category;
	this.enclosure;
	this.guid;
	this.source;

	var properties = new Array("title", "link", "description", "author", "comments", "pubDate");
	var tmpElement = null;
	for (var i=0; i<properties.length; i++)
	{
		tmpElement = itemxml.getElementsByTagName(properties[i])[0];
		if (tmpElement != null)
			eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
	}

	// this.category = new RSS2Category(itemxml.getElementsByTagName("category")[0]);
	this.enclosure = new RSS2Enclosure(itemxml.getElementsByTagName("enclosure")[0]);
	this.guid = new RSS2Guid(itemxml.getElementsByTagName("guid")[0]);
	this.source = new RSS2Source(itemxml.getElementsByTagName("source")[0]);
}

//objects inside the RSS2Channel object
function RSS2Category(catElement)
{
	if (catElement == null)
	{
		this.domain = null;
		this.value = null;
	}
	else
	{
		this.domain = catElement.getAttribute("domain");
		this.value = catElement.childNodes[0].nodeValue;
	}
}

//object containing RSS image tag info
function RSS2Image(imgElement)
{
	if (imgElement == null)
	{
	this.url = null;
	this.link = null;
	this.width = null;
	this.height = null;
	this.description = null;
	}
	else
	{
		imgAttribs = new Array("url","title","link","width","height","description");
		for (var i=0; i<imgAttribs.length; i++)
			if (imgElement.getAttribute(imgAttribs[i]) != null)
				eval("this."+imgAttribs[i]+"=imgElement.getAttribute("+imgAttribs[i]+")");
	}
}

//object containing the parsed RSS 2.0 channel
function RSS2Channel(rssxml)
{
	//required
	this.title;
	this.link;
	this.description;

	//array of RSS2Item objects
	this.items = new Array();

	//optional vars
	this.language;
	this.copyright;
	this.managingEditor;
	this.webMaster;
	this.pubDate;
	this.lastBuildDate;
	this.generator;
	this.docs;
	this.ttl;
	this.rating;

	//optional objects
	// this.category;
	this.image;

	var chanElement = rssxml.getElementsByTagName("channel")[0];
	var itemElements = rssxml.getElementsByTagName("item");

	for (var i=0; i<itemElements.length; i++)
	{
		Item = new RSS2Item(itemElements[i]);
		this.items.push(Item);
		//chanElement.removeChild(itemElements[i]);
	}

	var properties = new Array("title", "link", "description", "language", "copyright", "managingEditor", "webMaster", "pubDate", "lastBuildDate", "generator", "docs", "ttl", "rating");
	var tmpElement = null;
	// this.category = new RSS2Category(chanElement.getElementsByTagName("category")[0]);
	this.image = new RSS2Image(chanElement.getElementsByTagName("image")[0]);
}

//PROCESSES

//uses xmlhttpreq to get the raw rss xml
function getRSS()
{
	//call the right constructor for the browser being used
	if (window.ActiveXObject)
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest)
		xhr = new XMLHttpRequest();
	else
		alert("not supported");

	//prepare the xmlhttprequest object
	xhr.open("GET",rssurl,true);
	xhr.setRequestHeader("Cache-Control", "no-cache");
	xhr.setRequestHeader("Pragma", "no-cache");
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4)
		{
			if (xhr.status == 200)
			{
				if (xhr.responseText != null)
					processRSS(xhr.responseXML);
				else
				{
					alert("Failed to receive RSS file from the server - file not found.");
					return false;
				}
			}
			else
				alert("Error code " + xhr.status + " received: " + xhr.statusText);
		}
	}

	//send the request
	xhr.send(null);
}

//processes the received rss xml
function processRSS(rssxml)
{
	RSS = new RSS2Channel(rssxml);
	showRSS(RSS);
}

//shows the RSS content in the browser
function showRSS(RSS)
{

    divTags = YD.getElementsByClassName("boxBottom", "div", YD.get("featuredBox"));
    
    while(divTags[0].firstChild) divTags[0].removeChild(divTags[0].firstChild);    

//populate the items

    for (var i=0; i<rsscount && i<RSS.items.length; i++)
    {
        galimage = RSS.items[i].description;

        galimage = galimage.replace(/^.+src="(.*?)" .*/, "$1") ;
        galimage = galimage.replace(/(.*-)Th(-\d+)?(\.\w+)/i, "$1Ti$2$3") ;

        pubdate = RSS.items[i].pubDate ;
        pubdate.match(/^\w{3}, (\d\d) (\w{3}) (\d{4}) (\d\d):(\d\d):\d\d -\d\d\d\d/) ;

        // Fix up date formatting
        if (RegExp.$4>12) { meridian = 'pm'; hrs = RegExp.$4-12 } else { meridian = 'am'; if (RegExp.$4==0) { hrs = 12 } else { hrs = RegExp.$4-0 }} ;

        fixdate = "updated: " + RegExp.$2 + " " + RegExp.$1 + ", " + RegExp.$3 + " " + hrs + ":" + RegExp.$5 + meridian + " PST" ;

        miniBox = document.createElement("div");
        miniBox.className = "miniBox miniminiBox";

        photoBox = document.createElement("div");
        photoBox.className = "photo";
        miniBox.appendChild(photoBox);

        photoLink = document.createElement("a");
        photoLink.setAttribute("href", RSS.items[i].link);
        photoBox.appendChild(photoLink);

        photoImg = document.createElement("img");
        photoImg.setAttribute("border", "0");
        photoImg.setAttribute("alt", RSS.items[i].title);
        photoImg.setAttribute("title", RSS.items[i].title);
        photoImg.src = galimage;
        photoImg.className = "imgBorder";
        photoLink.appendChild(photoImg);

        albumTitle = document.createElement("p");
        albumTitle.className = "albumTitle";
        miniBox.appendChild(albumTitle);
        albumLink = document.createElement("a");
        albumLink.className = "nav";
        albumLink.setAttribute("href", RSS.items[i].link);
        albumTitle.appendChild(albumLink);

        albumLinkText = document.createTextNode(RSS.items[i].title);
        albumLink.appendChild(albumLinkText);

        albumUpdated = document.createElement("p");
        albumUpdated.className = "updated";
        miniBox.appendChild(albumUpdated);
        albumUpdatedText = document.createTextNode(fixdate);
        albumUpdated.appendChild(albumUpdatedText);

        spacerDiv = document.createElement("div");
        spacerDiv.className = "spacer";
        miniBox.appendChild(spacerDiv);

        divTags[0].appendChild(miniBox);
        // insertAfter(miniBox, divTags[0].childNodes[divTags[0].childNodes.length-2]);

    }
    spacerDiv = document.createElement("div");
    spacerDiv.className = "spacer";
    divTags[0].appendChild(spacerDiv);

    //we're done
    return true;
}

var xhr;


/*==============================*/
/*== Bulk Zoom thumbnail v3.4 ==*/
/*==============================*/
var thumbnailArray = new Array();
var thumbnailCount;
var thumbnailItem;
var thumbnailEXIFArray = new Array();
var reqIncrement = 0;

YE.onAvailable("toolsButton",function() {
  var menu = SM.buttons.toolsButton.button.getMenu();
  menu.subscribe('render',function(){
    this.getSubmenus()[2].subscribe('render',function(){
      this.addItem({ text: "Bulk Zoom Thumbnail", 'onclick': { 'fn': processThumbnails} });
    })
  })
});

YE.on(window, "load", onStartBulk);

function processThumbnails() {
  var re = /\/photos\/(\d+)_(\w+)\-(Ti|Th)/;

  pageWorking('Loading...');

  YD.get("bulkzoom_toolbox").style.display = "";

  var divTag = YD.inDocument("thumbnails") ? YD.get("thumbnails") : YD.get("photos");

  if (divTag) {
    var divTags = YD.getElementsByClassName("photo", "div", divTag);
    for (var i = 0, len = divTags.length; i < len; i++) {
      if (re.test(divTags[i].innerHTML)) {
        re.exec(divTags[i].innerHTML);
        thumbnailEXIFArray.push({"id": RegExp.$1, "key": RegExp.$2});
      }
    }
  }
  getThumbnailEXIF();
}

function maskThumbnails(objThumbnail, j) {
  var re1 = /\/gallery\/\d+_\w+\/\d+\/(\d+)_(\w+)/;
  var re2 = /javascript\:openLB\(([0-9]+),/;
  var re3 = /#(\d+)(_(\w+))?/;

  var divTag = YD.inDocument("thumbnails") ? YD.get("thumbnails") : YD.get("photos");

  if (divTag) {
    divTags = YD.getElementsByClassName("photo", "div", divTag);

    for (var i = 0, len = divTags.length; i < len; i++) {
      if (re1.test(divTags[i].innerHTML))
        re1.exec(divTags[i].innerHTML);
      else
      {
        if (re2.test(divTags[i].innerHTML))
          re2.exec(divTags[i].innerHTML);
        else {
          if (re3.test(divTags[i].innerHTML))
            re3.exec(divTags[i].innerHTML);
          else
            continue;
        }
          
      }

      var thumbnailId = RegExp.$1;
      var thumbnailKey = RegExp.$2;

      var aTags = divTags[i].getElementsByTagName("a");
      var imgTags = aTags[0].getElementsByTagName("img");

      if (objThumbnail.id == thumbnailId) {
        var maskedDiv = document.createElement("div");
        maskedDiv.id = thumbnailId + "_masked";
        maskedDiv.className = j;
        maskedDiv.style.cssText = "position: relative; background: transparent url('" + webServer+"/photos/toolthumbs.mg?tool=cropmask&Size=Small&ImageID="+ objThumbnail.id + "&ImageKey="+ objThumbnail.key + "') no-repeat; width: " + objThumbnail.imgWidth + "px; height: " + objThumbnail.imgHeight + "px; z-index: 1; margin:0px auto; text-align:left;";

        var clearedDiv = document.createElement("div");
        clearedDiv.id = thumbnailId + "_cleared";
        clearedDiv.className = j;
        clearedDiv.style.cssText = "position: absolute; background: url('" + objThumbnail.url + "') no-repeat; width: " + objThumbnail.imgWidth + "px; height: " + objThumbnail.imgHeight + "px; z-index: 2; clip:rect(0px," + objThumbnail.imgWidth + "px," + objThumbnail.imgHeight + "px,0px);";

        maskedDiv.appendChild(clearedDiv);

        var cropboxDiv = document.createElement("div");
        cropboxDiv.id = thumbnailId + "_cropbox";
        cropboxDiv.className = j;
        cropboxDiv.style.cssText = "position: absolute; left: 0px; top: 0px; width: " + (objThumbnail.imgWidth-4) + "px; height: " + (objThumbnail.imgHeight-4) + "px; border: solid 2px blue; z-index: 3; cursor: move";
        YE.on(cropboxDiv, "mousedown", testMouseBulk);
        clearedDiv.appendChild(cropboxDiv);

        var ratioboxDiv = document.createElement("div");
        ratioboxDiv.id = thumbnailId + "_ratiobox";
        ratioboxDiv.className = j;
        ratioboxDiv.style.cssText = "position: absolute; bottom: 0px; right: 0px; width: 25px; height: 25px; border-top: solid 2px blue; border-left: solid 2px blue;  cursor: pointer; cursor: hand; z-index: 4;";
        YE.on(ratioboxDiv, "mousedown", testZoomBulk); 
        cropboxDiv.appendChild(ratioboxDiv);
          
        var replaceNode = aTags[0];
        replaceNode.parentNode.replaceChild(maskedDiv, replaceNode);
        divTags[i].style.width = objThumbnail.imgWidth + "px";
        divTags[i].style.height = objThumbnail.imgHeight + "px";
      }
    }
  } 
}

function getThumbnailEXIF()
{
  var thumbnail = thumbnailEXIFArray.shift();

  if (thumbnail) {
    var postArray = new Array();
    postArray['method'] = "getImageInfo";
    postArray['imageId'] = thumbnail.id;
    postArray['imageKey'] = thumbnail.key;
    ajax_query(processThumbnailEXIF, webServer+'/rpc/image.mg', postArray, true);
    window.setTimeout(getThumbnailEXIF, 100);
  }
  else
  {
    removePageWorking();

    if (YD.hasClass(document.body,"loggedIn"))
      YD.get("bulkSave").disabled = false;
  }
}

function processThumbnailEXIF(response) {

  var json = eval('(' + response + ')');

  var imgWidth = parseInt(json.result.OriginalWidth);
  var imgHeight = parseInt(json.result.OriginalHeight);

  var obj = {"id": json.result.ImageID, "key": json.result.imageKey, "url": json.result.SmallURL};

  obj.imgHeight = (imgWidth < imgHeight) ? 300 : Math.round((imgHeight / imgWidth) * 400);
  obj.imgWidth = (imgWidth < imgHeight) ? Math.round((imgWidth / imgHeight) * 300) : 400;
  obj.ratio = 0;
  obj.invRatio = 0;
  obj.marginTop = 0;
  obj.marginLeft = 0;
  obj.cropHeight = obj.imgHeight;
  obj.cropWidth = obj.imgWidth;
  obj.oRatio = (imgWidth / obj.imgWidth);
  obj.cropDiff = 0;

  thumbnailArray.push(obj);

  maskThumbnails(thumbnailArray[thumbnailArray.length-1], "bzt_"+ (thumbnailArray.length-1));
}

function zoomThumbnails() {
  if (!thumbnailItem) {
    thumbnailItem = 0;
    thumbnailCount = thumbnailArray.length;
  }

  var thumbnail = thumbnailArray.shift();
  YD.get("bulkzoom_toolbox").style.display = "none";
  
  if (thumbnail) {
    thumbnailItem++; 

    postArray = new Array();
    postArray['method'] = 'crop';
    postArray['croptype'] = 'thumb';
    postArray['imageId'] = thumbnail.id;
    postArray['imageKey'] = thumbnail.key;
    postArray['action'] = "doit";
    postArray['cropH'] = Math.round(parseInt(thumbnail.cropHeight) * parseFloat(thumbnail.oRatio));
    postArray['cropW'] = Math.round(parseInt(thumbnail.cropWidth) * parseFloat(thumbnail.oRatio));
    postArray['cropX'] = Math.round(parseInt(thumbnail.marginLeft) * parseFloat(thumbnail.oRatio));
    postArray['cropY'] = Math.round(parseInt(thumbnail.marginTop) * parseFloat(thumbnail.oRatio));

    reqIncrement ++;
    pageWorking('Processing thumbnails');
    window.setTimeout('ajax_query(thumbReqHandler, webServer+\'\/rpc\/tools.mg\', postArray, true, true);', 10);
    window.setTimeout(zoomThumbnails, 50);
  } 
}


function thumbReqHandler() {
  reqIncrement--;

  if (thumbnailArray.length == 0 && reqIncrement == 0) {
      window.location.reload();
  }
}

var smallestBulk = 75;   
var mouseXBulk = 0;
var mouseYBulk = 0;
var mouseToolBulk = "move";
var hideRatioBulk = false;    
var scaleBulk = 1;
var pageLoadedBulk = false;

function onStartBulk() {
  pageLoadedBulk = true;
}        

function moveBulk(X,Y,e) {
  if (pageLoadedBulk == true)
  {
    try {
      var objClass = (e.srcElement) ? e.srcElement.className : e.target.className;
      var obj = thumbnailArray[objClass.replace("bzt_", "")];

      X = X*scaleBulk;
      Y = Y*scaleBulk;
      var newLeft = obj.marginLeft+X;
      var newTop = obj.marginTop+Y;                                
      var stopX = obj.imgWidth - obj.cropWidth;
      var stopY = obj.imgHeight - obj.cropHeight;

      if (newLeft < 0)
        newLeft = 0;

      if (newLeft > stopX)
        newLeft = stopX;

      if (newTop < 0)
        newTop = 0;

      if (newTop > stopY)
        newTop = stopY;

      obj.marginLeft = newLeft;
      obj.marginTop = newTop;

      var objNode = (e.srcElement) ? e.srcElement : e.target;

      while (objNode.id != obj.id + "_cropbox")
        objNode = objNode.parentNode;

      updateCropBulk(objNode);
    }
    catch(e) {}
  }
  else {
    window.alert("Page loading, please wait.");
  }
}        

function zoomBulk(X,Y,e)
{
  if (pageLoadedBulk == true) {
    try {
      var objClass = (e.srcElement) ? e.srcElement.className : e.target.className;
      var obj = thumbnailArray[objClass.replace("bzt_", "")];              

      var Xadj = (obj.ratio == 0) ? obj.cropWidth+(X*scaleBulk) : 0;
      var Yadj = (obj.ratio == 0) ? obj.cropHeight+(Y*scaleBulk) : 0;

      var newWidth = obj.cropWidth+(X*scaleBulk);
      var newHeight = Math.round(newWidth*obj.ratio)+Yadj;

      if (newWidth < smallestBulk) {
        newWidth = smallestBulk;
        newHeight = Math.round(newWidth*obj.ratio)+Yadj;
      }

      if (newHeight < smallestBulk) {
        newHeight = smallestBulk;
        newWidth = Math.round(newHeight*obj.invRatio)+Xadj;
      } 

      if (newWidth+obj.marginLeft > obj.imgWidth) {
        newWidth = obj.imgWidth-obj.marginLeft;
        newHeight = Math.round(newWidth*obj.ratio)+Yadj;
      } 

      if (newHeight+obj.marginTop > obj.imgHeight) {
        newHeight = obj.imgHeight-obj.marginTop;
        newWidth = Math.round(newHeight*obj.invRatio)+Xadj;
      }                

      obj.cropWidth = newWidth;
      obj.cropHeight = newHeight;

      var objNode = (e.srcElement) ? e.srcElement : e.target;

      while (objNode.id != obj.id + "_cropbox")
        objNode = objNode.parentNode;

      updateCropBulk(objNode);
    }
    catch(e) {}
    
  }
  else {
    window.alert("Page loading, please wait.");
  }
}        

function changeRatioBulk(newRatios) {
  if (pageLoadedBulk == true) {
    var newRatio = newRatios.split(",");

    for (i=0; i<thumbnailArray.length; i++) {
      var obj = thumbnailArray[i];

      if (obj.imgHeight > obj.imgWidth) {
        obj.ratio = newRatio[1];
        obj.invRatio = newRatio[0];
      }
      else {
        obj.ratio = newRatio[0];
        obj.invRatio = newRatio[1];
      }

      if (obj.ratio == 0) {
        YD.get('customRatio').style.display = "none";
        obj.marginTop = 0;
        obj.marginLeft = 0;
        obj.cropHeight = obj.imgHeight;
        obj.cropWidth = obj.imgWidth;
      }
      else {
        if (newRatios == "custom") {
          obj.ratio = document.cropTool.ratioH.value/document.cropTool.ratioW.value;
          obj.invRatio = document.cropTool.ratioW.value/document.cropTool.ratioH.value;
          YD.get('customRatio').style.display = "block";
        }
        else
          YD.get('customRatio').style.display = "none";

        obj.cropWidth = Math.round(1 * obj.imgWidth);

        obj.cropHeight = Math.round(obj.cropWidth * obj.ratio);        

        if ((obj.cropHeight > obj.imgHeight)||(obj.cropWidth > obj.imgWidth)) {
          obj.cropHeight = obj.imgHeight;  
          obj.cropWidth = Math.round(obj.cropHeight * obj.invRatio);
        }   

        obj.marginTop = ((obj.imgHeight - obj.cropHeight)/2);
        obj.marginLeft = ((obj.imgWidth - obj.cropWidth)/2);
      }

      updateCropBulk(YD.get(thumbnailArray[i].id + "_cropbox"));
    }
  }
  else {
     window.alert("Page loading, please wait.");
  }
}        

function rotateBulk() {
  if (pageLoadedBulk == true) {
    for (i=0; i<thumbnailArray.length; i++) {
      var obj = thumbnailArray[i];

      var Xadj = (obj.ratio == 0) ? obj.cropHeight : 0;
      var Yadj = (obj.ratio == 0) ? obj.cropWidth : 0;

      var temp = obj.invRatio;
      obj.invRatio = obj.ratio;
      obj.ratio = temp;
      temp = obj.cropWidth;
      obj.cropWidth = obj.cropHeight;
      obj.cropHeight = temp;  

      if (obj.cropWidth + obj.marginLeft > obj.imgWidth) {

        obj.marginLeft = obj.imgWidth - obj.cropWidth;

        if (obj.marginLeft < 0) {
          obj.marginLeft = 0;
          obj.cropWidth = obj.imgWidth - obj.marginLeft;
          obj.cropHeight = Math.round(obj.cropWidth * obj.ratio)+Yadj;                        
        }
      } 

      if (obj.cropHeight + obj.marginTop > obj.imgHeight) {
        obj.marginTop = obj.imgHeight - obj.cropHeight;

        if (obj.marginTop < 0) {
          obj.marginTop = 0;
          obj.cropHeight = obj.imgHeight - obj.marginTop;
          obj.cropWidth = Math.round(obj.cropHeight * obj.invRatio)+Xadj;
        }
      }

      updateCropBulk(YD.get(obj.id + "_cropbox"));
    }
  }
  else
    window.alert("Page loading, please wait.");
}        

function updateCropBulk(e) {
  var objClass = e.className;
  var obj = thumbnailArray[objClass.replace("bzt_", "")];

  e.parentNode.style.clip = "rect("+obj.marginTop+"px "+(obj.marginLeft+obj.cropWidth)+"px "+(obj.marginTop+obj.cropHeight)+"px "+obj.marginLeft+"px)";
  e.style.top = obj.marginTop+"px";
  e.style.left = obj.marginLeft+"px";
  e.style.width = obj.cropWidth-obj.cropDiff+"px";
  e.style.height = obj.cropHeight-obj.cropDiff+"px";
}        

function mouseMoveBulk(e) {
  if (!e) var e = window.event;

   var objClass = (e.srcElement) ? e.srcElement.className : e.target.className;

  if (lookMouse) {
    var tempX = mouseXBulk;
    var tempY = mouseYBulk;
    mouseXBulk = e.clientX;
    mouseYBulk = e.clientY;
    var x = mouseXBulk-tempX;
    var y = mouseYBulk-tempY;

    if (mouseToolBulk == "zoom") {
      if (thumbnailArray[objClass.replace("bzt_","")].ratio == 0)
        zoomBulk(x,y,e);
      else
        zoomBulk(x,0,e);
    }
    else
      moveBulk(x,y,e)
  }
}

function testMouseBulk(e) {
  state = true;
  if (!e) var e = window.event;

  if (mouseToolBulk != "zoom") {
    lookMouse = state;

    if (state == true) {
      mouseToolBulk = "move";
      mouseXBulk = e.clientX;
      mouseYBulk = e.clientY;
      document.onmousemove = mouseMoveBulk;
    }
  }
}

function testZoomBulk(e) {
  state=true;
  if (!e) var e = window.event;

  lookMouse = state;
  if (state == true) {	            
    mouseToolBulk = "zoom"
    mouseXBulk = e.clientX;
    mouseYBulk = e.clientY;
    document.onmousemove = mouseMoveBulk;
  }
}

function cancelMouse() {
  mouseToolBulk = "move";
  lookMouse = false;
}

document.onmouseup = cancelMouse;
