/* 2009 Alan Languirand
  You are free to use this code and modify it for your own photo gallery, just maintain this original copyright at the top of the document
  
    To use flickr_gallery, you need to do two things:
    
    first - setup your galleries
    create a new div and set it's class to "fg_photoGallery" to tell this script to turn it into a photo gallery
    next, change it's "title" attribute to the path of the flickr rss feed of the photo set you'd like to display
    like this:
    <div class="fg_photoGallery" title="http://api.flickr.com/services/feeds/photoset.gne?set=[setnumber]&nsid=[idnumber]&lang=en-us">
    </div>
    
    the correct url can be optainted by clicking on the photoset and copying the url for the rss feed at the bottom of the set's landing page
    
    next - setup your galleries

    <script type="text/javascript">
        setup_photoGallery("path/to/stylesheet.css", "path/to/template.html");
    </script>
    
    
    
*/


    function setupGalleryLinks(){
        $(".fg_photoGalleryLink").each(function(){        
        //add our template HTML to the flagged divs
        //$(this).load(template);
        
        //add a variable to ask the flickr api to return the feed pre-formatted as am array javascript argument lists
        var url = $(this).attr("title") + "&format=json&jsoncallback=?";
        
        //set a tracking object since the $(this) keywork will no longer reference our div in the .getJSON call
        var currentGallery = $(this);
        
                $.getJSON(url,
                    function(data){
                        //use most recent image as the poster image
                      //alert();
                        $("<img/>").attr({"src": data.items[0].media.m.replace(/m.jpg/, "s.jpg"), "title": data.title.replace(/Content from /, "")}).appendTo(currentGallery);
                        $("<a>").append(data.title.replace(/Content from /, "")).attr({href: "#top"}).appendTo(currentGallery); 
                    });

        currentGallery.click(function(){
            var gal = $(this).attr("title");
            $("#main_gallery").empty().attr({"title": gal});
            setup_photoGallery();
            });
        });
        $(".fg_photoGalleryLink:first").click();
    }

    function setup_photoGallery(message, template, cssFile, mode, target){
        
        //not the most elegent decision structure, but the simplest to implement
        if (template){}
        else {
            var template = "common/template.html";
            }
        //tooltip for large image in galleries
        if (message){}
        else{
            var message = "click to view a larger version on flickr.";
            }
        
        if (cssFile){
            addStyle(cssFile, true);
            }
        else{
            addStyle("sbc_portal.css", true);
            }
        

        $(".fg_photoGallery").each(function(){        
        //add our template HTML to the flagged divs
        $(this).load(template);
        
        //add a variable to ask the flickr api to return the feed pre-formatted as am array javascript argument lists
        var url = $(this).attr("title") + "&format=json&jsoncallback=?";
        
        //set a tracking object since the $(this) keywork will no longer reference our div in the .getJSON call
        var currentGallery = $(this);
        
                $.getJSON(url,
                    function(data){
                        //set a flag to make the first image large
                        var first = true;
                        var count = 0;
                    
                    //make sure the thumbnail div is empty, then fill it up with thumbnails from the feed
                        currentGallery.find(".fg_thumbs").empty();
                      
                      //loop over all the items retruned by our ajax call
                      $.each(data.items, function(i,item){
                        //small hack of the flickr file system to get small square images as thumbnails 
                        var smallImage = item.media.m.replace(/m.jpg/, "s.jpg"); //while the large image is loaded, the smaller thumbnail is stretched into it's place to provide immediate user feedback
                        var largeImage = item.media.m.replace(/m.jpg/, "d.jpg"); 
                        //reference full size image in the alt tag
                        $("<img/>").attr({"alt": largeImage, "src": smallImage, "id": count}).appendTo(currentGallery.find(".fg_thumbs"));
                        if (first == true){
                            //makes most recent image the larger display image
                            first = false;
                            $("<img/>").attr({"src": item.media.m, "title": message}).appendTo(currentGallery.find(".fg_main_image a"));
                            currentGallery.find(".fg_main_image a").attr({"href": item.link});
                            }
                        count++;      
                      });
                      //pull data from the feed
                      
                      
                      currentGallery.find(".fg_desc").append(data.description);
                      currentGallery.find(".fg_title a").append(data.title.replace(/Content from /, ""));
                      
                      //add the thumbnail click events
                      if (mode == "list") {
                        currentGallery.find(".fg_title a").attr({"href": target});
                        var counterList = 0;
                        currentGallery.find(".fg_thumbs img").each(function(){
                            
                            $(this).wrap("<a></a>").parent().attr({
                                "href": target + "/photos"
                            });
                            
                            counterList++;
                        });
                      }
                      else {
                      currentGallery.find(".fg_title a").attr({"href": data.link});
                      currentGallery.find(".fg_thumbs img").click(function(){
                            currentGallery.find(".fg_loading").show();
                            //stretch thumbnail image into place, load larger image, then swap urls once the data has arrived. This provides immediate feedback for the click event
                            var handle = $(this).attr("alt");
                            //.replace(/s.jpg/, "t.jpg");
                            currentGallery.find(".fg_main_image a").attr({"href": data.items[parseInt($(this).attr("id"))].link});
            
                            var newHandle = $(this).attr("alt");
                            
                            //stretch thumbnail image into place
                            currentGallery.find(".fg_main_image img").attr({src: handle});
                            var theImage = new Image();
                            
                            //oad larger image
                            theImage.src = newHandle;
                            theImage.onload = function() {
                                    //then swap urls once the data has arrived
                                    currentGallery.find(".fg_loading").fadeOut();
                                    currentGallery.find(".fg_main_image img").attr({"src": newHandle});
                                    }//onload 
                        });
                        currentGallery.find(".fg_thumbs img:first").click();
                      }
                    });

        });
        
    }
    
function addStyle(css, isfile) { // addStyle(css, [isfile])  css=string of CSS code or link/to/tylesheet, set isfile to true if css=link/to/stylesheet
        if(isfile == true){
            $.get(css, function(data){
              addStyle(data);
            });}
        else{
          var style = document.createElement( 'style' );
          style.type = 'text/css';
          var head = document.getElementsByTagName('head')[0];
          head.appendChild( style );
          if( style.styleSheet )  // IE
             style.styleSheet.cssText = css;
          else  // other browsers
             style.appendChild( document.createTextNode(css) );
          return style;
        }
       }

    function debug(text){
                $(".debug").empty().append(text);
            }
