/********************************************
 * Just some jQuery love in here...         *
 * Just some jQuery love in here...         *
 * Just some jQuery love in here...         *
 *******************************************/

 // Age Gate only, dynamically set background image src based on window size
$(function() {
  if ($('body#ageGate').length) {
    function setImageSrc() {
      var img   = $('.scale-image'),
          base  = '/images/age-gate/main-bg-',
          ww    = $(window).width();

      if (ww > 1024) {
        img.attr('src', base + 'large.jpg').attr('width', '2000').attr('height', '2000');
      } else if (ww > 960) {
        img.attr('src', base + 'medium.jpg').attr('width', '1024').attr('height', '1024');
      } else {
        img.attr('src', base + 'small.jpg').attr('width', '960').attr('height', '960');
      }
    }

    $(window).resize(setImageSrc);
    setImageSrc();
  }
});

$(document).ready(function() {
  // scale certain background images as the browser window resizes
  function scaleImages() { $('.scale-image').each(scaleImage); }
  function scaleImage(_,image) {
    var img       = $(image),
    imgData   = img.data(),
    width     = img.attr('width')  || img.width(),
    height    = img.attr('height') || img.height(),
    offParent = img.offsetParent(),
    parent    = offParent.is('body') ? $(window) : offParent,
    pWExp     = (imgData.parentWidthExpression || '%w').replace(/[^\d\(\)\/\*\+\-%w]*/g, ''),
    pWidth    = parseInt(eval(pWExp.replace(/%w/g, parent.width()))),
    pHeight   = parent.height(),
    newHeight = pWidth  * (height / width),
    newWidth  = pHeight / (height / width),
    centerHor = false,
    centerVer = false;

    // make adjustments based on the parent dimensions and the original image dimensions:
    if (newHeight < pHeight) { newHeight = pHeight; }
    if (newHeight < height ) { newHeight = height;  }
    if (newWidth < pWidth) { newWidth = pWidth; }
    if (newWidth < width ) { newWidth = width;  }

    // set the new dimensions:
    img.width(newWidth).height(newHeight);

    // adjust the positioning so that the image appears centered:
    if (imgData.center == true || imgData.centerHorizontal == true) { centerHor = true; }
    if (imgData.center == true || imgData.centerVertical == true)   { centerVer = true; }
    if (centerHor) { img.css('left', (pWidth  - newWidth ) / 2); }
    if (centerVer) { img.css('top',  (pHeight - newHeight) / 2); }
  };

  $(window).resize(scaleImages);
  scaleImages();
});

// replace stylized radio inputs
$(function() {
  $(':input[data-style]').each(function() {
    var input = $(this).hide(),
        name  = input.attr('name'),
        id    = input.attr('id'),
        style = input.data('style'),
        span  = $('<span name="'+name+'" class="radio-'+style+'"></span>').insertAfter(input);

    if (input.is(':checked')) { span.addClass('checked'); }

    span.add('label[for='+id+']').click(function() {
      input.closest('form').find('[name="'+name+'"]').removeClass('checked').removeAttr('checked');
      input.attr('checked', 'checked');
      span.addClass('checked');
    });
  });
});

// SIGN-UP SLIDER-DUDE
$(function(){
  $('#signUpPopUp').toggle(function(e){
    $(this).addClass('open');
    $('#loginBox').stop().animate({top:'10px'}, 200);
    $('html, body').stop().animate({scrollTop:$('body').position().top}, 200);
    e.preventDefault();
  }, function(){
    $(this).removeClass('open');
    $('#loginBox').stop().animate({top:'102px'}, 200);
    $('html, body').stop().animate({scrollTop:$('body').position().top}, 200);
  });
});
$(function(){
  $('#signUpSlideDown').toggle(function(e){
    $('#loginBox.headBox').stop().animate({top:'42px'}, 200);
    $('html, body').stop().animate({scrollTop:$('body').position().top}, 200);
    e.preventDefault();
  }, function(){
    $('#loginBox.headBox').stop().animate({top:'-52px'}, 200);
    $('html, body').stop().animate({scrollTop:$('body').position().top}, 200);
  });
});

// PASSWORD SIKE!
function pwdFocus() { $('#fakePassword').hide(), $('#loginPassword').show().focus(); }
function pwdBlur() {
  if ($('#loginPassword').attr('value') == '') {
    $('#loginPassword').hide(), $('#fakePassword').show().blur();
  }
}

// marquee navigaton and autoplay
$(function() {
  var marqueeInterval, m = '#marquee', nb = '#marquee .next-button';

  // setup marquee buttons
  $(m).find('.prev-button, .next-button').click(function(e) {
    var methodA, methodB, slide, caption;

    if (e) { e.preventDefault(); }

    methodA = $(this).hasClass('next-button') ? 'next' : 'prev';
    methodB = methodA == 'next' ? 'prevAll' : 'nextAll';
    slide   = $('#marquee .slide:visible');
    number  = slide.attr('id').match(/slide(\d+)/)[1];
    caption = $('#marq_caption_' + number);

    $('#marquee .slide, #marquee .caption').fadeOut(200);

    if (slide[methodA]().length) {
      // go to next
      slide.add(caption)[methodA]().fadeIn(300);
    } else {
      // wrap around
      slide[methodB]('.slide').last().fadeIn(300);
      caption[methodB]('.caption').last().fadeIn(300);
    }
  });

  // autoplay the marquee (trigger the "next" button every 7 seconds)
  marqueeInterval = setInterval(function() { $(nb).click(); }, 7000);

  // if user mouses over marquee, stop cycling
  $(m).hover(function() { clearInterval(marqueeInterval); });
});


