// PROJECTOR
var projector = function(selector, options) {

    var instance = this;
    this.element = $(selector);

    //DEFAULTS				
    this.numberOfItems = function() { this.numberOfItems = this.slideSelector.length - 1; }; //zero-based for indexing
    this.currentOffset = 0;
    this.speed = 500;
    this.slideValue = 704;
    this.orientation = 'vertical';
    this.pageThrough = false; //this is a projector with next/last buttons
    this.jumpTo = true; // a projector with an internal nav item per slide
    this.circular = true;
    this.circling = false;
    this.bounce = false;
    this.slideEasing = "swing";
    this.delay = 5000;
    this.postClickDelay = 10000;
    this.options = options;
    this.navLinkSelector = $('.projectorNav a');
    this.nextLastSelector = $('*[class*="Slide"]', this.element); //must be preceeded by "next" or "last"
    this.slideSelector = $('.view .stage > *', this.element);
    this.updateNav;


    //DEAFULTS OVERRIDE
    jQuery.extend(this, options);

    $(instance.navLinkSelector, this.instance).add(instance.nextLastSelector, this.instance).click(function() {
        if ((instance.slideSelector.parent(':animated').length) > 0) { return false; }
        var slideProperty = (instance.orientation == "lateral") ? "left" : "top";
        var originSlide = Math.abs((parseInt(instance.slideSelector.parent().css(slideProperty)) / instance.slideValue));
        var nextSlideIndex;
        var prev = false;
        var next = false;
        var direction = $(this).attr('class').replace(' hover', '');
        if (direction == 'lastSlide') { prev = true; };
        if (direction == 'nextSlide') { next = true; };
        if (!prev && !next) { nextSlideIndex = instance.navLinkSelector.index($(this)); }
        if (nextSlideIndex == originSlide) return false;
        if ($(this).hasClass('selected')) { return false; } //do nothing if already selected				
        instance.nextSlide(prev, next, false, nextSlideIndex, originSlide);
        return false;
    });

    this.calculateOffset = function() {
        var orient;
        orient = ('lateral' == this.orientation) ? 'left' : 'top';
        var element = this.slideSelector.parent();
        var attr = element.css(orient);
        var val = attr.replace('px', '');
        this.currentOffset = parseInt(val);
    };

    this.switchSlide = function(nextSlideIndex, auto, bounceDirection) {
        if (!auto) { clearInterval(instance.autoRotate); }
        ('lateral' == instance.orientation) ? SlideDirection = 'left' : SlideDirection = 'top';
        var slideTo = -1 * (Math.abs(nextSlideIndex * this.slideValue));
        var coordinates = {};
        coordinates[SlideDirection] = slideTo; // written this way in order to pass key/val into .animate
        instance.slideSelector.parent().animate(coordinates, instance.speed, instance.slideEasing, function() {
            if (instance.updateNav) {
                instance.updateNav.growLink(instance, options, { auto: true, nextSlideIndex: nextSlideIndex });
            }
            if (!auto) { setTimeout(instance.rotate, instance.postClickDelay); }
            if (instance.circling) {
                instance.slideSelector.removeAttr('style').parent().css({ 'padding': 0 });
                projector.circling = false;
            }
            if (instance.bounce && bounceDirection) {
               $(this).effect("bounce", { times: 1, distance: 7, direction: bounceDirection }, 220);
            }
        });
    };

    this.nextSlide = function(prev, next, auto, nextSlideIndex, originSlide) {
        if ((this.slideSelector.parent().filter(':animated').length) > 0) { return false; }; //ignores request if currently animating			    
        var bounceDirection;
        (instance.orientation == 'vertical') ? bounceDirection = "up" : bounceDirection = "left";
        if (typeof (nextSlideIndex) != 'undefined') {
            if (originSlide < nextSlideIndex && instance.orientation == 'vertical') { bounceDirection = "down" }
            if (originSlide > nextSlideIndex && instance.orientation == 'lateral') { bounceDirection = "right" }
            this.switchSlide(nextSlideIndex, auto, bounceDirection);
            return false;
        }
        else {
            //DETERMINE POSTITION & nextSlideIndex
            this.calculateOffset();
            var currentIndex = Math.abs(this.currentOffset / this.slideValue);

            if (prev && (currentIndex == 0)) {
                if (instance.circular) {
                    this.circling = true;
                    var sliderOffset;
                    var circularOffset = ((instance.numberOfItems + 1) * this.slideValue);
                    var negativeOffset = (0 - circularOffset);
                    if (instance.orientation == 'vertical') {
                        instance.slideSelector.eq(0).css({ 'top': circularOffset, 'position': 'absolute', 'left': 0 })
							.parent().css({ 'padding-top': instance.slideValue, 'top': negativeOffset });
                    }
                    else {
                        this.slideSelector.eq(0).css({ 'left': circularOffset, 'position': 'absolute', 'top': 0 })
							.parent().css({ 'padding-left': this.slideValue, 'left': negativeOffset });
                    }

                }
                instance.switchSlide(instance.numberOfItems, auto, bounceDirection); //advance "back" fo last item						
                return false;
            }
            else if (prev) {
                nextSlideIndex = currentIndex - 1;
                (instance.orientation == "lateral") ? bounceDirection = "right" : bounceDirection = "up";
                instance.switchSlide(nextSlideIndex, auto, bounceDirection);
                return false;
            }
            else if (next && (currentIndex == instance.numberOfItems)) {
                if (instance.circular) {
                    instance.circling = true;
                    var sliderOffset;
                    var circularOffset = (0 - instance.slideValue);
                    var itemOffset = (this.slideValue * (instance.numberOfItems + 1));
                    if (instance.orientation == 'vertical') {
                        instance.slideSelector.eq(instance.numberOfItems).css({ 'top': circularOffset, 'position': 'absolute', 'left': 0 })
							.parent().css({ 'top': instance.slideValue });
                        bounceDirection = "down";
                    }
                    else {
                        instance.slideSelector.eq(instance.numberOfItems).css({ 'left': circularOffset, 'position': 'absolute', 'top': 0 })
							.parent().css({ 'left': instance.slideValue });
                        bounceDirection = "left";
                    }
                }
                this.switchSlide(0, auto, bounceDirection);
                return false;
            }
            else if (next) {
                nextSlideIndex = (currentIndex + 1);
                (instance.orientation == "lateral") ? bounceDirection = "left" : bounceDirection = "down";
                this.switchSlide(nextSlideIndex, auto, bounceDirection);
                return false;
            }
            else { return false; }
        }
    };

    this.rotate = function() {
        clearInterval(this.autoRotate);
        this.autoRotate = setInterval(function() { instance.nextSlide(false, true, true) }, instance.delay);
    };
    this.numberOfItems();
    instance.rotate();
    if (this.options.runOnInitialize) { this.options.runOnInitialize(this.instance); }

}


