(function($){
	$.fn.jumpintogallery = function(imgobject) {

        /* we are dealing with three different inputs
         * 1.id appended as anchor to url when first opening the gallery
         * 2.change requested by clicking on a thumbnail on the gallery page
         * 3.existing image in HTML
         */

        //1.
        var imageIdfromUrl = window.location.hash.substr(1);
        var pattern=new RegExp("^[a-zA-Z0-9_-]+$");
        test=pattern.exec(imageIdfromUrl);
        if(test!=null){
          imageIdfromUrlCl=test;
        }else {
          imageIdfromUrlCl='img_05_Mt_Hutt';
        }
        var imageToUse=imageIdfromUrlCl;

        //2. takes precedence over url
        if(imgobject !=undefined){
            var imageIdfromScript = $(imgobject).attr('id');
            imageToUse=imageIdfromScript;
            wait=2;
        }

        //3.
        var imageObjfromHtml = $("#imageholder >img:first");
        var imageIdfromHtml = imageObjfromHtml.attr('id');

        if (imageToUse==imageIdfromHtml || (imageIdfromHtml=="firstimage" && imageToUse=="img_05_Mt_Hutt")){
          //nothing to do return
          return this;
        }

        changeimage(imageToUse,imageObjfromHtml);

        function changeimage(imageToUse,imgobject) {

            //update the description from the alt text
            var alttext = $("#"+imageToUse+" img").attr('alt');
            $("#description").animate({
                        opacity: 0
                  },500, function(){$("#description").html(alttext).animate({
                        opacity: 1
                  },500);
            });

            var imageSrc= 'images/gallery/'+imageToUse+'.jpg';
            //imgobject.attr({src : imageSrc});
            imgobject.crossfade(imageSrc,imgobject);

        }

		  // returns the jQuery object to allow for chainability.
		  return this;
	}


// create crossfade as a plugin
$.fn.crossfade = function (newImageSrc,oldImageObj) {

        var oldImageSrc=oldImageObj.attr('src');
        var imageHolder=oldImageObj.parent();

        // copy the original image to the background
        imageHolder.css({'background':'#F5F5DD url(' + oldImageSrc +') no-repeat right top','height':'266px','float':'right','overflow':'hidden','width':'578px'})

        //fade new image over the css background image
        $(new Image()).load(function() {
            newImageObj=imageHolder.prepend('<img src="'+newImageSrc+'" width="578" height="266" style="opacity:0; filter: alpha(opacity=0)">');
            newImageObj.find('img:first').show().animate({
                  opacity: 1
              },500,removeImg(imageHolder));
        }).attr('src',newImageSrc);

        //remove the image
        function removeImg(imageHolder){
            imageHolder.find('img:last').animate({
                  opacity: 0
              },500, function(){imageHolder.find('img:last').remove()
              });
        }


        return this;
};

})(jQuery);
