// This file contains a collection of hacks that couldn't be done in CSS or require modifying
// the document in a way that can't be done from the header/footer

$(document).ready(function(){
	// Alternate Larger Image View
	// Tanner Burson <tanner.burson@gmail.com>
	// October 2009
	// This hack uses a slightly modified lightbox library to allow us to have a "view larger size"
	// option for our product. Due to our inconsitent availability of larger sized images, it 
	// attempts to detect whether the larger size exists before placing the link.
	
    var ejcs = {
        zoomSize : "900",       // 'tag' for larger size images
        defaultSize : "350",    // 'tag' for normal size images
        flipPrefix : "back_",   // currently unused but 'tag' for alternative view
        origPath : "",
        
        imageChangeSize : function(size1,size2) {
            var pattern = new RegExp('(-)' + size1 + '(\.jpg)$');
            if (this.origPath.match(pattern)){
                var replacement = '$1' + size2 + '$2';
                return "prodimg/" + this.origPath.replace(pattern,replacement);
            }
            else 
                return "prodimg/imgnotfound";
        },
        setup : function() { //This function detects if the large image for the main image exists.  If not, we don't call the hook so we get no zoom.
						var ejcs = this;
            if($(".itemPicture").length == 0) return; // we're on a page without an item picture.  run!
						ejcs.colorHash();
						ejcs.facebookLike();
						
            var checkHook = new Image();                        
            ejcs.origPath = $(".itemPicture").attr('src').split('prodimg/')[1];
            checkHook.onload = function() { // The only way I know to check an images existence from clientside. blech. currently does double loading.
                    ejcs.lightboxHook();    
            }
            checkHook.src = ejcs.imageChangeSize(ejcs.defaultSize,ejcs.zoomSize);
        },
        imagePath : function() {
            return $(".itemPicture").attr('src').split('prodimg/')[1];
        },
        lightboxHook : function() {
            // Change to manually calling an event of our choosing which then triggers the lightbox event
            var ejcs = this;
            $('.itemPicture').wrap('<a href="#"></a>').click(function(){
                ejcs.origPath = $(".itemPicture").attr('src').split('prodimg/')[1]; // Reset the base path in case they've changed colors
                $(this).lightbox.start($('<a href="' + ejcs.imageChangeSize(ejcs.defaultSize,ejcs.zoomSize) + '"></a>')[0]); //The actual call into the modified lightbox library
                return false; // don't redirect page to #
            });
            $('a[@rel*=lightbox]').lightbox({customEvents: true}); //hack of lightbox to not auto-call on click but let me intercept
            $('.bodyTextSmall > .itemNum').before('<span style="font-size: x-small">Click Image to Enlarge</span>'); //add some text below as instructions
        },
				colorHash : function() {
					// Using url anchor hash (http://something/else.html#hash) direct link to a specific color
					// Tanner Burson <tanner.burson@gmail.com>
					// September 2010
					// This hack sniffs out the correct javascript array element for a given color.
					// It works on the assumption that all color/size combos of a given item will have the same
					// image. It could be extended to handle size if it was necessary.

					var currentId = $("input[@name='itemid']").val();
					var hash = document.location.hash.substr(1);
					hash = hash.substr(0,hash.indexOf('?'));
					var color=hash.replace('-',' '); // the requested color name
					if(!currentId || !color) return; //Can't find the item id, let's just stop here.
					var foundId=undefined;
					//Loop over the 'gridimages' array to find the first one that matches our requested color
					//store it's ID in 'foundId' to use with the switch function.
					$(window['gridimages'+currentId]).each(function(idx,gi){
						if (gi.dim1.toUpperCase() == color.toUpperCase()){
							foundId=gi.gridid;
							return false;
						}
					});
					if (!foundId) return; //We can't find a color that matches, let's not muck anything up.

				  //Call the built in 'swapCellImages' function with our correct ID, this actually does the
				  //color switch. Everything up until now was just information gathering.
					window['swapCellImages' + currentId].apply(null,[foundId,'','','','select']);
					$('select.colorSizeSelector option:selected').removeAttr('selected');
					$("select.colorSizeSelector option[value='" + foundId + "']").attr('selected','selected');
				},
				facebookLike : function() {
					var iframe = $('<iframe src="http://www.facebook.com/plugins/like.php?href=' + encodeURIComponent(document.location.href)+'&amp;layout=button_count&amp;show_faces=false&amp;width=150&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>');
					$('a > img[src="graphics/message.gif"]').parent().parent().prepend(iframe);
				}
    }
    ejcs.setup(); //Self calling so all we have to do is include this script.
});
