//--------------------------------------------------------------------------------------------------------------------
// MarkHiddenThumbs puts a red X on thumbnails in the Smugmug view that are hidden
//
// Installation and support is here: http://www.dgrin.com/showthread.php?t=143433.
//--------------------------------------------------------------------------------------------------------------------
if (typeof(JLF) == "undefined") var JLF = new Object;

// Declare a global object with our various methods on it.  This puts all of our methods in their own namespace like YUI does.
JLF.HiddenMarkers = 
{
	// global data variables on the object
	oldHidePhoto: "",
	
	// externally accessible methods
	
	// Replacement for the built-in hidePhoto function.  
	// It calls the original function, then updates the hidden marker for the affected thumb
	NewHidePhoto: function(status, ImageID, ImageKey)
	{
		var retVal = JLF.HiddenMarkers.oldHidePhoto.apply(this, arguments);
		var thumb = YD.get("photoBox_" + ImageID);
		if (thumb)
		{
			JLF.HiddenMarkers.MarkSingleHiddenThumb(thumb);
		}
		return(retVal);
	},
	
	// Set the style from a whole style string rather than one attribute at a time
	SetStyleString: function(element, str)
	{
		var styles = str.split(/\s*;\s*/);
		for (var i in styles)
		{
			var pieces = styles[i].split(/\s*:\s*/);
			if (pieces.length > 1)
			{
				YD.setStyle(element, pieces[0], pieces[1]);
			}
		}
	},
	
	// Update the hidden status of a single thumb
	MarkSingleHiddenThumb: function(element)
	{
		try
		{
			// get existing marker if here
			var markers = YD.getElementsByClassName("hiddenMarker", "div", element);
			var imageID = element.id.substr(9);		// strip off "photoBox_" off the id to get just the id
			if (photoInfo[imageID].Status == "Hidden")
			{
				// if there is no marker yet, add one
				if (!markers || (markers.length == 0))
				{
					var links = element.getElementsByTagName("a");
					var imgs = links[0].getElementsByTagName("img");
					var newDiv = document.createElement("div");
					newDiv.className = "hiddenMarker";
					JLF.HiddenMarkers.SetStyleString(newDiv, "position: absolute; top:1px; left:5px; z-index:10; color: #F00; font-size: 14pt; font-weight: bold; font-family: Arial;");
					newDiv.innerHTML = "X";
					imgs[0].parentNode.insertBefore(newDiv, imgs[0]);
				}
			}
			else	// not hidden now
			{
				// if there's a hidden marker, then remove it
				if (markers && (markers.length != 0))
				{
					markers[0].parentNode.removeChild(markers[0]);		// remove it
				}
			}
		} catch (e) {}
	},
	
	// Update the hidden status of all thumbs
	// Only written to work in the Smugmug view when logged in
	// Other views don't appear to have the photoInfo array which gives us the hidden status
	MarkAllHiddenThumbs: function()
	{
		
		if (YD.hasClass(document.body, "loggedIn") && YD.hasClass(document.body, "smugmug"))
		{
			YD.getElementsByClassName("photo", "div", YD.get("thumbnails"), JLF.HiddenMarkers.MarkSingleHiddenThumb);
		}
	}
};

// Install our replacement function for hidePhoto
if (typeof(hidePhoto) == "function")
{
	JLF.HiddenMarkers.oldHidePhoto = hidePhoto;
	hidePhoto = JLF.HiddenMarkers.NewHidePhoto;
}

// Register for notifications when the Smugmug view has been rendered
onPhotoShow.subscribe(JLF.HiddenMarkers.MarkAllHiddenThumbs);

// --------------------------------------
// End of MarkHiddenThumbs code
// --------------------------------------


function hasPath(sPath)
{
re = new RegExp("\/" + sPath + "(\/|$)");
return re.test(window.location)
} 

if (hasPath("galleries"))
YD.addClass(document.body, "galleries");


// -----------------------------------------------------------
// Code to add descriptions to categories and/or sub-categories
// -----------------------------------------------------------