// Push them Gallery buttons away from the gang!
$(function() {
    var gal   = $('#contentFeed .gallery'),
        // make sure to only select the #contentFeed .gallery .(next|prev)-button elements!
        next  = gal.find('.next-button'),
        prev  = gal.find('.prev-button'),
        rows  = gal.find('.row'),
        mid   = rows.eq(Math.floor(rows.length / 2));

  if (!(jQuery.browser.msie && jQuery.browser.version < 8)) {
    prev.add(mid.find('.column.first')).mouseenter(function() {
      prev.stop().animate({left:'6px'}, 200);
    }).mouseleave(function() {
      prev.stop().animate({left:'36px'}, 200);
    });
    next.add(mid.find('.column.last')).mouseenter(function() {
      next.stop().animate({right:'7px'}, 200);
    }).mouseleave(function() {
      next.stop().animate({right:'37px'}, 200);
    });
  }
});

// FEATURES MENU
$(function() {
	
  var 	$nav = $('#featuresNav'), 
  		$feat = $('#features');
  var __features_clear = true;
  var $featCurrent = '#features_winners';
 
  if ($nav.length && $feat.length) {	
  	
  	// VEGAS BABY.
  	if ($feat.hasClass('vegas')) {
		$cityId = $('#homecity').val();


 		if ($feat.find('.slides').children(':visible').length<1) {
  			if ($cityId!='0') {
  				$feat.find('.slides').children('.featuredCrew'+$cityId).show();
  			} else {
 				$feat.find('.slides').children(':first').show();
 			}
 		}
  		
 	    $nav.find('li a').click(function(e) {
 	    	
	      e.preventDefault();
	      if(!__features_clear)
	        return;
	      $nav.find('.current').removeClass('current'), $(this).closest('li').addClass('current');
	      
	      $new = $(this).attr('href');
	      $feat.find('.slides').children(':visible').fadeOut(), 
	      $slides = $feat.find('.slides').children().remove();

	      $($featCurrent).append($slides);
		  $slides = $($new).children().remove();

		  $feat.find('.slides').append($slides);
		  
		  setTimeout(function(){ 

			  switch ($new) {
			  	case '#features_vegas':
			  		$feat.find('.slides :hidden').fadeIn();
			  		$feat.find('.prev-button, .next-button').hide(); break;
			  	case '#features_wildcards':
			  	case '#features_winners':
					if ($feat.find('.slides').children('.featuredCrew'+$cityId).length>0) {
		  				$feat.find('.slides').children('.featuredCrew'+$cityId).fadeIn();
		  			} else {
		 				$feat.find('.slides').children(':first').fadeIn();
		 			}
			  		$feat.find('.prev-button, .next-button').show(); break;
			  }

			}, 200);
		  
		  

	      $featCurrent = $new;

	      __features_clear = false;
	      setTimeout(function(){ __features_clear = true; }, 410);
	      
	    });
 		
		$feat.find('.prev-button, .next-button').click(function(e) {
			      e.preventDefault();
			      if(!__features_clear)
			        return;
			      var current = $('#features .slides').find('.slide:visible').fadeOut(),
			          type    = $(this).attr('class').match(/(\w+)-button/)[1],
			          opType  = type == 'next' ? 'prevAll' : 'nextAll';
			      if (current[type]().length) {
			        current[type]().fadeIn();
			      } else {
			        current[opType]().last().fadeIn();
			      }
			      __features_clear = false;
			      setTimeout(function(){ __features_clear = true; }, 410);
		}); 
		 		
  	} else {

	    $nav.find('li a').click(function(e) {
	      e.preventDefault();
	      if(!__features_clear)
	        return;
	      $nav.find('.current').removeClass('current'), $(this).closest('li').addClass('current');
	      $feat.find('.slide:visible').fadeOut(), $($(this).attr('href')).fadeIn();
	      __features_clear = false;
	      setTimeout(function(){ __features_clear = true; }, 410);
	    });
	    $feat.find('.prev-button, .next-button').click(function(e) {
	      e.preventDefault();
	      if(!__features_clear)
	        return;
	      var current = $feat.find('.slide:visible').fadeOut(),
	          curLink = $nav.find('.current').removeClass('current'),
	          type    = $(this).attr('class').match(/(\w+)-button/)[1],
	          opType  = type == 'next' ? 'prevAll' : 'nextAll';
	      if (current[type]().length) {
	        curLink[type]().addClass('current');
	        current[type]().fadeIn();
	      } else {
	        curLink[opType]().last().addClass('current');
	        current[opType]().last().fadeIn();
	      }
	      __features_clear = false;
	      setTimeout(function(){ __features_clear = true; }, 410);
	    });
    
    }
  }
});



