// Copyright 2010 Noah Feldman. All Rights Reserved.

/**
 * @fileoverview a collection of utilities for
 * simple slideshows and misc dom manipulations
 * requires jQuery
 * @author nfeldman@nsfdesign.com
 */
 
jQuery.extend(jQuery.easing, {
	easeInOutQuad:function (e, a, b, c, d) { if((a /= d / 2) < 1) { return c / 2 * a * a + b }return-c / 2 * (--a * (a - 2) - 1) + b }
	});

var NSF = {};

NSF.isNode = function(node, test) { 
    return (node.nodeName.toLowerCase() === test);
}

NSF.gNext = function(x, len) { // gets the next in a sequence from x, when x is last, return to the beginning
    return x %= len;
}

NSF.getTarget = function (link) {
	return (link.match(/^#/)) ? link.substring(link.indexOf('#') + 1) : '';
}
// somewhat general purpose show/hide with IE support
NSF.showHide = function(toHide, toShow, clss, spd1, spd2) {
	var ease = jQuery.easing.easeInOutQuad ? 'easeInOutQuad' : 'swing',
		spd1 = spd1 ? spd1 : 660,
		spd2 = spd2 ? spd2 : spd1;
		
    if (!NSF.isActive) {
        this.showHide.hide = function(toHide, clss) {
            NSF.isActive = true;
            toHide.animate({ opacity: 0 }, spd1, ease, function () {
                $(this).removeClass(clss).css({ display: 'none'});
                NSF.isActive = false;
            });
        }

        this.showHide.show = function(toShow, clss) {
            NSF.isActive = true;
            toShow.css({ display: 'block', opacity: 0 }).animate({ opacity: 1 }, spd2, ease, function () {
                if (!$.support.opacity) {
                    this.style.removeAttribute('filter');
                }
                NSF.isActive = false;
            }).addClass(clss);
        }
    }
    this.showHide.hide(toHide, clss, spd1);
    this.showHide.show(toShow, clss, spd2);
}

// TODO streamline creation of paging content w/ a pager object; adv as a method of pager
// most of what follows is painfully redundant and embarrassing
if ($('#gallerybox').length > 0) {
	NSF.gAdv = function(e) {
		e.preventDefault();

		var parent = $(e.target).parent('li'),
			nSlide = parent.data('id');

		nSlide = NSF.gNext(nSlide, NSF.gLen);

		this.gAdv.gAuto = function(e) {
			if (!NSF.gPause) {
				NSF.gPager.children('li').eq(nSlide).children('a').click();
			} 
		} 

		if (!parent.hasClass('current')) {
			NSF.gPager.children('.current').removeClass('current');
			parent.addClass('current');
			NSF.showHide($('#gallerybox > li.current'), $('#gallerybox > li').eq(nSlide - 1), 'current', 500, 660);
		}
		NSF.gAuto = setTimeout(NSF.gAdv.gAuto, 3500); 
	}

    NSF.gal = $('#gallerybox');
    NSF.gPager = $('#pager');
    NSF.gLen = NSF.gal.children('li').length;
    
    NSF.gal.bind('mouseenter', function (e) {
        NSF.gPause = true;
        clearTimeout(NSF.gAuto);
    }).bind('mouseleave', function (e) {
        NSF.gPause = false;
         NSF.gAdv.gAuto();
    });

    NSF.gPager.bind('click', function (e) {
        if (NSF.isNode(e.target, 'a')) {
            clearTimeout(NSF.gAuto);
            NSF.gAdv(e);
        }
    });
    
    // initialize slideshow
    (function () {
        var i = NSF.gLen, 
            g = NSF.gal.children('li'),
            p = NSF.gPager.children('li'),
            j;
        while (i--) {
            j = i + 1;
            g.eq(i).data('id', j).css({ zIndex: NSF.gLen - i, opacity: j > 1 ? 0 : 1, display:  j > 1 ? 'none' : 'block'});
            p.eq(i).data('id', j);
        }
        NSF.gPager.children('li').eq(0).children('a').click();
    }());
}

function products() {
    var prd = $('#nsf-main'),
		pager = $('#nav'),
		pLen = prd.children('div').length,
		// pHash,
		pAdv = function(e) {
		e.preventDefault();

		var parent = $(e.target).parent('li'),
			nSlide = parent.data('id');

		nSlide = NSF.gNext(nSlide, pLen);
		
		if (!parent.hasClass('current')) {
			pager.children('.current').removeClass('current');
			parent.addClass('current');
			NSF.showHide(prd.children('.current'), prd.children('div').eq(nSlide - 1), 'current', 300, 400);
		}
		
	};
    pager.bind('click', function (e) {
        if (NSF.isNode(e.target, 'a')) {
            pAdv(e);
			location.hash = $(e.target).data('hash');
        }
    });
	
	// initialize tabs
    (function () {
        var i = pLen, 
            g = prd.children('div'),
            p = pager.children('li'),
            j, k,
			l = location.hash.slice(1);
			
        while (i--) {
            j = i + 1;
			k = NSF.getTarget(p.eq(i).children('a').attr('href'));
			l = (l == k) ? +i : l; // if there is a hash, change l to the slide number 

            g.eq(i).data('id', j).css({ zIndex: pLen - i, opacity: 0, display:  j > 1 ? 'none' : 'block' }).attr('id', g.eq(i).attr('id') + '_div'); 
            p.eq(i).data('id', j).children('a').data('hash', k);
        }

		$('html').removeClass('jsTogl');

		l = (typeof l == 'number') ? l : 0; // if there isn't a hash, go to the first slide
		pager.children('li').eq(l).children('a').click();
    }());
}

if ($('#products').length > 0) {
	products();
}



// misc
(function ($) { 
	var items = $('#carousel > a'),  iLength = items.length, i = 0, content = $('#content');
	// group carousel links into threes and wrap in divs
	while (i <= iLength) {
		items.slice(i, i + 3).wrapAll('<div></div>');
		i += 3;
	}
if (content.height() > 620) { 
//	content.append('<div id="black-gradient"></div>');
}
$('.scrollable').scrollable({ease: 'easeInOutQuad', speed: 500}); // requires jquery tols http://flowplayer.org/tools/index.html


$('#nav-global > li > a').bind('click', function (e) {
	var that = $(this);
	e.preventDefault();
    if (!that.parent('li').hasClass('active')) {
		$('#nav-global .active').children('ul').fadeOut(300, function() {
			$(this).parent('li').removeClass('active');
		});
		that.next('ul').css('display', 'none').parent('li').addClass('active').children('ul').fadeIn(200, function () {
			if (!$.support.opacity) {
				this.style.removeAttribute('filter');
			}
		});
	}
});

$('#subscribe input[type=text]').focus(function () {
	$('#subscribe label').hide();
}).blur(function () {
	if ($(this).val().length === 0) {
		$('#subscribe label').show();
	}
}).next().val(''); 

// fix for the places where the mailing list is still stuck in a table cell
if ($('#mailing-list').parent().parent().is('td')) {
// I really hope we get to fix this in the next version
	if ($('#mailing-list').parent('div').position().top < 0) {
		$('#mailing-list').parent('div').css('marginTop', -65);
	}
	$('#mailing-list label').css({zIndex: 1, marginLeft: 30, marginTop: 5});
	$('#mailing-list').parents('td').css({ padding: 0}).attr('valign', 'top').end();
}

// more mailing list requires jquery tools http://flowplayer.org/tools/index.html
$('body').append('<div class="simple_overlay" id="submit"><div class="contentWrap"></div></div>');
$('input[rel="#submit"]').overlay({
		mask: '#444',
		onBeforeLoad: function() {
			var wrap = this.getOverlay().find(".contentWrap"), email = $('#subscribe input[type=text]').val();
			wrap.load('/global-embeds/modal-form', function () {$('#submit input[type=text]').focus(function () {
					$(this).prev('label').hide();
				}).blur(function () {
				if ($(this).val().length == 0) {
					$(this).prev('label').show();
				}
			});
			if ($('#email').val().length == 0 && email) {
					$('#email').focus().val(email);
				}
		});
		}
	});
$('a[rel*=external]').attr('target', '_blank');
}(jQuery));
