(function($) {
	$(document).ready(function() {
		$.addStylesheet('gallery');
		var search = window.location.search;
        if (!search) {
            return false;
        }
        search = search.split('?')[1];
        var chunks = search.split('&');
        var found = false;
        var categoryId = null;
        for (var i = 0; i < chunks.length; i++) {
            var chunk = chunks[i].split('=');
            if (chunk[0] == "id") {
                categoryId = chunk[1];
                found = true;
                break;
            }

        }
        if (!found) {
            return false;
        }
		var url = '/consumer/util/ajax/gallery.jsp';
		var Box = $('#gallery-large-image');
		var Thumbs = $('#gallery-thumbnails');
		var index = 0;
		var max = 0;
		var images = [];
		var thumbs = [];
		var ready = true;
		var update_credits = function(designer, city, state, photographer) {
			if (photographer) {
				$('#photo-credit').text(['Photo by ', photographer].pack());
			} else {
				$('#photo-credit').text('');
			}
			if (designer && city && state) {
				var label = (window.location.pathname.indexOf('tvl') > -1) ? '' : "Designer ";
				$('#designer-credit').text([label, designer, ' - ', city, ', ', state].pack());
			} else {
				$('#designer-credit').text('');
			}
		};

		var init = function(imageId, direction, lastName, set, node) {
			var params = {
				categoryId: categoryId,
				internetExplorer: new Date().getTime()
			};
			if (imageId && direction) {
				params.imageId = imageId;
				params.direction = direction;
			}
			if (lastName) {
				params.lastName = lastName;
			}
			if (set && imageId) {
				params.set = set;
				params.imageId = imageId;
			}

			$.get(url, params, function(data, textStatus) {

                var json = data.trim().parseJSON();

                if (json) {
                    try {
                        if (json.length < 5) {
                            if (node && node.ident().match(/back|last/i)) {
                                node.fadeTo(250, 0.25);
                                setTimeout(function() {
                                    node.fadeTo(150, 0.75);
                                }, 1000);
                                index = 0;
                                return false;
                            }
                        }
                    } catch(ex) {
                        alert(ex);
                    }

                    images = [];
                    thumbs = [];
                    index = 0;
                    Box.empty();
                    Thumbs.find('tr').empty();
                    // Add cells to the thumbnail table
                    var row = Thumbs.find('tr:first');
                    for (var i = 0; i < json.length; i++) {
                        row.append('<td class="thumbnail-cell">');
                    }
                    Thumbs.append("<tr><td colspan='" + json.length + "'><table id='gallery-thumbnail-navigation'><tbody><tr><td><a href='#' id='last-set'></a></td><td><a href='#' id='next-set'></a></td></tr></tbody></table></td></tr>");
                    $('#next-set, #last-set').dblclick(function() {
                        return false;
                    });
                    $('#next-set').click(function() {
                        var button = $(this);
                        if (ready) {
                            ready = false;
                            var id = Thumbs.find('tr:first img:last').ident().split('-')[1];
                            init(id, null, null, "nextSet", $(this));
                            setTimeout(function() {
                                ready = true;
                            }, 1000);
                        } else {
                            button.fadeTo(250, 0.25);
                            setTimeout(function() {
                                button.fadeTo(250, 1);
                            }, 1000);
                        }
                        return false;

                    });
                    $('#last-set').click(function() {
                        var button = $(this);
                        if (ready) {
                            ready = false;
                            var id = Thumbs.find('tr:first img:first').ident().split('-')[1];
                            init(id, null, null, "lastSet", $(this));
                            setTimeout(function() {
                                ready = true;
                            }, 1000);
                        } else {
                            button.fadeTo(250, 0.25);
                            setTimeout(function() {
                                button.fadeTo(250, 1);
                            }, 1000);
                        }
                        return false;

                    });

                    var length = json.length;
                    var tlength = 0;
                    var active = false;
                    $.each(json, function(i) {
                        images[i] = new Image();
                        images[i].largeURL = json[i].largeURL;
                        images[i].thumbURL = json[i].thumbURL;
                        images[i].designer = json[i].designer;
                        images[i].city = json[i].city;
                        images[i].state = json[i].state;
                        images[i].photographer = json[i].photographer;
                        if ($.browser.msie) {
                            images[i].src = [json[i].largeURL, ['ie', new Date().getTime()].join('=')].join('?');
                        } else {
                            images[i].src = json[i].largeURL;
                        }

                        images[i].id = json[i].id;
                        images[i].index = i;
                        var onloadReady = false;
                        if (params.set != null && params.set == 'lastSet') {
                        	if (i === (length-1) ) {
                        		onloadReady = true;
                        	}
                        } else {
                        	if (i === 0) {
                        		onloadReady = true;                                
                            }
                        }
                        if (onloadReady) {
                        	onloadReady = false;
                        	images[i].onload = function() {
                                var img = $(this);
                                Box.append(img);
                                var credits = img[0];
                                update_credits(credits.designer, credits.city, credits.state, credits.photographer)
                                Box.width(img.width()).height(img.height());
                                $('#gallery-back, #gallery-next').height(img.height());
                            };
                        }
                        
                        thumbs[i] = new Image();
                        if ($.browser.msie) {
                            thumbs[i].src = [json[i].thumbURL, ['ie', new Date().getTime()].join('=')].join('?');
                        } else {
                            thumbs[i].src = json[i].thumbURL;
                        }

                        thumbs[i].id = ['t-', json[i].id].pack();
                        thumbs[i].index = i;
                        thumbs[i].onload = function() {
                            tlength++;
                            Thumbs.find('td').eq(this.index).append($(this));
                            if (params.set != null && params.set == 'lastSet') {
                            	if (this.index === (length-1) ) {
                            		$(this).addClass('current-thumbnail');
                            		index = this.index;
                            	}
                            } else {
                            	if (this.index === 0) {
                                    $(this).addClass('current-thumbnail');
                                }
                            }
                            
                            if (tlength === length) {
                                Thumbs.find('img').click(function() {
                                    Thumbs.find('img').removeClass('current-thumbnail').removeAttr('style');
                                    $(this).addClass('current-thumbnail');
                                    index = $(this)[0].index;
                                    if (images[index]) {
                                        if ($.browser.msie) {
                                            var ie_img = new Image();
                                            ie_img.src = [images[index].largeURL, ['ie', new Date().getTime()].join('=')].join('?');
                                            ie_img.onload = function() {
                                                ie_img = $(ie_img);
                                                Box.find('img').remove();
                                                Box.append(ie_img);
                                                Box.height(ie_img.height());
                                                Box.width(ie_img.width());
                                                $('#gallery-back, #gallery-next').height(ie_img.height());
                                            };

                                        } else {
                                            var img = $(images[index]);
                                            Box.find('img').remove();
                                            Box.append(img);
                                            Box.height(img[0].height);
                                            Box.width(img[0].width);
                                            $('#gallery-back, #gallery-next').height(img.height());
                                        }
                                        //LOKVIK-2522
                                        update_credits(images[index].designer, images[index].city, images[index].state, images[index].photographer);
                                    }

                                }).mouseover(function() {
                                    if (!$(this).hasClass('current-thumbnail')) {
                                        $(this).fadeTo(250, 0.75);
                                    }
                                }).mouseout(function() {
                                    if (!$(this).hasClass('current-thumbnail')) {
                                        $(this).fadeTo(250, 1.0);
                                    }
                                });
                            }
                        };
                    });

                    var bar_ready = true;
                    var bar_click = function() {
                        var bar = $(this);
                        if (bar_ready) {
                            bar_ready = false;
                            var dir = "back";
                            if ($(this).ident().match(/next/i)) {
                                index++;
                            } else {
                                index--;
                            }
                            var image = images[index];
                            if (image) {
                                var img = $(image);
                                Box.find('img').replaceWith($(img));
                                Box.width(img.width())
                                Box.height(img.height());
                                $('#gallery-back, #gallery-next').height(img.height());
                                var credits = img[0];
                                update_credits(credits.designer, credits.city, credits.state, credits.photographer)

                                Thumbs.find('img').removeClass('current-thumbnail').removeAttr('style');
                                Thumbs.find('td').eq(index).find('img').addClass('current-thumbnail');


                            } else {
                                if (index > 0) {
                                    // We're moving forward
                                    var id = Thumbs.find('img:last').ident().split('-')[1];
                                    var direction = "forward";
                                    init(id, direction, null, null, $(this));
                                } else if (index < 0) {
                                    var id = Thumbs.find('img:first').ident().split('-')[1];
                                    var direction = "back";
                                    init(id, direction, null, 'lastSet', $(this));
                                }
                            }
                            setTimeout(function() {
                                bar_ready = true;
                            }, 750);
                        }
                        return false;
                    }

                    var add_bars = function() {
                        var back = $('#gallery-back');
                        var next = $('#gallery-next');
                        if (back.length > 0 || next.length > 0) {
                            return false;
                        }
                        back = $('<div id="gallery-back"></div>');
                        next = $('<div id="gallery-next"></div>');
                        Box.append(back).append(next);
                        back.dblclick(function() {
                            return false;
                        });
                        next.dblclick(function() {
                           return false;
                        });
                        back.fadeTo(0, 0.75).height(Box.height()).show().click(bar_click);
                        next.fadeTo(0, 0.75).height(Box.height()).show().click(bar_click);
                    }

                    Box.bind('mouseenter', add_bars);

                } else {
                    if (node.ident().match(/back|last/i)) {
                        index = 0;
                    } else {
                        index = Thumbs.find('tr > td > img').length - 1;
                    }

                    node.fadeTo(250, 0.25);
                    setTimeout(function() {
                        node.fadeTo(150, 0.75);
                    }, 1000);
                }
                /*
                LOKVIK-1498: Internet Explorer incorrectly puts the header flyouts behind the body content.
                This function needs to run to force it to display them above.
                 */
                if ($.browser.msie) {
                    var nodes = $('#global_cart_popup, #global_myaccount_popup_main_links, #global_login_popup, .nav-primary ul');
                    $.each(nodes, function(i, item) {
                        IEOnly.zIndex($(this), 2000 - i);
                    });

                }
			});
            setInterval(function() {
                Box.find('img:gt(0)').remove();
                Thumbs.find('.thumbnail-cell:gt(4)').remove();
            }, 10);
		};

        var locker = new ClickLocker();
        $('#gallery-last-names a').click(function() {
            if (locker.isLocked()) {
                return false;
            }
            locker.lock();
			init(null, null, $(this).ident(), null, $(this));
            locker.unlock();
			return false;
		});
		init();
	});
})(jQuery);
