$(function () {
    //lens();
    var footFix = footClone();
    var mobile = navigator.userAgent.match(/iPad/i) != null;
    var autoSlide;
    positionFooter();
    temp_tabs();
    home_load();


    //    function lens() {
    //        var width = $(window).width();
    //        var height = width * 0.7868525896414343;
    //        var calc_width = width + 'px';
    //        var calc_height = height + 'px';
    //        var image_area = calc_width + " " + calc_height;
    //        if (width > 1004 && width < 2400) {
    //            $('#index_block').css({ 'background-size': image_area });
    //        }
    //    }

    function home_load() {
        if ($('.home').length > 0) {//if this is the home page
            $(window).load(function () {//when the rest of the DOM has loaded
                $.ajax({
                    url: 'getHomesSlides.ajax', //get this file
                    cache: true,
                    success: function (html) {
                        home_slide(html); //send the file over here
                    }
                });
            });
        }
    }

    function home_slide(html) {//slide home!
        var ra = html.split('||'); //check to see if ajax call wask ok
        if (ra[0] === "OK") {//if everything checks out
            $(html).addClass('slideshow').appendTo('#index_block'); //add this block right onto the home page
            var backSlide = $(html).clone(); //clone the block
            // backSlide.children().first().clone().appendTo(backSlide); //clone the first slide and add the copy to the back
            // backSlide.children().first().next().clone().appendTo(backSlide); //the second slide
            //backSlide.children().first().next().next().clone().appendTo(backSlide); //and the third slide
            backSlide.children().last().clone().insertBefore(backSlide.children().first());
            backSlide.children().last().prev().clone().insertBefore(backSlide.children().first());
            backSlide.children().first().next().next().clone().appendTo(backSlide);
            backSlide.children().first().next().next().next().clone().appendTo(backSlide);
            backSlide.totalWidth = 0; //handler for how wide to make the slideshow
            backSlide.appendTo('.prev'); //add to the DOM



            backSlide.children('li').each(function (index, object) {//for each slide
                var elementOffsetX;
                backSlide.totalWidth += 1004 //child.width();//add 1004 (or the width of the slide) to the total width
                //image loading code
                var src = $(object).children('img').attr('src'); //grab the image source
                $(object).children('img').remove(); //remove the image
                $(object).children('span').remove(); //and it's spans
                $(object).css({ 'float': 'left', width: '1004px', display: 'block', overflow: 'hidden' }); //make the whole slide float left
                var overlay = new Image(); //create a new blank image
                $(overlay).load(function () {//when the blank image has loaded
                    $(this).hide(); //hide it
                    $(this).appendTo(object); //put it on the DOM
                    $(this).fadeIn('slow'); //fade it in
                }).attr('src', src); //the new image's source should be the original image source (it's at the end to solve a jQuery bug)
            });

            //backSlide.css({ width: backSlide.totalWidth, position: 'relative', left: '-1004px' }); //position the rear slideshow to not show the first image (which will be in the middle)
            elementOffsetX = $('#contentwrap').position().left;
            backSlide.css({ width: backSlide.totalWidth, position: 'relative', left: elementOffsetX - (1000 * 2) });
            $('.slideshow').dbSlider({ width: 'auto', height: '790px', c_scheme: 1, caption: true, caption_size: '40%', effect: 2 }); //turn the whole thing into a slideshow
        } else {
            console.log(html); //if the ajax call didn't go through correctly, log the issue
        }
    };

    function bg_fit() {
        var calc_width, calc_height;
        var width = $(window).width(); //w' aspect ratio: 2.025316455696203
        var height = $(window).height(); // h' aspect ratio: 0.49375
        var test = width / height;
        if (test > 2.025316455696203) {

            var new_height = width * 0.49375;
            calc_width = width + 'px';
            calc_height = new_height + 'px';
        } else {
            var new_width = height * 2.025316455696203;

            calc_width = new_width + 'px';
            calc_height = height + 'px';
        }
        var image_area = calc_width + " " + calc_height;
        $('#pagewrap').css({ 'background-size': image_area });
    }

    function footClone() {
        var origin = $('footer');
        footFix = origin.before(origin.clone()).css({ width: origin.width(), visibility: 'hidden' }).addClass('footer_fixed');
        return footFix;
    }

    function positionFooter() {
        if ($(document).width() > 1100) {
            var swap = $(window).height() + $(window).scrollTop();
            var temp = $('#pageWrap.home').length;
            var wrap = (temp > 0) ? ($('#pageWrap.home').height() - 30) : $('#pagewrap').height();
            if (swap < wrap) {
                $('footer').css({ visibility: 'hidden', display: 'block' });
                footFix.css('visibility', 'visible');
            } else {
                $('footer').css({ visibility: 'visible', display: 'block' });
                footFix.css('visibility', 'hidden');
            }
        } else if (mobile) {
            footFix.css('display', 'none');
            $('footer').css({ visibility: 'visible', paddingBottom: '8px' });
        } else {
            footFix.css('display', 'none');
            $('footer').css({ visibility: 'visible' });
        }
    }

    function bg_load(object) {
        var img = $(object).css('backgroundImage');
        img = img.substr(4, img.length - 5);
        if (img.charAt(0) === '\"') {
            img = img.substr(1, img.length - 2);
        };

        $(object).css('backgroundImage', 'none');
        var placeOver = new Image();

        $(placeOver).load(function () {
            var temp_fill = $('<div></div>').css({ backgroundColor: 'rgb(55,44,40)', width: '100%', height: $('#pagewrap').height(), display: 'block', position: 'absolute', zIndex: 0 }).prependTo('#pagewrap');
            $(object).css({ backgroundImage: 'url(' + img + ')' });
            temp_fill.animate({ opacity: 0 }, { duration: 300, easing: 'easeOutSine' });
            bg_fit();
        }).attr({ src: img + '?random=' + (new Date()).getTime() });
    }

    function temp_tabs() {
        $('#event_bar .event_tabs .tab').click(function () {
            var tabRoot = this;
            var tabIndex = $(tabRoot).index(); //Get which tab just got clicked
            if (tabIndex != $('.active_tab').index()) { //if the tab isn't the current tab
                $('.event_tabs li').removeClass('selected'); //take the selected class off everything
                $(tabRoot).addClass('selected'); //add the selected class to the tab that got clicked
                $('.active_tab').removeClass('active_tab').addClass('reset_tab'); //get the currently active ul and hide it
                $('.event_box > div').eq(tabIndex).removeClass('reset_tab').addClass('active_tab'); //unhide the ul for the tab that was clicked
            }
        });
    }



    $(window).resize(bg_fit);
    //$(window).resize(lens);
    $(window).resize(positionFooter);
    $(window).scroll(positionFooter);
    if ($('#pagewrap').css('backgroundImage')) {
        bg_load($('#pagewrap'));
    }
});
//end of on document ready events

