var window_w = 0;
var window_h = 0;
var bg_ratio = 1;
var main_h   = 0;
var focusEvent;
var focus_id = -1;
var hover_id = -1;
var cur_id   = -1;
var cur_content = new Array();
var activeSubnav = -1;
var MB_MIN_WIDTH  = 500;
var MB_MIN_HEIGHT = 200;
var BG_MIN_WIDTH  = 0;
var BG_MIN_HEIGHT = 0;
var imgObj = new Image();
var bgPlayer;
var cmtEditTimer;

$(document).ready(function() {
	//Set up background resizing
	//setBackground();
	BG_MIN_WIDTH  = parseInt( $('#background').css('min-width') );
	BG_MIN_HEIGHT = parseInt( $('#background').css('min-height'));

	if($('#background > img').width() > 1) {
		bg_ratio = $('#background > img').width()/$('#background > img').height();
	} else {
		$('#background').css('visibility','hidden');
		$(window).load( function() {
			prepareResize();
			//fixScroll();
		});
	}
	
	$.postingComment = false;
	
	/*var win_w = $(window).width();
	if(win_w < 1000) {
		num_p = 1000-win_w;
		$('.navlink > img').each( function() {
			var h = $(this).height();
			var w = $(this).width();			
			var ratio = w/h;
			var dx = Math.ceil((w/1000)*num_p);
			var dy = dx/ratio;
			$(this).width(w-dx);
			$(this).height(h-dy);
			$(this).css('margin-top',dy);
		});
		/*$('#kulogo').width(num_p);
	}*/
		
	$(window).resize(function() {
		//resize_fn();
		
		//attempt to detect when resizing is finished
		if(this.resizeEvent) {
			clearTimeout(this.resizeTO);
		}
		this.resizeEvent = setTimeout(function() {
        	$(this).trigger('resizeEnd');
   		}, 500);		
	});
	resize_fn();
	
	$(window).bind('resizeEnd', function() {
	    $('#overlay_content').html(cur_content[cur_id]);
	    resize_fn();
	});

	$('.fancybox').fancybox({
		'overlayOpacity' : 0.7,
		'transitionIn'	 : 'elastic',
		'transitionOut'	 : 'elastic',
		'overlayColor'   : '#333333'
	});

	//$('#tourScroller').corner();
	//DD_roundies.addRule('#tourScroller', '10px', true);
	
	if($('#page_callname').html() == 'welcome') {
		populateTourScroller();
		setNumComments($('#bg_id').html());
	}
	
	/*if($('#page_callname').html() == 'media') {
		$(".jspContainer").mousewheel(function(event, delta) {
			$('.vidpopup').hide();
			$('.photopopup').hide();
		});
	}
	else if($('#page_callname').html() == 'photos') {
		$(".jspContainer").mousewheel(function(event, delta) {
			$('.photopopup-big').hide();
		});
	}
	else if($('#page_callname').html() == 'gear') {
		$(".jspContainer").mousewheel(function(event, delta) {
			$('.photopopup-big').hide();
		});
	}
	else if($('#page_callname').html() == 'kutube') {
		$(".jspContainer").mousewheel(function(event, delta) {
			$('.vidpopup').hide();
		});
	}
	else if($('#page_callname').html() == 'userprofile') {
		$(".jspContainer").mousewheel(function(event, delta) {
			$('.videopopup-big, .photopopup-big, .friendpop').hide();
		});
		$('.monkeyvillemainrow').width($(window).width()-40);
	}
	else if($('#page_callname').html() == 'community') {
		$(".jspContainer").mousewheel(function(event, delta) {
			$('.videopopup-big, .photopopup-big').hide();
		});
		$('.monkeyvillemainrow').width($(window).width()-40);
	}*/
	
	setupCommentsLink();
		
	//Deal with active nav links
	var activeNav = 0;
	var activeSub = 0;
	$('.navlink').each(function() {
		if($(this).attr('href') == $('#page_callname').html()+".html")
		{
			activeNav = $(this);
		}
	});
	//Also see if a subnav page is active
	$('.subnavlink').each(function() {
		if($(this).attr('href') == $('#page_callname').html()+".html")
		{
			$(this).parent().parent().parent().children('.navlink').each(function(i,e) {
				activeNav = $(this);
			});
			activeSub = $(this);
		}
	});
	if(activeNav != 0)
	{
		activeNav.children('img').each(function() {
			var src = $(this).attr('src');
			var p = src.lastIndexOf('.');
			src = src.substring(0,p)+"-active"+src.substring(p);
			$(this).attr('src',src);
			$(this).removeClass('img_hover');
			$(this).die();
		});
	}
	if(activeSub != 0)
	{
		activeSub.children('img').each(function() {
			var src = $(this).attr('src');
			var p = src.lastIndexOf('.');
			src = src.substring(0,p)+"-active"+src.substring(p);
			$(this).attr('src',src);
			$(this).removeClass('img_hover');
			$(this).die();
		});
	}
	//Preload image link hovers
	$('.img_hover').each(function() {
		var src = $(this).attr('src');
		var p = src.lastIndexOf('.');
		var src_on = src.substring(0,p)+"-on"+src.substring(p);
		imgObj.src = src_on;
	});
	//Set up image link hover events
	$('.img_hover').live('mouseover', function() {
		var src = $(this).attr('src');
		var p = src.lastIndexOf('.');
		var src_on = src.substring(0,p)+"-on"+src.substring(p);
		$(this).attr('src', src_on);
	});
	$('.img_hover').live('mouseout', function() {
		var src = $(this).attr('src');
		var p = src.lastIndexOf('-');
		var src_off = src.substring(0,p)+src.substring(p+3);
		$(this).attr('src', src_off);
	});
	//Set up nav hovers with subnav menus
	$('.navlink').each(function(i, e) {
		var td = $(this).parent();
		var link = $(this);
		var subnav = "";
		if(td.children('.subnav').length > 0)
		{
			td.children('.subnav').children('li').each(function() {
				subnav += "<span class=\"subnavitem\">"+$(this).html()+"</span>";
			});
		}
		link.mouseover(function() {
			if(activeSubnav != i)
			{
				if(subnav != "")	activeSubnav = i;
				else				activeSubnav = -1;
				$('#subnav_div').css('visibility','hidden');
				$('#subnav_div').html(subnav);
				recenterSubnav();
				$('#subnav_div').hide();
				$('#subnav_div').css('visibility','visible');
				$('#subnav_div').fadeIn(300);
			}
		});
	});
	//Automatically show subnav for current page
	if(activeNav != 0) activeNav.mouseover();
	
	//Make inputs with default data clear on focus/refill on unfocus when empty
	$('.nice_default').each(function() {
		$(this).focus(function(eo) {
			if($(this).val() == $(this).attr('defaultValue')) $(this).val('');
		});
		$(this).blur(function(eo) {
			if($(this).val() == '') $(this).val($(this).attr('defaultValue'));
		});
	});
	
	//Set up hovers for social buttons
	$('.social_button, .social-form input[type="button"], .social-form input[type="submit"], .cab_lbl').hover(function() {
		$(this).css({
			color: '#ffeb83',
			'border-top-color': '#505050',
			'border-left-color': '#505050',
			'border-bottom-color': '#303030',
			'border-right-color': '#303030'
		});
	}, function() {
		$(this).css({
			color: '#fff',
			'border-top-color': '#606060',
			'border-left-color': '#606060',
			'border-bottom-color': '#404040',
			'border-right-color': '#404040'
		});
	});
	$('.social-form select').change(function() {
		$(this).blur();
	});
	//Hovers for avatar thumbnails
	$('.avborder, .avborder-mv, .avborder-st, .avborder_sm, .avborder_sm-mv, .avborder_sm-st').hover(function() {
		$(this).css('border-style', 'solid');
	}, function() {
		$(this).css('border-style', 'outset');
	});
	//Hovers for editable social content
	$('.cmt_editable').mouseenter(function() {
		$(this).css('border-color', '#999');
		var temp = $(this);
		if(cmtEditTimer) clearTimeout(cmtEditTimer);
		cmtEditTimer = setTimeout(function() {temp.children('.control').css('visibility', 'visible');}, 500);
	});
	$('.cmt_editable').mouseleave(function() {
		$(this).css('border-color', '#666');
		if(cmtEditTimer) clearTimeout(cmtEditTimer);
		$(this).children('.control').css('visibility', 'hidden');
	});
	
	
	

	var hConfig = {
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
		interval: 400, // number = milliseconds for onMouseOver polling interval
		timeout: 400, // number = milliseconds delay before onMouseOut
		over: function() {
			showOverlay(hover_id);
        },
        out: function() {}
	}
	$('.overlay_link').hoverIntent(hConfig);
	$('.overlay_link').mouseenter( function() {
		hover_id = $(this).attr('id');
		animateFocus(hover_id);
	});
	$('.overlay_link').mouseout(clearFocus);
	//$('.overlay_link').bind('hover', function() {/*showOverlay(hover_id);*/alert('hover done!');} );

	
	//Initialize overlay links
	$('.overlay_link').each(function() {
		var w    = $(this).children('.img_fade:first').width();
		var h    = $(this).children('.img_fade:first').height();
		
		var src  = $(this).children('.img_fade').attr('src');
		var file = src.substr(0,src.length-4);
		var ext  = src.substr(src.length-3);
		var activeImg = "'"+file+'-active.'+ext+"'";
		
		$(this).css({'height':h,'width':w,'display':'block'});
		$(this).append('<span class="focusFade" style="width:'+w+'px; height:'+h+'px; background-image: url('+activeImg+')"></span>');
		
		$('.focusFade').addClass('transparent');
	});
	
	
	function animateFocus(id) {
		if(cur_id != id) {
			$('#'+id).css('position','relative');		
			$('#'+id+' .focusFade').animate( {opacity: 1}, { queue:false, duration:600 },'linear');
			$('#'+id+' > img').animate( {opacity: 0}, { queue:false, duration:2000 });
		}
	}
	
	
	$(window).load(function() {
		fixScroll();
		//setTimeout(fixScroll,500);
	});
	
	//Close the overlay if the user clicks outside of it
	if($('a.overlay_click, a.overlay_link').length > 0)
	{
		$('input').click(function(e) {e.stopPropagation();});
		$('a.overlay_click, a.overlay_link').click(function(e) {
			showOverlay($(this).attr('id'));
			e.stopPropagation();
		});
		$(document).click(function(e) {
			if($('#magicBox').length>0) {
				var mx = e.pageX; var my = e.pageY;
				var ox = $('#magicBox').offset().left;
				var oy = $('#magicBox').offset().top;
				var ow = $('#magicBox').outerWidth();
				var oh = $('#magicBox').outerHeight();
				if(mx < ox || mx > (ox+ow) || my < oy || my > (oy+oh)) closeOverlay();
			}
		});
	}
});



