// Convert un-tabbed display into tabbed display and activate tabs
var ANTabs = {
	init: function() {
		// Only run if we have tabs
		if (! $.fn.tabs) return;

		var $tabs = $('div.tabs');
		if ($tabs.length == 0) return;

		var $tabnav = $('<ul class="tabNav selfClear"></ul>');
		$tabs.prepend($tabnav);
		$tabs	.find('> div')
					.each( function(i) {
						var id = this.id;
						// Descending search for header values
						var $header = $(this).find('h2:first');
						if ($header.length == 0)
							$header = $(this).find('h3:first');
						if ($header.length == 0)
							$header = $(this).find('h4:first');

						// Use title value if available
						var title = $header.attr('title');

						// Only remove the header if we're using the actual header text
						if (title) {
							$header.attr('title', '');
						} else {
							title = $header.html();
							$header.remove();
						}

						$tabnav.append('<li id="' + id + 'Tab"><a href="#' + id + '" class="noPopup png_bg"><span>' + title + '</span></a></li>');
					});
					$tabnav.find('li:first').addClass('first');
					$tabnav.find('li:last').addClass('last');
		// Need delay for browsers to get their DOM in order
		setTimeout(function() {
			$tabs.tabs({
				// Prevent outline on selection
				select: function(event, ui) {
					$(ui.tab).blur();
				}
			});
			$tabs.find('.hideOnLoad').removeClass('hideOnLoad');
		}, 500);

		// Support for linking into a different tab on the page
		$('a.tabLink').live('click', function(e) {
			e.preventDefault;
			var hash = this.hash;
			if (hash.substr(0, 1) != '#')
				hash = '#' + hash;
			$tabs.tabs('select', hash);
		});
	}
};
$(document).ready(ANTabs.init);

/* begin - Navigation Primary */
var NavigationPrimary = {
  init: function() {    
		var c = this;
		var n = $('#NavigationPrimary > ul');
		
		// Use bgiframe to fix dropdowns over selects if it's available.
		$.fn.bgiframe && $('li', n).bgiframe();

		// Mark parent elements so that we can style them with CSS
		$('> li', n).each(function() { c.markParents(this); });
  	
  	// Use the hoverintent plugin if it's available
  	  $('li', n).hover(this.mouseenter, this.mouseleave);
  },
  markParents: function(li) {
    var c = this;
    if ($('> ul', li).size() > 0)
	    $(li).addClass('parent').find('> a').addClass('parent').end().find('> ul li').each( function() { c.markParents(this); });
	},
	mouseenter: function() { $(this).addClass('over').children('a').addClass('over'); },
	mouseleave: function() { $(this).removeClass('over').children('a').removeClass('over'); }
};
$(function() { NavigationPrimary.init(); });
/* end - Primary Navigation */

var SearchMenu = {
	init: function() {
		$('li.search').hover(SearchMenu.mouseenter, SearchMenu.mouseleave)
			.find('form').submit(SearchMenu.submit);
	},
	mouseenter: function(event) { $(this).addClass('searchOver'); },
	mouseleave: function(event) { $(this).removeClass('searchOver'); },
	submit: function(event) {
		event.preventDefault();
		var $$ = $(this);
		var url = $(this).find('select').val();
		var term = escape($(this).find('input[name=query]').val());
		if (url.indexOf('picosearch') != -1) {
			// searching .com
			url += '?query=' + term + '&index=' + $(this).find('input[name=index]').val();
		} else {
			// searching snapstore
			url += '?q=' + term;
		}
		document.location = url;
	}
};
$(document).ready(SearchMenu.init);

var GlobalMenu = {
	init: function() {
		$('li.global').hover(GlobalMenu.mouseenter, GlobalMenu.mouseleave);
	},
	mouseenter: function(event) { $(this).addClass('globalOver'); },
	mouseleave: function(event) { $(this).removeClass('globalOver'); }
};
$(document).ready(GlobalMenu.init);

/* Customer carousel for mast on homepage  */
var HomeMastCustomersCarousel = {
	init: function() {
		if (! $.fn.jcarousel)
			return;
		$('body.home #Mast  ul.carousel').each(function() {
			$(this).find('.hideOnLoad').removeClass('hideOnLoad');
			$(this).jcarousel({
				wrap: 'circular',
				vertical: true,
				visible: 1,
				scroll: 1
			});
		});
	}
};
$(document).ready(HomeMastCustomersCarousel.init);

var FeaturedSnapsCarousel = {
	init: function() {
		if (! $.fn.jcarousel)
			return;
		$('section.featuredSnaps ul.carousel').each(function() {
			$(this).find('.hideOnLoad').removeClass('hideOnLoad');
			$(this).jcarousel({
				wrap: 'circular',
				visible: 1,
				scroll: 1,
				auto: 9
			});
		});
	}
};
$(document).ready(FeaturedSnapsCarousel.init);

