if(!butterfinger){var butterfinger={};}
butterfinger.bfdl=function(me){
	
	$(document).ready(function(){
	
		me=butterfinger.bfdl;
		
		// add target="_blank" to all links with rel="external"
		$("a[rel='external']").attr("target", "_blank");

		
		//set up root var for different environments
		var root = window.location.host;
		
		// Init Home page scroller for Backstory items
		initHomeCarousel();
		
		// Enable Homepage video switcher from thumbs
		initHomeVids();
		
		// Init News Ticker on Homepage
		initTicker();
		
		//Init Backstory Page functionality
		initBackstory();
		
		//Init Rating Functionality
		initRatings();
		
		//Show Comment Fields
		initComments();

		initKeySearchGame();
	});
	
	var initHomeCarousel = function() {
		
		// container var
		var el = $('.home #content_sub');
		var items = $('.home #content_sub ul li');
		if(el.length > 0) {
			if(items.size() > 5){
				$('#prev, #next').show();
			}
			$(el).find('.wrapper').jCarouselLite({
				btnPrev: "#prev",
				btnNext: "#next",
				circular: true,
				visible: 5, 
				start: 0
			});

		}
		
	};
	
	var initHomeVids = function() {
		
		// clicked element
		var el = $('.home #content_feature li a');
		el.click(function(e) {
			
			//console.log($(this).attr('href'));
			// remove active class from matched elements
			$(el).removeClass('active');
			
			//add class to clicked element
			$(this).addClass('active');
			
			//remove swf from embed - removes element it replaced, also
			swfobject.removeSWF('flashContent');
			
			//re-add flashContent div
			$('#videoContainer').append('<div id="flashContent"></div>');
			
			// Re-embed new swf
			var params = { allowScriptAccess: "always", allowFullScreen: "true", wmode: "opaque" };
			var atts = { id: "flashContent" };
			swfobject.embedSWF($(this).attr('href'), "flashContent", "419", "254", "8", "expressInstall.swf", null, params, atts);
			
			// prevent click
			e.preventDefault();
		});
	
	};
	
	var initTicker = function() {
	
		$("#ticker ul").liScroll({travelocity: 0.1}); 
		
	}
	
	var initBackstory = function() {
		
		// clickable element
		var el = $('.backstory #content_sub li a');
		
		// container var for slider
		var scroll = $('.backstory #content_sub');
		if (scroll.length > 0) {
			
			$(scroll).find('.wrapper').jCarouselLite({
				btnPrev: "#prev",
				btnNext: "#next",
				circular: false,
				visible: 5, 
				start: 0
			});
		
		}
		
		//click on an element
		el.click(function(e) {
			
			// if already active, do nothing
			if($($(this).attr('href')).hasClass('active')) {
			
			} 
			
			// if not active, switch feature item
			else {
			
				//remove class from feature item
				$('#content_main li').removeClass('active');
				
				// add class to selected feature item
				$($(this).attr('href')).addClass('active');
				
				// remove class from clickable elements
				$(el).removeClass('active');
				
				// add class to clicked element
				$(this).addClass('active');
				
				// fade out current feature item
				$('#content_main li:visible').fadeOut(800);
				
				//fade in selected feature item
				$($(this).attr('href')).fadeIn(800);
				//console.log($(this).attr('href'));
			}
			
			// prevent click
			e.preventDefault();
		});
	
	};
	
	var initRatings = function() {
		
		// container var
		var container = $('#rate');
		
		// get body id
		var page = getBodyId();

		// click rating button
		$(container).find('a').click(function(e) {
			
			// Set vidID based on body ID
			var vidID = page+'sVideo';
			var action = '';			
			
			//set values for tu/td to send to server
			if(e.currentTarget.id == 'tu') {
				action = "approve";				
			} else if(e.currentTarget.id == 'td') {
				action = "disapprove";
			}
			
			// create data string to send via ajax
			var dataToPost = {
				"vid": vidID, 
				"action": action
			}
			
			//console.log($(this).attr('id'));
			//console.log(vidID);
			//console.log(tu);
			//console.log(td);
			
			// Hide #not-rated, show #waiting
			$('#not-rated').hide();
			$('#waiting').show();
			
			// send ajax request
			$.ajax({
				type: "POST",
				url: "handlers/RatingHandler.ashx",
				//contentType: "application/json; charset=utf-8",
				//dataType: "json", 
				data: dataToPost, 
				success: function(result) {
					//console.log(result.Approved);
					
					//Hide #waiting, show #rated
					$('#waiting').hide();
					$('#rated').show();
					//if(result.replace(/\s/g,"") != ''){
						$('#rated').find('li.tu').html('<span class="thumbs-up">Thumbs Up</span> '+result.Approved);
						$('#rated').find('li.td').html('<span class="thumbs-down">Thumbs Down</span> '+result.Disapproved);
					//} else {
					//	$('#rated').replaceWith('<p>Error occured. Please try Again.</p>');
					//}
				},
				error: function() {
					$('#rated').replaceWith('<p>Error occured. Please try Again.</p>');
				}
			});
			
			//prevent click
			e.preventDefault();
		});
			
	};
	
	var initComments = function() {
		
		// clickable element
		var el = $('a#add-comment');
		
		// get body id
		var page = getBodyId();
		
		//init errorMsg var
		var errorMsg = '';
		
		// element is clicked
		el.click(function(e) {
		
			// slide down comment form
			$('#comment-form').slideDown();
			
			// prevent click
			e.preventDefault();
		});
		
		// Set vidID based on body ID
		var vidID = page+'sVideo';

		$('#comment-form').find('.submit').click(function(e){
			//console.log('clicked');
			
			// set vars for checking conditions
			var nPost = $('#comment-form input[name=name]').val();
			var ePost = $('#comment-form input[name=email]').val();
			var cPost = $('#comment-form textarea[name=commentPost]').val();
			var isFB = $('#comment-form input[name=ctl00$content$chkPublishToFacebook]:checked').val();
			var fbID = '';
			//console.log(isFB);
			
			// Set different client side checks for fb vs not fb
			/*if(isFB){
				//Catch exceptions for FB users and build error messages
				if(nPost == ''){
					errorMsg = '-Name is Required.'+"\n";
				}
				if(nPost != '' && nPost.length >30){
					errorMsg = '-Name must be under 30 characters.'+"\n";
				}
				if(cPost == '') {
					errorMsg +='-Comment is Required.'+"\n";
				}
				if(cPost != '' && cPost.length >600) {
					errorMsg +='-Comment must be under 600 characters.'+"\n";
				}
			//} else {*/
				
				//Catch exceptions for other users and build error messages
				if(nPost == ''){
					errorMsg = '-Name is Required.'+"\n";
				}
				if(nPost != '' && nPost.length >30){
					errorMsg = '-Name must be under 30 characters.'+"\n";
				}
				if(ePost == ''){
					errorMsg +='-Email Address is Required.'+"\n";
				} else if(ePost != '' && !isValidEmailAddress(ePost)) {
					errorMsg +='-Invalid Email Address'+"\n";
				}
				if(cPost.replace(/\s/g,"") == '') {
					errorMsg +='-Comment is Required.'+"\n";
				}
				if(cPost != '' && cPost.length >600) {
					errorMsg +='-Comment must be under 600 characters.'+"\n";
				}
			//}

			// If no error messages, continue with ajax post
			if(errorMsg) {
				alert(errorMsg);
				errorMsg = '';
				e.preventDefault();
			} else {
				
				// build data to send
				var dataToPost = {
					"vid": vidID, 
					"name": nPost,
					"email": ePost,
					"commentPost": cPost, 
					"fbid": fbID
				}
				
				// Handle Ajax Request
				$.ajax({
					type: "POST",
					url: "handlers/CommentHandler.ashx",
					data: dataToPost, 
					success: function(result) {
						//console.log(result);
						
						// Close form
						//$('#comment-form').slideUp();
						
						// reset form
						//$('#comment-form input[name=name]').val('');
						//$('#comment-form input[name=email]').val('');
						//$('#comment-form textarea[name=commentPost]').val('');
						
						
						if(isFB){
							//console.log(isFB);
							//console.log('call fb_publish');
							fb_publish(cPost);
						} else {
						
							if(result.replace(/\s/g,"") == ''){
							
								// refresh page
								$('#comment-form input[name=name]').val('');
								$('#comment-form input[name=email]').val('');
								$('#comment-form textarea[name=commentPost]').val('');
								window.location.reload();
								//fb_publish();
								
							} else {
								
								alert('-Name is invalid.');
								
							}
						}
						
					}, 
					error: function(){
						
						$('#comment-form').html('<p>There was an error submitting your comment.  Please try again later. </p>');
					}
				});
					
				
				// prevent click
				e.preventDefault();
				
			}
		});
		
		
	}
	
	var initKeySearchGame=function(){
		var $ = document.id;
		$$('#mm_playnow_new,a[rel=modal]').addEvents({
			'click':function(e){
				e.stop();
				showGameModal(this.get('href'));
			}
		});
		/*
		if($$('body.home').length<1){return;}
		if(window.location.hash=='#play'){
			showGameModal($(document).getElement('#iwg_playnow').get('href'));
		}//*/
	};

	var showGameModal=function(url){
		var $ = document.id;
		var dialog = new Element('div');
		var modalHeader = new Element('div',{'class':'modal-header'}).inject(dialog);
		modalHeader.grab(new Element('img',{
			'class':'logo',
			'src':'images/h2modal-logo.png',
			'alt':'Unlock the BUTTERFINGER $1,000,000 Game',
			'width':215,
			'height':127
		}));
		modalHeader.grab(new Element('a',{
			'class':'modal-hide',
			'text':'X'
		}));
		var modalContent = new Element('div',{'class':'modal-content'}).inject(dialog);
		modalContent.grab(new IFrame({
			src:url,
			scrolling:'no',
			frameborder:'0',
			events:{
				load:function(){
					var content = $(this.contentWindow.document.body).getElement('.modal-frameContent');
					this.setStyles({width:content.getStyle('width'),height:content.getStyle('height')});
					modal.position();
				}
			}
		}));
		var modal = new Threshold.Modal(dialog,{dialogPin:false}).show();
	};

	var popup = function(url, name, width, height){
		var oWindow = window.open(url, name, "height=" + height + ", width=" + width + ", top=100, left=100, resizable=yes, scrollable=yes, scrollbars=yes");
		if (oWindow == null) {
			//alert("Your popup blocker won’t allow you access to this window.");
		}  else {
			//continue on
		}
	} 
	
	var commentCallback = function(){
		
		// reset form
		$('#comment-form input[name=name]').val('');
		$('#comment-form input[name=email]').val('');
		$('#comment-form textarea[name=commentPost]').val('');
		window.location.reload();
	}

	var isValidEmailAddress = function(emailAddress) {
		var pattern = new RegExp(/^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/i);
		return pattern.test(emailAddress);
	}
	
	var getBodyId=function(){
		var matches = $('body').attr('class').match(/erik|lou|charisma/i) || [];
		var page = matches.length>0?matches[0]:'';
		return page.replace(/\b[a-z]/g,function(match){return match.toUpperCase();});
	};
	
	// public members
	return{
		popup:popup, 
		commentCallback:commentCallback,
		showGameModal:showGameModal
	};
	
}();