//Scroller code for the events bar
(function ($) {
    //USAGE: $('whatever content').scroller({ container: $('the container'), content: $('the content') });
    var scroller = {//the master object
        defaults: {
            active: false, //whether or not the object is currently being scrolled
            position: [0, 0], //where the scrollbar is
            content: null, //the content being scrolled over
            container: null, //the container for the content
            curEvent: jQuery.Event(), //what's going on
            scrub: [], //all of the scroll bars
            maxDist: 0//the space between the end of the scrub bar and the edge of the box

        },
        opt: {}, //an array to hold all of the user options for the scroller, this is the object to refer to whenever data needs to be moved
        init: function (options) {//initiate the scroller
            scroller.opt = $.extend(scroller.defaults, options); //pull the default varibles into the opt variable, and modify them by the user options
            for (var i = 0; i < scroller.opt.content.length; i++) {//for each returned content block
                var scope = $(scroller.opt.content[i]); //get the object currently being modified
                scope.parent().addClass('tab_' + i)
                if (i === 0) {
                    scope.parent().addClass('active_tab');
                } else {
                    scope.parent().addClass('reset_tab');
                }
                var calc = function(){
                    var count = 0;
                    scope.children().each(function(){
                        count += $(this).width() + parseInt($(this).css('paddingLeft')) + parseInt($(this).css('paddingRight'));
                    });
                    return count + scope.children().length;
                }
                var scalar = calc();//this is just for the HAS implementation, but it makes the width of the ul the sum of the widths of its lis
                var box_width = scroller.opt.container.width(); //the width of the containder
                var box_diff = scalar - box_width; //the difference between the content and the container
                scope.css('width', scalar);
                if (box_diff > 0) {//if the content is wider than the container
                    var bar = $('<div />').addClass('scroller').css({//create a div that represents the background of the scroll bar
                        width: box_width,
                        height: '4px',
                        backgroundColor: '#ccc',
                        display: 'block'
                    });

                    scroller.opt.scrub[i] = $('<div />').addClass('scrubber').css({//create a div that represents the scrubber for the scroll with a relative position
                        width: Math.floor((box_width / scalar) * box_width),
                        height: '8px',
                        backgroundColor: '#F26649',
                        position: 'relative',
                        cursor: 'pointer',
                        left: 0
                    });

                    bar.appendTo(scope.parent()); //add the scroll bar to the DOM as a part of its parent object
                    scroller.opt.scrub[i].appendTo(bar).bind('mousedown', { object: scroller.opt.scrub[i], content: scope }, scroller.moused)
                        .bind('mouseenter mouseleave', { object: scroller.opt.scrub[i] }, scroller.hover); //add the scrubber to the dom and listen for mouseovers and clicks
                    scroller.opt.scrub[i].maxDist = bar.width() - scroller.opt.scrub[i].width(); //set the maximum distance the scrubber can travel
                    scroller.opt.scrub[i].hover = false; //sets whether or not the scrubber is being hovered over
                    scroller.opt.scrub[i].boxDiff = box_diff;
                }
            }

        },

        block: function (event) {//blocks text getting selected
            try {
                event.stopPropagation();
                event.preventDefault();
            } catch (err) { }
        },

        moused: function (event_md) {//when user clicks on the scubber
            if (scroller.opt.active) {//if it's set to active
                scroller.block(event_md);
                $(document).bind('mousemove', { object: event_md.data.object, content: event_md.data.content }, scroller.mousem);
                $(document).bind('mouseup', { object: event_md.data.object }, scroller.mouseu); //make the document listen for both mouse movement and mouse up
                scroller.opt.position = [event_md.clientX - event_md.data.object.position().left, event_md.clientY - event_md.data.object.position().top]; //return the scrubber's current position
            } else {
                scroller.opt.curEvent = event_md; //if it's not active yet
                scroller.opt.active = true; //make it active
                scroller.moused(scroller.opt.curEvent); //then call this function again
            }
        },

        mouseu: function (event_mu) {//when the user is no longer pressing the mouse
            if (scroller.opt.active) {//if in the active state
                scroller.block(event_mu);
                $(document).unbind('mousemove', this.mousem); //stop listening for mouse movement
                scroller.opt.curEvent = event_mu;
            }
            scroller.opt.active = false; //make the object no longer active
            if (event_mu.data.object.hover === false) {
                event_mu.data.object.animate({ height: '8px' }, 200);
            }

        },

        mousem: function (event_mm) {
            scroller.block(event_mm);
            var scrubLeft = Math.floor(event_mm.clientX - scroller.opt.position[0]); //figure out where the mouse is in relation to the scrubber
            var curLeft = parseInt(event_mm.data.object.css('left')); //return the current position of the scrubber
            if (scrubLeft <= event_mm.data.object.maxDist && scrubLeft >= 0) {//if the mouse relationship to the scrubber is between 0 and the maximum allowed distance
                event_mm.data.object.css('left', Math.floor(scrubLeft)); //make the position of the scrubber equal to that of the mouse
                event_mm.data.content.css('left', Math.floor((curLeft / event_mm.data.object.maxDist) * event_mm.data.object.boxDiff * -1));//move the content inversely proportional to the width of the content over the width of the container
            } else if (scrubLeft > event_mm.data.object.maxDist) {//if the mouse is further than the scrubber is allowed, put the scrubber and the content at the maximum distance
                event_mm.data.object.css('left', event_mm.data.object.maxDist);
                event_mm.data.content.css('left', event_mm.data.object.boxDiff * -1);
            } else {//otherwise make everything 0
                event_mm.data.object.css('left', 0);
                event_mm.data.content.css('left', 0);
            }
        },

        hover: function (event_mo) {//when you hover over the scrollbar, make it bigger.
            if (event_mo.type != 'mouseleave') {//if the triggering event is not 'mouseleave'
                event_mo.data.object.filter(':not(:animated)').animate({height: '12px'}, 100);//animate the scrubber getting bigger
                event_mo.data.object.hover = true; //return that the user is hovering over the object
            } else if (event_mo.type === 'mouseleave') {//if the event passed is mouseleave
                event_mo.data.object.hover = false; //return that the mouse is no longer hovering over the scrubber
                if (scroller.opt.curEvent.type != 'mousedown') {//if the last event triggered is not mousedown (which would be the mouseup event)
                    event_mo.data.object.animate({height: '8px'}, 100);//animate the scrubber returning to 5px height
                }
            }
        }

    };

    $.fn.scroller = function (method) {//the actual instantiation of the scrollbar object
        if (scroller[method]) {//if this object is instantiated with a method, call that method, otherwise run from the beginning with any options applied
            return scroller[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return scroller.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }
    };
} (jQuery));
//End code for the scroller


//Slider Code!!!

(function ($) {

    $.fn.dbSlider = function (options) {//the default options
        var defaults = {
            time: 2000, //how long between slides (on auto-advance)
            width: 600, //the default width of the slideshow
            height: 400, //default height of the slideshow
            effect: 1, //default transition effect
            caption_size: '85%', //how large the caption is, will take any valid width value
            blocksize: { height: '', width: '' }, //unused, but refers to some effects
            duration: 700, //how long each transition takes
            controls: true, //whether or not the controls are present
            c_scheme: 0, //which style of controls is being used
            direction: 'adv', //indicates whether the slideshow is moving forward or back
            caption: true, //whether or not the caption is present
            customblock: {//special variables for transition effects
                cubegrow: { height: 100, width: 100 },
                stripefade: { height: 100, width: 40 }
            },
            callback: function () { } //callback
        };


        var options = $.extend(defaults, options); //add user input to defaults (always use this variable)
        var root = $(this); //reference to the root calling object
        var li; //create variable container for the slides
        if (temp = root.find("li")) { li = temp } else { return }; //find all the lis in the root element and put them in the variable li
        var imgs; //create a variable to hold the images
        try {//if the slideshow has images
            imgs = (temp = li.find("img")) ? temp : imgs = null;//add those images to the imgs variable
        } catch (err) {console.log(err) }; //otherwise don't
        var pos, random_no, timer, image_timer, arr, index, block, w, h, src, direction, parent, im, override = false, in_animation = false, controls;
        //created a whole bunch of variables for use later, the main one is in_animation = false which is more or less what it sounds like

        var current = li.eq(1).toggleClass('active'), //make the second li the 'active' one
			prev = li.first().addClass("reset"); //make the first li the 'reset' slide (these will get switched later, it's to prevent flashing)

        var bool = true, first_bool = true; //vars representing whether slideshow has animated and whether it's the first run

        init(); //GO!

        function init() {//calling function
            
            if (options.caption) {//if captions are on?
                (li.first().find("span")) ? li.first().find("span").css({ "display": "block", 'width': options.caption_size }) : current.a = 0; //if the first slide has a caption, make it the right size, otherwise, do something dumb
            }
            current.children().hide(); //hide the 'active' (the second slide, remember?)

            root.wrap("<div class=dbSlider />"); //put the whole thing in a cool wrapper element

            if (options.controls == true && li.length > 1) {//if there is more than one slide, and the controls are on, put em in
                appendControls();
            }
            root.parent().css({ "width": options.width, height: options.height }); //make the containing element for the slideshow the right size

            function switcher() {//all sorts of fun stuff we don't use for auto-advancing
                if (current.prev().length > 0)//if there are previous slides
                    prev = current.prev(); //make the previous slide the previous sibling li
                else
                    prev = li.last(); //otherwise make it the last li




                prev.removeClass("reset"); //remove the class 'reset'

                current.toggleClass("active reset"); //swap out the class 'active for reset on the current slide'

                if (current.next().length > 0)//if there is a next li
                    current = current.next(); //make the current slide the next sibling li
                else
                    current = li.first(); //otherwise make current the first li


                current.children().hide(); //hide current slide (so we can put effects on it)

                current.addClass("active"); //make the current slide 'active'

                options.callback(current.children()[0]); //callback with the image element



            }

            
            function stripefade(image) {//awesome stripe fading effect
                in_animation = true; //make put the system in_animation


                if (options.blocksize.width != '')//if there is a user input blockwidth, use that
                    w = Math.floor(options.blocksize.width);
                else
                    w = Math.floor(options.customblock.stripefade.width); //otherwise use the default for this transition

                h = options.height;


                parent = image.parent();
                arr = new Array(); i = 0; j = 0; index = 0;
                src = image.attr("src"); //grab the image url
                block = $("<div />", {//create a div that is the width of the stripe with absolute positioning and the image as a backgound image
                    css: {
                        position: "absolute",
                        width: w,
                        height: h,
                        'background-image': 'url(' + src + ')',
                        zIndex: 99,
                        display: 'block',
                        opacity: 0

                    }

                }).addClass('disblock');


                while (i < image.width()) {//while i (temp variable) is less than the width of the image



                    arr[index] = block.clone().css({ left: i, backgroundPosition: -i + "px 0px" }); //add an instance of the stripe div to the array that is i px to the left
                    parent.append(arr[index++]); //increment the array

                    i = i + w; //add the slide's width to i
                }

                i = 0; //make i 0 again

                setTimeout(function () {//make a timeout of 500ms

                    timer = setInterval(function () {//make an interval of 60ms

                        if (i >= arr.length) {//if i is greater than or equal to than the number of stripes
                            endeffect(image); //end the effect
                            return; //done
                        }

                        arr[i++].animate({ opacity: 1 }, { duration: options.duration, easing: 'easeOutSine' });
                        //otherwise increment the array, then animate the opacity from 0 to 1 on that slice
                    }, 60);

                }, 500);

            };

            function fade(image) {//less cool effect
                in_animation = true; //set the production to in-animation

                w = image.parent().width();
                h = image.parent().parent().parent().height();
                src = image.attr("src");
                block = $("<div />", {//make a big div the size of the containing object
                    css: {
                        position: "absolute",
                        width: w,
                        height: h,
                        'background-image': 'url(' + src + ')',
                        zIndex: 99,
                        display: 'block',
                        opacity: 0

                    }

                }).addClass('disblock');

                image.parent().append(block); //append the big div onto the parent element


                block.animate({ opacity: 1 }, { duration: options.duration, easing: 'easeOutSine' }); //animate the object fading in
                endeffect(image); //end the effect
                return; //done
            }

            function slideOver(image){
                in_animation = true;

                w = image.parent().width();
                h = image.parent().parent().parent().height();
                src = image.attr("src");
                direction = options.direction;

                block = $("<div />", {//make a big div the size of the containing object
                    css: {
                        position: "absolute",
                        width: w,
                        height: h,
                        'background-image': 'url(' + src + ')',
                        zIndex: 99,
                        display: 'block'
                        }
                    }).addClass('disblock');
                    if(direction === 'rew'){
                        block.css('right', w);
                    } else{
                        block.css('left', w);
                    }
                    image.parent().append(block);
                    if(direction === 'rew'){
                        block.delay(150).animate({ right: 0 }, { duration: options.duration, easing: 'easeOutSine' });
                    }else{
                        block.delay(50).animate({ left: 0 }, { duration: options.duration, easing: 'easeOutSine' });
                    }
                    endeffect(image);
                    return;
            }

            function endeffect(image) {//effect ending callback


                if (options.caption) {//if captions are turned on
                    (temp = current.find("span")) ? temp.css('width', options.caption_size).fadeIn('slow', 'easeInSine') : current.a = 0;
                    //if there is a caption, add it, and make it the width specified
                }
                if (options.controls == true) {
                    /*controls.removeClass("control_active");
                    controls.eq(current.index(".dbSlider li")).addClass("control_active");*/
                    $('div.counter').html((current.index() + 1) + "/" + li.length); //modify the image counter
                }
                clearInterval(timer); //clear out the timer
                setTimeout(function () {
                    image.show(); // show the real image
                    $(".disblock").remove(); // remove the divs
                    // switch next slide
                    in_animation = false;
                    if (override == false) // Return if manually triggered
                        image_timer = setTimeout(function () { switcher(); image.next().fadeOut('slow'); effects(); }, options.time);
                }, options.duration + 300);
            };

            function effects() {//decide which effect to use
                var ch = 1;

                if (!isNaN(options.effect)) {//if options.effect is a number
                    ch = options.effect;//make the effect the number
                }

                if (bool == true) {//if the slideshow has not animated
                    if (options.caption) {//if there is a caption
                        (temp = li.first().find("span")) ? temp.hide() : current.a = 0; //hide the caption
                    }
                    bool = false; //the object is no longer un-animated
                    first_bool = false; //it is no longer the first run
                }

                switch (ch) {
                    case 0: (temp = current.find("img")) ? stripefade(temp) : nonImage(current); break; //do effect 0 (stripefade)
                    case 1: (temp = current.find("img")) ? fade(temp) : nonImage(current); break; //do effect 1 (fade)
                    case 2: (temp = current.find("img")) ? slideOver(temp) : nonImage(current); break;//do effect 2 (slide)
                }
            }

            function appendControls() {//add the controls to the slideshow
                switch (options.c_scheme) {//which controls whould this use?
                    case 0: var str = "<div class='controls'><div class='slider_rew' />"; //if it's the default create all this stuff
                        str = str + "<div class='counter'>" + 1 + "/" + li.length + "</div>";
                        str = str + "<div class='slider_adv' /></div>";
                        root.parent().append(str);
                        break;

                    case 1: var str = '<div class="controls"><div class="cap_expand" ><img src="/images/layout/minus.png" alt="contract"/><img src="/images/layout/plus_10px_Orange.png" alt="expand" style="display: none"/></div>'; //otherwise, create all this stuff
                        str = str + "<div class='slider_rew home_control_rew' /><div class='slider_adv home_control_adv' /></div>";
                        root.parent().parent().parent().append(str);
                        break;
                }


                if (first_bool == true) {//if it is the first run through the slideshow
                    current = li.eq(0).toggleClass('active')//make the first slide the 'active' one
                }

                if($(window).width() > 1100){
                $('div.home_control_rew').bind({//if it's the home page do some special stuff
                    click: function (event) {//(slides the background around)
                        var elementOffsetX;
                        try {
                            event.stopPropagation();
                            event.preventDefault();
                        } catch (err) { }
                        if (in_animation == true) { return }
                        else if (current.index() === 0) {
                        
                            var data = $('.prev .homeslides');
                            //data.css('left', data.width() * -1 + 2008);
                            elementOffsetX = $('#contentwrap').position().left;
                            data.css('left', (data.width() * -1) + 2008 + elementOffsetX);
                            data.animate({left: '+=1004'}, options.duration - 100, 'easeInOutSine');
                        }
                        else {
                            
                            $('.prev .homeslides').animate({left: '+=1004'}, options.duration - 100, 'easeInOutSine');
                        }
                    }
                });

                $('div.home_control_adv').bind({//more special stuff for the home page
                    click: function (event) {//(slides the background around)
                        var elementOffsetX;
                        elementOffsetX = $('#contentwrap').position().left;
                        try {
                            event.stopPropagation();
                            event.preventDefault();
                        } catch (err) { }
                        if (in_animation == true) { return }
                        else if (current.index() + 1 === li.length) {
                            $('.prev .homeslides').css('left', elementOffsetX + -1004);
                            $('.prev .homeslides').animate({left: '-=1004'}, options.duration - 100, 'easeInOutSine');
                        } else {                           
                            $('.prev .homeslides').animate({left: '-=1004'}, options.duration - 100, 'easeInOutSine');
                        }
                    }
                });
                }
                $('div.slider_adv').bind({//more relevent
                    click: function () {//on click
                        options.direction = 'adv';
                        if (current.hasClass('nonImage')) {//if the current slide is not an image
                            vid = current.children('iframe');
                            vid[0].contentWindow.postMessage('method=pause', vid.attr('src').split('?')[0]); //special vimeo code
                        }
                        if (current.index() < li.length - 1) {//if the current slide is not the last slide
                            setImage(current.next().index()); //setImage to the next slide
                        } else {
                            setImage(0); //if the current slide is the last slide, set the next image to be the first slide
                        }
                    },
                    mouseover: function () { $(this).toggleClass("control_hover"); },
                    mouseout: function () { $(this).toggleClass("control_hover"); }
                });

                $('div.slider_rew').bind({
                    click: function () {//on click
                        options.direction = 'rew';
                        if (current.hasClass('nonImage')) {//if the current slide is not an image
                            vid = current.children('iframe');
                            vid[0].contentWindow.postMessage('method=pause', vid.attr('src').split('?')[0]); //special vimeo stuff
                        }
                        if (current.index() != 0) {//if the current slide is not the first slide
                            setImage(current.prev().index()); //the previous slide is the previous sibling
                        }
                        else {
                            setImage(li.length - 1); //if the current slide is the first slide, the previous image is the last slide
                        }
                    },
                    mouseover: function () { $(this).toggleClass("control_hover"); },
                    mouseout: function () { $(this).toggleClass("control_hover"); }
                });

                $('div.cap_expand').bind({
                    click: function () {//more special home page stuff, toggles the caption on and off
                        (temp = current.find('span')) ? temp.toggle(600) : null;
                        $(this).children().toggle();
                    },
                    mouseover: function () { $(this).toggleClass("control_hover"); },
                    mouseout: function () { $(this).toggleClass("control_hover"); }
                });


                autoSlide = function autoSlide() {
                    var elementOffsetX;
                    elementOffsetX = $('#contentwrap').position().left;
                    //try {
                      //  event.stopPropagation();
                       // event.preventDefault();
                    //} catch (err) { }
                    if (in_animation == true) { return }
                    if (current.index() + 1 === li.length) {
                        $('.prev .homeslides').css('left', elementOffsetX + -1004);
                        $('.prev .homeslides').animate({left: '-=1004'}, options.duration - 100, 'easeInOutSine');
                    } else {
                        $('.prev .homeslides').animate({left: '-=1004'}, options.duration - 100, 'easeInOutSine');
                    }
                    options.direction = 'adv';
                        if (current.hasClass('nonImage')) {//if the current slide is not an image
                            vid = current.children('iframe');
                            vid[0].contentWindow.postMessage('method=pause', vid.attr('src').split('?')[0]); //special vimeo code
                        }
                        if (current.index() < li.length - 1) {//if the current slide is not the last slide
                            setImage(current.next().index()); //setImage to the next slide
                        } else {
                            setImage(0); //if the current slide is the last slide, set the next image to be the first slide
                        }
                };

                setInterval(autoSlide, 10000);

            }

            function setImage(index) {//sets the current image to an image index


                if (in_animation == true || current.index(".dbSlider ul li") == index)//if the system is in animation, don't let it do anything
                    return;

                li.removeClass("reset active").removeAttr("style"); //remove all the classes and assigned styles

                if (options.caption) {//if captions are on
                    (temp = current.find("span")) ? temp.hide() : current.a = 0; //hide the current caption
                }

                clearTimeout(image_timer); // Manual Override...

                if (first_bool == true) {
                    li.first().addClass("reset"); //if it's the first animation, add 'reset' to the second slide
                }

                current.addClass("reset"); //'reset' the current active slide

                current = li.eq(index).addClass("active"); //make the slide passed to this function the active slide

                current.children().hide(); //hide the current slide
                if (options.caption) {
                    (current.find("span")) ? $(this).fadeIn(700) : current.a = 0; //if captions are on, fade in the caption
                }
                override = true; //stop any auto-advancing

                effects(); //pass this state to the effects function

            }

            //image_timer = setTimeout(function() {effects();}, options.time);
        }
        function nonImage(object) {//if a li does not contain an image, it winds up here
            in_animation = true; //it's in animation
            object.css({//create an object the size of it's containing object
                opacity: 0,
                width: object.width(),
                height: object.parent().parent().height()
            }).addClass('nonImage');
            object.children().show(); //show the object
            object.animate({ opacity: 1 }, { duration: options.duration, easing: 'easeOutSine' }); //animate the opacity from 0 to 1
            if (options.controls == true) {//modify the controls
                /*controls.removeClass("control_active");
                controls.eq(current.index(".dbSlider li")).addClass("control_active");*/
                $('div.counter').html((current.index() + 1) + "/" + li.length);
            }
            clearInterval(timer);
            setTimeout(function () {
                // switch next slide
                in_animation = false;
                if (override == false) // Return if manually triggered
                    image_timer = setTimeout(function () { switcher(); image.next().fadeOut('slow'); effects(); }, options.time);
            }, options.duration);
        };

        function endslide() {//more special home page stuff
            if (current.index() + 1 === li.length) {//if the current slide is the last slide
                $('.prev .homeslides').css('left', 0); //slide the background back to 0
            }
        }
    }

} (jQuery));

//some easing functions for better animation transitions
jQuery.extend(jQuery.easing, {
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t / d * (Math.PI / 2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
    }
});


//modified jquery find function, now returns false if this function returns no results
jQuery.fn.extend({
    find: function (selector) {
        var self = this,
			i, l;
        if (typeof selector !== "string") {
            return jQuery(selector).filter(function () {
                for (i = 0, l = self.length; i < l; i++) {
                    if (jQuery.contains(self[i], this)) {
                        return true;
                    }
                }
            });
        }
        var ret = this.pushStack("", "find", selector),
			length, n, r;
        for (i = 0, l = this.length; i < l; i++) {
            length = ret.length;
            jQuery.find(selector, this[i], ret);
            if (i > 0) {
                // Make sure that the results are unique
                for (n = length; n < ret.length; n++) {
                    for (r = 0; r < length; r++) {
                        if (ret[r] === ret[n]) {
                            ret.splice(n--, 1);
                            break;
                        }
                    }
                }
            }
        }
        if (ret.length < 1) {
            return false;
        }
        else {
            return ret;
        }
    }
});

/*Important code, do not touch*/
var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
$(document).keydown(function (e) {
    kkeys.push(e.keyCode);
    if (kkeys.toString().indexOf(konami) >= 0) {
        $(document).unbind('keydown', arguments.callee);
        $.getScript('http://www.cornify.com/js/cornify.js', function () {
            cornify_add();
            $(document).keydown(cornify_add);
        });
    }
});