function addCategoryTitleToBreadcrumb(description) 
{
    var breadCrumb = YD.get("breadcrumb");
    if (breadCrumb)
    {
        var divTag = document.createElement("div");
        divTag.className = "categoryDescription";
        divTag.innerHTML = description;
        breadCrumb.parentNode.insertBefore(divTag, breadCrumb.nextSibling);
    }
}

function addCategoryTitleToThumbs(descriptionObject, boxObjectName) 
{
    var re = /\>([^\<]+)<\/a>/i;    // pattern to find the category name between the <a> and </a> tags
    var divTag = YD.get(boxObjectName);
    if (divTag) 
    {
        var divTags = YD.getElementsByClassName("albumTitle", "p", divTag);
        for (var i = 0; i < divTags.length; i++) 
        {
            var matches = re.exec(divTags[i].innerHTML);    // get just the category name
            // if we found a category name and the category name exists in our categoryDescription object, then add the description
            if (matches && (matches.length > 1) && descriptionObject[matches[1]] != undefined) 
            {
                var pTag = document.createElement("p");
                pTag.className = "categoryDescription";
                pTag.innerHTML = descriptionObject[matches[1]];
                divTags[i].parentNode.insertBefore(pTag, divTags[i].nextSibling);
            }
        }
    }
}

/* Category descriptions */
function addCategoryDescription() 
{
    var categoryDescription = {
        // list "categoryname" : "category title",
        // or "categoryname.subcategoryname" : "subcategory title",
        // Examples:
        // "Kenya"  : "Our vacation to Kenya",
        // "Kenya.Highlights" : "The highlights galleries from our vacation to Kenya",
           "Jumble.Disneyland" : "<i>Disneyland As Seen Through My Lens</i>"

    };
    
    var re, matches, i;        // various local variables

    // now fix it so that it works automatically even if the category or sub-category name has spaces in it
    // we replace those spaces with underscores (which is what the classname does) and add those to our object so we can match those too
    for (i in categoryDescription) 
    {
        var newName = i.replace(/ /g, "_");
        categoryDescription[newName] = categoryDescription[i];    // add a property to the object that has only underscores in the name
    }
    // on the homepage, we want to check for category names and add a description if a match found
    // on a category page, we want to check to see if the category that the page is needs a description under the breadcrumb
    //      and, we need to see if any of the sub-category items on the page need us to add a description under the name
    // on a sub-category page, we want to check to see if the sub-category that the page is needs a description under the breadcrumb
    if (YD.hasClass(document.body, "category")) 
    {
        // fetch the category name
        re = /category_(\S+)/i;
        matches = re.exec(document.body.className);
        if (matches && (matches.length > 1)) 
        {
            var categoryName = matches[1];
            // now see if we have a subcategory too
            if (YD.hasClass(document.body, "subcategory")) 
            {
                re = /subcategory_(\S+)/i;
                matches = re.exec(document.body.className);
                if (matches && (matches.length > 1)) 
                {
                    var subcatName = matches[1];
                    // category and subcategory so we are on a subcategory page showing a list of galleries in this subcategory
                    // we need to just add a subcategory title to this page if the category-subcategory matches
                    var fullName = categoryName + "." + subcatName;
                    if (categoryDescription[fullName])
                    {
                        addCategoryTitleToBreadcrumb(categoryDescription[fullName]);
                    }
                }
            }
            // here we're on a category page
            // we need to add a category description for the category page
            // and potentially add subcategory descriptions to the subcategory names displayed on this page
            else 
            {
                if (categoryDescription[categoryName])
                {
                    addCategoryTitleToBreadcrumb(categoryDescription[categoryName]);
                }
                // now we need to build a temporary subcategoryDescription object that has only the subcategory names in it that are in this category
                var subcatDescriptions = {};
                re = new RegExp("^" + categoryName + "\\.(.+)$", "i");
                for (i in categoryDescription)
                {
                    matches = re.exec(i);
                    if (matches && (matches.length > 1))
                    {
                        subcatDescriptions[matches[1]] = categoryDescription[i];
                    }
                }
                addCategoryTitleToThumbs(subcatDescriptions, "subcategoriesBox");
            }
        }
    }

    // then see if we're on the homepage
    if (YD.hasClass(document.body, "homepage")) 
    {
        addCategoryTitleToThumbs(categoryDescription, "categoriesBox");
    }
}