/* Customer carousel for mast on homepage  */
var CustomersCarousel = {
	init: function() {
		if (! $.fn.jcarousel)
			return;
		$('#Content section.customer ul.carousel').each(function() {
			$(this).find('.hideOnLoad').removeClass('hideOnLoad');
			$(this).jcarousel({
				wrap: 'circular',
				visible: 1,
				scroll: 1,
				auto: 9,
		        buttonNextHTML: null,
		        buttonPrevHTML: null,
                itemVisibleInCallback: CustomersCarousel.itemVisibleInCallback,
                initCallback: CustomersCarousel.initCallback,
                animation: 0
			});
		});
	},
    itemVisibleInCallback: function(c, el, i, state) {
        $(el).fadeTo('slow', 1.0, function() { CustomersCarousel.fadeInCallback(c, el, i, state); });
    },
    fadeInCallback: function(c, el, i, state) {
        setTimeout(function() {

            $(el)
                    // Must animate almost to 0, cause if we go to 0, then the element
                    // gets display="none" and it auto switches to the next slide
                    .fadeTo('slow', 0.001, function() {
                            c.next();
                    } );
        }, 5000);
    },
    initCallback: function(carousel) { CustomersCarousel.carousel = carousel; }
};
$(document).ready(CustomersCarousel.init);

/* Carousel for features on homepage  */
var HomeFeaturesCarousel = {
    carousel: null,
    paused: false,
	externalPause: false,
    clicked: 0,
    init: function() {
        $('body.home section.features ul.carousel').each(function(i) {
            $(this).find('li.hideOnLoad').removeClass('hideOnLoad').css({opacity: .001});
            $(this).jcarousel({
                // auto: 2,
		        buttonNextHTML: null,
		        buttonPrevHTML: null,
                wrap: 'both',
                visible: 1,
                scroll: 1,
                itemVisibleInCallback: HomeFeaturesCarousel.itemVisibleInCallback,
                initCallback: HomeFeaturesCarousel.initCallback,
                animation: 0
            });
			var $ul = $('<ul class="carouselNav"/>');
			$ul.append('<li class="prev">prev</li>');
			for (var i = 1, max = $(this).find('li').length; i <= max; i++) {
				$ul.append('<li class="index">' + i + '</li>');
			}
			$ul.append('<li class="next">next</li>');
			$ul.find('li.index:first').addClass('active');
			$('body.home section.features h2').after($ul);
			// $('body.home section.features h2').after('<ul class="carouselNav"><li class="one active">1</li><li class="two">2</li><li class="three">3</li></ul>');
			//.after('<ul class="carouselNav"><li class="one active">1</li><li class="two">2</li><li class="three">3</li><li class="four">4</li></ul>');
            $('body.home section.features ul.carouselNav li')
                                    .live('mouseover', HomeFeaturesCarousel.navMouseover)
                                    .live('mouseout', HomeFeaturesCarousel.navMouseout);
            $('body.home section.features ul.carouselNav li.index')
									.live('click', HomeFeaturesCarousel.navClick);
			$('body.home section.features ul.carouselNav li.next')
									.live('click', HomeFeaturesCarousel.nextClick)
									.live('mouseover', HomeFeaturesCarousel.nextMouseover)
									.live('mouseout', HomeFeaturesCarousel.nextMouseout);
			$('body.home section.features ul.carouselNav li.prev')
									.live('click', HomeFeaturesCarousel.prevClick)
									.live('mouseover', HomeFeaturesCarousel.prevMouseover)
									.live('mouseout', HomeFeaturesCarousel.prevMouseout);
			
        });
        $('body.home section.features').live('mouseover', HomeFeaturesCarousel.mastMouseover)
                            .live('mouseout', HomeFeaturesCarousel.mastMouseout);
    },
    /* Called when the image/slide loads. First it fades in the new image, then
        it uses jQuery's animate function to delay before fading out the image.
        Once the image has faded out there is a callback to tell the carousel
        to transition to the next slide/image and the process starts over again.
    */
    itemVisibleInCallback: function(c, el, i, state) {
        $('body.home section.features ul.carouselNav').find('li.active').removeClass('active').end().find('li:eq(' + i + ')').addClass('active');
        $(el).fadeTo('slow', 1.0, function() { HomeFeaturesCarousel.fadeInCallback(c, el, i, state); });
    },
    fadeInCallback: function(c, el, i, state) {
        if (HomeFeaturesCarousel.paused || HomeFeaturesCarousel.externalPause) {
            setTimeout(function() { HomeFeaturesCarousel.fadeInCallback(c, el, i, state); }, 500);
            return;
        }
        setTimeout(function() {
            if (HomeFeaturesCarousel.paused || HomeFeaturesCarousel.externalPause) {
                setTimeout(function() { HomeFeaturesCarousel.fadeInCallback(c, el, i, state); }, 500);
                return;
            }
            $(el)
                     // Must animate almost to 0, cause if we go to 0, then the element
                    // gets display="none" and it auto switches to the next slide
                    .fadeTo('slow', 0.001, function() {
                        if (HomeFeaturesCarousel.clicked <= 0) {
							HomeFeaturesCarousel.clicked = 0;
                            c.next();
                        } else
                            HomeFeaturesCarousel.clicked--;
                    } );
        }, 5000);
    },
    mastMouseover: function(e) {
		HomeFeaturesCarousel.paused = true;
	},
    mastMouseout: function(e) {
		HomeFeaturesCarousel.paused = false;
	},
    initCallback: function(carousel) { HomeFeaturesCarousel.carousel = carousel; },
    navClick: function(e) {
        HomeFeaturesCarousel.clicked++;
        HomeFeaturesCarousel.carousel.scroll($.jcarousel.intval($(this).text()));
    },
	nextClick: function(e) {
		HomeFeaturesCarousel.clicked++;
		HomeFeaturesCarousel.carousel.next();
	},
	nextMouseover: function(e) { $(this).addClass('nextOver'); },
	nextMouseout: function(e) { $(this).removeClass('nextOver'); },
	prevClick: function(e) {
		HomeFeaturesCarousel.clicked++;
		HomeFeaturesCarousel.carousel.prev();
	},
	prevMouseover: function(e) { $(this).addClass('prevOver'); },
	prevMouseout: function(e) { $(this).removeClass('prevOver'); },
    navMouseover: function(e) { $(this).addClass('hover'); },
    navMouseout: function(e) { $(this).removeClass('hover'); },
	pauseCarousel: function() {
		HomeFeaturesCarousel.externalPause = true;
	},
	unPauseCarousel: function() {
		HomeFeaturesCarousel.externalPause = false;
	}
};
$(document).ready(HomeFeaturesCarousel.init);