function loadOverlayContent() {
	
}



function showOverlay(id) {
	if(id != cur_id) {
		$('#'+cur_id+' .focusFade').animate( {opacity: 0}, { queue:false, duration:500 });
		$('#'+cur_id+' .img_fade' ).animate( {opacity: 1}, { queue:false, duration:100 });
		cur_id = id;
		//$('#'+cur_id+' .focusFade').fadeTo(150,0.7);
		$('#'+cur_id+' .focusFade').fadeTo(100,0.9);
		$('#'+cur_id+' .focusFade').fadeTo(150,0.5);
		$('#'+cur_id+' .focusFade').fadeTo(100,1.0, function() {
			if(typeof cur_content[cur_id] == 'undefined') {
				$.post('ajindex.php?i='+id, {}, function(data) {								
					cur_content[cur_id] = data;
					$('#magicBox').show();
					$('#overlay_content').html(data);
					$('#overlay_content').hide();
					$('#overlay_content').fadeIn(600, function() { } );
					resize_fn();
					$('#overlay_close').click(closeOverlay);
					$('#overlay_content .onload').load(resize_fn);
				}, "html");
			} else {
				$('#magicBox').show();
				$('#overlay_content').html(cur_content[cur_id]);
				$('#overlay_content').hide();
				$('#overlay_content').fadeIn(600, function() {/*resize_fn();*/});
				resize_fn();
			}
		});
	}
}