YE.onDOMReady(addCategoryDescription);

// ------------------------------------------------------------------
// End of code to add descriptions to categories and/or sub-categories
// -----------------------------------------------------------------


//------------------------------------------------------------------------------------------
// Highlight the link in your navbar that matches the current page.
//
// See http://www.dgrin.com/showthread.php?t=141678 for documentation.
//------------------------------------------------------------------------------------------
YE.onContentReady("navcontainer", 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 = 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/")
				{
					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.addClass(links[galleriesIndex], "navCurrentPage navCurrentPageGallery");
				YD.addClass(links[galleriesIndex].parentNode, "navCurrentPageParent navCurrentPageParentGallery");
			}
		}
	}
});

function AddReferralCode()  {
  var links = this.getElementsByTagName("A");
  if (links && (links.length != 0)) {
    var smugLink = links.item(0);
    smugLink.href = "http://www.smugmug.com/?referrer=uGbVp0Q0PxiBw";
  }
}
YE.onAvailable('footer', AddReferralCode);

function norobotmail(aUser, aDomain) { document.location = "mailto:" + aUser + "@" + aDomain; }


//   add drop to buy button 
//   dgrin.com/showthread.php?p=1034789#post1034789 
//   http://www.dgrin.com/showthread.php?p=1341940#post1341940 


SM.util.RequestManager.getInstance().on('BuyButton.onComplete', function() {

YE.onDOMReady(AddItemsToBuyButton);

function AddItemsToBuyButton()
{
 var buyButton = YAHOO.widget.Button.getButton("buyButton");
 if (buyButton)
 {
 var newBuyItem = { text: "View Catalog", url: "http://www.smugmug.com/prints/catalog/B", target: "_blank"};
 buyButton.getMenu().addItem(newBuyItem);
 }
}
});





// Clear links and thus clickability from photos in journal galleries
//-------------------------------------------------------------

YE.onDOMReady(ClearLinksFromMany);

function ClearLinksFromMany()
{
    var listOfGalleries = [
        "8507849",             /*  Limited Edition Collection Aviation*/
        "8507932",             /* Limited Edition Colour Portrait Collection*/
        "8404390",             /* Limited Edition Collection colour Landscape*/
        "8507915",             /* Limited Edition Animal Collection*/
        "8507873",             /* Limited Edition BW Portrait Collection*/
        "8507906",             /* Limited Edition BW Landscape Collection*/
        "8501704",             /* Limited Edition BW Abstract Collection*/
        "10355117",            /*  About Me */
        "7160837",            /* Contact Us */
        "8122279",            /* How Do I Buy */
        "7831940",            /* FAQ - no comma after the last entry in the list */
        "10935545"             /* Your Investment */ 
    ];
    if (window.AlbumID)
    {
        for (var i in listOfGalleries)
        {
            if (window.AlbumID == listOfGalleries[i])
            {
                removeLinkFromImg();
                break;
            }
        }
    }
}

function removeLinkFromImg() 
{
	var oList = YD.getElementsByClassName("photo", "div");
	for (var i=0; i < oList.length; i++)  
	{
		var aTags = oList[i].getElementsByTagName("a");
		for (var j=0; j < aTags.length; j++)
		{
			try 
			{
				// get rid of the href on the <a> tag
				aTags[j].removeAttribute("href");
				// get rid of the alt and title tags on the <img> tag
				aTags[j].firstChild.removeAttribute("alt");
				aTags[j].firstChild.removeAttribute("title");
			} catch (e) {}
		}
	}
}