function defaultValues() {
	$('input[data-default], textarea[data-default]').live('focus', function() {
		var input = $(this);
		if (this.value == input.attr('data-default')) { this.value = ''; }
	});
	$('input[data-default], textarea[data-default]').live('blur', function() {
		var input = $(this);
		if (this.value == '') { this.value = input.attr('data-default'); }
	});
}

// DEFAULT VALUES FOR FORM INPUTS
$(function () { defaultValues(); });

// HANDLE CITY LOCALE MENU
$(function() {
  if ($('#city_locale').length) {
    var $cur  = $('#city_locale'),
        $ind  = $cur.find('.indicator'),
        $menu = $('#pickYourLocale');

    $cur.click(function(e) {
      e.preventDefault();
      if (!$cur.hasClass('selected')) { $cur.addClass('shadowed selected'); }
      if ($menu.is(':visible')) { $ind.html('+'), $menu.slideUp(200); }
      else { $ind.html('&ndash;'), $menu.slideDown(200); }
    });
  }
});

function crewslug()
{
	$.ajax($('#crewurl').val() + 'crews/slug', {
		data: 'data[Crews][name]=' + $('#crewname').val() + '&data[Crews][cities_id]=' + $('#crewcity').val(),
		dataType: 'html',
		success: function (data)
		{
			$('#crewslug').html(data);
		},
		type: 'POST'
	});
}

$('input#crewname').blur(crewslug);
$('select#crewcity').change(crewslug);
$(function ()
{
	if ($('#crewurl').length && '' != $('#crewname').val() && '' != $('#crewcity').val())
	{
		crewslug();
	}
});

$('a.reply-button').live('click', function ()
{
	$(this).closest('div.details').nextAll('form.post-a-comment-form').show(300);
	return false;
});

$('#crewGallery a.first').click(function ()
{
	$('#crewGallery a.last').removeClass('current');
	$(this).addClass('current');
	
	$('#crewGallery').children('.gallery').last().hide();
	$('#crewGallery').children('.gallery').first().show();
	
	return false;
});

$('#crewGallery a.last').click(function ()
{
	$('#crewGallery a.first').removeClass('current');
	$(this).addClass('current');
	
	$('#crewGallery').children('.gallery').first().hide();
	$('#crewGallery').children('.gallery').last().show();
	
	return false;
});

//Home feed functions
function loadHomeFeedPage(section, page, action, delta, callback)
{
	var current = $('#' + section + ' #' + page).val();
	
	if (current)
	{
		if (!isNaN(delta))
		{
			current = parseInt(current) + delta;
		}
		$.ajax($('#happenings #homeurl').val() + 'home/' + action + '/' + $('#happenings #homecity').val() + '/' + current,
		{
			dataType: 'html',
			success: function (data)
			{
				$('#' + section).html(data);
				if (callback && typeof callback === 'function') { callback(); } // scuse my cruft
			}
		});
	}
	
	return true;
}

$(function ()
{
	loadHomeFeedPage('contentFeed', 'homepagegallery', $('#default_gallery_view').val(), null, agb.addCFP); // scuse my cruft
	loadHomeFeedPage('whatsHappening', 'homepagefeed', 'feed');
	loadHomeFeedPage('leadingCrews', 'homepagecrews', 'topcrews');
});

//Crew feed functions
function loadCrewFeedPage()
{
	var page = $('#crewFeed .crewfeed').length;
	
	if (page)
	{
		$.ajax($('#crewFeed #crewurl').val() + 'crews/feed/' + $('#crewFeed #crewid').val() + '/' + page + '/0',
		{
			dataType: 'html',
			success: function (data)
			{
				if (data)
				{
					$('#crewFeed .crewfeed').last().html(data);
				}
				else
				{
					$('#crewFeed #loadMoreActivityFeed').hide();
				}
			}
		});
	}
	
	return true;
}

$(loadCrewFeedPage);
$('#loadMoreActivityFeed a').click(function ()
{
	loadCrewFeedPage();
	
	return false;
});