/*!
 * liScroll 1.0
 * Examples and documentation at: 
 * http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html
 * 2007-2010 Gian Carlo Mingati
 * Version: 1.0.2 (30-MARCH-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires:
 * jQuery v1.2.x or later
 * 
 */


jQuery.fn.liScroll = function(settings) {
		settings = jQuery.extend({
		travelocity: 0.07
		}, settings);		
		return this.each(function(){
				var $strip = jQuery(this);
				$strip.addClass("newsticker")
				var stripWidth = 0;
				var $mask = $strip.wrap("<div class='mask'></div>");
				var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
				var containerWidth = $strip.parent().parent().width();	//a.k.a. 'mask' width 	
				$strip.find("li").each(function(i){
				stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar
				});
				$strip.width(stripWidth);			
				var totalTravel = stripWidth+containerWidth;
				var defTiming = totalTravel/settings.travelocity;	// thanks to Scott Waye		
				function scrollnews(spazio, tempo){
				$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
				}
				scrollnews(totalTravel, defTiming);				
				$strip.hover(function(){
				jQuery(this).stop();
				},
				function(){
				var offset = jQuery(this).offset();
				var residualSpace = offset.left + stripWidth;
				var residualTime = residualSpace/settings.travelocity;
				scrollnews(residualSpace, residualTime);
				});			
		});	
};