function clearFocus() {
	$('.focusFade').stop();
	$('.img_fade').stop();
	$('.focusFade').animate( {opacity: 0}, { queue:false, duration:0 });
	$('.img_fade').animate(  {opacity: 1}, { queue:false, duration:0 });
	if(cur_id != -1) {
		$('#'+cur_id+' .focusFade').animate( {opacity: 1},  { queue:false, duration:0 });
	}
	
	//$('#deal_of_the_day').css('background-image','');
}

//Controller for when the window is resized
//	makes sure bg image is resized and vertically center stuff in the main div
function resize_fn()
{
	var old_w = window_w;
	var old_h = window_h;
	window_w = $(window).width();
	window_h = $(window).height() - $('#bottom').outerHeight();
	
	if($('#background > img').width() > 1) {
		resize_bg();
	}
	
	//Fix the top bar's width since it's fixed and padding/margins don't work right
	$('#top').width(window_w - 40);
	
	if($('#magicBox').length > 0)
	{
		if($('#tourScroller').length > 0) {
			var new_w  = window_w - $('#home_side_links').outerWidth() - $('#jukebox').outerWidth() - 115;
			var ts_pos = $('#tourScroller').offset();
			var new_h  = Math.round(ts_pos.top) - 185;
		} else {
			new_w = 800; //window_w - 200;
			new_h = window_h - 300;
			$('#magicBox').css('position','absolute');
			$('#magicBox').css('top','50px');
			$('#magicBox').css('left',Math.round((window_w-new_w)/2)+'px');	
		}
		$('#magicBox').width ( (new_w > MB_MIN_WIDTH ) ? new_w : MB_MIN_WIDTH  );
		//$('#magicBox').height( (new_h > MB_MIN_HEIGHT) ? new_h : MB_MIN_HEIGHT );
		
		//$('#magicBox').css('margin-left','-'+($('#home_side_links').outerWidth()+50)+'px');
		//$('#magicBox').css('padding-left',($('#home_side_links').outerWidth()+60)+'px');
		
		$('#overlay_content').height('').height('auto');
		if(cur_id == "whats_happening" || cur_id == "promotions") {
			var avail_w = $('#magicBox').width() - 110;
			var new_w   = Math.floor(avail_w/3);
			$('#overlay_content').width($('#magicBox').width() - 5);
			$('.overlay_sub').width(new_w);
			$('#overlay_sub_last').width(avail_w-2*new_w);
			$('.overlay_sub').height('').height('auto');
			var max_h = 0;
			$('.overlay_sub').each( function() {
				if($(this).height()>max_h) {
					max_h = $(this).height();
				}
			});
			$('.overlay_sub').height(max_h);
			//$('.overlay_sub').height($('#magicBox').height() - 40);
			
			//vertically center contents
			/*if(cur_id == "promotions") {
				$('.overlay_sub img').each( function() {
					var img_h = $(this).height();
					if(img_h == 0) {
						$(this).load(function(){
							img_h = this.height;
							$(this).css('margin-top',($('.overlay_sub').height()-$(this).height())/2);
						});
					} else {
						$(this).css('margin-top',($('.overlay_sub').height()-$(this).height())/2);
					}
				});
			} else if(cur_id == "whats_happening") {
				$('.overlay_sub .vcenter').each( function() {
					var div_h = $(this).height();
					$(this).css('margin-top',($('.overlay_sub').height()-$(this).height())/2);
				});
			}*/
			
			//$('.overlay_sub img.resize').width(new_w - 20);
			$("a[rel=group]").fancybox({
				'transitionIn'	:	'elastic',
				'transitionOut'	:	'elastic',
				'speedIn'		:	300, 
				'speedOut'		:	200, 
				'overlayShow'	:	false,
				'titlePosition' :   'over'
			});

		} else {
			$('#overlay_content').width('auto');
			$('.overlay_full').height($('#magicBox').height() - 40);
		}
		
	}
	
	if($('#bgPlayer').length>0) {
		resize_player();
	}
	
	//Now make sure stuff in the main div is vertically centered
	var main = $('#main').position();
	var bottom = $('#bottom').position();
	var mt = parseInt($('#bottom').css('margin-top'));
	var mb = parseInt($('#main').css('margin-bottom'));
	var space = bottom.top - mt - main.top - mb;
	var pt = parseInt($('#main').css('padding-top'));
	var pb = parseInt($('#main').css('padding-bottom'));
	main_h = space - pt - pb;
	$('#main').height(main_h);
	
	/*
	//#overlay can have its own scrollbar and not affect overall page size if we want
	//if($('#overlay').outerHeight() > main_h) $('#overlay').height(main_h);
	//If we have more content than space in the window, push bottom content down
	if($('#main').outerHeight() > main_h)
	{
		var pos = $('#main').outerHeight() - main_h;
		$('#bottom').css('bottom', '-'+pos+'px');
	}
	//Otherwise, center it vertically
	else
	{
		//Assuming each child div of #main should be the same vertical level
		//	if not, wrap all the children in a div so we center everything at once
		$('#main').height(main_h);
		$('#main').children('div').each(function(i, e) {
			var h = $(this).outerHeight();
			var m = Math.round((main_h - h)/2.0);
			$(this).css('margin-top', m);
		});
	}*/
	//positionTick();
	recenterSubnav();
}