// Initialize modals (shadow-boxes, light-boxes, whatever…)
$(function() {
	
	//--------------
	//Begin handling of auto-open lightbox deep links.  This works by inserting a link that simualtes
	//a real link, and then triggering it.
	var hash = window.location.hash;
	if (hash) {
		
		//get id from hash.  Assumes there is only one variable
		hash = hash.split('=');
		key = hash[0].substr(1);
		val = hash[1];
		
		//gallery
		if (key == 'gallery_id') {
			var url = '/medias/view/'+val;
			launchDeepLink(url, 'gallery');
		}
	}
	
	//-------------
	//Init fancybox
	
  if ($.fancybox) {
    var onStart, onComplete, commonOptions;

    onStart = function(a,i,opts) {
      $('#fancybox-left').prepend( '<div class="left-bottom-wing" />');
      $('#fancybox-right').prepend('<div class="right-bottom-wing" />');
    }

    onComplete = function(a,i,opts) {
      defaultValues();
      if (opts.titleShow && opts.title && opts.title !== '') {
        $('#fancybox-content .gallery-media').css({ 'padding-top':'50px' });
        $('#fancybox-title').addClass('heading').prepend('<span class="left-wing" />');
      }
    }

    commonOptions = {
      'centerOnScroll'  : true,
      'padding'         : 0,
      onStart           : onStart,
      onComplete        : onComplete
    }

	//add listeners everywhere
	var addListeners = function() {
		$('.gallery .lightbox-it, .gallery .vote').fancybox(commonOptions);
	    $('#crewQuickGallery .lightbox-it').fancybox(commonOptions);
	    $('#crewFeed .lightbox-it').fancybox(commonOptions);
	    $('#completedChallenges .lightbox-it').fancybox(commonOptions);
	    $('.fan-uploads .lightbox-it').fancybox($.extend({}, commonOptions, {
	      'title'           : 'Fan Uploads Awaiting Approval',
	      'titlePosition'   : 'top'
	    }));
	    //$('.compChall li a').fancybox(commonOptions);
			$('#whatsHappening a.lightbox-it').fancybox(commonOptions);
	    $('#leadingCrews .entry .first a').fancybox(commonOptions);
	    $('.leftBar213 a[href^="/users/feature/"], .leftBar213 a[href^="/crews/feature/"]').fancybox(commonOptions);
	}
	addListeners();
	
	//Invoking listners from ajax complete because it doesn't support "live" method and my attempts to enable it
	//using http://stackoverflow.com/questions/2532070/fancybox-getting-fancybox-to-bind-using-live-to-items-being-loaded-onto-the-pa
	//failed.
	$('body').bind('ajaxComplete', function() {
		addListeners();
	});
  }

});

//re-parse all like buttons anytime there is an AJAX complete.  A little wasteful but will make sure
//all instances get caught regardless of future developers who may be ignorant of this requirement
$(function() {
	$('body').bind('ajaxComplete', function() {
		try{ FB.XFBML.parse(); }
		catch(ex){}
	});
});

// handle one click links via ajax, like votes
$(function() {
	
  // get all of em
  $('.ajax-link').live('click',function(e) {
    
	// grab the clicked element
    var el  = $(this),

	// grab its href attribute
	url = el.attr('href'),
	
	// text to show on successful action, basically whenever it is clicked
	// e.g. <a data-success-text='It worked!'>Click Me</a>
	successText   = el.data('success-text'),
	
	// text to show on duplicate action, whenever the user has already voted, for instance
	// e.g. <a data-duplicate-text='You have already done this.'>Click Me</a>
	duplicateText = el.data('duplicate-text');
	if (!duplicateText) duplicateText = "You've already voted";

    // prevent the browser from just following the href and also, prevent duplicate clicks
    e.preventDefault();
	el.die();

    // if already disabled, do nothing
    if (el.hasClass('disabled')) return;

    // change label to indicate voting
    el.addClass('disabled');

    // set the text to the action-successful text
    el.text(successText);

    // GET submit to location as AJAX
    $.get(url, function(data) {
	
		// handle responses
		// if (data.stat == 'ok') 
		if (data.type == 'already_voted') {
			if (duplicateText) alert(duplicateText);
		}
	
		//grey out the button
		if (el.hasClass('button')) el.addClass('gray-button');

    }, 'json');
  });
});

//create and execute a fake link for the purpose of deep linking to AJAX
function launchDeepLink(url, parent_class) {
	var html = '<span class="'+parent_class+' deep-link" style="display:none"><a href="'+url+'" class="lightbox-it" rel="crew-gallery">Empty</a></span>';
	$('body').prepend(html);
	setTimeout(function() {
		$('.deep-link a').trigger('click');
	}, 500);
}

//handle the zipcode lookup during registration
$(function() {
	
	//don't continue if not on registration page
	if (!$('#BasicRegistration').length) return;
	
	//vars
	var zip_field = $('#BasicRegistration .eachRow.zip input');
	var city_field = $('#BasicRegistration .eachRow.city .field');
	
	//hide the market city by default
	$('#BasicRegistration .eachRow.city').hide(0);
	
	//listen for updates on the zipcode, wait till there is 5
	var check = function() {
		
		//hide or show
		var zip = zip_field.val();
		if (zip.length == 5) {
			
			//disable zip input
			$('#BasicRegistration .eachRow.city').show(300);
			zip_field.attr("disabled", "true");
			
			//submit request to the server
			city_field.text('Finding closest...');
			$.post('/users/get_city_from_zip', {zip:zip}, function(data) {
				
				//re enable field
				zip_field.removeAttr("disabled");
				
				//display status
				if (data.stat == 'ca') {
					city_field.text('Sorry, California residents are not elligible to participate.');
				} else if (data.stat == 'ok') {
					city_field.text(data.city+', '+data.state);
					city_field.append('<input type="hidden" name="data[Users][cities_id]" value="'+data.id+'" />');
				} else {
					city_field.text('A matching city could not be found.');
				}
				
			},'json');
			
		} else {
			$('#BasicRegistration .eachRow.city').hide(300);
			city_field.text('');
		}
		
	};
	
	//trigger the check function, including on load incase the page is autofilled from reload
	// but only trigger if we have the DOM elements we expect!
	if (zip_field.length && city_field.length) {
	  zip_field.change(check);
	  check();
	}
	
});