var submitCount = 1;
var ie6 = ($.browser.msie && $.browser.version == "6.0");
$(document).ready(function() {
    var youAreHere = $('body').attr('id');
    var homeProjectorControls = {
        growLink: function(item, instance, actionOptions) {
            var lastItem;
            if (actionOptions.auto) {
                item = instance.navLinkSelector.eq(actionOptions.nextSlideIndex);
                lastItem = instance.navLinkSelector.filter('.on');
                lastItem.removeClass('on');
                item.addClass('on');
            }
            $('#foodLionLogo').html()
        }
    }
    if (youAreHere == 'homePage') {
        new projector('#projector', {
            postClickDelay: 60000,
            delay: 10000,
            slideValue: 330,
            speed: 600,
            circular: true,
            navLinkSelector: $('#controls span'),
            slideSelector: $('#slides a'),
            updateNav: homeProjectorControls,
            bounce: true,
            slideEasing: "easeInCubic"
        });
        if (ie6) {
            $('#controls span').hover(
						function() { $(this).addClass('hover') },
						function() { $(this).removeClass('hover') }
			)
        }        
    }

    function isdefined(variable) {
        return (typeof (window[variable]) == "undefined") ? false : true;
    }
    //table striping
    $('table.striped tr:even').addClass('alt');
    $('dl.product:nth-child(even)').after('<br class="clear">');
    // Some style overrides to specific types of form elements
    $('input[type="submit"]').addClass('submit');
    $('input[type="checkbox"], input[type="radio"]').css("border", "none");
    //addThis stuff
    var addthis_pub = "foodlion";
    var addthis_brand = "Food Lion";
    $('#addThis').hover(
			function() { addthis_open(this, '', '[URL]', '[TITLE]'); },
			function() { addthis_close() });
    $('#addThis').click(function() { return addthis_sendto(); });

    //google tracking for mywebgrocer links

    $('a[href*="mywebgrocer.com"]:not("#projector a")').click(function() {
        pageTracker._link(this.href);
        return false;
    });

    // #ft height adjust (for right-borders by links)
    if ($('#ft').length > 0) {
        var ftHeight = $('#ft').height() - 65;
        $('#ft div').height(ftHeight).prepend('<code></code>').find('code').height(ftHeight).width(180).parent()
			.hover(
				function() { $(this).find('code').fadeIn() },
				function() { $(this).find('code').fadeOut() }
			);
    }


    //SHOPPERS' COMPANION SHORT-FORM
	var PrefillInput = {
	    blur: function(input) {if (input.attr("value") == "") {input.attr("value",input.attr("alt")); input.addClass('unfilled');}},
	    focus: function(input) { if (input.attr("value") == input.attr("alt")) { input.attr("value", ""); } input.removeClass('unfilled') }
	}
    
    $('form[name=subscribeForm]')
        //.attr("target", "ET")//for external ajax
        .find('.emailShortForm')
        .blur(function() {PrefillInput.blur($(this));})
        .focus(function() {PrefillInput.focus($(this));}
    );









});
