PW = PW || {};
if (typeof PW.gallery == "undefined") {

(function() {
    var source  = {};
    var cursor  = {};
    var query   = {};
    var current = null;
    var total   = 0;
    var curitem = 0;
    var maxpage = 0;
    var minpage = 0;
    var title   = "";
    var init    = true;

    var slideWidth = 550;
    var perPage    = 10;

    function diffObject(b, a) {
        return b.filter(function(i) {return typeof a[i] == "undefined";});
    };
    
    function sortObject(o) {
        var sorted = {},
            keys = [];

        for (var i in o) {
            if (o.hasOwnProperty(i) && i != "info") {
                keys.push(parseInt(i));
            }
        }
        keys.sort(function(a,b) {
            return parseInt(a) - parseInt(b);
        });
        for (var i in keys) {
            sorted[keys[i]] = o[keys[i]];
        }

        sorted['info'] = {min:keys[0], max:keys[i], size:keys.length};

        return sorted;
    };

    function cursorGetPageProcess(response, callback, prepend) {
        if (response.data.numFound == -1 || typeof response.data.numFound == "undefined") {
            total += response.data.docs.length;
        } else {
            total = response.data.numFound;
        }

        if (total == 0) {
            Plum.message("Error", "Sorry this gallery doesn't contain any items.");
            return;
        }

        if (response.gallery) {
            $(response.gallery).appendTo("body");
        }

        if (init && $('.slideshow-wrapper').length === 0) {
            $('body').append($("#galleryTemplate").html(), {title:title});
        }
        init = false;

        var id = null, pos;
        for(var i in response.data.docs) {
            pos = query.offset+parseInt(i);
            id  = response.data.docs[i].object_id;
            source[id] = response.data.docs[i];
            cursor[pos] = id;

            $("#outfitsContainer")[prepend ? 'prepend' : 'append']
                ($("#galleryImage").html(), $.extend({style:
                    "position:absolute;" +
                    "float:left;"+
                    //"position:relative;"+
                    "left:" + (slideWidth*(pos)) + "px;"
                },source[id]));

            $("#slideBox")
                .append($('#galleryFriend').html(), source[id]);
        }

        cursor = sortObject(cursor);

        $('#slideInner').css({
            'width': slideWidth * cursor.info.max,
            'height': 580
        });

        if (callback) {
            PW.gallerySupport[callback]();
        }
    }
    
    var fetching = false;
    function cursorGetPage(page, callback, prepend) {
        if (fetching) {
            return;
        }
        query.limit  = perPage;
        query.offset = perPage * page;

        query.getTemplate = $("#galleryTemplate").length == 0 && $('.slideshow-wrapper').length == 0 ? true : '';

        fetching = true;
        $.post("/closet/getGallery", query, function(response) {
            fetching = false;
            cursorGetPageProcess(response, callback, prepend);

            if (page >= maxpage) {
                maxpage = page;
            } else {
                minpage = page;
            }
            
            logClicktale('PW.gallerySupport.cursorGetPageProcess(' + JSON.stringify(response) + ', ' + JSON.stringify(callback) + ', ' + JSON.stringify(prepend)+ ')');


        }, 'json').error(function() {
            fetching = false;
        });
    }

    // closet window {{{
    /**
     *  Close modal window
     */
    function close() {
        $('body').css('overflow', '');
        $(".slideshow-wrapper").hide();
        $(".slideshow-wrapper").remove();
    }

    $(".slideshow-close").live("click", function(e) {
        e.preventDefault();
        close();
        
        logClicktale('PW.gallerySupport.close()');
    });
    // }}}
    
    function navUpdate(forward) {
        curitem =  forward ? curitem+1 : curitem-1;
        renderCurrent( cursor[curitem] );

        // Hide / show controls
        manageControls(curitem, forward);
        // Move slideInner using margin-left
        $('#slideInner').animate({
            'marginLeft' : slideWidth*(-curitem)
        });
    }
    
    // Create event listeners for .controls clicks {{{
    $('.control').live('click', function(e){
        e.preventDefault();
        if (!$(this).is(":visible")) {
            return;
        }
        // Determine new position
        var forward = ($(this).attr('id')=='rightControl'||$(this).hasClass('slide'));
        
        navUpdate(forward);
        logClicktale('PW.gallerySupport.navUpdate(' + JSON.stringify(forward) + ')');
        
        return false;
    });
    // }}}

    // key functions {{{
    $('body').keydown(function(e) {
        if (e.srcElement != this) {
            return;
        }
        switch (e.keyCode) {
        case 27: // esc
            close();
            e.preventDefault();
            break;
        case 32: // space
        case 38: // up
        case 39: // right
            $("#rightControl").trigger("click");
            e.preventDefault();
            break;
        case 40: // down
        case 37: // left
            $("#leftControl").trigger("click");
            e.preventDefault();
            break;
        }   
    });
    // }}}

    // favorite, fb share {{{
    $('.wishlist-button').live('click', function(e) {
        if (current) {
            wishlist_toggle(current.object_id, function(added) {
                if (added) {
                    source[current.object_id].wishlist = true;
                } else {
                    source[current.object_id].wishlist = false;
                }
            });
        }
        e.preventDefault();
        return false;
    });

    $('#btnCommentPost').live('click', function(e) {
        if (current) {
            comment_post(current.object_id, function(json) {
                source[ current.object_id].activity = json.activity;
                renderCurrent(current.object_id);
            });
            $("#btnCommentPost").val('');
        }
        e.preventDefault();
        return false;
    });

    function favoriteUpdate(that, response) {
        if (response && response.message) {
            that.attr('class', 'gallery-fav  gallery-' + (response.message[0] == "-" ? 'un' : '' ) + 'favorite');
        }
        var count = $(".gallery-favcount span:first").html(response.total).parent();
        if (!response.total) {
            count.hide();
        } else {
            count.show();
            count.find('span:last').html(response.total == 1 ? 'person loves' : 'people love');
        }
    }
    
    $(".gallery-fav").live("click", function(e) {
        if (current) {
            var that = $(this);
            fav_toggle(current.object_id, function(response) {
                favoriteUpdate(that, response);
                
                logClicktale('PW.gallerySupport.favoriteUpdate(jQuery(\'.gallery-fav\')[0], ' + JSON.stringify(response) + ')');
            });
        }
        e.preventDefault();
        return false;
    });

    $(".gallery-facebook-share").live("click", function(e) {
        if (current) {
            fbShare2({
                name:current.name,
                title: current.name,
                link: "http://www.plumwillow.com/closet/" + current.object_id,
                picture: current.thumb,
                description: current.description
            });
        }
        e.preventDefault();
    });
    // }}}

    function renderItem(id) {
        var zdata = source[id];
        if (!zdata) {
            return;
        }

        zdata.thumb = Plum.config((zdata.object_type == "i" ? "item" : "outfit") + "_base_url") +  zdata.object_id + '-250';

        $('div.friends-like-box').hide();
        $('div.image-' + id).show();

        $(".gallery-more").attr('href', '/closet/' + zdata.object_id);
        $(".gallery-fav").attr('class', 'gallery-fav  gallery-' + (zdata.has_fav ? 'un' : '') + 'favorite');
        var count = $(".gallery-favcount span:first").html(zdata.hearts).parent();
        if (!zdata.hearts) {
            count.hide();
        } else {
            count.show();
            count.find('span:last').html(zdata.hearts == 1 ? 'person loves' : 'people love');
        }

        if (zdata.object_type == "outfit") {
            $('.item-details').hide();
        } else {
            if (zdata.wishlist) {
                $('.wishlist-button').attr('class', 'wishlist-button wishlist-remove');
            } else {
                $('.wishlist-button').attr('class', 'wishlist-button wishlist');
            }
            $('.gallery-buy').attr('href', '/closet/' + zdata.object_id + '/buy');
            $('.gallery-item-price').html('$' + zdata.price);
            $('.item-details').show();
        }

        // fix data
        $("#slideshow-bottom").html(' ')
            .append($("#galleryDetailTemplate").html(), zdata);
        current = zdata;
    }
    
    // Render the info of an item {{{
    /**
     *  Render current item info
     */
    function renderCurrent(id) {
        renderItem(id);
        logClicktale('PW.gallerySupport.renderItem(' + JSON.stringify(id) + ')');
    }
    // }}}

    // manageControls (position) {{{
    function manageControls(position, forward){
        // Hide left arrow if position is first slide
        if(position==0){
            $('#leftControl').hide() 
        } else{ 
            $('#leftControl').show() 
        }
        
        if (forward) {
            if (position+5 >= cursor.info.max) {
                // get more results
                cursorGetPage(maxpage+1);
            }
        } else {
            if (minpage > 0 && cursor.info.min+5 > position) {
                cursorGetPage(minpage-1, '', true);
            }
        }

        // Hide right arrow if position is last slide
        if(position>=cursor.info.max) {
            $('#rightControl').hide() 
        } else{ 
            $('#rightControl').show() 
        }
    }
    // }}}
    
    function initSlideshow() {
        // Remove scrollbar in JS
        $('#slidesContainer').css('overflow', 'hidden');
        $('body').css('overflow', 'hidden');

        // Insert controls in the DOM
        $('#slideshow')
            .prepend('<span class="control" id="leftControl">Clicking moves left</span>')
            .append('<span class="control" id="rightControl">Clicking moves right</span>');

        // Hide left arrow control on first load
        manageControls(curitem, true);

        var id = cursor[curitem];
        // show more info

        renderCurrent(id);
        var offset = curitem-cursor.info.min;
        $('#slideInner').css({'marginLeft' : slideWidth*(-curitem)});
    }
    
    function slideshow(curQuery, options) {
        if (typeof curQuery != "object") {
            return;
        }
        close();

        // save query
        query   = curQuery;
        current = null;
        curitem = 0;
        maxpage = 0;
        minpage = 0;
        cursor  = {};
        init    = true;
        load    = maxpage;

        if (options) {
            if (options.current) {
                curitem = parseInt(options.current);
                maxpage = Math.floor(curitem/perPage); 
                minpage = maxpage;
                load    = maxpage;
            }
            if (options.title) {
                title = options.title;
            }
        }

        // load information from the current query 
        cursorGetPage(load, 'initSlideshow');
    }

    PW.gallery = slideshow;
    PW.gallerySupport = {
    	close: close,
    	renderItem: renderItem,
    	favoriteUpdate: favoriteUpdate,
    	navUpdate: navUpdate,
    	cursorGetPageProcess: cursorGetPageProcess,
    	initSlideshow: initSlideshow
    };
})();


$(".juice-carouslider a").live("click", function(e) {
    e.preventDefault();
    var that = $(this),
        surfaceid = that.parents("ul").attr('id'),
        parent    = that.parents('.thumbnailPaginator'),
        container = that.parents("li");

    var pages = 0, current=0, tmp = container;

    for (tmp = container; tmp.length > 0; pages++, tmp=tmp.prev());
    for (tmp = that.parent(); tmp.length > 0; current++, tmp=tmp.prev());

    var title = $('h2:first', parent).text();
    var args  = $("input[class^=" + surfaceid + "]", parent).val();

    PW.gallery({paginatorid: surfaceid.substr(10), args: args}, {preloadPages: pages, current: (container.parents("ul").find("li:first").find('div').length * (pages-1)) +  current -1, title:title});

    return false;
});

$(".tagcloud a").live("click", function(e) {
    var that = $(this),
        tag  = that.text();

    PW.gallery({collection: that.parent().hasClass('outfits') ? 'outfits' : 'items' , tags:tag, sort: {hearts:-1}}, {title:tag});

    e.preventDefault();
    return false;
});

$(".view-contest #outfits .look img").live('click', function(e) {
    e.preventDefault();
    var that  = $(this),
        name  = $('meta[http-equiv="contest:name"]').attr('content'),
        type  = $('meta[http-equiv="contest:type"]').attr('content'),
        title = $('meta[http-equiv="contest:title"]').attr('content');

    var current=0, tmp = that.parents('.look'), pages = parseInt($('.page-count span:first').text());
    for (; tmp.length > 0; current++, tmp=tmp.prev());

    PW.gallery({contest:name, type: type}, {
        title:title,
        preloadPages: pages * Math.ceil(25/10),
        current: 25 * (pages-1) + current -1
    });

    return false;
});

}

