/**
 * NOTE: To use this file you need jScrollPane.js, jquery.mousewheel.js (these are required for scrollable dropdowns)
 * and jquery.livequery.js (for styling selects that are dynamically added to the page (or hidden to begin with))
 *
 * It is recommended that you set selects to display: none in your CSS as correct width values are only picked up
 * properly (from the CSS file) when selects are hidden
 *
 * When creating styled selects we assume that:
 * - The select element has a width applied in the CSS
 * - The majority of CSS for the look and feel of the styled selects will be done in a CSS file based on the classes
 *   we apply to each element
 */

(function($) {

    var StyledSelectField = function(element,index){
        this.element = $(element);
        this.index = index;
        this.selectElementWidth = this.element.outerWidth();

        this.styledSelectOptionFocus = 0;
        this.open = false;
        this.mouseIn = false;
        this.optionsMouseIn = false;
        this.textInputTimeout = null;

        this.styledSelectWrapper = null;
        this.styledSelectHolder = null;
        this.styledSelectSelected = null;
        this.styledSelectOptionHolder = null;
        this.styledSelectArrow = null;
        this.styledSelectBottom = null;
        this.styledSelectBottomRight = null;

        this.downArrowInterval = null;
        this.upArrowInterval = null;

        var self = this;
        
        this.buildStyledSelect = function() {
            self.element.hide();
            self.styledSelectWrapper = jQuery('<span></span>').attr({
                'className': 'selectWrapper'
            });
            self.styledSelectHolder = jQuery('<div></div>').attr({
                'className': 'styledSelect'
            });
            self.styledSelectSelected = jQuery('<div></div>').attr({
                'className': 'selectedOption'
            });
            self.styledSelectOptionHolder = jQuery('<div></div>').attr({
                'className': 'optionHolder'
            }).hide();
            self.styledSelectArrow = jQuery('<div></div>').attr({
                'className': 'selectArrow'
            });
            self.styledSelectBottom = jQuery('<div></div>').attr({
                'className': 'selectFooter'
            }).hide();
            self.styledSelectBottomRight = jQuery('<div></div>').addClass('selectFooterRight');

            self.element.wrap(self.styledSelectWrapper);

            self.styledSelectHolder.append(self.styledSelectArrow);
            self.styledSelectHolder.append(self.styledSelectSelected);
            self.styledSelectHolder.append(self.styledSelectOptionHolder);
            self.styledSelectBottom.append(self.styledSelectBottomRight);
            self.styledSelectHolder.append(self.styledSelectBottom);

            self.styledSelectWrapper = self.element.parent();

            self.styledSelectWrapper.append(self.styledSelectHolder);

            // this is added to stop the window from moving on keydown
            self.styledSelectWrapper.prepend(jQuery("<input/>").addClass('dummy').css({
                'opacity': '0',
                'position': 'absolute',
                'left': '-9999px'
            }));

            // get all dom elements
            self.styledSelectHolder = jQuery('.styledSelect', self.styledSelectWrapper);
            self.styledSelectSelected = jQuery('.selectedOption', self.styledSelectWrapper);
            self.styledSelectOptionHolder = jQuery('.optionHolder', self.styledSelectWrapper);
            self.styledSelectArrow = jQuery('.selectArrow', self.styledSelectWrapper);

            // build options html
            self.element.children().each(function(i) {
                var optionElement = jQuery(this);
                var value = optionElement.val();
                var text = optionElement.text();

                var styledSelectOption = jQuery('<div></div>').addClass('option');
                var styledSelectOptionValue = jQuery('<span></span>').addClass('optionValue').css({
                    display: 'none'
                }).text(value);
                var styledSelectOptionText = jQuery('<span></span>').addClass('optionText').text(text);
                styledSelectOption.append(styledSelectOptionValue, styledSelectOptionText);

                self.styledSelectOptionHolder.append(styledSelectOption);

                // check if this option is selected
                if (self.element.val() == value) {
                    self.styledSelectSelected.html('<span>' + text + '</span>');
                } else if (i == 0) {
                    self.styledSelectSelected.html('<span>' + text + '</span>');
                }
            });

            self.styledSelectOptions = self.styledSelectOptionHolder.children();
        };

        this.applyStyles = function() {
            self.styledSelectWrapper.css({
                'z-index': (9999 - jQuery(jQuery("body").data("StyledSelectField")).length),
                'width': parseInt(self.selectElementWidth+4) + 'px'
            });

            self.styledSelectHolder.css({
                'width': parseInt(self.selectElementWidth+4) + 'px'
            });

            self.styledSelectSelected.css({
                'width': parseInt(self.selectElementWidth)-(parseInt(self.styledSelectArrow.css('width').substr(0, self.styledSelectArrow.css('width').length-2))) + 4 + 'px'
            });

            self.styledSelectOptionHolder.css({
                'width': parseInt(self.selectElementWidth + 2) + 'px' //width: parseInt(self.selectElementWidth+5)+'px'
            });
        };

        this.addEventHandlers = function() {
            jQuery('input.dummy', self.styledSelectWrapper).focus(function(){
                if (!self.open) {
                    self.openSelect();
                }
            }).bind('textEntry', function() {
                self.searchSelect();
            });

            self.styledSelectWrapper.hover(function(){
                if(!self.open) self.styledSelectWrapper.find('.selectArrow').css('background-position','left -'+parseInt(self.styledSelectWrapper.height())+'px');
            },function(){
                if(!self.open) self.styledSelectWrapper.find('.selectArrow').css('background-position','left top');
            });


            self.styledSelectHolder.click(function(event) {
                event.stopPropagation();
                if (self.open) {//&& !$this.optionsMouseIn
                    self.closeSelect();
                } else {
                    self.closeAllSelects();
                    jQuery('input.dummy', self.styledSelectWrapper).focus();
                }
            });

            self.styledSelectHolder.bind('mouseenter', function() {
                self.mouseIn = true;
            }).bind('mouseleave', function() {
                self.mouseIn = false;
            });

            self.styledSelectOptions.each(function(i) {
                jQuery(this).hover(function() {
                    self.setFocus(jQuery(this));
                }, function() {
                    jQuery(this).removeClass('optionHover');
                });

                jQuery(this).click(function(event) {
                    event.stopPropagation();
                    if (self.open) {
                        self.setFocus(jQuery(this));
                        self.closeSelect();
                        self.setSelected(this);
                    }
                });
            });

            jQuery(document).click( function(event) {
                self.closeAllSelects();
            });

        };

        this.addScrollbar = function() {
            if (self.styledSelectOptionHolder.outerHeight() > 150) {
                self.styledSelectOptionHolder.css({
                    height: '150px',
                    //'border-right':0,
                    paddingRight: '0'
                });
                self.styledSelectOptionHolder.jScrollPane(
                {
                    //showArrows: true,
                    //scrollbarWidth: 12
                    showArrows: false,
                    scrollbarWidth: 0
                }
                );

                jQuery(self.styledSelectHolder).find('div.jScrollPaneContainer').css({
                    position: 'relative',
                    overflow: 'visible'
                }).hide();
            }else{
                self.styledSelectOptionHolder.css({
                    width: parseInt(self.selectElementWidth+2)+'px'
                });
            }
        };

        this.setFocus = function(element, jumpToSelected) {
            if (self.styledSelectOptions.index(element) != self.styledSelectOptionFocus) {
                self.removeFocus(jQuery(self.styledSelectOptions[self.styledSelectOptionFocus]));
            }
            self.optionsMouseIn = true;
            element.addClass('optionHover');

            // if the dropdown has a scrollbar we need to keep the focused element in view
            if (jQuery('div.jScrollPaneTrack', self.styledSelectHolder).length) {
                var scrollContainerHeight = jQuery('div.jScrollPaneContainer', self.styledSelectHolder).height();
                var optionHeight = element.height();
                var optionOffset = element.position();
                var optionHolderPosition = self.styledSelectOptionHolder.position();

                var maxViewablePosition = scrollContainerHeight - optionHeight;
                var currentPosition = optionOffset.top + optionHolderPosition.top;
                if (jumpToSelected) {
                    if (currentPosition > maxViewablePosition) {
                        jQuery('div.jScrollPaneContainer', self.styledSelectHolder).trigger('mousewheel', -0.75);
                        self.setFocus(element, true);
                    } else if (currentPosition < 0) {
                        jQuery('div.jScrollPaneContainer', self.styledSelectHolder).trigger('mousewheel', 0.75);
                        self.setFocus(element, true);
                    }
                }
            }
            self.styledSelectOptionFocus = self.styledSelectOptions.index(element);
        };


        this.removeFocus = function(element) {
            element.removeClass('optionHover');
        };

        this.attachKeyPressHandler = function() {
            if (self.open) {
                self.styledSelectWrapper.bind('keydown', function(event) {
                    switch (event.keyCode) {
                        case 38:
                            // up
                            setFocusUp();
                            if (!jQuery.browser.safari) {
                                self.upArrowInterval = setInterval(function() {
                                    self.setFocusUp();
                                }, 150);
                            }
                            break;
                        case 40:
                            // down
                            setFocusDown();
                            if (!jQuery.browser.safari) {
                                self.downArrowInterval = setInterval(function() {
                                    self.setFocusDown();
                                }, 150);
                            }
                            break;
                        case 13:
                            // enter
                            event.preventDefault();
                            self.setSelected(jQuery(self.styledSelectOptions[self.styledSelectOptionFocus]));
                            self.closeSelect();
                            break;
                        case 9:
                            // tab
                            closeSelect();
                            break;
                    }
                }).bind('keyup', function(event) {
                    switch (event.keyCode) {
                        case 38:
                            // up
                            clearInterval(self.upArrowInterval);
                            break;
                        case 40:
                            // down
                            clearInterval(self.downArrowInterval);
                            break;
                        default:
                            self.checkForTextInput(event.keyCode);
                            break;
                    }
                }).bind('keypress', function(event) {
                    switch(event.keyCode) {
                        case 9:
                            // tab
                            self.closeSelect();
                            break;
                    }
                });
            }
        };

        this.checkForTextInput = function(keyCode) {
            if ((keyCode >= 65 && keyCode <= 90)) {
                clearTimeout(self.textInputTimeout);
                self.textInputTimeout = setTimeout(function() {
                    jQuery('input.dummy', self.styledSelectWrapper).val('');
                }, 1000);
                jQuery('input.dummy', self.styledSelectWrapper).trigger('textEntry');
            }
        };

        this.setFocusUp = function() {
            if (self.styledSelectOptionFocus != 0) {
                self.removeFocus(jQuery(self.styledSelectOptions[self.styledSelectOptionFocus]));
                self.setFocus(jQuery(self.styledSelectOptions[self.styledSelectOptionFocus-1]), true);
            }
        };

        this.setFocusDown = function() {
            if ((self.styledSelectOptionFocus + 1) < this.styledSelectOptions.length) {
                self.removeFocus(jQuery(this.styledSelectOptions[this.styledSelectOptionFocus]));
                self.setFocus(jQuery(this.styledSelectOptions[this.styledSelectOptionFocus+1]), true);
            }
        };

        this.detachKeyPressHandler = function() {
            self.styledSelectWrapper.unbind('keydown');
        };

        this.addScrollbarListener = function() {
            var scrollbar = jQuery('div.jScrollPaneTrack', self.styledSelectHolder);
            if (jQuery(scrollbar).length) {
                scrollbar.bind('mouseenter', function() {
                    self.optionsMouseIn = true;
                }).bind('mouseleave', function() {
                    self.optionsMouseIn = false;
                });
            }
        };

        this.removeScrollbarListener = function() {
            var scrollbar = jQuery('div.jScrollPaneTrack', self.styledSelectHolder);
            if (jQuery(scrollbar).length) {
                scrollbar.unbind('mouseenter').unbind('mouseleave');
            }
        };

        this.closeSelect = function() {
            self.styledSelectHolder.find('.selectFooter').hide();
            self.styledSelectOptionHolder.parent('div.jScrollPaneContainer').hide();
            self.styledSelectWrapper.css({
                'background-position':'left top'
            });
            self.styledSelectWrapper.find('.selectedOption').css('background-position','left top');
            self.styledSelectWrapper.find('.selectArrow').css('background-position','left top');
            self.styledSelectOptionHolder.hide();
            self.open = false;
            self.detachKeyPressHandler();
            self.removeScrollbarListener();
            clearInterval(self.upArrowInterval);
            clearInterval(self.downArrowInterval);
        };

        this.openSelect = function() {
            self.styledSelectOptionHolder.show();
            self.styledSelectOptionHolder.parent('div.jScrollPaneContainer').show();
            self.styledSelectWrapper.find('.selectedOption').css('background-position','left -'+parseInt(self.styledSelectWrapper.height()*2)+'px');
            self.styledSelectWrapper.find('.selectArrow').css('background-position','left -'+parseInt(self.styledSelectWrapper.height()*2)+'px');
            self.styledSelectWrapper.find('.selectFooter').show();
            self.open = true;
            self.setFocus(jQuery(self.styledSelectOptions[self.styledSelectOptionFocus]));
            self.attachKeyPressHandler();
            self.addScrollbarListener();
        };

        this.closeAllSelects = function() { 
            jQuery(jQuery("body").data("StyledSelectField")).each(function(i) {
                    this.closeSelect();
                }
            );
        };

        this.setSelected = function(optionElement) {
            var value = jQuery('.optionValue', optionElement).text();
            var text  = jQuery('.optionText', optionElement).text();

            self.element.val(value);

            self.styledSelectSelected.find('span').text(text);
            self.element.change();
        };

        this.searchSelect = function() {
            var searchVal = jQuery('input.dummy', self.styledSelectWrapper).val();
            var results = jQuery("span.optionText", self.styledSelectOptionHolder);
            var regexp = new RegExp("^" + searchVal);
            if (results.length) {
                results.each(function(i) {
                    if (regexp.test(jQuery(this).text().toLowerCase())) {
                        self.setFocus(jQuery(this).parent(), true);
                        return false;
                    }
                });
            }
        };
    };
    
    $.fn.StyledSelectField = function(options) {
        return this.each(function(index) {
            var select = new StyledSelectField(jQuery(this),index);
            select.buildStyledSelect();
            select.applyStyles();
            select.addEventHandlers();
            select.addScrollbar();
            var selectElements = jQuery("body").data("StyledSelectField");
            if (!selectElements || !selectElements.length) {
                selectElements = new Array();
            }
            selectElements[selectElements.length] = select;
            jQuery("body").data("StyledSelectField", selectElements);
        });
    }



})(jQuery);


var thumbsArr = new Array();
var imagesArr = new Array();

var thumbs = jQuery("div.productImageHolder .thumbholder a");
var images = jQuery("div.productImageHolder .center");

images.each(function(i){
    imagesArr[i] = jQuery(this);
});