/** mostly lifted from lachlan hardy - lachstock.com.au **/


(function($){  
    $.fn.flickrPolaroid = function(options) {  

        var defaults = {
                photoset_id: "72157616287853781",
                key: "48d7a3c7c487033cc3117d26ce7c135f"
            }, options = $.extend(defaults, options);
            
        function splitline (str, max) {
            var arr = str.split(" "),
                sofar = 0,
                result = "";
            
            for (i=0; i<arr.length; i++) {
                result += arr[i];
                if (sofar + arr[i].length > max) {
                    result += "\n";
                    sofar = 0;
                } else {
                    result += " ";
                    sofar += arr[i].length;
                }
            }
            
            return result
        }
            
        return this.each(function() {  
            canvas = $(this);
            
            function flickrPic (item) {
                
                $("<a/>").attr("href", item.url)
                         .attr("id", "polaroid")
                         .prependTo(canvas);

                var imgWidth = parseInt(item.width),
                    imgHeight = parseInt(item.height),
                    paperMargin = 20, // SETTING
                    paperWidth = imgWidth + 2 * paperMargin,
                    paperHeight = imgHeight + (1 + 1.618) * paperMargin, // all hail the golden ratio
                    rotation = 360 - Math.ceil(Math.random() * 18), // 18 is a SETTING (max cc rotation in degrees)
                    theta = Math.PI * rotation / 180, // convert to radians for convenience
                    polaroidWidth = Math.abs(paperWidth * Math.cos(theta)) + Math.abs(paperHeight * Math.sin(theta)),
                    polaroidHeight = Math.abs(paperWidth * Math.sin(theta)) + Math.abs(paperHeight * Math.cos(theta)),
                    r = Raphael("polaroid", polaroidWidth + 6 + 200, polaroidHeight + 6); // the +6 is to accomodate the drop shadow. the +200 is temp, for the text stuff

                //dropshadow
                r.rect(
                    0 + 4, // x-offset
                    Math.abs(paperWidth * Math.sin(theta)) + 4, // y-offset
                    paperWidth, 
                    paperHeight
                ).attr({
                    fill: "#000",
                    opacity: .15,
                    stroke: "#000",
                    "stroke-width": 4,
                    "stroke-opacity": .3
                }).rotate(
                    rotation, //quantity
                    0, // x-pivot
                    Math.abs(paperWidth * Math.sin(theta)) // y-pivot
                );

                // paper
                r.rect(
                    0, // x-offset
                    Math.abs(paperWidth * Math.sin(theta)), // y-offset
                    paperWidth, 
                    paperHeight
                ).attr({
                    fill: "#f6f6f6",
                    stroke: "#cccccc",
                    "stroke-width": 1,
                    "stroke-opacity": 1
                }).rotate(
                    rotation, //quantity
                    0, // x-pivot
                    Math.abs(paperWidth * Math.sin(theta)) // y-pivot
                );   

                //photo
                r.image(
                    item.image, 
                    0 + Math.sqrt(2 * paperMargin * paperMargin) * Math.cos(theta + Math.PI / 4), // x-offset
                    Math.abs(paperWidth * Math.sin(theta)) + Math.sqrt(2 * paperMargin * paperMargin) * Math.sin(theta + Math.PI / 4), // y-offset
                    imgWidth, 
                    imgHeight
                ).rotate(
                    rotation, 
                    0 + Math.sqrt(2 * paperMargin * paperMargin) * Math.cos(theta + Math.PI / 4),// + Math.abs(paperMargin * Math.cos(theta)), // x-pivot
                    Math.abs(paperWidth * Math.sin(theta)) + Math.sqrt(2 * paperMargin * paperMargin) * Math.sin(theta + Math.PI / 4)// + Math.abs(paperMargin * Math.cos(theta)) // y-pivot
                );
                
                //arrow
                r.image('/site_media/images/arrow.png', paperWidth, 100, 80, 22);
                
                // caption
                r.text(paperWidth + 120, 140, splitline(item.title, 20))
                 .attr({"font": '700 10px "Georgia"'})
                 .rotate(355, paperWidth + 80, 130);

            }


            function callFlickr() {
                $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=" + options.key + "&photoset_id=" + options.photoset_id + "&format=json&jsoncallback=?",
                    function(data){
                        $("#polaroid").add("span", canvas).add("#refresh-link").remove();
                        var photos = data.photoset.photo
                        var arr = jQuery.makeArray(photos);
                        var rndNum = Math.ceil(Math.random() * (photos.length - 1));
                        var photo = photos[rndNum];
                        var item = {
                            url: 'http://www.flickr.com/photos/35059019@N02/' + photo.id + '/in/set-72157616287853781',
                            width: '',
                            height: '',
                            image: 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg',
                            title: photo.title
                        }

                        $.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=" + options.key + "&photo_id=" + photo.id + "&format=json&jsoncallback=?",
                            function(data){
                                var size = data.sizes.size[2]; //small
                                item.width = size.width;
                                item.height = size.height;
                                item.image = size.source;
                                flickrPic(item);
                            }); // .getJSON to flickr.photos.getSizes
                    }); // .getJSON to flickr.photosets.getPhotos
            }; // function callFlickr()

            
            callFlickr();

        });  
    };  
})(jQuery);