function resize_bg() {
	window_w = $(window).width();
	window_h = $(window).height() - $('#bottom').outerHeight();
	window_ratio = window_w/window_h;
	
	if(window_ratio > bg_ratio) {
		var w = window_w;
		var h = Math.round(w/bg_ratio);
	} else {
		var h = window_h;
		var w = Math.round(h*bg_ratio);
	}
	$('#background').width ( (w > BG_MIN_WIDTH ) ? w : BG_MIN_WIDTH );
	$('#background').height( (h > BG_MIN_HEIGHT) ? h : BG_MIN_HEIGHT);
	$('#background > img').width ( (w > BG_MIN_WIDTH ) ? w : BG_MIN_WIDTH );
	$('#background > img').height( (h > BG_MIN_HEIGHT) ? h : BG_MIN_HEIGHT);
}

function resize_player() {
	bgPlayer.pause();
	window_w = $(window).width();
	window_h = $(window).height();// + 25;
	/*window_ratio = window_w/window_h;
	
	if(window_ratio > bg_ratio) {
		var w = window_w;
		var h = Math.round(w/bg_ratio);
	} else {
		var h = window_h;
		var w = Math.round(h*bg_ratio);
	}
	
	
	$('#bgPlayer').width ( (w > BG_MIN_WIDTH ) ? w : BG_MIN_WIDTH );
	$('#bgPlayer').height( (h > BG_MIN_HEIGHT) ? h : BG_MIN_HEIGHT);/**/
	$('#bgPlayer').width ( window_w );
	$('#bgPlayer').height( window_h ); /**/
}

