// for the Second homepage (galleries)
function hasPath(sPath)
{
re = new RegExp("\/" + sPath + "(\/|$)");
return re.test(window.location)
}

if (hasPath("galleries"))
YD.addClass(document.body, "galleries");

// *******

// script to replace a user's name in the breadcrumb with "Home"
YE.onContentReady("breadCrumbTrail", ReplaceTopOfBreadcrumbWithHome);

function ReplaceTopOfBreadcrumbWithHome()
{
    var str = this.innerHTML.replace(/\n/g, " ");
    this.innerHTML = str.replace(/\>[^\<]+<\/a>/i, ">Home</a>");
}


// *******

//------------------------------------------------------------------------------------------
// Highlight the link in your navbar that matches the current page.
//
// See http://www.dgrin.com/showthread.php?t=141678 for documentation.
//------------------------------------------------------------------------------------------
YE.onContentReady("myNav", function ()
{
	function AddTrailingSlash(str)
	{
		if (str.search(/\/$/) == -1)
		{
			str = str + "/";
		}
		return(str);
	}
	
	function StripDomainAndHash(oldStr)
	{
		var str = oldStr.replace(/#.*$/, "");	// get rid of hash value
                str = str.replace(/\?.*$/, "");         // to work with forced view
		str = AddTrailingSlash(str);	// make sure it always ends in a slash
		str = str.replace(/^https?:\/\/[^\/]*/, ""); // get rid of domain on the front
		return(str);
	}
	
	var links = this.getElementsByTagName("a");
	if (links && (links.length > 0))
	{
		var pageURL = StripDomainAndHash(window.location.href);
	
		var foundExactMatch = false;
		var partialIndex = -1;		// index of best partial match
		var partialLength = 0;		// length of the best partial match
		var galleriesIndex = -1;	// index of the /galleries link
		
		// check each link for an href match with our current page
		for (var i = 0; i < links.length; i++)
		{
			var testLink = StripDomainAndHash(links[i].href); // relative link will be turned into absolute link here
			if (testLink == pageURL)
			{
				YD.addClass(links[i], "navCurrentPage navCurrentPageExact");
				YD.addClass(links[i].parentNode, "navCurrentPageParent navCurrentPageParentExact");
				foundExactMatch = true;
				break;
			}
			// if testLink is not the top level (don't want to do partial matches for top level)
			else if (testLink != "/")
			{
				// if the testLink is contained within the pageURL 
				// (e.g. the current page link is longer than the navbar link and starts with it),
				// remember it as a partial match
				if (pageURL.indexOf(testLink) == 0)
				{
					// save the longest partial match (assuming it to be the most specific)
					if (testLink.length > partialLength)
					{
						partialIndex = i;
						partialLength = testLink.length;
					}
				}
				else if ( (testLink == "/galleries/") || (testLink == "/keyword/") )
				{
					galleriesIndex = i;
				}
			}
		}
		if (!foundExactMatch)
		{
			// since we had no exact match, check for partial matches
			if (partialIndex != -1)
			{
				YD.addClass(links[partialIndex], "navCurrentPage navCurrentPagePartial");
				YD.addClass(links[partialIndex].parentNode, "navCurrentPageParent navCurrentPageParentPartial");
			}
			// if no exact match and no partial matches 
			// and we did have a galleries link 
			// and we're on a gallery page or a category or subcategory page
			// then, mark the galleries link
			else if ((galleriesIndex != -1) && (YD.hasClass(document.body, "galleryPage") || YD.hasClass(document.body, "category") || YD.hasClass(document.body, "keywordPage")))
			{
				YD.addClass(links[galleriesIndex], "navCurrentPage navCurrentPageGallery");
				YD.addClass(links[galleriesIndex].parentNode, "navCurrentPageParent navCurrentPageParentGallery");
			}
		}
	}
});


// *******

// stop filmstrip auto move
filmstripMove = 0;

// *******

//====TagThumbs====
// adds a CSS classname to the minibox for a category or sub-category thumb so you can then style them individually with CSS (including hiding them)
// in category or sub-category view, this adds a class name of the form thumbnail_catname_subcatname_galleryname
// for gallery thumbs, it also adds a class thumbnail_gallery_xxxxxxx (where xxxxxx is the gallery ID)
// If you are displaying your galleries as a flat list (no categories), 
//    then you only get the thumbnail_gallery_xxxxxxx class name (because category and subcategory are not known)
function TagThumbs() 
{
	// get current category and subcategory
	var info = GetCategoryInfo();
	
	// get list of miniBox divs in the "this" object
	var miniBoxList = YD.getElementsByClassName('miniBox', 'div', this);

	// for each miniBox, get the category or sub-category name from the albumTitle div
	for (var i = 0; i < miniBoxList.length; i++) 
	{
		// get the albumTitle p tag
		var titleTags = YD.getElementsByClassName("albumTitle", "p", miniBoxList[i]);
		if (titleTags && (titleTags.length > 0))
		{
			// get the link in the albumTitle
			var linkTags = titleTags[0].getElementsByTagName('a');
			if (linkTags && (linkTags.length > 0))
			{
				// grab the name of the category/subcategory from the thumb
				var thumbName = linkTags[0].innerHTML;
				thumbName = thumbName.replace(/\s+|\&[a-z]+;|[^_a-zA-Z0-9-]/g, "_");	// replace illegal CSS chars with underscore
				var newClassName = "thumbnail_";
				if (info.cat)
				{
					newClassName += info.cat + "_";
				}
				if (info.subcat)
				{
					newClassName += info.subcat + "_";
				}
				newClassName += thumbName;
				YD.addClass(miniBoxList[i], newClassName);
			}
		}
		
		// get the photo div in each miniBox
		var photoTags = YD.getElementsByClassName("photo", "div", miniBoxList[i]);
		if (!photoTags || (photoTags.length == 0))
		{
			photoTags = YD.getElementsByClassName("photoLarge", "div", miniBoxList[i]);
		}
		if (photoTags && (photoTags.length > 0))
		{
			// get the link in the photo tag
			var photoLinkTags = photoTags[0].getElementsByTagName('a');
			if (photoLinkTags && (photoLinkTags.length > 0))
			{
				// grab the URL of the gallery
				var link = photoLinkTags[0].href;
				// href should be "/gallery/5608799_ZJ27n"
				var matches = link.match(/\/gallery\/(\d+)_/);
				if (matches && (matches.length > 1))
				{
					YD.addClass(miniBoxList[i], "thumbnail_gallery_" + matches[1]);
				}
				
			}
			
		}
	}
}

YE.onContentReady('categoriesBox', TagThumbs);
YE.onContentReady('subcategoriesBox', TagThumbs);
YE.onContentReady('galleriesBox', TagThumbs);

//====End of TagThumbs====


//====GetCategoryInfo====
// Retrieves category and subcategory names from the body tag classes
// returns an object
function GetCategoryInfo()
{
    var info = new Object;
    info.cat = "";
    info.subcat = "";
    
    if (YD.hasClass(document.body, "category"))
    {
        var re = /category_(\S+)/i;
        var matches = re.exec(document.body.className);
        if (matches && (matches.length > 1))
        {
            info.cat = matches[1];
        }
        if (YD.hasClass(document.body, "subcategory"))
        {
            re = /subcategory_(\S+)/i;
            matches = re.exec(document.body.className);
            if (matches && (matches.length > 1))
            {
                info.subcat = matches[1];
            }
        }
    }
    return(info);
}

//******

// This is a script to combine the categories with the gallery listing to have just one continuous listing of thumbs
YE.onContentReady("subcategoriesBox", CombineCategoriesWithGalleries);

function IsArrayEmpty(testVal)
{
    return(!testVal || (testVal.length == 0));
}

function CombineCategoriesWithGalleries()
{
    // get miniBoxes in the subcategoriesBox object
    var miniBoxes = YD.getElementsByClassName("miniBox", "div", this);
    // get target galleriesBox object
    var galleriesObj = document.getElementById("galleriesBox");
    var galleryMiniBoxes = new Array;

    // now find the right miniBox in the galleriesBox in order to insert the sub-categories
    if (galleriesObj)
    {
        galleryMiniBoxes = YD.getElementsByClassName("miniBox", "div", galleriesObj);
    }
    
    // if we don't have everything we need, then return without doing anything
    if (!galleriesObj || IsArrayEmpty(miniBoxes) || IsArrayEmpty(galleryMiniBoxes) || (window.location.hash == "#stop"))
    {
        this.style.display = "block";        
        return;
    }
    
    // move all the sub-categories over to the gallery listing
    for (var i in miniBoxes)
    {
        miniBoxes[i].parentNode.removeChild(miniBoxes[i]);
        galleryMiniBoxes[0].parentNode.insertBefore(miniBoxes[i], galleryMiniBoxes[0]);
    }
}

// ****

// -------------------------------------------------------------------------------------------
// Start of Code to auto-open a gallery that is all alone in a category
//
// If page is a category page or a sub-category page and there is only one 
// thumbnail on the page (whether it's a sub-category or a gallery thumb)
// we will auto-open it.
// -------------------------------------------------------------------------------------------
YE.onContentReady("category", function()
{
    try
    {
        // if there are any parameters following the category URL, then don't auto-open
        if (window.location.search.length != 0) return;
        var boxes = Sizzle(".boxBottom .miniBox", this);
        // if one and only one miniBox, then just open it
        if (boxes.length == 1)
        {
            var links = Sizzle("a", boxes[0]);
            window.location.replace(links[0].href + "?ao=0");
        }
    } catch (e) {}
});

// on a gallery page, add search params to each cat/sub-cat link in the breadcrumb 
// to prevent auto-open when we navigate back up the params
YE.onContentReady("breadCrumbTrail", function()
{
    if (YD.hasClass(document.body, "galleryPage"))
    {
        var navs = Sizzle("a.nav", this);
        for (var i = 1; i < navs.length; i++)
        {
            if (navs[i].href.indexOf("?") == -1)
            {
                navs[i].href += "?ao=0";
            }
        }
    }
});

// -------------------------------------------------------------------------------------------
// End of Code to auto-open a gallery that is all alone in a category
// -------------------------------------------------------------------------------------------

// ****

//  Guestbook in About Me 
if (YAHOO.util.Dom.hasClass(document.body, "gallery_10785457"))
{
   var objElement = document.getElementById("comment_header")
   if (objElement != null) {
     var str = new String(objElement.innerHTML);
     str = str.replace('Gallery Comments', 'Guestbook')
     objElement.innerHTML = str; 
   }
}

//******

// code to force any gallery page to Smugmug view (even keyword and search pages)

function ForceSmugmugView()
{
    // if we're on a galleryPage, and the view isn't already smugmug(allthumbs_stretch)
    if (!YD.hasClass(document.body, "allthumbs_stretch"))
    {
        var url = window.location.toString();
        var re = new RegExp(/forceView=(\d+)/);
        var match = re.exec(url);
        var curTime = new Date();
        if (match && (match.length > 1))
        {
            var prevTime = new Date();
            prevTime.setTime(match[1]);
            // check to see if we've already done this in the last 60 seconds to avoid loops
            if (curTime - prevTime < (60*1000))
            {
                return;
            }
        }
        var postData = 'tool=setCookie&value=17&type=Template';
        var broken = function() {};
        var reloadPage = function() 
        {
            var newUrl;
            if (match)
            {
                newUrl = url.replace(/forceView=\d+/, "forceView=" + curTime.getTime());
            }
            else if (url.indexOf("?") != -1)
            {
                newUrl = url.replace("?", "?forceView=" + curTime.getTime() + "&");
            }
            else if (url.indexOf("#") != -1)
            {
                newUrl = url.replace("#", "?forceView=" + curTime.getTime() + "#");
            }
            else
            {
                newUrl = url + "?forceView=" + curTime.getTime();
            }
            window.location.replace(newUrl);
        };
        var callback = {
            success: reloadPage,
            failure: broken,
            scope: this
        };
        YAHOO.util.Connect.asyncRequest('POST','/rpc/settings.mg', callback, postData);
    }
}

// only trigger this function if there is a stylebar because that means the gallery isn't locked into a particular view
YE.onAvailable("viewingStylesButton", ForceSmugmugView);


// *****

//------------------------------------------------------------------------------------------------------------------------------------------
// Script to allow you to use CSS to hide any individual menu items in the Share or Style menus
// This script will add a class name to each top level menu item in the Share and Style menus.
// That class name will be of the form "buttonname_menuitemname_menuitem".
// The class name will be all lowercase and any spaces or other non-alpha numeric chars in it will be converted to underscores.
// Here are some examples of class names:
//    share_be_social_menuitem
//    share_social_bookmarking_menuitem
//    style_traditional_menuitem
//
// And some example CSS to hide a menu item would look like this:
//    .share_be_social_menuitem {display:none;}
//    .style_traditional_menuitem {display:none;}
//
// You can also hide menu items only in certain contexts using all the normal Smugmug CSS classifiers. 
// To hide social bookmarking only in your vacation category, you would use CSS like this:
//    .category_Vaction .share_be_social_menuitem {display:none;}
//------------------------------------------------------------------------------------------------------------------------------------------

YE.onContentReady("viewingStylesButton", TagMenuItemsSetup);
YE.onContentReady("shareButton", TagMenuItemsSetup);

function TagMenuItemsSetup()
{
    // now that the object is created, we can register an interest in the beforeShowEvent
    // we can't modify the menu until then because of lazyLoading
    var button = YAHOO.widget.Button.getButton(this.id);
    var menu = button.getMenu();
    var menuName = button.get("label");
    menu.beforeShowEvent.subscribe(TagMenuItems);
    
    function TagMenuItems(event, args, data)
    {
        // called in the context of the menu
        try
        {
            // get the list of menu items in our menu
            var menuItems = this.getItems();
            
            // look through each menu item to see if it matches anything in our stylesToRemove array
            for (var i = 0; i < menuItems.length; i++)
            {
                // get the text value from the menu item and make it into a new class name
                var newClassName = menuItems[i].cfg.config.text.value;
                newClassName = menuName + "_" + newClassName + "_menuitem";
                newClassName = newClassName.replace(/\s+|\&[a-z]+;|[^_a-zA-Z0-9-]/g, "_");    // replace illegal CSS chars with underscore
                // add the new class name to the menu item so we can hide/style it with pure CSS
                YD.addClass(menuItems[i].id, newClassName.toLowerCase());
                
                // if this item itself is a sub-menu, then register for it's show event too
                var submenu = menuItems[i].cfg.getProperty("submenu");
                if (submenu)
                {
                    submenu.beforeShowEvent.subscribe(TagMenuItems);
                }
            }
            // no need to call this again everytime we show the menu
            this.beforeShowEvent.unsubscribe(TagMenuItems);
        } catch (e) {}        // catch any exceptions and ignore them - errors will just cause the styles not to get removed, but not affect any other scripts
    }
}

//****