//launch the QR code window
$(function() {
	$('#crew_toolbox .qr_code a').click(function(e) {
		e.preventDefault();
		
		//open window
		var dst = $(this).attr('href');
		var win = window.open('/crews/qr?id='+escape(dst),'qr',"menubar=0,resizable=1,width=500,height=500");
		
	});
});

//fill images in the marquee
$(function() {
  // only if there is a marquee with slides
  if (!$('#marquee .slides').length) return;

  // vars
  var parent_h = $('#marquee .slides').height();

  // loop through each marquee slide image
  $('#marquee .slide img').each(function() {
    var img = $(this), interval, offset;

    // wait for it to load, using interval cause it's reportedly more dependable
    interval = setInterval(function() {
      if (!img.height()) { return; } else { clearInterval(interval); }

      // position it
      offset = (parent_h - img.height()) / 2;
      if (offset > 0) img.css('paddingTop', offset + 'px');
    }, 10);
  });
});

//make the filters on the crew search work
$(function() {
	
	//only on the crew page
	if ($('#TheCrewSearch').length == 0) return;
	
	//the pulldowns
	$('form#crewfilter select').change(function () {
		$('form#crewfilter').submit();
	});
	
	//make pagination repost the crew filter.  Doing it this way because submitting this form as GET
	//looks really messy.  And refactoring it isn't worth the time at this point
	$('.paginator a').click(function(e) {
		e.preventDefault();
		var url = $(this).attr('href');
		$('form#crewfilter').attr('action', url);
		$('form#crewfilter').submit();
	});
});