function closeOverlay()
{
	//$('#magicBox').html('');
	$('#magicBox').hide();
	$('#overlay_tick').hide();
	cur_id = -1;
	clearFocus();
}

function recenterSubnav()
{
	if(activeSubnav != -1)
	{
		var width = $('#subnav_div').outerWidth(true);
		var mid = Math.round($('#subnav_div').outerWidth()/2.0);
		var off = $('#subnav_area').offset().left;
		var space = $('#top').width() - 40;
		var parentCenter = 0;
		$('.navlink').each(function(i, e) {
			if(i == activeSubnav)
			{
				parentCenter = $(this).offset().left + Math.round($(this).width()/2.0);
			}
		});
		var x = parentCenter - mid - off;
		if(x < 5) x = 5;
		if(x + width > space) x = space - width;
		$('#subnav_area').css('padding-left', x+'px');
	}
}

function positionTick() {
	if($('#overlay_tick').length>0) {
		var offset_y = new Array()
		offset_y['promotions'] = 40;
		offset_y['whats_happening'] = 84;
		offset_y['deal_of_the_day'] = 126;
		$('#overlay_tick').offset( {
			top:  $('#magicBox').offset().top+offset_y[cur_id],
			left: $('#magicBox').offset().left-22
		});
		$('#overlay_tick').show();
	}
}