/* begin - open new window for external links and pdfs */
$(document).ready(function () {
        // Open fully qualified links, secure HTTP connection links, PDF links and specific links with class 'popup' in a new browser window
		$('a[href^="http://"],a[href^="https://"],a[href$=".pdf"],a.popup')
			.not($('a.noPopup,a.youtube,a[href^="http://www.snaplogic.com"],a[href^="http://prelaunch.snaplogic.com"],a[href^="http://store.snaplogic.com"]'))
			.popupwindow(); 
	});
/* end - open new window for external links and pdfs */

$(document).ready(function() {
	$("a.youtube").click(function(e) {
		e.preventDefault();
		$.fancybox({
			'titleShow'     : false,
			'transitionIn'  : 'elastic',
			'transitionOut' : 'elastic',
			'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'      : 'swf',
			'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
		});
	});
	
	$('a.webinarModal').click(function(event) {
		event.preventDefault();
		var width = $(this).data('width');
		var height = $(this).data('height');
		var self = this;
		$.fancybox(
			'<div id="PlayerWrapper"><div id="WebinarPlayer" style="width:' + width + 'px;height:'+height+'px;"></div></div>',
			{
				autoDimensions: false,
				width: width + 3,
				height: height + 3,
				onComplete: function() {
					flowplayer('WebinarPlayer', '/downloads/flowplayer-3.2.7.swf', self.href);					
				}
			}
		);
	});
	
	$('.productThumb a').fancybox({
		'titleShow'     : false,
		'transitionIn'  : 'elastic',
		'transitionOut' : 'elastic'
	});
});

$(document).ready(function() {
	$('a[href^="http://store.snaplogic.com/"]').click(function(e) {
		_gaq.push(['_trackEvent', 'External Link', 'Click', this.href]);
	});
});

$(document).ready(function() {
	if($('#WhitePaperForm').length || $('#TrialForm').length){
		$("#state").removeClass('required');
		$("#state").hide();
		$("#StateLabel").hide();

		$("#country").change(function(e) {
			var country = $("#country").val();
			if (country == 'United States' || country == 'Canada') {
				$("#state").addClass('required');
				$("#state").show();
				$("#StateLabel").show();
				$("#StateLabel span").show();
				if (country == 'United States') {
					$("#state .province").hide();
					$("#state .usState").show();
				} else {
					$("#state .province").show();
					$("#state .usState").hide();
				}
			} else {
				$("#state").removeClass('required');
				$("#state").hide();
				$("#StateLabel").hide();
			}
		});
		$('#WhitePaperForm').validate();
		$('#TrialForm').validate();
	}
});

$(document).ready(function() {
	// Prevent trackalyzer button from breaking design
	$('img[src^="http://t2.trackalyzer.com/"]').css('position', 'absolute');
});
