﻿jQuery.fn.eventsPicker = function() {
    // Variables

    var container = $(this);
    var slider = container.find('.slider');
    var sliderWidth = slider.width();
    var sliderItemWidth, sliderItemCount, sliderLastIndex, sliderItemSpacing;
    var sliderIndex = 0;

    container.before('<div class="slideLeft"><a href="#"><img src="/Content/images/arrow-left.png" alt="Previous" /></a></div>');
    container.after('<div class="slideRight"><a href="#"><img src="/Content/images/arrow-right.png" alt="Next" /></a></div>');

    slider.find('.event .eventDetail').hide();

    /// Functions

    var calculateSliderData = function() {
        sliderItemWidth = slider.find('.event img:first').width();

        sliderItemSpacing = slider.find('.event').css('margin-right');
        if (sliderItemSpacing && typeof (sliderItemSpacing) !== 'undefined') {
            sliderItemWidth = sliderItemWidth + parseInt(sliderItemSpacing.replace(/px/, ''));
        }

        sliderItemCount = sliderWidth / sliderItemWidth;
        sliderLastIndex = sliderItemCount - (container.width() / sliderItemWidth);
    }

    var sliderScrollTo = function(i) {
        var marginLeft = 0 - (i * sliderItemWidth);
        slider.animate({
            marginLeft: marginLeft + 'px'
        }, 'normal', 'swing');
    }

    var sliderNext = function() {
        if (sliderIndex < sliderLastIndex) {
            sliderIndex++;
            sliderScrollTo(sliderIndex);
        }
    }

    var sliderPrev = function() {
        if (sliderIndex > 0) {
            sliderIndex--;
            sliderScrollTo(sliderIndex);
        }
    }

    var handleArrowKeys = function(e) {
        //Not in a textarea or textbox
        if (e.target.type !== 'text' && e.target.type !== 'password'
            && e.target.type !== 'textarea' && e.target.type !== 'select') {
            switch (e.keyCode) {
                case 37:
                    sliderPrev();
                    e.preventDefault();
                    break;
                case 39:
                    sliderNext();
                    e.preventDefault();
                    break;
            }
        }
    }

    // Setup

    // will be correct if image is cached, incorrect otherwise
    calculateSliderData();

    // this event will fire if the image was not cached, which will re-calculate the
    // slider width once the image has finished loading
    slider.find('.event img:first').load(function() {
        calculateSliderData();
    });

    $(document).bind('keydown', handleArrowKeys);

    /// Events

    // show form when hovering over the event iamge    
    slider.find('.event').hover(
        function() {
            var thisEvent = $(this);
            thisEvent.siblings().find('img').show();
            thisEvent.find('.eventOptions').animate({ top: '-70px' }, 300, 'swing');
        },
        function() {
            var thisEvent = $(this);
            thisEvent.find('.eventOptions').animate({ top: '0px' }, 300, 'swing');
        }
    );

    container.find('form.eventForm input[type="button"]').click(function() {
        var form = $(this).closest('form')
        var action = form.attr('action').replace(/Authorize/i, 'AuthorizeJSON');
        var pass = form.find('input[type="password"]').val();
        var errors = form.find('.error');
        errors.html('').hide();
        $.getJSON(action + '?password=' + pass, function(result) {
            if (result === true) {
                form.submit();
            } else {
                errors.html('<ul><li>Incorrect password.</li></ul>');
                errors.show();
            }
        });
    });

    container.prev('.slideLeft').find('a').click(function() {
        sliderPrev();
        return false;
    });

    container.next('.slideRight').find('a').click(function() {
        sliderNext();
        return false;
    });
}