//
//
//
//
// BURNER'S
// CORNER
// WON'T
// MESS
// WITH
// YOU
var agb = {};
(function ($) {
	var thisWin = $(window);
	
	
	
	//
	//
	// FORGOT PASSWORD
	(function () {
		
		
		//
		// STATE
		var isOpen = false;
		
		
		//
		// ELEMENTS
		var link = $('#forgot_link');
		var view = $('#forgot_view');
		var form, email, closeButton, caption, sendButton, successMsg, okayButton;
		
		
		//
		// METHODS
		// one time per page load
		var init = function () {
			build();
			addEventListeners();
		};
		// assemble elements
		var build = function () {
			form        = $('#forgot_form');
			email       = $('#forgot_email');
			closeButton = $('#forgot_close');
			caption     = form.children('p');
			sendButton  = form.children('button');
			successMsg  = $('#forgot_success');
			okayThx     = successMsg.children('form');
		};
		// reset forgot dialog
		var reset = function () {
			successMsg.hide();
			form.show();
			caption.text("Give us your email and we'll help you reset your password");
			email.val('EMAIL ADDRESS');
		};
		
		
		//
		// HANDLERS
		// open dialog
		var open = function (e) {
			if(e) { e.preventDefault(); }
			if(isOpen) { return; }
			isOpen = true;
			view.show();
		};
		// close dialog
		var close = function (e) {
			if(e) { e.preventDefault(); }
			if(!isOpen) { return; }
			view.hide();
			reset();
			isOpen = false;
		};
		// submit form
		var submitForm = function(e) {
			if(e) { e.preventDefault(); }
			if(!checkEmail()) { return; }
			//submit the form
			$.post(form.attr('action'), form.serialize(), function(data) {
				if (data.stat == 'ok') {
					form.hide();
					successMsg.show();
				} else {
					caption.text('There was a problem with your email');
				}
			}, 'json');
		};
		// did they do email?
		var checkEmail = function () {
			var value = email.val();
			if(!value || value === 'EMAIL ADDRESS') {
				caption.text('Please enter your email address');
				return false;
			}
			return true;
		};
		
		
		//
		// LISTENERS
		var addEventListeners = function () {
			// overrule "Forgot Password" link
			link.bind('click', open);
			// enable close button
			closeButton.bind('click', close);
			// close button for okay
			okayThx.bind('submit', close);
			// we do the form
			form.bind('submit', submitForm);
		};
		
		
		//
		// EXECUTION
		if(link && view) { init(); }
		
		
		
	})();
	// END FORGOT PASSWORD
	//
	//
	
	
	
	//
	//
	// POLL & SURVEY RESULTS
	agb.fillResults = function (resultsList) {
		if (!resultsList) { return false; }
		var foo = new ResultsFill();
		foo.init(resultsList);
	};
	var ResultsFill = function () {
		
		
		//
		// VARIABLES
		var listTop, boxWidth;
		
		
		//
		// ELEMENTS
		var list, boxes;
		
		
		//
		// METHODS
		// interface
		this.init = function (resultsList) {
			if (!resultsList) { return false; }
			build(resultsList);
			addEventListeners();
			scrollHandler();
		};
		// assemble elements & variables
		var build = function (resultsList) {
			list = resultsList;
			boxes = list.children('li');
			listTop = list.offset().top;
			boxWidth = $(boxes[0]).width();
		};
		// check if poll results have scrolled into view
		var checkScrolled = function () {
			var winTop = thisWin.scrollTop();
			var winBottom = winTop + thisWin.height();
			return (listTop <= winBottom);
		};
		// fill poll result bars
		var fillBars = function () {
			for (var i = 0, len = boxes.length; i < len; i++) {
				var bar = $(boxes[i]).children('div');
				var percent = parseInt(bar.attr('data-percent'), 10);
				if (typeof percent !== 'number') { continue; } 
				var barWidth = boxWidth*(percent/100);
				bar.animate({width:barWidth+'px'}, 1000);
			}
		};
		
		
		//
		// HANDLERS
		// activate poll results if visible
		var scrollHandler = function () {
			if (checkScrolled()) {
				// only needs to be seen once
				thisWin.unbind('scroll', scrollHandler);
				fillBars();
			}
		};
		
		
		//
		// LISTENERS
		var addEventListeners = function () {
			// check if visible each time user scrolls
			thisWin.bind('scroll', scrollHandler);
		};
		
		
	};
	
	
	
	//
	//
	// VIDEO MADNESS
	// a Page has a Box and a Gallery (which has many Sets)
	// 
	// [ page [ box ] [ gallery [ set ] [ set ] [ ... ] ] ]
	//
	(function () {
		agb.videoPage = {};
		var vPage, vBox, vGallery;
		
		// initialized by views/medias/videos.php
		agb.videoPage.init = function (vidID) {
			vPage = new VideoPage();
			vPage.init(vidID);
		};
		
		// entire medias/videos
		function VideoPage() {
			var video_box = $('#video_marquee');
			var video_gallery = $('#video_contentFeed');
			this.init = function (vidID) {
				// got the important bits?
				if (video_box && video_gallery) {
					// fire up the box and gallery
					vBox = new Box(video_box);
					vGallery = new Gallery(video_gallery);
					vBox.init();
					vGallery.init(vidID);
				}
			};
		}
		
		// the video player box
		function Box(box) {
			if (!box) { return; }
			var redWrap, vidDrop, vidDiv, vidPlayer, vidMeta, nextBtn, prevBtn, loadInd;
			this.init = function () {
				vidDrop = box.find('#video_drop');
				redWrap = box.find('div.popup');
				prevBtn = box.find('a.prev-button');
				nextBtn = box.find('a.next-button');
				loadInd = box.find('#load_ind');
				buildNav();
			};
			this.loadURL = function (url) {
				if (!url) { return false; }
				// clear out old video
				if (vidDiv) { vidDiv.html(' '); }
				// show loading indicator
				loadInd.css({display:'block'});
				// get that video
				vidDrop.load(url+' #vid_div', handleVideo);
			};
			this.atFirstVid = function () {
				prevBtn.css({display:'none'});
				nextBtn.css({display:'block'});
			};
			this.atMidVid = function () {
				prevBtn.css({display:'block'});
				nextBtn.css({display:'block'});
			};
			this.atLastVid = function () {
				prevBtn.css({display:'block'});
				nextBtn.css({display:'none'});
			};
			var handleVideo = function (e) {
				// hide loading indicator
				loadInd.css({display:'none'});
				// start that
				vidPlayer = VideoJS.setup('viddy');
				// update variables
				vidDiv = $('#vid_div');
				vidMeta = $('#vid_meta');
				var vidHeight = vidDiv.data('height');
				var metaHeight = vidMeta.height();
				// match black
				vidDrop.height(vidHeight);
				// match red
				redWrap.height(vidHeight + metaHeight);
				// match gray
				box.height(redWrap.height() - 25);

				// no internet explorer
				if ($.browser.msie) {
					var ver = 9;
					try {
						ver = parseInt($.browser.version,10);
					} catch	(e) {
						// well, hope for the best
					}	
					if (ver < 9) {
						// fix knock right bug
						vidDiv.find('object').css({
							position: 'relative',
							left: '-360px'
						});
					}
				}
				
				/*
				// vertical center
				vidDiv.css({
					position: 'relative',
					top: (vidDrop.height() - vidDiv.data('height')) / 2
				});
				*/
			};
			var buildNav = function () {
				nextBtn.bind('click', nextClick);
				prevBtn.bind('click', prevClick);
			};
			var nextClick = function (e) {
				if (e) { e.preventDefault(); }
				vGallery.nextVid();
			};
			var prevClick = function (e) {
				if (e) { e.preventDefault(); }
				vGallery.prevVid();
			};
		}
		
		// the thumb gallery area
		function Gallery(gallery) {
			if (!gallery) { return; }
			var sets, currentSet, filterBtns;
			this.init = function (vidID) {
				buildSets();
				buildFilters();
				if (!vidID) {
					// just show first set
					sets[0].show();
				} else {
					// pass along the hunt
					showSetWithVid(vidID);
				}
			};
			this.nextVid = function () {
				if (sets[currentSet]) {
					sets[currentSet].nextVid();
				}
			};
			this.prevVid = function () {
				if (sets[currentSet]) {
					sets[currentSet].prevVid();
				}
			};
			var buildSets = function () {
				currentSet = 0;
				sets = gallery.find('div > div > div > div.slides');
				for (var i = 0, len = sets.length; i < len; i++) {
					sets[i] = new Set($(sets[i]));
					sets[i].init();
				}
				// no sets found? that sucks, but don't let it break js
				if (!sets) { sets = [{show:function () {}}]; }
			};
			var buildFilters = function () {
				// store filter buttons and add click handlers
				filterBtns = gallery.find('div > div > ul.nav > li > a');
				for (var i = 0, len = filterBtns.length; i < len; i++) {
					var button = $(filterBtns[i]);
					button.bind('click', makeFilterClick(button));
				}
			};
			var makeFilterClick = function (button) {
				return function (e) {
					if (e) { e.preventDefault(); }
					filterBtns.addClass('gray-button');
					button.removeClass('gray-button');
					filterSets(button.attr('data-filter'));
				};
			};
			var filterSets = function (filter) {
				// walk through sets, show the match
				var found = false;
				for (var i = 0, len = sets.length; i < len; i++) {
					var set = sets[i];
					if (set.filter === filter) {
						if (i === currentSet) { return; }
						currentSet = i;
						set.show();
						found = true;
					} else {
						set.hide();
					}
				}
				// not found? bad markup. show first set.
				if (!found) { sets[0].show(); }
			};
			var showSetWithVid = function (vidID) {
				if (!vidID) { sets[0].show(); }
				for (var i = 0, len = sets.length; i < len; i++) {
					var vidIndex = sets[i].findVid(vidID);
					if (vidIndex >= 0) {
						sets[i].show(vidIndex);
						return;
					}
				}
				// no videos found? show first set
				sets[0].show();
			};
		}
		
		// a set of thumbs
		function Set(set) {
			if(!set) { return; }
			var thumbs, thumbCount, currentThumb;
			this.init = function () {
				this.filter = set.data('filter');
				setupThumbs();
			};
			this.nextVid = function () {
				var next = getCurrentIndex() + 1;
				if (next < thumbCount)
				selectThumb(next);
			};
			this.prevVid = function () {
				var prev = getCurrentIndex() - 1;
				if (prev >= 0)
				selectThumb(prev);
			};
			this.hide = function () {
				set.css({display:'none'});
				resetThumbs();
			};
			this.show = function (index) {
				set.css({display:'block'});
				selectThumb(index || 0);
			};
			this.findVid = function (vidID) {
				// search thumb for vid id, return index
				for (var i = 0; i < thumbCount; i++) {
					var thumb = $(thumbs[i]);
					if (!thumb) { continue; }
					if (vidID === thumb.data('id')) {
						return i;
					}
				}
				return -1;
			};
			var setupThumbs = function () {
				// store thumbs, add listeners & data
				thumbs = set.find('a');
				thumbCount = thumbs.length;
				for (var i = 0; i < thumbCount; i++) {
					var thumb = $(thumbs[i]);
					thumb.infoPane = thumb.find('div.video_rollover');
					thumb.click(makeThumbClick(thumb));
					thumb.hover(makeThumbMsIn(thumb), makeThumbMsOut(thumb));
					thumb.attr('data-index', i);
				}
			};
			var makeThumbClick = function (thumb) {
				return function (e) {
					if (e) { e.preventDefault(); }
					selectThumb(thumb.data('index'));
				};
			};
			var makeThumbMsIn = function (thumb) {
				return function (e) {
					if (e) { e.preventDefault(); }
					thumb.infoPane.animate({top:'70px'});
				};
			};
			var makeThumbMsOut = function (thumb) {
				return function (e) {
					if (e) { e.preventDefault(); }
					thumb.infoPane.animate({top:'125px'});
				};
			};
			var selectThumb = function (index) {
				// make sure we got what we need
				if (index === currentThumb) { return; }
				var thumb = $(thumbs[index]);
				if (!thumb) { return; }
				// update overlays
				thumbs.children('span').css({display:'none'}).data('selected', false);
				thumb.children('span').css({display:'block'}).data('selected', true);
				// update current position
				currentThumb = index;
				checkPositionForBox();
				// get and load video url
				var target = thumb.attr('href');
				if (!target) { return; }
				vBox.loadURL(target);
				// update url
				if (!history.replaceState || !window.location.pathname) { return; }
				var vidID = thumb.data('id');
				if (!vidID) { vidID = '_'; }
				if (window.location.pathname === '/medias/videos') {
					history.replaceState({}, vidID, 'videos/'+vidID);
				} else {
					history.replaceState({}, vidID, vidID);
				}
			};
			var checkPositionForBox = function () {
				// check position within set and tell Box
				var current = getCurrentIndex();
				if (current === 0) {
					vBox.atFirstVid();
				} else if (current === thumbCount - 1) {
					vBox.atLastVid();
				} else {
					vBox.atMidVid();
				}
			};
			var resetThumbs = function () {
				// kill all overlays
				thumbs.children('span').css({display:'none'});
				currentThumb = -1;
			};
			var getCurrentIndex = function () {
				// ugh it kept behaving like a string
				return parseInt(currentThumb,10)
			};
		}
		
		
	})();
	// END VIDEO MADNESS
	//
	//
	
	
	
	
	//
	//
	// CHALLENGE ACCORDION
	(function () {
		
		// constants
		var UNIQUE_ID = '#challengeSubmission';
		var FORM      = 'form';
		var SECTIONS  = 'div.each-photo-upload';
		var OPENCLOSE = 'a.open_close';
		var COLLAPSE  = 'div.collapseable';
		var SPEED     = 400;
		
		// the build
		var mediaForm;
		var mediaSecs;
		function init() {
			var chaSub = $(UNIQUE_ID);
			if (!chaSub) { return; }
			var formObj = chaSub.find(FORM);
			if (!formObj) { return; }
			mediaForm = new Form();
			mediaForm.init(formObj);
		}
		
		// main form
		function Form() {
			var isSubmitted = false;
			var form;
			this.init = function (formObj) {
				if (!formObj) { return; }
				form = formObj; 
				addEventListeners();
				buildSections();
			};
			this.checkSubmitted = function () {
				return isSubmitted;
			};
			var buildSections = function () {
				mediaSecs = [];
				var secObjs = form.find(SECTIONS); 
				for (var i = 0, len = secObjs.length; i < len; i++) {
					mediaSecs.push(new Section());
					mediaSecs[i].init($(secObjs[i]));
					mediaSecs[i].collapseIt();
				}
			};
			var addEventListeners = function () {
				form.bind('submit', handleSubmit);
			};
			var handleSubmit = function (e) {
				
				// TODO: check for success?
				
				isSubmitted = true;
			};
		}
		
		// media section
		function Section() {
			var here = this;
			var isExpanded = true;
			var section, collapseable, openClose;
			
			var sectionName;
			
			this.init = function (secObj) {
				if (!secObj) { return; }
				section = secObj;
				openClose = section.find(OPENCLOSE);
				openClose.addClass('this_opened');
				sectionName = section.find('h4').first().text();
				collapseable = section.find(COLLAPSE);
				if (!collapseable) { 
					collapseable = { 
						slideDown: function () {}, 
						slideUp:   function () {} 
					}; 
				}
				addEventListeners();
			};
			this.collapseIt = function () {
				if (!isExpanded) { return; }
				collapseable.slideUp(SPEED, function () {
					isExpanded = false;
				});
				openClose.addClass('this_closed').removeClass('this_opened');
			};
			var collapseAll = function () {
				for (var i = 0, len = mediaSecs.length; i < len; i++) {
					mediaSecs[i].collapseIt();
				}
			};
			var expandThis = function () {
				if (isExpanded) { return; }
				collapseAll();
				collapseable.slideDown(SPEED, function () {
					isExpanded = true;
				});
				openClose.addClass('this_opened').removeClass('this_closed');
			};
			var addEventListeners = function () {
				section.bind('click', handleClick);
				openClose.bind('click', handleOpenClose);
			};
			var handleClick = function (e) {
				if (mediaForm.checkSubmitted()) { return; }
				if (isExpanded) { return; }
				expandThis();
			};
			var handleOpenClose = function (e) {
				if (e) { 
					e.stopPropagation(); 
					e.preventDefault();
				}
				if (mediaForm.checkSubmitted()) { return; }
				if (isExpanded) {
					here.collapseIt();
				} else {
					expandThis();
				}
			};
		}
		
		//
		// EXECUTION		
		$(init);

	})();
	// END ACCORDION
	//
	//



	//
	//
	// VIDEO THUMB PLAYHEADS
	(function () {

		// ADDITION
		var PLAYHEAD = '<span class="playhead"></span>';
		
		// ACTION
		function addPlayheads(workspace) {
			if (!workspace)        { return; }
			if (!workspace.length) { return; }
			var thumbs = workspace.find('div.gallery').find('div.video').find('img');
			for (var i = 0, len = thumbs.length; i < len; i++) {
				thumbs.eq(i).before(PLAYHEAD);
			}
		}

		// EXECUTION
		$(function () {
			addPlayheads($('#crewGallery'));
		});

		// CRUFFFFT... home page is AJAXed
		agb.addCFP = function () {
			addPlayheads($('#contentFeed'));
		};

	})();
	// END PLAYHEADS
	//
	//

	
})(jQuery);
// END BURN
//
//
//


