var flk = {
    pool : "", // optional pool (defaults to Secret Pickle Supper Club group/pool )
    per_page : "" // optional number of images to display per page.
};
(function flickr(){
    var _sizes = {
                    small:"_s",
                    thumb:"_t",
                    medium:"_m",
                    none:"",
                    big:"_b",
                    original:"_o"
                };
    var _key = "ef9f062d66ed0a7dab291ade01586b6e"; // put your flickr api key here!
    var _url = "http://api.flickr.com/services/rest/?";
    var _pool = this.pool || "1357027@N21";
    var _per_page = this.per_page || "49"; 
    var currentPage = null;
	var currentItem = null;
    delete this.pool;
    delete this.per_page;
    var staging = $(document.createElement("div")).css({
        position:"absolute",
        left:"-500em",
        top:"-500em"
    });
    $(document.body).append(staging);
    function getPhotos(page){
        page = page || 1;
        var href = _url + "api_key="+_key+"&group_id="+_pool+"&page="+page+"&per_page="+_per_page+"&format=json&jsoncallback=flk.paint&method=flickr.photos.search&tags=Secret+Pickle+Gallery&extras=owner_name,url_z,path_alias";
        var scr = document.createElement("script");
        scr.src = href;
        scr.id = "page_"+page;
        document.head = document.head || document.getElementsByTagName('head')[0];
        document.head.appendChild(scr);
    };
    this.throwError = function(){
        $("#gallery").append("<h2>There was an error getting photos.</h2>");
    };
    function buildPagination(page,pages){
        currentPage = page;
        var destination = $("#gallery"), topNav = $("<ul class='gallery-nav clearfix' id='s-top-nav' ></ul>"), botNav = $("<ul class='gallery-nav clearfix' id='s-bot-nav' ></ul>");
        for(var x = 0;++x<=pages;){
            var strMenuItem = x == page ? "<li class='current' >"+x+"</li>" : "<li>"+x+"</li>";
            topNav.append(strMenuItem);
            botNav.append(strMenuItem);
        }
        destination.before(topNav).after(botNav);
        $(".gallery-nav li").bind("click",movePage);
        var firstItem = $("#s-top-nav li").first();
        var lastItem = $("#s-top-nav li").last();
        !firstItem.hasClass("current") ? firstItem.before($("<li class='previous' >"+(currentPage-1)+"</li>").bind("click",movePage)) : null;
        !lastItem.hasClass("current") ? lastItem.after($("<li class='next' >"+(currentPage+1)+"</li>").bind("click",movePage)) : null;
        firstItem = $("#s-bot-nav li").first();
        lastItem = $("#s-bot-nav li").last();
        !firstItem.hasClass("current") ? firstItem.before($("<li class='previous' >"+(currentPage-1)+"</li>").bind("click",movePage)) : null;
        !lastItem.hasClass("current") ? lastItem.after($("<li class='next' >"+(currentPage+1)+"</li>").bind("click",movePage)) : null;
        // align the top and bottom nav 
        $("#s-top-nav").css({
            marginLeft : ($("#s-top-nav").parent().width() / 2) - ($("#s-top-nav").width() /2)
        });
        $("#s-bot-nav").css({
            marginLeft : ($("#s-bot-nav").parent().width() / 2) - ($("#s-bot-nav").width() /2)
        });
    };
    
    function movePage(){
        if($(this).hasClass("current")) return false;
        var pageToGet = $(this).text();
        getPhotos(pageToGet);
    };
    
	function handleKeys(ev){
		var figs = $("#gallery figure");
        var toGet = null;
		if ((ev.which && ev.which == 39) && (currentItem < _per_page)) {
			toGet = currentItem + 1;
			$(figs[toGet]).trigger("click");
		} else if ((ev.which && ev.which == 37) && (currentItem > 0)) {
			toGet = currentItem - 1;
		    $(figs[toGet]).trigger("click");
		}
		if((ev.which && ev.which == 27)){
			closeShow();
		}
        
	}

    this.paint = function(objPhotos){
        var gal = $("#gallery");
        gal.empty();
        $(".gallery-nav").remove();
        var photos = objPhotos["photos"] ? objPhotos["photos"]["photo"] || [] : this.throwError();
        buildPagination(objPhotos["photos"]["page"],objPhotos["photos"]["pages"]);
        for(var i=-1;++i < photos.length;){
            var img = "<figure><a href='http://farm"+photos[i].farm+".static.flickr.com/"+photos[i].server+"/"+photos[i].id+"_"+photos[i].secret+".jpg' target='_blank'><img src='http://farm"+photos[i].farm+".static.flickr.com/"+photos[i].server+"/"+photos[i].id+"_"+photos[i].secret+"_s.jpg' alt='"+photos[i].title+"' width='75' height='75' /></a>";
                img += "<figcaption><p>Photo by: <a href='http://www.flickr.com/people/"+photos[i].pathalias+"/' target='_blank' >"+ photos[i].ownername +"</a></p></figcaption></figure>";
            gal.append($(img).bind("click",display).data('extras',{height_z:photos[i].height_z,position:i,pid:photos[i].id,name:photos[i].ownername,title:photos[i].title}));
        }
    };
    function buildWindow(){
        return $(document.createElement("div")).addClass("modal").attr("id","modal");
    };
    function buildBlocker(){
        return $(document.createElement("div")).addClass("modal-blocker").attr("id","blocker").bind("click",closeShow);
    };
    function buildClose(){
        return $(document.createElement("div")).html("close").attr("id","modal-close").bind("click",closeShow);
    }
    function closeShow(){
		$(document).unbind("keyup",handleKeys);
        $("#modal").fadeOut(125,function(){
            $("#blocker").fadeOut(75);
        });
        return false;
    }
    function display(){
        if(!document.getElementById("blocker")){
            var blocker = buildBlocker();
            blocker.height($(document).height());
            $(document.body).append(blocker);
			$(document).bind("keyup",handleKeys);
        }else if(!$("#blocker").is(":visible")){
            $("#blocker").show();
			$(document).bind("keyup",handleKeys);
        }
        var img = $(this).find("a");
        var caption = $(this).find("figcaption p");
        var zsrc =img.attr("href");
        var extras = $(this).data('extras');
        var captionText =  caption.html();
        var modalContent = $("<a href='http://flickr.com/photos/"+extras.name+"/"+extras.pid+"' target='_blank' title='"+extras.title+"' ><img src='"+zsrc+"' id='modal-img' alt='"+extras.title+"' /></a>");
        staging.append(modalContent);
        $("#modal-img").bind("load",function(){
            $("#modal").remove();
            var clsBtn = buildClose();
            var modal = buildWindow();
                modal.append(modalContent);
                modal.append(captionText);
                modal.append(clsBtn);
            $(document.body).append(modal);
            modal.css({
                top: (($(window).height()/2)-(modal.height()/2)) + $(window).scrollTop(),
                left: ($(window).width()/2)-(modal.width()/2)
            });
		currentItem = extras.position;
        if(extras.position > 0) {
            modal.append($("<div class='previous'>"+parseInt(extras.position-1)+"</div>").bind("click",getImg));
        }
        if(extras.position < _per_page){
            modal.append($("<div class='next'>"+parseInt(extras.position+1)+"</div>").bind("click",getImg));
        }
        });
        return false;
    }
    function getImg(){
        var figs = $("#gallery figure");
        var toGet = $(this).text();
        $(figs[toGet]).trigger("click");
    }
    function init(){
        getPhotos();
    }
    $(document).ready(init);
}).apply(flk);