jQuery.fn.ajGallery = function() {
    /// Variables
    var container = $(this),

        thumb_width = 90 + (3 * 2) + (2 * 2),
        scrollUnit = 10,
        scrollInterval = 15,

        $thumbs = container.find('.thumbs'),
        thumbs_width = $thumbs.width(),
        thumbs_center = (thumbs_width / 2) - (thumb_width / 2),

        $main_image = container.find('.main_image'),

        $gallery = $thumbs.children('ul:first'),
        image_count = $gallery.children('li').length,
        gallery_width = image_count * thumb_width,

        $trace = $('#trace'),

    // init scroll position variables
        scrollPos = 0,
        minScroll = 0 - gallery_width + thumbs_width,
        maxScroll = 0,

    // hold last mouse position
        mouseX = 0,
        mouseY = 0,

    // lock keyboard navigation during animation so holding
    // down the arrow key doesn't queue up 100 movements
        animating = false;

    // determine bounds of auto-scroll zone
    var o = $thumbs.offset();
    var leftScrollBox = {
        left: o.left,
        top: o.top,
        right: o.left + 100,
        bottom: o.top + 90
    };
    var rightScrollBox = {
        left: o.left + thumbs_width - 100,
        top: o.top,
        right: o.left + thumbs_width,
        bottom: o.top + 90
    };

    /// Functions

    var slideshowControl = function(selector) {
        var that = {};

        var timer;
        var button = $(selector);
        var playing = false;

        button.toggle(
            function() {
                that.start();
                return false;
            },
            function() {
                that.stop();
                return false;
            }
        );

        that.delay = 3000;

        that.stop = function() {
            button.html('Play Slideshow');
            playing = false;
            //clearInterval(timer);
        };

        that.start = function() {
            button.html('Pause Slideshow');
            playing = true;
            //timer = setInterval(function() { that.next(); }, that.delay);
        };

        that.next = function() {
            if (playing) {
                moveNext();
            }
        }

        return that;
    }

    var startScroll = function(e) {
        $(document).bind('mousemove', captureMouse);
        var scrollTimer = setTimeout(doScroll, scrollInterval);
    }

    var stopScroll = function(e) {
        $(document).unbind('mousemove', captureMouse);
        if (typeof (scrollTimer) != 'undefined')
            clearTimeout(scrollTimer);
    }

    var captureMouse = function(e) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    }

    var doScroll = function() {
        if (mouseX >= leftScrollBox.left && mouseX <= leftScrollBox.right
            && mouseY >= leftScrollBox.top && mouseY <= leftScrollBox.bottom) {
            scrollPos += scrollUnit;
            ScrollThumbs();
        }
        else if (mouseX >= rightScrollBox.left && mouseX <= rightScrollBox.right
                && mouseY >= rightScrollBox.top && mouseY <= rightScrollBox.bottom) {
            scrollPos -= scrollUnit;
            ScrollThumbs();
        }

        scrollTimer = setTimeout(doScroll, scrollInterval);
    };

    var CheckScrollPos = function() {
        if (scrollPos <= minScroll)
            scrollPos = minScroll;
        if (scrollPos >= maxScroll)
            scrollPos = maxScroll;
    }

    var ScrollToThumb = function(i) {
        var start_pos = thumb_width * i;
        scrollPos = thumbs_center - start_pos;
        AnimateThumbs();
    }

    var AnimateThumbs = function() {
        CheckScrollPos();
        animating = true;
        $gallery.animate({ marginLeft: scrollPos + 'px' }, 750, 'swing', function() { animating = false; });
    }

    var ScrollThumbs = function() {
        CheckScrollPos();
        $gallery.css('margin-left', scrollPos);
    }

    var moveNext = function() {
        // check to see if galleria exists & that we're not 
        // already in the middle of an animation
        if ($.galleria && !animating) {
            $.galleria.next();
        }
    }

    var movePrev = function() {
        // check to see if galleria exists & that we're not 
        // already in the middle of an animation
        if ($.galleria && !animating) {
            $.galleria.prev();
        }
    }

    /// Setup

    // set thumbnail list container wide enough to hold all the images
    $gallery.css('width', gallery_width);

    var $galleria = container.find('.thumbs ul').galleria({
        history: true, // activates the history object for bookmarking, back-button etc.
        clickNext: false, // replaced galleria's clickNext with lightbox-style next/prev links
        insert: container.find('.main_image'), // the containing selector for our main image
        onImage: function(image, caption, thumb) {
        },
        onThumb: function(thumb) { // thumbnail effects goes here
            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // if thumbnail is active, fade all the way.
            var _fadeTo = _li.is('.active') ? '1' : '0.3';

            // fade in the thumbnail when finnished loading
            thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn(1500);

            // hover effects
            thumb.hover(
				function() { thumb.fadeTo('fast', 1); },
				function() { _li.not('.active').children('img').fadeTo('fast', 0.3); } // don't fade out if the parent is active
			)
        },
        onActivate: function() {
            try {
                var activeItemIndex = $gallery.find('li').index($('li.active'))
                ScrollToThumb(activeItemIndex);

                var activeItem = $gallery.find('li.active img');
                cartPopup.cartThumb.attr('src', activeItem.attr('src'));
            } catch (e) { }
        }
    });

    /// Events

    // monitor mouse position when over thumbs container
    $thumbs.hover(function() { startScroll(); }, function() { stopScroll(); });

    // keyboard navigation
    $(document).keydown(function(e) {
        //Not in a textarea or textbox
        if (e.target.type !== 'text' && e.target.type !== 'password'
            && e.target.type !== 'textarea' && e.target.type !== 'select') {
            var keyCode = e.keyCode || e.which,
            arrow = { left: 37, up: 38, right: 39, down: 40 },
            keys = { n: 78, p: 80 };

            if (keyCode == arrow.left || keyCode == keys.p) {
                movePrev();
                return false;
            } else if (keyCode == arrow.right || keyCode == keys.n) {
                moveNext();
                return false;
            }
        }
    });

    if ($.browser.msie) {
        $main_image.hover(
            function(e) {
                var offset = $(this).offset();
                var width = $(this).width();
                var halfway = width / 2;

                var trackMouseForPrevNext = function(e) {
                    var pos = e.pageX - offset.left;
                    if (pos > halfway) {
                        $('.lbNextLink').addClass('hover');
                        $('.lbPrevLink').removeClass('hover');
                    } else {
                        $('.lbPrevLink').addClass('hover');
                        $('.lbNextLink').removeClass('hover');
                    }
                };

                $(this).bind('mousemove', trackMouseForPrevNext);
            },
            function() {
                $('.lbPrevLink').removeClass('hover');
                $('.lbNextLink').removeClass('hover');
                $(this).unbind('mousemove');
            }
        );
    }

    $main_image.rightClick(function() {
        alert("Hey! Don't be a Stealy McStealerson!");
        return false;
    });

    slideshow = slideshowControl('a.slideshow');
}