// Prevent Duplicate submissions
$(function(){
    $('.click-happy').live('submit', function(){
        var _target = $(this).find('.click-happy-submit');
        var _label = '';
        switch(_target.html().toLowerCase()){
            case 'upload':
                _label = 'Uploading'; break;
            case 'submit':
                _label = 'Submitting'; break;
            default:
                _label = 'Submitting'; break;
        }
        _target.html(_label).addClass('gray-button').click(function(e){ e.preventDefault(); });
    });
    
    $('.global-error, .global-message').delay(800).fadeIn(500).delay(5000).fadeOut(350);
    
    $('#pollQuestions form').submit(function(e){
        e.preventDefault();

        var postData = {}; postData['PollVotes'] = {}; postData['PollVotes']['poll_choices_id'] = $('.poll-question input:checked').val();

        $.post('/poll_votes/cast/', {data: postData}, function(_data){
                $('#pollQuestions .poll-question').parent().html(_data).delay(200);
                agb.fillResults($("#poll_results"));
            });
    });
    
    $('#messages-inbox td').click(function(){
        if($(this).parent().data('msgid'))
            location.href = '/users/messages/'+$(this).parent().data('msgid');
        });
        
    $('.message-view a').each(function(){ $(this).attr('target', '_blank'); }); 
    
});






