/**
 * appleby slideGallery 
 * Developed by Andreas Glaser (www.strategem.ie)
 */

function slideGallery() {
    // set defaults
    this.defaults = {
    
        slideGalleryID: 'slideGallery',

        imageCurrentXMax: 230,
        imageCurrentYMax: 230,
        imageNextXMax: 153,
        imageNextYMax: 153,
        imageNext2XMax: 115,
        imageNext2YMax: 115,
        
        
        xSpaceNext: 200,
        xSpaceNext2: 140,
        imageIDStart: 3,
        startAnimation: true,
        
        xStep: 140,
        imageFocusMax: 2

    };
    this.items = new Array();
    this.allElements = new Array();
    // closure for this.
    var thisObject = this;
    // initiate slideGallery
    this.init = function (options) {
        // valid options
        var optionsArray = ['aspectRatio', 'slideGalleryID', 'imageFocusMax', 'onClick', 'opacityArray', 'percentLandscape', 'percentOther', 'preloadImages', 'reflections', 'reflectionGET', 'reflectionP', 'reflectionPNG', 'scrollbarP', 'imageIDStart', 'startAnimation', 'xStep', 'imageCurrentXMax', 'imageCurrentYMax', 'imageNextXMax', 'imageNextYMax', 'imageNext2XMax', 'imageNext2YMax', 'xSpaceNext', 'xSpaceNext2'];
        // validate opntions
        var max = optionsArray.length;
        for (var i = 0; i < max; i++) {
            var name = optionsArray[i];
            this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : thisObject.defaults[name];
        }
        this.allElements['imageDivs'] = new Array();
        this.allElements['images'] = new Array();
        this.allElements['mainDiv'] = document.getElementById(this.slideGalleryID);
        
        // set item variables
        this.items['amount'] = 0;
        this.items['objects'] = new Array();
        
        if (!this.allElements['mainDiv']) return;
        
        
        // pare inline json
        var json = $('#jsonItems').text();
        json = eval(json);
        thisObject.items['objects'] = json;
        thisObject.items['amount'] = json.length;


        // init variables
        this.imageIDCurrent = 0;
        this.imageIDTarget  = 0;
        
        this.posXCurrent    = 0;
        this.posXMemCurrent = 0;
        
        this.posXTarget     = 0;
        this.posXMemTarget  = 0;
        
        
        this.firstRefresh   = true;
        this.firstCheck     = true;
        this.busy           = false;

        
        this.createStructure();
    };
    // create html 5 structure
    this.createStructure = function () {
    
          // create slider div
        this.allElements['divSlider'] = thisObject.Helper.createDocumentElement('div', 'sliderDiv');

        // create main navigation divs
        this.allElements['divPreviousMain'] = thisObject.Helper.createDocumentElement('div', 'previous');
        this.allElements['divNextMain'] = thisObject.Helper.createDocumentElement('div', 'next');


        // add click event listeners to main navigation divs
        this.allElements['divPreviousMain'].onclick = function (event) {
            thisObject.MouseWheel.handle(1);
            return false;
        };

        this.allElements['divNextMain'].onclick = function () {
            thisObject.MouseWheel.handle(-1);
            return false;
        };


        // create images div
        this.allElements['imagesDiv'] = thisObject.Helper.createDocumentElement('div', 'images');

        // create image div containg the images
        for (var i = 0; i < thisObject.items['amount']; i++) {
            // create image div initially display:none
            this.allElements['imageDivs'][i] = thisObject.Helper.createDocumentElement('div', 'imagediv_' + i, 'imageDiv');
            this.allElements['imageDivs'][i].style.display = 'none';
            this.allElements['imageDivs'][i].i = i;
            // add click event listener      
            this.allElements['imageDivs'][i].onclick = function () {
                thisObject.glideTo(this.i);
            };
            this.allElements['imagesDiv'].appendChild(this.allElements['imageDivs'][i]);
        }

        // create highlighter div
        this.allElements['highlighterDiv'] = thisObject.Helper.createDocumentElement('div', 'highlighter');
        this.allElements['highlighterDiv'].onclick = function () {
            thisObject.showOverlay(thisObject.items['objects'][thisObject.imageIDCurrent]['itemUrl']);
        };

        this.allElements['highlighterInfoBoxDiv'] = thisObject.Helper.createDocumentElement('div', 'infoBox');
        this.allElements['captionDiv'] = thisObject.Helper.createDocumentElement('div', 'caption');
        this.allElements['descriptionDiv'] = thisObject.Helper.createDocumentElement('div', 'description');
        this.allElements['highlighterInfoBoxMoreDiv'] = thisObject.Helper.createDocumentElement('div', 'more');

        // append childs to info box
        this.allElements['highlighterInfoBoxDiv'].appendChild(this.allElements['captionDiv']);
        this.allElements['highlighterInfoBoxDiv'].appendChild(this.allElements['descriptionDiv']);
        this.allElements['highlighterInfoBoxDiv'].appendChild(this.allElements['highlighterInfoBoxMoreDiv']);
        this.allElements['highlighterDiv'].appendChild(this.allElements['highlighterInfoBoxDiv']);

        this.allElements['imagesDiv'].appendChild(this.allElements['highlighterDiv']);
        this.allElements['divSlider'].appendChild(this.allElements['divPreviousMain']);
        this.allElements['divSlider'].appendChild(this.allElements['imagesDiv']);
        this.allElements['divSlider'].appendChild(this.allElements['divNextMain']);
        this.allElements['divSlider'].appendChild(thisObject.Helper.createDocumentElement('div', 'clear-left', 'clear-left'));

        thisObject.allElements['mainDiv'].appendChild(this.allElements['divSlider']);

        // create footer nav structure
        this.allElements['divFooterNav'] = thisObject.Helper.createDocumentElement('div', 'footer-nav');
        this.allElements['divFooterNavControls'] = thisObject.Helper.createDocumentElement('div', 'footer-nav-controls');
        this.allElements['divFooterNavControlsLeft'] = thisObject.Helper.createDocumentElement('div', 'footer-nav-controls-left');
        this.allElements['divFooterNavControlsRight'] = thisObject.Helper.createDocumentElement('div', 'footer-nav-controls-right');
        this.allElements['divFooterNavControlsCenter'] = thisObject.Helper.createDocumentElement('div', 'footer-nav-controls-center');
        this.allElements['divFooterNavControls'].appendChild(this.allElements['divFooterNavControlsLeft']);
        this.allElements['divFooterNavControls'].appendChild(this.allElements['divFooterNavControlsRight']);
        this.allElements['divFooterNavControls'].appendChild(this.allElements['divFooterNavControlsCenter']);
        this.allElements['divFooterNav'].appendChild(this.allElements['divFooterNavControls']);

        this.allElements['divFooteBg'] = thisObject.Helper.createDocumentElement('div', 'footer-bg');
        this.allElements['divFooteBgNote'] = thisObject.Helper.createDocumentElement('div', 'footer-bg-note');
        this.allElements['divFooteBgNote'].innerHTML = '<p>Use the arrows to scroll through the selection</p>';
        this.allElements['divFooteBg'].appendChild(this.allElements['divFooteBgNote']);
        // add click event listeners to footer navifation
        this.allElements['divFooterNavControlsLeft'].onclick = function () {
            thisObject.MouseWheel.handle(1);
            return false;
        };
        this.allElements['divFooterNavControlsRight'].onclick = function () {
            thisObject.MouseWheel.handle(-1);
            return false;
        };

        // disable firefox doubleclick content selection for all nav dics
        this.allElements['divPreviousMain'].style.MozUserSelect = 'none';
        this.allElements['divNextMain'].style.MozUserSelect = 'none';
        this.allElements['divFooterNavControlsLeft'].style.MozUserSelect = 'none';
        this.allElements['divFooterNavControlsRight'].style.MozUserSelect = 'none';


        // append div structure to main div

        thisObject.allElements['mainDiv'].appendChild(this.allElements['divFooterNav']);
        thisObject.allElements['mainDiv'].appendChild(this.allElements['divFooteBg']);
        
        
        // show slideGallery
        this.allElements['mainDiv'].style.visibility = 'visible';
        

        // store elements in variables
        this.divImages = document.getElementById(thisObject.slideGalleryID + '_images');
        this.navigationDiv = document.getElementById(thisObject.slideGalleryID + '_navigation');
        this.scrollbarDiv = document.getElementById(thisObject.slideGalleryID + '_scrollbar');
        this.sliderDiv = document.getElementById(thisObject.slideGalleryID + '_slider');
        this.highlighterDiv = document.getElementById(thisObject.slideGalleryID + '_highlighter');
        this.infoBoxDiv = document.getElementById(thisObject.slideGalleryID + '_infoBox');
        this.captionDiv = document.getElementById(thisObject.slideGalleryID + '_caption');
        this.descriptionDiv = document.getElementById(thisObject.slideGalleryID + '_description');
        this.moreDiv = document.getElementById(thisObject.slideGalleryID + '_more');
        this.buttonNextDiv = document.getElementById(thisObject.slideGalleryID + '_next');
        this.buttonPreviousDiv = document.getElementById(thisObject.slideGalleryID + '_previous');

        
        // cache global variables
        this.divImagesWidth = this.divImages.offsetWidth;
        this.divImagesHeight = this.divImages.offsetHeight;
        this.maxHeight = Math.round(thisObject.divImagesWidth / thisObject.aspectRatio);
        this.maxHeight = 230;
        
        this.maxFocus = thisObject.imageFocusMax * thisObject.xStep;
        this.size = thisObject.divImagesWidth * 0.5;

        var mainDivWidth = this.allElements['mainDiv'].offsetWidth;
        var mainDivHeight = this.allElements['mainDiv'].offsetHeight;

        this.max = thisObject.items['amount'];
        
        // initiate input listeners
        this.MouseWheel.init();
        this.Key.init();

        
        // glide to start id
        var imageIDStart = this.imageIDStart - 1;
        
        // validate image start id
        imageIDStart < 0 ? 0 : imageIDStart;
        imageIDStart > this.items['amount'] ? this.items['amount'] - 1 : 0;
        
        
        this.glideTo(imageIDStart);
        thisObject.moveTo(500);
    };

    // main animation function
    this.moveTo = function (x) {
        
        this.posXCurrent = x;
  
        for (var i = 0; i < this.items['amount']; i++) {
            
            if (this.allElements['images'][i] == undefined && (i > this.imageIDCurrent - 5 && i < this.imageIDCurrent + 5)) {
                
                // create image element
                this.allElements['images'][i] = thisObject.Helper.createDocumentElement('img', i, 'image');
                this.allElements['images'][i].src = thisObject.items['objects'][i]['imageUrl'];
                
                // append image elment to image div
                this.allElements['imageDivs'][i].appendChild(this.allElements['images'][i]);
                this.allElements['imagesDiv'].appendChild(this.allElements['imageDivs'][i]);
            }
            
            
            var divImage = this.allElements['imageDivs'][i];
            var image = this.allElements['images'][i];
            
            
            $('#myslideGallery_imagediv_' + i).removeClass('currentItem nextItem nextItem2');
            

            
            
            // don't display outside of the viewer
            if (i > this.imageIDCurrent + 3 || i < this.imageIDCurrent - 3) {
                divImage.style.visibility = 'hidden';
                divImage.style.display = 'none';
            }
            else {
                /* Still hide images until they are processed, but set display style to block */
                divImage.style.display = 'block';
                var newImageH = 0;
                
                // add class to current higlighted item
                if (this.imageIDCurrent == i) {
                  var maxi = this.imageCurrentYMax;
                  newImageH = this.imageCurrentYMax;

                  
                }
                else if ((this.imageIDCurrent - 1) == i || (this.imageIDCurrent + 1) == i) {
                  var maxi = this.imageNextYMax;
                  newImageH = this.imageNextYMax;
                }
                else {
                  var maxi = this.imageNext2YMax;
                  newImageH = this.imageNext2YMax;
                }

        
          
                var newImageW = (image.offsetWidth / image.offsetHeight) * newImageH;
                
                
                // calculate top to center div and image
                var newImageTop = (this.divImagesHeight / 2) - newImageH / 2 - 30;
                var imageDivX = this.allElements['imagesDiv'].offsetWidth;
                var diff = 0;
                if (this.imageIDCurrent != i) {
                    if (this.imageIDCurrent > i) diff = -70;
                    else diff = +70;
                }
                this.allElements['imageDivs'][i].style.left = x + (imageDivX / 2) - (newImageW / 2) + diff + 'px';
                //image.style.left = xs - (image.pc / 2) / z * thisObject.size + 'px';
                if (newImageW && newImageH) {
                    this.allElements['images'][i].style.width = newImageW + 'px';
                    this.allElements['images'][i].style.height = newImageH + 'px';
                    this.allElements['imageDivs'][i].style.width = newImageW + 'px';
                    this.allElements['imageDivs'][i].style.height = newImageH + 'px';
                    this.allElements['imageDivs'][i].style.top = newImageTop + 'px';
                }
                divImage.style.visibility = 'visible';
            }
            x += thisObject.xStep;
        }
    };

    // initiates glide animation
    this.glideTo = function (imageID) {
        
        // set current item id
        this.imageIDCurrent = imageID;
        
        // remember last position
        this.posXMemCurrent = this.posXCurrent;
        
        // calculate new position
        this.posXTarget = -imageID * thisObject.xStep;
        this.posXMemTarget = this.posXTarget;
        

        // set new current image id
        this.allElements['captionDiv'].innerHTML = '<p>' + thisObject.items['objects'][imageID]['itemTitle'] + '</p>';
        //this.allElements['descriptionDiv'].innerHTML = thisObject.items['objects'][imageID]['itemDesc'];
        this.allElements['divFooterNavControlsCenter'].innerHTML = '<p style="font-weight:bold">' + (imageID + 1) + ' </p><p>of ' + thisObject.items['amount'] + '</p>';


        // animate gliding to position x
        if (thisObject.busy === false) {
            window.setTimeout(thisObject.animate, 30);
            thisObject.busy = true;
        }
    };
    
    // animator
    this.animate = function () {
        switch (thisObject.posXTarget <= thisObject.posXCurrent - 1 || thisObject.posXTarget >= thisObject.posXCurrent + 1) {
        case true:
            thisObject.moveTo(thisObject.posXCurrent + (thisObject.posXTarget - thisObject.posXCurrent) / 6);
            window.setTimeout(thisObject.animate, 30);
            thisObject.busy = true;
            break;
        default:
            thisObject.busy = false;
            break;
        }
    };
    
    
    this.showOverlay = function (url) {
        $('#canvasOverlay').empty().prepend('<div id="ctrProductOverlay">' + '<div id="productOverlay">' + '<div id="contentProductOverlay"></div>' + '<span id="btnClose"></span>' + '</div>' + '</div>');
        $(document).scrollTop(0);
        $('#bgCanvasOverlay').height($(window).height()).addClass('overlayLoader').css('opacity', '0.6').fadeIn('fast');
        $('#contentProductOverlay').load(url + ' .product', thisObject.showProdDetail);
    };
    this.resizeOverlayBg = function (ctr) {
        var docHeight = $('#canvas').height() + parseInt($('#canvas').css('padding-top').slice(0, $('#canvas').css('padding-top').length - 2));
        if ($('#bgCanvasOverlay').is(':visible')) {
            var overlayHeight = $(ctr).height() + parseInt($(ctr).css('margin-top').slice(0, $(ctr).css('margin-top').length - 2));
            if ($(window).height() > docHeight || $(window).height() > overlayHeight) {
                $('#bgCanvasOverlay').height($(window).height());
            }
            else {
                if (docHeight > overlayHeight) {
                    $('#bgCanvasOverlay').height(docHeight);
                }
                else {
                    $('#bgCanvasOverlay').height(overlayHeight + 20);
                }
            }
        }
    };
    this.validateCallbackForm = function () {
        $('#ctrCallbackForm').append('<iframe id="salesforce" width="0" height="0" style="visibility:hidden;overflow:hidden"></iframe>');
        $("#salesforce").attr('src', '/salesforce-form.html');
        $('#callbackForm').validate({
            rules: {
                first_name: 'required',
                last_name: {
                    required: function (element) {
                        return $("#first_name").val() != '';
                    }
                },
                phone: {
                    required: function (element) {
                        return $("#first_name").val() != '' && $("#last_name").val() != '' && $("#email").val() == '';
                    },
					number: function(element) {
						return $("#first_name").val() != '' && $("#last_name").val() != '' && $("#email").val() == '';
					}
                },
                email: {
                    required: function (element) {
                        return $("#first_name").val() != '' && $("#last_name").val() != '' && $("#phone").val() == '';
                    },
                    email: function (element) {
                        return $("#first_name").val() != '' && $("#last_name").val() != '' && $("#phone").val() == '';
                    }
                },
                comment: {
                    required: function (element) {
                        return $("#first_name").val() != '' && $("#last_name").val() != '' && ($("#phone").val() != '' || $("#email").val() != '');
                    }
                }
            },
            messages: {
                first_name: 'First name required!',
                last_name: 'Last name required!',
                phone: {
					required: 'Phone/email required!',
					number: 'Valid No. required!'
				},
                email: {
                    required: 'Email/phone required!',
                    email: 'Valid email required!'
                },
                comment: 'Comment required!'
            },
            errorLabelContainer: "#ctrErrors",
            submitHandler: function () {
                var post = {
                    name: $("#first_name").val() + ' ' + $("#last_name").val(),
                    telephone: $("#phone").val(),
                    email: $("#email").val(),
                    priceRange: $("#price_range").val(),
                    comment: $("#comment").val(),
                    productCode: $("#productCode").val(),
                    productName: $("#productName").val()
                };
                $.ajax({
                    type: 'POST',
                    url: '/contact-form-handler',
                    data: post,
                    dataType: 'json',
                    error: function () {
                        //alert('Unexpected response!');
                        return false;
                    },
                    success: function (responseData) {
                        if (responseData.status == 'ok') {
                            $('#wrprCallbackForm').hide();
                            $('#thxCallbackForm').fadeIn('slow');
                        }
                    }
                });
				
				var name = $("#first_name").val() + ' ' + $("#last_name").val();
				var d = new Date();
				var timestamp = Number(d);
				
				$("#salesforce").contents().find("#00N20000002MQKX").attr('value', $("#productCode").val());
				$("#salesforce").contents().find("#00N20000002MQKc").attr('value', $("#productName").val());
				$("#salesforce").contents().find("#00N20000002MQKm").attr('value', $("#productDescription").val());
				$("#salesforce").contents().find("#00N20000002MQKh").attr('value', $("#productCategories").val());
				$("#salesforce").contents().find("#Name").attr('value', name);
				$("#salesforce").contents().find("#mobile").attr('value', $("#phone").val());
				$("#salesforce").contents().find("#email").attr('value', $("#email").val());
				$("#salesforce").contents().find("#00N20000001wWqE").attr('value', $("#price_range").val());
				$("#salesforce").contents().find("#description").attr('value', $("#comment").val());
				$("#salesforce").contents().find("#lead_source").attr('value', 'Website');
				$("#salesforce").contents().find("#create_date").attr('value', timestamp);
				$("#salesforce").contents().find("#first_name").focus();
				$("#salesforce").contents().find("#salesforceForm").submit();
				
                /*$("#salesforce").contents().find("#product_id").attr('value', $("#productCode").val());
                $("#salesforce").contents().find("#product_name").attr('value', $("#productName").val());
                $("#salesforce").contents().find("#product_description").attr('value', $("#productDescription").val());
                $("#salesforce").contents().find("#product_categories").attr('value', $("#productCategories").val());
                $("#salesforce").contents().find("#first_name").attr('value', $("#first_name").val());
                $("#salesforce").contents().find("#last_name").attr('value', $("#last_name").val());
                $("#salesforce").contents().find("#phone").attr('value', $("#phone").val());
                $("#salesforce").contents().find("#email").attr('value', $("#email").val());
                $("#salesforce").contents().find("#00N20000001wWqE").attr('value', $("#price_range").val());
                $("#salesforce").contents().find("#description").attr('value', $("#comment").val());
                $("#salesforce").contents().find("#lead_source").attr('value', 'Website');
                console.log($("iframe").contents().find("#salesforceForm"));
                $("#salesforce").contents().find("#first_name").focus();
                $("#salesforce").contents().find("#salesforceForm").submit();*/
            }
        });
    };
    this.showProdDetail = function () {
        var url = thisObject.items['objects'][thisObject.imageIDCurrent]['itemUrl'];
        var docHeight = $('#canvas').height() + parseInt($('#canvas').css('padding-top').slice(0, $('#canvas').css('padding-top').length - 2));
        $('#bgCanvasOverlay').removeClass('overlayLoader');
        $('#canvasOverlay').height(docHeight).fadeIn('fast', function () {
            $('#name').css('background', '#cc9');
            $('#productOverlay').show(500, function () {
                var flashvars = {};
                var params = {
                    wmode: "transparent"
                };
                var attributes = {};
                swfobject.embedSWF("/assets/flash/product-overlay-stars.swf", "stars", "650", "40", "9.0.0", "/assets/flash/expressInstall.swf", flashvars, params, attributes);
                thisObject.resizeOverlayBg('#ctrProductOverlay');
                $(window).resize(function () {
                    thisObject.resizeOverlayBg('#ctrProductOverlay');
                });

  							var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  								$.getScript(gaJsHost + 'google-analytics.com/ga.js');
  								try {
  									var pageTracker = _gat._getTracker("UA-11580230-1");
  									pageTracker._trackPageview(url);
  								} catch(err) {}


                $.getScript('/assets/js/libraries/jquery.validate.js', thisObject.validateCallbackForm);

                $('#first_name').focus();
                $('.focus').focus(function () {
                    $('.focus').each(function () {
                        $(this).css('background', '#fff');
                    });
                    $(this).css('background', '#cc9');
                });
                $('.shot').click(function () {
                    var url = $(this).attr('href');
                    $('#ctrProdImg').append('<div class="loading"></div>');
                    var img = new Image();
                    $(img).load(function () {
                        $('#ctrProdImg').html(this);
                        $('.loading').fadeOut('fast', function () {
                            $(this).remove();
                        });
                    }).attr('src', url);
                    return false;
                });
                $('.shotAssoc').click(function () {
                    var url = $(this).attr('href');
                    $('#bgCanvasOverlay').addClass('overlayLoader');
                    $('#productOverlay').hide();
                    $('#contentProductOverlay').load(url + ' .product', showProdDetail);
                    return false;
                });
            });
        });
        $('#btnClose').click(function () {
            $('#productOverlay').hide();
            $('#canvasOverlay').hide();
            $('#bgCanvasOverlay').fadeOut('fast');
        });
        /*$('#btnClose').click(function() {
         $('#productOverlay').hide(500, function() {
         $('#canvasOverlay').hide();	
         $('#bgCanvasOverlay').fadeOut('fast');
         });														
         });*/
        if ($('#p1').length > 0 && $('#p2').length > 0) {
            $('#p2').next('SPAN').hide();
        }
        if (!($('#p1').length > 0) && $('#p2').length > 0) {
            $('.hdrAdditionalProds').eq(0).hide();
        }
        $('.hdrAdditionalProds SPAN').click(function () {
            window.print();
        });
    };
    /* Mouse Wheel support */
    this.MouseWheel = {
        init: function () {
            /* Init mouse wheel listener */
            if (window.addEventListener) {
                thisObject.allElements['mainDiv'].addEventListener('DOMMouseScroll', thisObject.MouseWheel.get, false);
            }
            thisObject.Helper.addEvent(thisObject.allElements['mainDiv'], 'mousewheel', thisObject.MouseWheel.get);
        },
        get: function (event) {
            var delta = 0;
            if (!event) {
                event = window.event;
            }
            if (event.wheelDelta) {
                delta = event.wheelDelta / 120;
            }
            else if (event.detail) {
                delta = -event.detail / 3;
            }
            if (delta) {
                thisObject.MouseWheel.handle(delta);
            }
            thisObject.Helper.suppressBrowserDefault(event);
        },
        handle: function (delta) {
            var change = false;
            var newImageID = 0;
            if (delta > 0) {
                if (thisObject.imageIDCurrent >= 1) {
                    newImageID = thisObject.imageIDCurrent - 1;
                    change = true;
                }
            }
            else {
                if (thisObject.imageIDCurrent < (thisObject.max - 1)) {
                    newImageID = thisObject.imageIDCurrent + 1;
                    change = true;
                }
            }
            /* Glide to next (mouse wheel down) / previous (mouse wheel up) image  */
            if (change === true) {
                thisObject.glideTo(newImageID);
            }
        }
    };

    /* Key support */
    this.Key = {
        /* Init key event listener */
        init: function () {
            document.onkeydown = function (event) {
                thisObject.Key.handle(event);
            };
        },
        /* Handle the arrow keys */
        handle: function (event) {
            var charCode = thisObject.Key.get(event);
            switch (charCode) {
                /* Right arrow key */
            case 39:
                thisObject.MouseWheel.handle(-1);
                break;
                /* Left arrow key */
            case 37:
                thisObject.MouseWheel.handle(1);
                break;
            }
        },
        /* Get the current keycode */
        get: function (event) {
            event = event || window.event;
            return event.keyCode;
        }
    };
    /* Helper functions */
    this.Helper = {
    
        /* Add events */
        addEvent: function (obj, type, fn) {
            if (obj.addEventListener) {
                obj.addEventListener(type, fn, false);
            }
            else if (obj.attachEvent) {
                obj["e" + type + fn] = fn;
                obj[type + fn] = function () {
                    obj["e" + type + fn](window.event);
                };
                obj.attachEvent("on" + type, obj[type + fn]);
            }
        },

        // set element opacity
        setOpacity: function (object, value) {
            if (thisObject.opacity === true) {
                object.style.opacity = value / 10;
                object.style.filter = 'alpha(opacity=' + value * 10 + ')';
            }
        },
        /* Creates HTML elements */
        createDocumentElement: function (type, id, optionalClass) {
            var element = document.createElement(type);
            element.setAttribute('id', thisObject.slideGalleryID + '_' + id);
            if (optionalClass !== undefined) {
                id += ' ' + optionalClass;
            }
            element.setAttribute('class', id);
            element.setAttribute('className', id);
            return element;
        },
        /* Suppress default browser behaviour to avoid image/text selection while dragging */
        suppressBrowserDefault: function (e) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            else {
                e.returnValue = false;
            }
            return false;
        }
    };
}
/* DOMContentLoaded event handler - by Tanny O'Haley [4] */
var domReadyEvent = {
    name: "domReadyEvent",
    /* Array of DOMContentLoaded event handlers.*/
    events: {},
    domReadyID: 1,
    bDone: false,
    DOMContentLoadedCustom: null,
    /* Function that adds DOMContentLoaded listeners to the array.*/
    add: function (handler) {
        /* Assign each event handler a unique ID. If the handler has an ID, it has already been added to the events object or been run.*/
        if (!handler.$$domReadyID) {
            handler.$$domReadyID = this.domReadyID++;
            /* If the DOMContentLoaded event has happened, run the function. */
            if (this.bDone) {
                handler();
            }
            /* store the event handler in the hash table */
            this.events[handler.$$domReadyID] = handler;
        }
    },
    remove: function (handler) {
        /* Delete the event handler from the hash table */
        if (handler.$$domReadyID) {
            delete this.events[handler.$$domReadyID];
        }
    },
    /* Function to process the DOMContentLoaded events array. */
    run: function () {
        /* quit if this function has already been called */
        if (this.bDone) {
            return;
        }
        /* Flag this function so we don't do the same thing twice */
        this.bDone = true;
        /* iterates through array of registered functions */
        for (var i in this.events) {
            this.events[i]();
        }
    },
    schedule: function () {
        /* Quit if the init function has already been called*/
        if (this.bDone) {
            return;
        }
        /* First, check for Safari or KHTML.*/
        if (/KHTML|WebKit/i.test(navigator.userAgent)) {
            if (/loaded|complete/.test(document.readyState)) {
                this.run();
            }
            else {
                /* Not ready yet, wait a little more.*/
                setTimeout(this.name + ".schedule()", 100);
            }
        }
        else if (document.getElementById("__ie_onload")) {
            /* Second, check for IE.*/
            return true;
        }
        /* Check for custom developer provided function.*/
        if (typeof this.DOMContentLoadedCustom === "function") {
            /* if DOM methods are supported, and the body element exists (using a double-check
             including document.body, for the benefit of older moz builds [eg ns7.1] in which
             getElementsByTagName('body')[0] is undefined, unless this script is in the body section) */
            if (typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null)) {
                /* Call custom function. */
                if (this.DOMContentLoadedCustom()) {
                    this.run();
                }
                else {
                    /* Not ready yet, wait a little more. */
                    setTimeout(this.name + ".schedule()", 250);
                }
            }
        }
        return true;
    },
    init: function () {
        /* If addEventListener supports the DOMContentLoaded event.*/
        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", function () {
                domReadyEvent.run();
            }, false);
        }
        /* Schedule to run the init function.*/
        setTimeout("domReadyEvent.schedule()", 100);

        function run() {
            domReadyEvent.run();
        }
        /* Just in case window.onload happens first, add it to onload using an available method.*/
        if (typeof addEvent !== "undefined") {
            addEvent(window, "load", run);
        }
        else if (document.addEventListener) {
            document.addEventListener("load", run, false);
        }
        else if (typeof window.onload === "function") {
            var oldonload = window.onload;
            window.onload = function () {
                domReadyEvent.run();
                oldonload();
            };
        }
        else {
            window.onload = run;
        }
        /* for Internet Explorer */
        /*@cc_on
         @if (@_win32 || @_win64)
         document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
         var script = document.getElementById("__ie_onload");
         script.onreadystatechange = function()
         {
         if (this.readyState == "complete")
         {
         domReadyEvent.run(); // call the onload handler
         }
         };
         @end
         @*/
    }
};
var domReady = function (handler) {
    domReadyEvent.add(handler);
};
domReadyEvent.init();
/* Create slideGallery instances when the DOM structure has been loaded */
domReady(function () {
    var instanceOne = new slideGallery();
    instanceOne.init({
        slideGalleryID: 'slideGallery'
    });
});