
var $brutal = {
	init:function() {
		$brutal.initializeHome();
		$brutal.initializeMedia();
		$brutal.initializeShared();
		$brutal.initializeBlog();
		$brutal.initializeMusic();
	},
	
    initializeHome:function () {

		$j('#media-items-carousel').jcarousel({
	        initCallback: $brutal.media_carousel_initCallback,
	        buttonNextHTML: null,
	        buttonPrevHTML: null
		});
		$j('#media-items-carousel').css('visibility','visible');
		
		$j('#thoughts-carousel').jcarousel({
	        scroll: 1,
	        initCallback: $brutal.thoughts_carousel_initCallback,
	        buttonNextHTML: null,
	        buttonPrevHTML: null
		});	
		$j('#thoughts-carousel').css('visibility','visible');
		
		if($j('#mini-blog-post-date').length) {
			var diff = $brutal.getDateDifference($j('#mini-blog-post-date').html());
			$j('#mini-blog-post-day').html((diff == 0 ? "Today":diff+" days ago"));
		}
		
		$j('.signup-popup-link').click(function() {
			openCenteredWindow($j(this).attr('href'), 'signup', 475, 660);
			return false;
		});
		
		if($j('#single-media-id').length && $j('#video-comment-container').length)
			$brutal.loadHomeVideoExtras($j('#single-media-id').val());
		
		$j('#video-pagination a').click(function() {
			if(homevideos) {
				var id = $j(this).attr('id');
				var vid = $brutal.getHomeVideo(id);
				if(vid) {
					document.getElementById('brvidplayer').pauseMovie();
					document.getElementById('brvidplayer').setQueryStringParameters({embedCode:vid.embed, autoplay:vid.autoplay, hide:'share,fullscreen'});
					
			        $j('#video-pagination a').each(function() {
			        	$j(this).parent().addClass('number');
			        	$j(this).removeClass('number').removeClass('selected');
			        });
			        $j(this).parent().removeClass('number');
			        $j(this).addClass('number').addClass('selected');
			        
			        $brutal.loadHomeVideoExtras(vid.id);
					
				}
			}

			return false;
		});
		
	},
	
	loadHomeVideoExtras:function(id) {
		$j('#video-comment-container').html('');
		if(homevideos) {
			var vid = $brutal.getHomeVideo(id);
			var diff = $brutal.getDateDifference(vid.commentdate);
			
			if(vid.commentauthor != '') {
				var html = '<div class="right"><a href="/media/'+vid.id+'#comments"><span class="plus">+</span><span class="plus-link"> Add Comment</span></a></div>Latest comment from <span class="brutal-red">'+vid.commentauthor+'</span> '+(diff == 0 ? "today":diff+" days ago")+'<br/><p>'+vid.comment+' ... <a href="/media/'+vid.id+'#comments">more</a></p>';
				$j('#video-comment-container').html(html);				
			}
			
			$j('#single-media-share-download').attr('href', vid.downloadfile);
			
			$j('#single-media-title').html('<a href="'+vid.url+'">'+vid.title+'</a>');
			
			if(vid.thumbsup > vid.thumbsdown) {
				$j('#single-media-rock-on').addClass('rock-on-active');
				$j('#single-media-thumbs-down').removeClass('thumbs-down-active');
			} else if(vid.thumbsup < vid.thumbsdown) {
				$j('#single-media-rock-on').removeClass('rock-on-active');
				$j('#single-media-thumbs-down').addClass('thumbs-down-active');
			}
			
			$j('#single-media-id').val(id);
			
		}
	},
	
	getHomeVideo:function(id) {
		if(homevideos) {
			for(i = 0; i < homevideos.length; i++) {
				if(homevideos[i].id == id)
					return homevideos[i];
			}
		}
		return null;
	},

	initializeMedia:function () {
		
		$brutal.initializeMediaItems();
		
		$j('.media-sort-button').click(function() {
			$brutal.loadMediaItems($j(this).attr('href'));
			return false;
		});
		
		$j('.media-download').click(function() {
			return confirmLegal();
		});
		
		$j('#back-to-listings-link').click(function() {
			history.back();
			return false;
		});
		
		$j('#media-filter-link').click(function() {
			var url = $j(this).attr('href');
			tb_show(null, url, null);
			return false;
		});

	},

	initializeBlog:function () {
		$j('#single-blog-rock-on, #single-blog-thumbs-down').click(function() {
			var vote  = ($j(this).hasClass("rock-on"))? "up":"down";
			var url = '/blog/'+$j('#single-blog-id').val()+'!thumb?thumb='+vote;
			var cookie = 'blBlogRates'+$j('#single-blog-id').val();
			$brutal.rateme($j('#single-blog-id').val(), $j('#single-blog-rock-on'), $j('#single-blog-thumbs-down'), $j('#single-blog-feedback'), url, cookie);
			
			return false;
		});
		
	},

	initializeShared:function () {
		if($j("#comments").length)
			$brutal.loadComments(1,25);
		
		$j('#global-page-share').click(function() {
			var url = '/popup!page?bookmark='+escape(location.href)+'&height=550&width=573';
			tb_show("Share this page", url, null);
			return false;
		});
		
		$j('.commerce-lightbox').click(function() {
			//var pagename = "/commercebox/commerce-lightbox.html?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=626&width=920&modal=true";
			var url = '/popup!retailer?height=450&width=573';
			tb_show(null, url, null);
			
			return false;
		});
		
		$j('#single-media-rock-on, #single-media-thumbs-down').click(function() {
			var vote  = ($j(this).hasClass("rock-on"))? "up":"down";
			var url = '/media/'+$j('#single-media-id').val()+'!thumb?thumb='+vote;
			var cookie = 'blMediaRates'+$j('#single-media-id').val();
			$brutal.rateme($j('#single-media-id').val(), $j('#single-media-rock-on'), $j('#single-media-thumbs-down'), $j('#single-media-feedback'), url, cookie);
			
			return false;
		});
		
		$j('#single-media-share-email').click(function() {
			var url = '/popup/'+$j('#single-media-id').val()+'!media?height=550&width=573';
			tb_show('share media', url, null);
					
			return false;
		});

		$j('#single-media-share-embed').click(function() {
			var url = '/popup/'+$j('#single-media-id').val()+'!media?height=550&width=573';
			tb_show('share media', url, null);

			return false;
		});
		
		$j('#single-media-share-download').click(function() {
			if($j(this).attr('href') == '') {
				alert('There are currently no downloads for this media item.  Please try again later.');
				return false;
			} else {
				return confirmLegal();
			}
		});
		
		$brutal.initializeScrollableContainer();
		
		$j('.link-target-blank').click(function() {
			$j(this).attr('target','_blank');
		});
		
	},

	initializeMediaItems:function () {
		$j('.media-item-image').hover(
				function() {
					$j(this).children('.media-button-wrap').each(function(){$j(this).show();});
					$j(this).children('img').each(function(){$j(this).hide();});
				},
				function() {
					$j(this).children('.media-button-wrap').each(function(){$j(this).hide();});
					$j(this).children('img').each(function(){$j(this).show();});
				}
				);
		if($j('.media-item-feedback').length) {
			$j('.media-item-feedback').hide();
		}
		$j('.media-thumbs').unbind('click').click(function() {
			var vote  = ($j(this).hasClass("rock-on"))? "up":"down";
			var mediaId = $j(this).parent().children('.media-item-id').val();
			var url = '/media/'+mediaId+'!thumb?thumb='+vote;
			var cookie = 'blMediaRates'+mediaId;
			
			$brutal.rateme(mediaId, $j(this).parent().children('.rock-on'), $j(this).parent().children('.thumbs-down'), $j(this).parent().children('.media-item-feedback'), url, cookie);
			
			return false;
		});
		$j('.media-button-share').unbind('click').click(function() {
			var url = $j(this).attr('href');
			tb_show(null, url, null);
			return false;
		});
		$j('.media-button-download').click(function(){
			if($j(this).attr('href') == '') {
				alert('There are currently no downloads for this media item.  Please try again later.');
				return false;
			} else {
				return confirmLegal();
			}
		});
		$j('.media-item, .feature-media-item').each(function() {
			var up = $j(this).children('.media-item-rank-up').val();
			var down = $j(this).children('.media-item-rank-down').val();
			if(up > down) {
				$j(this).children('.rock-on').addClass('rock-on-active');
			}else if(down > up) {
				$j(this).children('.thumbs-down').addClass('thumbs-down-active');
			}
		});
	},
	
	rateme:function(id,up,down,feedback,url,cookie) {
		if(isLoggedIn){
			if(document.cookie.indexOf(cookie)<0) {
				$j.getJSON(url, function(results) {
					if(results.up > results.down) {
						up.addClass('rock-on-active');
						down.removeClass('thumbs-down-active');
					} else if (results.up < results.down) {
						up.removeClass('rock-on-active');
						down.addClass('thumbs-down-active');						
					} else {
						up.removeClass('rock-on-active');
						down.removeClass('thumbs-down-active');
					}
					document.cookie = cookie + ' =true; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
					feedback.text('Thanks!').fadeIn().animate({opacity:1.0}, 1000).fadeOut();
				});
			} else {
				feedback.text('Rated previously').fadeIn().animate({opacity:1.0}, 1000).fadeOut();
			}
		} else {
			feedback.text('Please login').fadeIn().animate({opacity:1.0}, 1000).fadeOut();
		}
	},

	loadMediaItems:function (url) {
		// media list
		$j('#media-loader').show();
		$j('#media-all-container').hide();
		$j('#media-all-container').load(url+'pageSize='+$j('#media-list-page-size').val(), null, function() {
			$j('#media-loader').hide();
			$j('#media-all-container').show();
			$brutal.initializeMediaItems();
			
			$j('.media-pager-button').click(function() {
				$brutal.loadMediaItems($j(this).attr('href'));
				return false;
			});
			
			tb_init('a.thickbox, area.thickbox, input.thickbox');
			
		});	
	},

	loadBlogs:function (url) {
		$j('#blog-loader').show();
		$j('#blog-list-container').hide();
		$j('#blog-list-container').load(url+'pageSize='+$j('#blog-list-page-size').val(), null, function() {
			$j('#blog-loader').hide();
			$j('#blog-list-container').show();	
			
			$j('.blog-pager-button').click(function() {
				$brutal.loadBlogs($j(this).attr('href'));
				return false;
			});
		});
	},

	media_carousel_initCallback:function (carousel) { 
		$j('#media-pagination a').bind('click', function() {
	        carousel.scroll($j.jcarousel.intval(($j(this).text()-1)*4+1));
	        $j('#media-pagination a').each(function() {
	        	$j(this).parent().addClass('number');
	        	$j(this).removeClass('number').removeClass('selected');
	        });
	        $j(this).parent().removeClass('number');
	        $j(this).addClass('number').addClass('selected');
	        return false;
	    });
	},

	thoughts_carousel_initCallback:function (carousel) { 
	    $j('#thoughts-next').bind('click', function() {
	        carousel.next();
	        return false;
	    });
	 
	    $j('#thoughts-prev').bind('click', function() {
	        carousel.prev();
	        return false;
	    });	
	},

	loadComments:function (pageNum, pageSize) {
		$j("#comments").load(
				escape($j('#id').val()) + '!comments?_cC=' + pageSize + '&_cP='
						+ pageNum + '&_rf=' + Math.random(), function() {
					$j(".flag").click( function() {
						$j(this).next().fadeIn("fast");
					});
					$j(".close-share").click( function() {
						$j(this).parent().fadeOut("medium");
					});
					
					$j('.comment-submit').click(function() {
						$brutal.sendComment($j('#submitcomment').attr('action'));
						return false;
					});
					
					
					$j('.comment-pager-button').click(function() {
						var p = getUrlParam($j(this).attr('href'),'_cP');
						var c = getUrlParam($j(this).attr('href'),'_cC');
						$brutal.loadComments(p,c);
						return false;
					});
					
					$j('.comment-flag-popup-link').click(function() {
						var url = $j(this).attr('href');
						tb_show(null, url, null);
						return false;
					});
					
					if($j('.output-today').length) {
						var now = new Date();
						$j('.output-today').text(now.toLocaleDateString());
					}
					
					$brutal.initializeScrollableContainer();

				});
			},
	
	initializeScrollableContainer: function() {
		// re-initialize scrollable area
		$j('.content-scroll-container').jScrollPane({showArrows:true, scrollbarWidth: 18, arrowSize: 18, dragMaxHeight: 81});					
		$j('.media-content-scroll-container').jScrollPane({showArrows:true, scrollbarWidth: 18, arrowSize: 18, dragMaxHeight: 81});					
		$j('.small-blog-scroll-container').jScrollPane({showArrows:true, scrollbarWidth: 18, arrowSize: 18, dragMaxHeight: 81});					
    },

	sendComment:function (url) {
		c = $j('#comment-text').val();
		data = {
			userComment : c
		};
		$j.get(url, data, function(data) {
			$j("#commentcount").text(Math.abs($j("#commentcount").text()) + 1);
			$brutal.loadComments(1, 25);
		});
	},

	flagComment:function (url, comment) {
		data = {
			cid : comment
		};
		$j.get(url, data, function(data) {
			tb_remove();
		});
	},

	getUrlParamfunction:function (url, param) {
		param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+param+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec(url);
		if( results == null )
		  return "";
		else
		  return results[1];
	},
	
	initializeMusic:function () {
	
		$j('#music-player-toggle').click(function() {
			if($j(this).text() == 'Sound Off') {
				document.getElementById('brmusicplayer').sendEvent('STOP');
				$j(this).text('Sound On');
				document.cookie = 'enablemusic=false; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
			} else {
				document.getElementById('brmusicplayer').sendEvent('PLAY', 'true');
				$j(this).text('Sound Off');
				document.cookie = 'enablemusic=true; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
				if(document.getElementById('brvidplayer'))
					document.getElementById('brvidplayer').pauseMovie();
			}
			return false;
		});
				
	},
	
	startVideo:function() {
		try {
			if(document.getElementById('brvidplayer'))
				document.getElementById('brvidplayer').playMovie();
		} catch(e){
			//do nothing
		}
	},
	
	stopVideo:function() {
		try {
			if(document.getElementById('brvidplayer'))
				document.getElementById('brvidplayer').pauseMovie();
		} catch(e){
			//do nothing
		}
	},
	
	getDateDifference:function (dt) {
		var arr = dt.split('/');
		var post = new Date(arr[2], arr[0]-1, arr[1]);
		var now = new Date();
		var diff = Math.round((now - post)/(1000*60*60*24));
		
		return diff;
	},
	
	brutalSendToFriend:function (el) {
		
		var email = $j('#send-to-friend-email').val();
		var url = $j('#send-to-friend-url').val();
		$j('#send-to-friend-container').load(url+(url.indexOf('?') > -1 ? '&':'?')+'useremail='+email);
		tb_remove();
	},
	
	ooyalaEventHandler:function(playerId, eventName, p) {
		switch(eventName)
		{
		case 'apiReady':		
			return;
		case 'playheadTimeChanged':
			return;
		case 'stateChanged':
			$brutal.ooyalaOnStateChanged(p);
			return;
		case 'currentItemEmbedCodeChanged':
			return;
		case 'totalTimeChanged':
			return;
		case 'embedCodeChanged':
			return;
		case 'volumeChanged':
			return;
		case 'loadComplete':
			return;
		}
	},
	
	ooyalaOnStateChanged:function(p) {
		if(p.state == 'buffering' || p.state == 'playing') {
			if(document.getElementById('brmusicplayer'))
				document.getElementById('brmusicplayer').sendEvent('STOP');
			$j('#music-player-toggle').text('Sound On');
		}
	},
	
	selectText: function(el) {
		el.focus();
		el.select();
	},
	
	filterUpdateClick: function() {
		// grab filters
		var filter = $j("input:checkbox[class=mediafilter]").getValue();
		
		// grab sort
		var sortby = $j('input:radio[name=mediasort]:checked').val();
		
		// reload page
		var type = (filter == '') ? '':'?type='+filter;
		var sort = (sortby == 'index') ? '':'!'+sortby;
		var url = '/'+$j('#filter-controller').val()+sort+type;
		
		document.location = url;
		
		return false;
	},
	
	filterClearSeeAll: function() {
		$j('#filter-see-all').attr('checked', false);
	},
	
	filterClearAll: function() {
		if($j('#filter-see-all').is(':checked')) {
			$j('.mediafilter').each(function() { $j(this).attr('checked', false); });
			$j('#filter-see-all').attr('checked', true);
		}
	}

}

