// hovers for (sources) partners in epic footer
//===============
function HoverPartners()
{
	jQuery(".hover-text").tipTip();
}

//	Portlets
//=================
function UpdateOrder()
{
	var wideCol = $("#wide-column").sortable('serialize',{key:"&w[]"});
	var medCol = $("#med-column").sortable('serialize',{key:"&m[]"});
	jQuery.ajax({
		type: "POST", 
		url: "/assets/scripts/reorder.php",
		data: wideCol+medCol,
		success: function(msg){
			eval(msg);
		}
	});
	FixBoxSizes();
}

function FixBoxSizes()
{
	//give all the columns the right class from launch.
	jQuery('#wide-column').children('.med-box').each(function(){
		jQuery(this).removeClass('med-box').addClass('wide-box');
	});
	jQuery('#med-column').children('.wide-box').each(function(){
		jQuery(this).removeClass('wide-box').addClass('med-box');
	});
	//fix for cols being moved from left to right
	jQuery('#med-column').find('section-content').css({left:"0px"});
}

jQuery(document).ready(function($) {
	FixBoxSizes();
	$("#index #wide-column, #index #med-column").sortable(
	{
		connectWith: '.connected', cancel: '.advertisement', opacity: 0.6, handle: 'h2',
		update: function(event, ui)
		{
			UpdateOrder();
		},
		placeholder: 'dotted', tolerance: 'pointer'
	});
	
	$('#wide-column').bind('sortupdate', function(event, ui) {
		$(this).children('.med-box').each(function(){
			$(this).removeClass('med-box').addClass('wide-box');
		});
	});
	$('#med-column').bind('sortupdate', function(event, ui) {
		$(this).children('.wide-box').each(function(){
			$(this).removeClass('wide-box').addClass('med-box');
		});
	});
	

// Parallax 
//===============
	jQuery('#parallax').jparallax({ytravel: 0.2});


	HoverPartners();
// Weather Module
//===============
	var inputBox = $("#weather-zip");
	function ZipClick(event)
	{
		if(event.keyCode == 13 || $(this).hasClass("weather-submit"))
		{
			var weatherDiv = inputBox.parents('#mod-weather');
			weatherDiv.find('.module-loading').fadeIn('fast',function(){
				weatherDiv.load("/modules/weather/global-weather.php",{ajaxed: 1, weatherZip: inputBox.val()},function()
				{
					weatherDiv.find('.module-loading').fadeOut('fast');
					inputBox = $("#weather-zip");
					inputBox.keydown(ZipClick);
					inputBox.next().click(ZipClick);
				});
			});
		}else{
			return true;
		}
		return false;
	}

	inputBox.keydown(ZipClick);
	inputBox.next().click(ZipClick);

// Tooltip hover 
//=================
	function HideToolTip()
	{
		$('body').unbind('click',HideToolTip);
		$("a.more-tip-close").trigger("click");
	};

	function ToolTipIt(e){
     	e.stopPropagation();
		$('.over-9000').removeClass('over-9000');
		var mod = $(this).parents('.wide-box, .med-box');
		var toolTipClass = "left";
		var toolTipCss = {position:"absolute",top:e.pageY, left:e.pageX};
		if(mod.hasClass('med-box'))
		{
			toolTipClass = "right";
			toolTipCss = {position:"absolute",top:e.pageY, left:e.pageX-400};
		}
		toolTip.removeClass('left').removeClass('right').addClass(toolTipClass);
		toolTip.css(toolTipCss)
		toolTip.empty().append($(this).next("div").clone(true)).children().animate({opacity: "show"}, "slow",function()
		{
			$('body').bind('click',HideToolTip);
		});
	}
	
	//Holder for the tooltips
	$("body").append("<div id='jq-tool-tip'></div>");
	var toolTip = $("div#jq-tool-tip");
	
	//Functions for tooltip
	$("a.more-tip").bind("click",ToolTipIt);
	
	toolTip.hoverIntent("", function()
	{
		$("a.more-tip-close").trigger("click");
	});
	toolTip.click(function(event){
     event.stopPropagation();
 	});
	
	$("a.more-tip-close").bind("click", function() {
		$('body').unbind('click',HideToolTip);
		toolTip.children().animate({opacity: "hide"}, "fast");
		$('.over-9000').removeClass('over-9000');
	});
	
	
	
// Sidebar stuff
//=================
	//open region curtains with click;
	function SideBarSlide()
	{
		var body = $(this).parents('.box-body').find('.section-content');
		var sidebar = $(this).parents('.box-body').find('.mini-sidebar');
		var mainDiv = $(this).parents('.wide-box, .med-box');
		
		
		
		if(mainDiv.hasClass(".wide-box"))
		{
			var newLeft = sidebar.css('left');
			if(newLeft == "200px")
			{
				sidebar.css({left:"-200px"});
			}
			if($(this).hasClass('out'))
			{
				sidebar.animate({left:'-200px'},'fast',function()
				{ 
					$(this).css({display:"none"}); 
					body.animate({width:'430px'},'fast',function()
					{
						body.removeAttr('style'); 
						body.addClass('full'); 
						body.parents('.box-body').find('a.in').fadeIn();
					});
				});
			}else{
				body.parents('.box-body').find('a.in').fadeOut();
				body.animate({width:'275px'},'fast',function()
				{ 
					sidebar.css({display:"block"}); 
					body.removeClass('full'); 
					body.removeAttr('style'); 
					sidebar.animate({left:'0px'},'fast'); 
				});	
			}
		}else{
			var newLeft = sidebar.css('left');
			if(newLeft == "-200px")
			{
				sidebar.css({left:"200px"});
			}
			if($(this).hasClass('out'))
			{
				sidebar.animate({left:'200px'},'fast',function()
				{ 
					$(this).css({display:"none"}); 
					body.removeAttr('style'); 
					body.addClass('full'); 
					body.parents('.box-body').find('a.in').fadeIn();
				});
			}else{
				body.parents('.box-body').find('a.in').fadeOut();
				sidebar.css({display:"block"}); 
				body.removeClass('full'); 
				body.removeAttr('style'); 
				sidebar.animate({left:'0px'},'fast'); 
			}
		}
	}
	
	$('.toggle-horiz').click(SideBarSlide);

	function LocalRegionPick()
	{
		var data = $(this).attr('class');
		if(data != "LOCAL")
		{
			data = data.substr(4,2);
		}
		//get my title element
		$(this).parents('div:first').find('input[type=hidden]:last').val(data);
		$(this).parents('div:first').find('input[type=hidden]:first').val("");
		//now have our map, we need to submit the hidden input that holds our value;
		SubmitCurtain($(this));
		return false;
	}
	
	$('ul.mini-map').children('li').click(LocalRegionPick);

	function SportsTeamPick()
	{
		var data = $(this).attr('class');
		if($(this).hasClass("SPORTS"))
		{
			data = "SPORTS";
		}
		//get my title element
		$(this).parents('div:first').find('input[type=hidden]:last').val(data);
		$(this).parents('div:first').find('input[type=hidden]:first').val("");
		//now have our map, we need to submit the hidden input that holds our value;
		SubmitCurtain($(this));
		return false;
	}
	$('ul.mini-sportsteams').children('li').click(SportsTeamPick);
	
	function MiniSelector()
	{
		var data = $(this).val();
		$(this).parents('div:first').find('input[type=hidden]').val(data);
		SubmitCurtain($(this));
		return false;
	}
	
	$("select[name=miniSelector]").bind('change', MiniSelector);
	function ReJquery(ele)
	{
		ele.find("a.more-tip").unbind("click",ToolTipIt).bind("click",ToolTipIt);
		$("a.more-tip-close").bind("click", function() {
			toolTip.children().animate({opacity: "hide"}, "fast");
		});
		ele.find('.toggle-horiz').click(SideBarSlide);
		//Specilailiezed curtains
		ele.find('ul.mini-map').children('li').click(LocalRegionPick);
		ele.find('ul.mini-sportsteams').children('li').click(SportsTeamPick);
		ele.find("select[name=miniSelector]").bind('change', MiniSelector);
		ele.find("ul.provider-logos a").bind("click",ProviderSelection);
		ele.find(".module-close").click(CloseModule);
		TwitterProfile(ele.find("img[rel=twitterPic]"));
		HoverPartners();
		LotteryJquery();
	}
	$(".module-loading").hide();
	function ProviderSelection()
	{
		var box = $(this).parents('.wide-box,.med-box');
		var input = box.find('input[name=sourceid]');
		input.val($(this).attr('ref'));
		SubmitCurtain(box.find(".mini-sidebar").children('img:first'));
		return false;
	}
	$("ul.provider-logos a").bind("click",ProviderSelection);
	
	function SubmitCurtain(ele)
	{
		try
		{
			//chance to fail here. If called as chain ele will be undefined
			var divEle = ele.parents(".mini-sidebar");
			if(!divEle.hasClass('mini-sidebar'))
			{
				divEle = ele;
			}
		}catch(err)
		{
			var divEle = $(this).parents(".mini-sidebar");
			ele = $(this);		
		}
		var loading = ele.parents(".wide-box, .med-box").find(".module-loading");
		loading.fadeIn('fast');
		var ins = divEle.find(':input');

		var settings = "set=";
		for(var y = 0; y<ins.length; y++)
		{
			if(ins[y].type=="radio" || ins[y].type=="checkbox")
			{
				if(ins[y].checked)
				{
					settings += ins[y].name+"="+ins[y].value+",";
				}
			}else{
				if(ins[y].value != "")
				{
					settings += ins[y].name+"="+ins[y].value+",";
				}
			}
		}
		//console.log(ins.lenght);
		//console.log(settings);
		var mod = ele.parents(".wide-box, .med-box").attr('id').substr(4);
		$.ajax({
			type: "POST",
			url: "/assets/scripts/update-settings.php",
			data: "mod="+mod+"&"+settings,
			success: function(msg){
				eval(msg);
				if(success){
					//find out what my box was.
					var content = $('#mod-'+mod);
					//wrapping the content load in an animation to create a pause
					content.animate({opacity:1},1000,function()
					{
						content.load("/assets/scripts/reload-module.php", {'mod':mod, 'ajaxed':'true'},function(){ 
								FixBoxSizes();
								$('a.in').hide();
								content.fadeIn('fast');
								ReJquery(content); 
								content.find(".module-loading").fadeOut('fast'); 
							});
					});
				}else{
					TossError('Failed to save settings. Try again later');
				}
		  	}
		});
		return false;
	}
	$(".mini-sidebar select").live('change',SubmitCurtain);


	
// Classifieds scripts
//===============
// a. subclass loader.
	//subclass div
	var subDiv = $('div#classifieds-sub-groups');
	var classDiv = $('div#classifieds-groups');
	//lisitings div
	var listingsDiv = $('div#classifieds-full-list');
	var classMin = 0;
	var classMax = 10;
	var subclassNum = 0;
	var listingsLoaded = false; //initial load of listings
	$("#CNNew").hide().click(function()
	{
		$("li",classDiv).removeClass('classSelected').fadeIn('fast');
		subDiv.hide();
		$(this).fadeOut('fast');
		return false;
	});
	$("#classifieds-groups").children('ul').children('li').click(function(event, sc)
	{
		ScrollIfLow();
		if(listingsLoaded)
		{
			listingsDiv.fadeOut('slow',function(){$(this).html('<div class="classifieds-step">Ç Select Classified Grouping first</div>').fadeIn('slow');});
		}
		//strip CN off the id
		$(this).addClass('classSelected').siblings().removeClass('classSelected').fadeOut('fast');
		$("#CNNew").fadeIn('slow');
		var classNum = $(this).attr('id').substr(2);
		subDiv.fadeOut('slow', function()
		{
			$(this).load(
				"classifieds/classes.php", 
				"cn="+classNum,
				function()
				{ 

					SubClassesRefresh(); 
					$(this).fadeIn('slow');
					if(sc !== null)
					{
						var an = $.GET('an');
						$('#SC'+sc).trigger('click', [an]);
						sc = null;					
					}
				}
			);
		});
		return false;
	});
	
	
// b. adds the clicks to the subclasses.
		//these clicks fill the listings
	function SubClassesRefresh()
	{
		$("#classifieds-sub-groups").children('ul').children('li').click(function(event, an)
		{
			ScrollIfLow();
			classMin = 0;
			classMax = 10;
			$(this).addClass('subclassSelected').siblings().removeClass('subclassSelected');
			//strip SC off the id
			subclassNum = $(this).attr('id').substr(2);
			listingsDiv.fadeOut('slow', function()
			{
				var extraData = "";
				if(an !== null && typeof(an) !== "undefined")
				{
					extraData = "&adnum="+an;
				}
				$(this).load(
					"classifieds/listings.php", 
					"sc="+subclassNum+"&limit="+classMin+","+classMax+extraData,
					function()
					{
						$(this).fadeIn('slow');
						//Make the listings searchable.
						listingsLoaded = true;
						$("#classifieds-submit-image").click(SearchClassifieds);
						$("#classifieds-full-list").find('form').bind('submit', SearchClassifieds);
						ListingsMoreButton();
					}
				);
			});
			return false;
		});
	}

// c. More button at the bottom of the listings.
	function ListingsMoreButton()
	{
		$('.more-button').click(function()
		{
			$(this).remove();
			classMin = classMax+1;
			classMax = classMin+10;
			var listingUl = $(this).par;
			$.ajax({
				type: "GET",
				url: "classifieds/listings.php",
				data: "sc="+subclassNum+"&ajax=true&limit="+classMin+","+classMax,
				success: function(msg){
			  		listingsDiv.children('ul').append(msg);
			  		ListingsMoreButton();
				}
			});
		});		
	}
	
//d. The refine search button
	function SearchClassifieds()
	{
		ScrollIfLow();
		classMin = 0;
		classMax = 10;
		var searchValue = $('#classifieds-search-text').val();
		if(searchValue != "" && typeof(searchValue) != 'undefined')
		{

			listingsDiv.fadeOut('slow', function()
			{
				$(this).load(
					"classifieds/listings.php", 
					"sc="+subclassNum+"&limit="+classMin+","+classMax+"&search="+searchValue,
					function()
					{
						$(this).fadeIn('slow');
						$("#classifieds-submit-image").click(SearchClassifieds);
						$("#classifieds-full-list").find('form').bind('submit', SearchClassifieds);
						ListingsMoreButton();
					}
				);
			});
		}
		return false;
	}
	
//e. Scrolls to the top of the page when items are refreshed
	function ScrollIfLow()
	{
		if($("#classifieds-groups").position().top > 500)
		{
			$('body').animate({scrollTop : 0},'slow'); 
		}
	}
	
	$('#classifieds-groups').scroller('#classifieds-wrapper');
	$('#classifieds-sub-groups').scroller('#classifieds-wrapper');
	
//f. Check if there was a category passed. If there was, check for sub category. then a search.
	var cn = $.GET('cn');
	if(cn !== null)
	{
		var subclass = $.GET('sc');
		$('#CN'+cn).trigger('click',[subclass]);
		cn = null;
	}

// Framer Script
//===============
	//closes the frame and loads the appropriate url.
	$('#close').click(function(){window.parent.window.location.href = window.parent.window.document.getElementById('ext-frame').src;});
	$('#backtomi').click(function(){window.parent.window.location.href = $(this).attr('href');});

// TWITTER FEEDER 



// Login Stuff 
//=================
	$("#show-login").click(function(){ $("#login-fields").slideToggle("fast"); $("#register-fields, #forgot-fields").slideUp("fast"); return false; });
	$("#forgot-link").click(function(){ $("#forgot-fields").slideToggle("fast"); $("#login-fields").slideUp("fast"); return false; });
	$("#show-register").click(function(){ $("#register-fields").slideToggle("fast"); $("#login-fields, #forgot-fields").slideUp("fast"); return false; });
	function hideFields(){$("#login-fields, #forgot-fields, #register-fields").slideUp('fast');}
	$(window).bind('click',hideFields);
	$("#login-fields, #forgot-fields, #register-fields").each(function(){
		this.onclick = function(e){ e.stopPropagation();}
	});
//make enterbutton work
	function RegisterSubmit()
	{ 
		var name = $("#register-name").val();
		var email = $("#register-email").val();
		var password = $("#register-password").val();
		var cpassword = $("#register-confirm-password").val();
		var zip = $("#register-zip").val();
		//also need to pass the column layouts
		var wideCol = $("#wide-column").sortable('serialize',{key:"&w[]"});
		var medCol = $("#med-column").sortable('serialize',{key:"&m[]"});
		$.ajax({
			type: "POST",
			url: "/assets/scripts/register.php",
			data: "name="+name+"&email="+email+"&password="+password+"&cpassword="+cpassword+"&zip="+zip+wideCol+medCol,
			success: function(msg){
				eval(msg);
				if(success)
				{
					location.reload(true);
				}else{
					//TossError(errorText);
				}
			}
		}); 
	}

	function LoginSubmit(){ 

		var email = $("#login-email").attr('value');
		var password = $("#login-password").attr('value');
		$('#login-status').html('Checking...');
		$.getJSON("/assets/scripts/login.php?email="+email+"&password="+password,
			function(data)
			{

				if(data.success)
				{
					data.action();
				}else{
					data.failure();
				}
			}
		);
		return false;
	}
	
	function ForgotSubmit(){
		var email = $("#forgot-email").attr('value');
		$.getJSON("/assets/scripts/forgot.php?email="+email,
			function(data){
				if(data.success)
				{
					data.action();
				}else{
					data.failure();
				}
			}
		); 
	}
	$("#register-submit").click(RegisterSubmit);
	$("#login-submit").click(LoginSubmit);
	$("#forgot-submit").click(ForgotSubmit);
	$("#login-fields").find('input').keyup(function(event){ if(event.keyCode == 13){ LoginSubmit(); }});
	$("#register-fields").find('input').keyup(function(event){ if(event.keyCode == 13){ RegisterSubmit(); }});
	$("#forgot-fields").find('input').keyup(function(event){ if(event.keyCode == 13){ ForgotSubmit(); }});
	$("#zip-change-box").find('input').keyup(function(event){ if(event.keyCode == 13){ $(this).parents('form').submit(); }});
	$("#change-zip").click(function(){
		$(this).next('div').slideToggle('fast');
	});
	$("#zip-from").attr('value',location.href);


// Minimize on dblclick
//=================
$("#wide-column, #med-column").children('div').children('h2').bind('dblclick',function()
{
	$(this).next('div').slideToggle('fast');
});

// Module List Accordians
//=============
$('.faq-questions dl').children('dd').hide();
$('.faq-questions dl').children('dt').click(function(){
	$(this).next('dd').slideToggle();
});
$("a.expand-faq").bind("click", function(){
	$(".faq-questions dd").slideDown(700);
	return false;
});
$("a.collapse-faq").bind("click", function(){
	$(".faq-questions dd").slideUp(700);
	return false;
});


$(".lottery dd").hide();

function LotteryJquery()
{
	$(".lottery dt").unbind('click');
	$(".lottery dt").bind('click', function(){
		$(this).next("dd").slideToggle("fast")
		.siblings("dd:visible").slideUp("fast");
		$(this).toggleClass("active");
		$(this).siblings("dt").removeClass("active");
	});
}
LotteryJquery();
	
// FACEBOX!
//===========
$('a[rel*=facebox]').facebox({
     loading_image : '../images/facebox-loader.gif',
     close_image   : '../images/facebox-close.gif'
});
// Add / Remove Modules
//===========
$('#modules .close,#done-edit').click(function(){ $("#modules").slideUp(); return false; });
$('#show-edit').bind('click', function(){
	$(this).parent().find('#modules').slideToggle();
});

$('#modules .action a').bind('click', function()
{
	var li = $(this).parents('li:first');
	var theModule = "mod"+li.attr('id').substr(3,20);
	var action = "add";
	var message = "Module Added";
	if($(this).hasClass('disable'))
	{
		action = "remove";
		message = "Module Removed";
	}
	var theData = "action="+action+"&m="+theModule;
	$.ajax({
		type: "POST",
		url: "/assets/scripts/add-remove-module.php",
		data: theData,
		success: function(msg){
			eval(msg);
			//return variable success. True - for good, false for error. if there is an errror its returned in errorText
			if(success)
			{
				//path is return by add-remove-module.php. It contains the path for js to call to add the module
				if(action == "add")
				{
					$.ajax({
						type: "POST",
						url: path,
						data: theData,
						success: function(msg){
							$("#wide-column").prepend(msg);
							//The below is to reinitialize all the actions each module can perform
							$(".module-loading").hide();
							var ele = $("#wide-column").children("div:first");
							ReJquery(ele);			
						}
					});
					EditListModuleChange(li,"disable");
				}else{
					$('#'+theModule).remove();
					EditListModuleChange(li,"enable");
				}
				
				TossSuccess(message);

			}else if(!success)
			{
				TossError(errorText);
			}
		}
	});
	return false; 
});

function EditListModuleChange(obj,make)
{
	if(make == "disable")
	{
		obj.addClass('enabled').removeClass('disabled').find('a').addClass('disable red').removeClass('enable green').html('Disable');
	}else{
		obj.addClass('disabled').removeClass('enabled').find('a').addClass('enable green').removeClass('disable red').html('Enable');	
	}
}

//check all modules and then set the proper toggles
$("[id^=mod-]").each(function()
{
	var module = $(this).attr('id').substr(4,30);
	EditListModuleChange($("#add-"+module),'disable');
});
$("#modules li").bind('click',function(){ $(this).find('a').trigger('click'); });
// Displays info to users
//===========
function TossError(errorText)
{
	if(typeof(errorText)=='undefined')
	{
		return false;
	}
	$.gritter.add({title: 'An error has occurred!',text: errorText,sticky: false,time: '3000'});
}

function TossSuccess(Text, refresh)
{
	if(typeof(Text)=='undefined')
	{
		return false;
	}
	if(refresh)
	{
		Text = Text+" <a href='#' onClick='location.reload()'>Refresh to see changes</a>";
	}
	$.gritter.add({title: 'Action Successful!',text: Text,sticky: false,time: '3000'});
}

//Fanshop Modules
//=====================
$("#fanshop-products>li").fadeTo("fast",0.75).hover(function(){
	$(this).fadeTo("fast",1);
	var text = $(this).find(".product-title").html();
	var div =  $("#product-title .product-title");
	div.html(text);
},function(){ $(this).fadeTo("fast",0.75); });

//Zvents Module
//=====================
//Tabs
$(".performers-tab").live('click',function(){
	$(this).parents('.box-body').find('input[name=section]').attr('value','search-performers');
	SubmitCurtain($(this).parents('.box-body'));
	return false;	
});
$(".events-tab").live('click',function(){
	$(this).parents('.box-body').find('input[name=section]').attr('value','search-events');
	SubmitCurtain($(this).parents('.box-body'));
	return false;	
});
$(".featured-tab").live('click',function(){
	$(this).parents('.box-body').find('input[name=section]').attr('value','featured');
	SubmitCurtain($(this).parents('.box-body'));
	return false;	
});

$(".start-over-events").live('click',function(){
	$(this).parents('.box-body').find('input[name=section]').attr('value','search-events');
	SubmitCurtain($(this).parents('.box-body'));
	return false;
});

$(".event-submit").live('click',function(){
	$(this).parents('.box-body').find('input[name=section]').attr('value','events-result');
	SubmitCurtain($(this).parents('.box-body'));
	return false;
});
$(".performer-submit").live('click',function(){
	$(this).parents('.box-body').find('input[name=section]').attr('value','performers-result');
	SubmitCurtain($(this).parents('.box-body'));
	return false;
});
$("#event-form input[type=text]").live('keyup',function(event){ if(event.keyCode == 13){ $(this).parents('.box-body').find('td a').trigger('click'); }});


// Reconfirm email on account popup
//===========
function BindResendConfirm()
{
	$("#resend-confirmation").bind("click",function()
	{
		$.ajax({
			type: "POST",
			url: "/assets/scripts/reconfirm-email.php",
			success: function(msg){
				eval(msg);
				//return variable success. True - for good, false for error.
				//if there is an errror its returned in errorText
				if(!success)
				{
					TossError(errorText);
				}else{
					TossSuccess('Confirmation sent.');
				}
			}
		});
		return false; 
	});
	
	$('.save-all').click(function()
	{
		var data = "a=update";
		$("#user-info :input").each(function(){
			data = data+"&"+$(this).attr('name')+"="+$(this).val();
		});
		$.ajax({
			type: "POST",
			data: data,
			url: "/assets/scripts/update-account.php",
			success: function(msg){
				eval(msg);
				//return variable success. True - for good, false for error.
				//if there is an errror its returned in errorText
				if(!success)
				{
					TossError(errorText);
				}else{
					TossSuccess('Settings have been updated!');
				}
			}
		});
		return false; 
	});
}

// Drop down menu for main nav
//===========
	var timeout;
	function DropMenu() {
		clearTimeout(timeout);
		$(this).find("ol.drop-down").stop(true,true).slideDown('fast');
		$(this).siblings('li').find("ol.drop-down").stop(true,true).slideUp('fast');
	}

	function RaiseMenu()
	{
		var id = this.id
		timeout = setTimeout('jQuery("#'+id+'").find("ol.drop-down").slideUp("fast");',1000);
	}
	$("ul#main-nav>li").mouseenter(DropMenu).mouseleave(RaiseMenu);

// Face Box 1-up windows
//===========
	if($.cookie('newUser')=="true")
	{
	   $.get('/assets/includes/welcome.php', function(data) { 
			$.facebox(data);
			var date = new Date();
			$(window).unbind('click',hideFields);
		   $('#welcome-login').click(function()
			{
					$('#fields-blacker-outer').css({display:'block'}).bind('click', hideFields).click(function()
					{
						$(this).fadeOut();
						$(window).bind('click',hideFields);						
					});
					
					$.facebox.close();
					$('#login-fields').slideDown('slow');
			});
			$('#welcome-register').click(function()
			{
					$('#fields-blacker-outer').css({display:'block'}).bind('click', hideFields).click(function()
					{
						$(this).fadeOut();
						$(window).bind('click',hideFields);						
					});
					
					$.facebox.close();
					$('#register-fields').slideDown('slow');
			});
	   });
	} 
	if($.cookie('message')!==null && $.cookie('message')!="")
	{
			var mess = $.cookie('message');
			mess = mess.replace(/\+/g, " ");
			TossSuccess(mess);
			$.cookie('message',"",0);
	} 

	$("#go-account").click(function()
	{
		$.get('/account/account.php', function(data) { 
				$.facebox(data);
				BindResendConfirm();
	    });
		return false;
	});
	

	$("#feedback-button").click(function()
	{
			$.facebox('<iframe src="http://surveys.polldaddy.com/s/5EA953AFCF907E6E/" width=800 height=500 marginheight="0" marginwidth="0" frameborder="0" scrolling="yes"  horizontalscrolling="no" verticalscrolling="yes"></iframe>');
		return false;
	});

// Pagination for the inside pages
//===========
	//relies on the wide-box having an id of paginate

	function PaginateIt()
	{
		//ajax in the next set of stories
		var url = location.pathname.split('/');
		//get number of articles so we know where to query from
		var count = $('.all-articles-list li').length;
		//our x variable is url[3]
		if(typeof(url[3])=='undefined')
		{
			url[3] = "";
		}
		data = "mod="+url[2]+"&x="+url[3]+"&paginated="+count;
		if(typeof(url[2])=="undefined" || url[2]=="")
		{
			TossError("Sorry we could not load any additional stories at this time. Please try again later.");
		}else{
			$.ajax({
				type: "POST",
				url: "/assets/scripts/paginate-inside-pages.php",
				data: data,
				success: function(msg){
					if($.trim(msg)=="NO MORE!")
					{
						return;
					}else{
						$('.all-articles-list').append(msg);
					}
				}
			});
		}
	}
	$("#paginate-more").bind('click',PaginateIt);

	//Draggable debug window
	$('#ultra-debug-awesomeness').draggable();
	
// Close module
//================
$(".module-close").click(CloseModule);

function CloseModule()
{
	var module = $(this).parents('div:first').attr('id');
	var answer = confirm ("Are you sure you want to remove this module? \r\n You can always add it again at a later.");
	if (answer)
	{
		var theData = "action=remove&m="+module;
		$.ajax({
			type: "POST",
			url: "/assets/scripts/add-remove-module.php",
			data: theData,
			success: function(msg){
				eval(msg);
				//return variable success. True - for good, false for error.
				//if there is an errror its returned in errorText
				if(success)
				{
					$('#'+module).remove();
				}else if(!success)
				{
					TossError(errorText);
				}
			}
		}); 
	}
}

$(".enter-contest").bind('click',function(){
	var text = $(this).parents('.box-body').find('h4').text();
	$(this).hide();
	$(this).next().show();
	$(this).parents('.box-body').find('input[type=hidden]').val(text);
	return false;
});
$(".exit-contest").bind('click',function(){
	$(this).hide();
	$(this).prev().show();
	$(this).parents('.box-body').find('input').val("");
	return false;
});

function TwitterProfile(eles)
{
	eles = eles.filter(function(index){
		//filter out only the first element with that src
		var src = $(this).attr('src');
		//check if the first element with this source is my element
		var first = $("img[src='"+src+"']");
		return ($(".tweet_list img").index(first) == index);
	});
	eles.each(function(){
		if($(this).attr('rel') == 'twitterPic')
		{
			var source = $(this).attr('src');
			var url = 'http://search.twitter.com/search.json?&q=from:'+source+'&callback=?';
			$.getJSON(url, function(data){
				$("img[src='"+source+"']").each(function()
				{	
					$(this).attr('src',data.results[0].profile_image_url);
					$(this).attr('rel',"");
					$(this).fadeIn('fast');
				});
			});
		}
	});
}
TwitterProfile($("img[rel=twitterPic]"))

//carousel for front page
$('#fanshop-products').jcarousel({
        scroll: 2
    });

//Lotto pick
$('.lotto-pick li').click(function()
{
	$.getJSON('http://dev.michigan.com/assets/scripts/make-lotto-numbers.php?g='+$(this).attr('class'),function(data)
	{
		$("#your-number").html(data.number);
	});
	$(this).parent().children().fadeOut();
	$("#picked-game").hide().attr('class',$(this).attr('class')).fadeIn();
});


//FB Login Button
//facebook integration
//FB.init({apiKey: '606d1058645e6ede564a6085adb56ac1', status: true, cookie: true, xfbml: true});


//Search Results
$("#show-more-results").bind('click',function(){
	var list = $("#search-ul").find('.dissapear');
	if(list.length <= 15){ $(this).remove(); }
	list.length = 15;
	list.each(function(){ $(this).fadeIn('fast').removeClass('dissapear'); });

});

// Restaurant module
//================
$('ul.forks a').live('click',function(){
	$('ul.forks a.active').removeClass('active');
	$(this).addClass('active').parent().prevAll().find('a').addClass('active');
	var price = $('ul.forks a').index(this)+1;
	$('ul.forks input').attr('value',price);
	return false;
});

$("#mod-restaurants a.search").live('click',function(){
	var content = $("#mod-restaurants");
	content.find('.module-loading').fadeIn('fast');
	var sets = InputsToJson(content);
	//console.log(sets);
	content.delay(1000).load("/assets/scripts/reload-module.php", {'mod':'restaurants', 'ajaxed':'true', 'section':'results','settings':sets},function(){ 
		content.fadeIn('fast');
		content.find(".module-loading").fadeOut('fast'); 
	}); 
	return false;
});

$("#mod-restaurants a.start-over").live('click',function(){
	var content = $("#mod-restaurants");
	content.find('.module-loading').fadeIn('fast');
	content.delay(1000).load("/assets/scripts/reload-module.php", {'mod':'restaurants', 'ajaxed':'true', 'section':'home'},function(){ 
		content.fadeIn('fast');
		content.find(".module-loading").fadeOut('fast'); 
	}); 
	return false;
});

$("#mod-restaurants .restaurant-result").live('click',function(){
	$(".venue-preview").html($(this).next().html()).fadeIn();
});


$(".randomize").live('click',function(){
	//select our final results first
	for(var x=0;x<20;x++){
		setTimeout("RandomRestaurantOption();",x*110);
	}
	return false;
});


//contest stuff
function PopUpPrint(e)
{
	var w = window.open();
   w.document.location = $(this).attr('href');
	return false;
}
$(".popupprint").bind('click',PopUpPrint);
$("#friend-form").jValidator();

//error messages
if(Get.x == 'error'){
	TossError(Get.y);
}


function InputsToJson(ele){
	var ins = ele.find(':input');
	var settings = "";
	for(var y = 0; y<ins.length; y++){
		if(ins[y].type=="radio" || ins[y].type=="checkbox")
		{
			if(ins[y].checked)
			{
				settings += '"'+ins[y].name+'":"'+ins[y].value+'",';
			}
		}else{
			if(ins[y].value != "")
			{
				settings += '"'+ins[y].name+'":"'+ins[y].value+'",';
			}
		}
	}
	return "{"+settings.substring(0,settings.length-1)+"}";
}

$(".auto-close").live('click',function(){
	$(this).parents('.closable').eq(0).fadeOut('fast');
	return false;
});
// end document ready 
//================
});


function RandomRestaurantOption(){
	var opts = $('select[name=cuisine] option');
	var optNum = Math.floor(Math.random()*opts.length);
	opts.eq(0).val(opts.eq(optNum).val());
	opts.eq(0).text(opts.eq(optNum).text());
	
	var forkNum = Math.floor(Math.random()*2);
	$("ul.forks a").eq(forkNum).trigger('click');
}


function CloseFaceBox()
{
	jQuery.facebox.close();
}

var moduleForDeactivation;

function Deactivate(theData)
{
	jQuery.ajax({
		type: "POST",
		url: "/assets/scripts/add-remove-module.php",
		data: theData,
		success: function(msg){
			eval(msg);
			//return variable success. True - for good, false for error.
			//if there is an errror its returned in errorText
			if(success)
			{
				jQuery('#'+moduleForDeactivation).remove();
			}else if(!success)
			{
				TossError(errorText);
			}
		}
	}); 
}