var cart = function() {
    var size = $("#ddlSize"),
	    quantity = $("#txtQuantity"),
	    adjustments = $("input[name='adjustments']"),
	    eventID = 0,
	    cartPhotoID = 0,
	    thumbnail = $('.cartThumb'),
        allFields = $([]).add(size).add(quantity).add(adjustments);

    $.getJSON('/Cart/GetOptions', function(result) {
        var radioContainer = $('#adjustments');
        var first = true;
        for (index in result) {
            var photoOption = result[index];
            if (first) {
                radioContainer.append('<div class="adjustment"><input type="radio" name="adjustments" value="' + photoOption.ID +
                            '" checked="checked" />' + photoOption.Description + '</div>');
                first = false;
            } else {
                radioContainer.append('<div class="adjustment"><input type="radio" name="adjustments" value="' + photoOption.ID +
                            '" />' + photoOption.Description + '</div>');
            }
        }
        radioContainer.append('<div class="clear"></div>');
    });

    var updateTips = function(t) {
        tips.text(t).effect("highlight", {}, 1500);
    }

    var checkRequired = function(o, n) {
        if (o.valueOf().length == 0) {
            o.addClass('ui-state-error');
            updateTips(n + ' is required.');
            return false;
        } else {
            return true;
        }
    }

    var checkLength = function(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    var checkRegexp = function(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    if ($('#cartdialog').length > 0) {
        $("#cartdialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 325,
            modal: true,
            buttons: {
                'Add To Cart': function() {
                    var bValid = true;
                    allFields.removeClass('ui-state-error');

                    bValid = bValid && checkRequired(quantity, 'Quantity');

                    if (bValid) {
                        var adjustmentValue = $('input[name="adjustments"]:checked').val();
                        $.post('/Cart/AddPhoto', { photoID: $.galleria.currentPhotoID,
                            sizeID: size.val(),
                            quantity: quantity.val(),
                            optionID: adjustmentValue
                        },
                            function(data) {
                                if (data.status === true) {
                                    if (data.count == 1) {
                                        cartPopup.cartItemCount.html(data.count + ' item');
                                    } else {
                                    cartPopup.cartItemCount.html(data.count + ' items');
                                    }
                                }
                            }, 'json'
                        );
                        $(this).dialog('close');
                    }
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            close: function() {
                allFields.val('').removeClass('ui-state-error');
                quantity.val('1');
                size.val('');
                thumbnail.attr('src', '');
                $('input[name="adjustments"]').removeAttr('checked');
                $('input[name="adjustments"]:first').attr('checked', 'checked');
            }
        });

        $('a.cart').click(function() {
            $('#cartdialog').dialog('open');
            return false;
        });
    }

    if ($('#editcartdialog').length > 0) {
        $("#editcartdialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 325,
            modal: true,
            buttons: {
                'Update Cart': function() {
                    var bValid = true;
                    allFields.removeClass('ui-state-error');

                    bValid = bValid && checkRequired(quantity, 'Quantity');

                    if (bValid) {
                        var adjustmentValue = $('input[name="adjustments"]:checked').val();
                        $.doPost('/Cart/UpdateCartPhoto', { cartPhotoID: cartPhotoID,
                            sizeID: size.val(),
                            quantity: quantity.val(),
                            optionID: adjustmentValue
                        });
                        $(this).dialog('close');
                    }
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            close: function() {
                allFields.val('').removeClass('ui-state-error');
                quantity.val('1');
                size.val('');
                $('input[name="adjustments"]').removeAttr('checked');
                $('input[name="adjustments"]:first').attr('checked', 'checked');
            }
        });

        $('a.editCart').click(function() {
            $('#editcartdialog').dialog('open');
            return false;
        });
    }

    $.extend({
        doGet: function(url, params) {
            document.location = url + '?' + $.param(params);
        },
        doPost: function(url, params) {
            var $form = $("<form method='POST'>").attr("action", url);
            $.each(params, function(name, value) {
                $("<input type='hidden'>")
                        .attr("name", name)
                        .attr("value", value)
                        .appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });

    return {
        cartThumb: $('.cartThumb'),
        cartItemCount: $('#cartItemCount'),
        setEventID: function(id) {
            eventID = id;
            this.getSizes();
        },
        getSizes: function() {
            if (typeof (eventID) !== 'undefined' && eventID > 0) {
                $.getJSON('/Cart/GetSizes/?eventID=' + eventID, function(result) {
                    size.html('');
                    for (index in result) {
                        var price = result[index];
                        var option = document.createElement('option');
                        option.value = price.ID;
                        option.innerHTML = price.Description + ' - ' + price.Price;
                        size.append(option);
                    }
                });
            }
        },
        getSizesForRate: function(id) {
            $.getJSON('/Cart/GetSizesForRate/?rateID=' + id, function(result) {
                size.html('');
                for (index in result) {
                    var price = result[index];
                    var option = document.createElement('option');
                    option.value = price.ID;
                    option.innerHTML = price.Description + ' - ' + price.Price;
                    size.append(option);
                }
            });
        },
        editCartPhoto: function(id, rateID) {
            cartPhotoID = id;
            this.getSizesForRate(rateID);

            $.getJSON('/Cart/GetCartPhotoData/' + id, function(result) {
                quantity.val(result.quantity);
                size.find('option:selected').removeAttr('selected');
                size.find('option[value="' + result.size + '"]').attr('selected', 'selected');
                $('input[name="adjustments"]:checked').removeAttr('checked');
                $('input[name="adjustments"][value="' + result.option + '"]').attr('checked', 'checked');
                thumbnail.attr('src', result.thumb);
            });

            $('#editcartdialog').dialog('open');
            return false;
        }
    }
}

jQuery(function($) {
    $('.uibutton').hover(
        function() { $(this).removeClass('ui-state-default').addClass('ui-state-hover'); },
        function() { $(this).removeClass('ui-state-hover').addClass('ui-state-default'); }
    );
    
    $('.events').eventsPicker();
    $('.album').ajGallery();

    cartPopup = cart();
    if (typeof (eventID) !== 'undefined') {
        cartPopup.setEventID(eventID);
    }

    $("a[rel='colorbox']").colorbox();
});    