// global overlay

var $globalOverlay = {
	hideOverlay: function() {
		$j('#globalOverlay').hide();
		$j('#main_image').show();
	},
	showOverlay: function() {
		$j('#main_image').hide();
		$j('#globalOverlay').show();
		//alert('showing overlay');
	}		
}

// territory gate
var $territoryOverlay = {
	init: function() {
		$j('.country-link').click(function() {
			var localeCode = $j(this).parent().attr('class');

			document.cookie = 'brutallocale = ' + localeCode + '; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/';
			if($j(this).attr('href') == '/home') {
				$territoryOverlay.hideTerritory();
				$agegateOverlay.showAgegate();

                return false;
			} 
		});
	},
	hideTerritory: function() {
		$j('#territory-container').hide();
	},
	showTerritory: function() {
		$j('#territory-container').show();
	}
}

// age gate
var $agegateOverlay = {
	months: new Array(),
	days: new Array(),
	init: function() {
	    $agegateOverlay.months[0]={name: "Jan",days: 31};
	    $agegateOverlay.months[1]={name: "Feb",days: 28};
	    $agegateOverlay.months[2]={name: "Mar",days: 31};
	    $agegateOverlay.months[3]={name: "Apr",days: 30};
	    $agegateOverlay.months[4]={name: "May",days: 31};
	    $agegateOverlay.months[5]={name: "Jun",days: 30};
	    $agegateOverlay.months[6]={name: "Jul",days: 31};
	    $agegateOverlay.months[7]={name: "Aug",days: 30};
	    $agegateOverlay.months[8]={name: "Sep",days: 30};
	    $agegateOverlay.months[9]={name: "Oct",days: 31};
	    $agegateOverlay.months[10]={name: "Nov",days: 30};
	    $agegateOverlay.months[11]={name: "Dec",days: 31};
	
		// create date dropdowns
		if($j('#monthInput').length) {
			var monthOptions='', dayOptions='', yearOptions='';
			for(i = 0; i < $agegateOverlay.months.length; i++)
				monthOptions += '<option value="'+(i+1)+'">'+$agegateOverlay.months[i]["name"]+'</option>';
			$j('#monthInput').html(monthOptions);
			for(i = 2009; i > 1899; i--)
				yearOptions += '<option value="'+i+'">'+i+'</option>';
			$j('#yearInput').html(yearOptions);
			for(i = 1; i <= $agegateOverlay.months[0]["days"]; i++)
				dayOptions += '<option value="'+i+'">'+i+'</option>';
			$j('#dayInput').html(dayOptions);
		}
	
		$j('#submitAgegate').click(function() {
			y = $j("#yearInput").val();
	        m = $j("#monthInput").val();
	        d = $j("#dayInput").val();

	        data = {
	            'year': y,
	            'month': m,
	            'day': d
	        };
	        $j.get('/agegate/', data, function(data) {
	            var age = parseFloat(data);
	            if (age > -1 && age < 17) {
	                $j("#unknown-age").hide();
	                $j("#no-perm").show();
	            } else {
	            	$globalOverlay.hideOverlay();
	            	
	            	showTerritory = false;
	            	showAgegate = false;
	            	
	            	try {
		    			if(flashvars && params && attributes)
		    				swfobject.embedSWF("http://www.ooyala.com/player.swf", "brutal-flash-player-container", "568", "319", "9.0.0","/swf/expressInstall.swf", flashvars, params, attributes);
	            	} catch(e) {
	            		// do nothing
	            	}
	            }
	        });
			return false;
		});
	},
	showAgegate: function() {
		$j('#agegate-container').show();
	},
	hideAgegate: function() {
		$j('#agegate-container').hide();
	},
	updateDays: function() {

		var prevDay = $j('#dayInput').val();
		
		var daysInMonth = parseInt($agegateOverlay.months[$j('#monthInput').val()-1]["days"]);
		
		// check for leap years
		daysInMonth += $agegateOverlay.isLeapYear($j('#yearInput').val()) && daysInMonth == 28 ? 1:0;
		
		var dayOptions='';
		for(i = 1; i <= daysInMonth; i++) {
			dayOptions += '<option value="'+i+'"'+(i == prevDay?' selected':'')+'>'+i+'</option>';
		}
		// need to rebuild entire select for safari :(
		$j('#agegate-day-selector').html('<select id="dayInput" name="day" class="ag-dd">'+dayOptions+'</select>');
	},
	isLeapYear: function(year) {
		return ((year%4 == 0) && (year%100 != 0 || year%400 == 0));
	}
}


/** global functions **/
function receiveOoyalaEvent(playerId, eventName, p) {
	$brutal.ooyalaEventHandler(playerId, eventName, p);
}

var musicplayer = null;

function playerReady(thePlayer) {
	musicplayer = window.document[thePlayer.id];
	addListeners();
}

function addListeners() {
	if (musicplayer) { 
		musicplayer.addControllerListener("ITEM", "itemListener");
	} else {
		setTimeout("addListeners()",200);
	}
}

function itemListener(obj) {
	var plst = null;
	plst = musicplayer.getPlaylist();
	if (plst) {
		$j('#song-name').text(plst[obj.index].title+' by '+plst[obj.index].author);
	}
}

$j(document).ready($brutal.init);