function populateTourScroller() {
	$.post('ajindex.php?i=tour_scroller', {}, function(data) {				
		$('#tourScroller').html(data);
		$('#tour-carousel').jcarousel();
		//begin shameless hack
		$('#tour-carousel').width($('#tour-carousel').width()+1000);
		//end shameless hack
	});
}

function setNumComments(id) {
	$.post('ajindex.php?i=num_comments&bg_id='+id, {}, function(data) {				
		$('#num_comments').html(data);
	});
}

function prepareResize() {
	var bg = $('#background > img');
	$(bg).removeAttr("width");
    $(bg).removeAttr("height");
    $(bg).css({ width: "", height: "" });
    bg_ratio = $(bg).width()/$(bg).height();
	resize_bg();
	$('#background').css('visibility','visible');
}

function setupCommentsLink() {
	$(".comments_link").fancybox({
		'autoScale'      : true,
		'width'          : 515,
		'height'		 : 'auto',
		'scrolling'      : 'auto',
		'overlayOpacity' : 0.7,
		'transitionIn'	 : 'elastic',
		'transitionOut'	 : 'elastic',
		'overlayColor'   : '#333333',
		'autoDimensions' : false,
		'onComplete'     : function() {
		    $("#fancybox-content > div").attr('id','fancy-scroll');
		    $("#fancy-scroll").height($("#fancybox-content").height());
		    setupFancyComments(this.href);
		}
	});
}

function setupFancyComments(url) {
	$('#commentsub').submit( function() {
		if($.postingComment == true) {
            return false;
        } else {
            $.postingComment = true;
            $('#cmt-form').unbind('submit');
            $('#cmt-form').submit( function() {
                return false;
            });
        }
    	$.fancybox.showActivity();
    	$.post("fastajax.php?action=postComment", $("#commentsub").serialize(), function() {
    		$('#fancy-scroll').load(url, function() { $.postingComment = false; $.fancybox.hideActivity(); setupFancyComments(); } );
    	});
    	return false;
    });
}

function setupScrollPanes() {}

function resizeFancyBox() {
	/*if($("#fancybox-content").height() < 200) {
		$("#fancybox-content #fancy-scroll").animate( {
			height: 200
		});
	}*/
}

function fixScroll() {}

function fixPopup(classname) {
	$('.'+classname).hide();
}


/*function setBackground() {
	var callname = $('#page_callname').html();
	$('#background').load('ajindex.php?i=bg_image&cn='+callname, function() {				
		resize_fn();
	});
}

function populateCommentsBox() {
	$.post('ajindex.php?i=bg_comments', {}, function(data) {				
		$('#bg_comments').html(data);
	});
}*/
