var ad_states = [];

$(window).load( function() {
	//Break out of frames
	if (top.location != self.location) {
		top.location = self.location;
	}
	
	$('div#useralert a.close').live('click', function(){
		$(this).parent().hide(250);
		$(this).parent().find('p').html();
	});
	
	if ($('#news-ticker #ticker').length) {
		$('#news-ticker #ticker').cycle('resume');
	}
	
	if ($('#UserUsername').val() != '') {
		$('#ajax-username-ph').hide();
	}
	
	if ($('#UserPassword').val() != '') {
		$('#ajax-password-ph').hide();
	}

	if ($('.scrollable').length > 0) {
		$('.scrollable').jScrollPane( {
			verticalDragMinHeight: 35,
			verticalDragMaxHeight: 35
		} );
	}
	// Load ads
	getAds();
} );


$(document).ready( function() {

	$('#page-blocker-shadow').css('opacity', 0.001);

	if ( $('#myaccount-container').length > 0 && $('#notifications').length > 0) {
		getNotifications();
		setInterval( function() {
			getNotifications();
		}, 45000);
	}
	
	$('#notifications').click( function() {
		$('#myaccount-dropdown').slideDown(250, function() {
			setTimeout(function() {
				$('#myaccount-notify-sub').slideDown(250);
				$('.myaccount-section[rel=myaccount-notify-sub]').addClass('active');
			}, 250);
		} );
	} );
	
	$('#remember-link').click( function() {
		if ($(this).hasClass('active')) { 
			$(this).removeClass('active');
			$('#login-rememberMe').val(0);			
		} else {
			$(this).addClass('active');
			$('#login-rememberMe').val(1);
		}
	} );
	
	$('#my-account-training').click( function() {
		if (!$('#train').hasClass('active')) { 
			$("#train").click();
		}
			if ($('#train-interface').css('display') == 'none') {
				setTimeout(function() {
					$('#show-train-interface').click();
				}, 500);
			}
		
	} );
	
	$('.view-ad').live('click', function() {
		var id = $(this).attr('rel');
		var ad_id = id.split('-')[2];
		
		if (typeof ad_states[ad_id] == "undefined") {
			ad_states[ad_id] = null;
		}
		
		if (typeof ad_states[ad_id] != "undefined" && ad_states[ad_id] != "open") {
			adevent(id, "click");
			ad_states[ad_id] = "open";
		}else {
			ad_states[ad_id] = null;
		}
		
		overlay_ad(this);
	} );
	
	$('.view-ad').live('mouseover', function() {
		var id = $(this).attr('rel');
		adevent(id, "mouseover");
	});
	
	$('a.ad-link').live('click',function() {
		var id = $(this).attr('rel')
		adevent(id, "target-click");
	});

	$('a.ad-close').live('click', function(event) {
		event.stopPropagation();
		var tar = '#' + $(this).attr('rel');
		$(tar).hide(250);
	});
	
	/* PAGE DEFAULTS */
	$.dash_search = {};
	$.dash_search.timer;
	
	/* EVENTS / ACTIONS */

		$('#showlogin-tab, #close-tab').click( function() {
			//$('#online-now-dropdown').slideUp(250);
			toggleLogin();
		});

			$('#ajax-username-ph').click( function() {
				$('#UserUsername').focus();
			} );

			$('#ajax-password-ph').click( function() {
				$('#UserPassword').focus();
			} );
			
			$('#UserUsername').focusin( function() {
				$('#ajax-username-ph').hide();
			});

			$('#UserUsername').focusout( function() {
				if ($('#UserUsername').val() == '') {
					$('#ajax-username-ph').show();
				}
			});

			$('#UserPassword').focusin( function() {
				$('#ajax-password-ph').hide();
			});
			
			$('#UserPassword').focusout( function() {
				if ($('#UserPassword').val() == '') {
					$('#ajax-password-ph').show();
				}
			});

		$('#login-tab').click( function() {
			ajaxLogin();
		});

		$('#UserPassword').keyup( function(event) {
			if (event.keyCode == 13) {
				ajaxLogin();
			}
		});

		$('a.main-section').click( function() {
			$('#search-close').click();
			$('#share-close').click();
			$('#radio-close').click();

			toggleSubSection(this);
		});

		$('#showaccount-tab').click( function() {
			//$('#online-now-dropdown').slideUp(250);
			$('#myaccount-dropdown').slideToggle(250);
			$('#showaccount-tab').toggleClass('active');
			$('#myaccount-dropdown .active').removeClass('active');
			$('#myaccount-dropdown .myaccount-subsection').slideUp(250);
		});

		$('.link-sub-sub').click( function() {
			var tar = '#' + $(this).attr('id') + '-sub';
			$('.dashboard-sub-sub').not($(tar)).slideUp(250);
			$(tar).slideToggle(250, function() {
				if ($(tar).is(":visible")) {
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				}
			});
		});

		$('#myaccount-dropdown .myaccount-section[rel]').click( function() {
			$('.myaccount-subsection').slideUp(250);

			if ($(this).hasClass('active')) {
				$('#' + $(this).attr('rel')).slideUp(250);
				$(this).removeClass('active');
				$('#' + $(this).attr('rel')).removeClass('active');
				return;
			}
			
			$('a.myaccount-section.active').removeClass('active');
			$('.myaccount-subsection.active').removeClass('active');
			$(this).addClass('active');
			$('#' + $(this).attr('rel')).addClass('active');
			$('#' + $(this).attr('rel')).slideDown(250);
		});

		$('#search').click( function() {
			$('#share-close').click();
			$('#radio-close').click();

			$('#search-interface').fadeToggle(250);
			$('#search-text').val('');
			$('#search-text').focus();
		});

		$('#search-close').click( function() {
			$('#search-interface').fadeOut(250);
			$('#search-results').hide(0, function() {
				$('#results').empty();
			});
		});

		$('#search-text').keyup( function(event) {
			searchTimer(event);
		});

		$('#train-overview a.train-section').click( function() {
			toggleTrainOverviewSection(this);
		});

		$('#curriculum-interface a.curriculum-section').click( function() {
			toggleCurriculumOverviewSection(this);
		});

		$('#show-train-interface').click( function() {
			$('#show-curriculum-interface').removeClass('active');
			$('#curriculum-interface, .curriculum-sub-section').slideUp(250);
			$('#train-overview, #train-overview .train-sub-section').slideUp(250);
			$('#train-interface #train-classes .z a.active').removeClass('active');

			$(this).toggleClass('active');
			$('#train-interface').slideToggle(250);
		});

			$('#train-interface .classes-page a').click( function() {
				var id = $(this).attr('curriculum_id');
				var url = "/dashboard/get_curriculum_details/" + id;
				
				$.getJSON(url, function(data){
					$('#training_class_list > tr').each(function(){
						$(this).remove();
					});
					var TrainingClasses = document.getElementById("training_class_list");
					$.each(data.TrainingCourse, function(courses,course){
						//Insert Course Names Here In The Future
						$.each(course.TrainingClass, function(classes,training_class){
							var NewClass = document.createElement("tr");
							var Name = document.createElement("td");
							if(data.Legend.first_name == null){
							Name.innerHTML = "<a href='/train/watch/football/"+ data.Position.name.toLowerCase().replace(' ','-') + "/" + data.TrainingCurriculum.id + "/" + training_class.training_course_id +"/"+ training_class.id +"'>" + training_class.title.substring(0,10).toUpperCase() + "</a>";	
							}else{
							Name.innerHTML = "<a href='/train/watch/football/"+ data.Position.name.toLowerCase().replace(' ','-') + "/" + data.Legend.first_name.toLowerCase() + "-" + data.Legend.last_name.toLowerCase() + "/" + training_class.training_course_id +"/"+ training_class.id +"'>" + training_class.title.substring(0,10).toUpperCase() + "</a>";
							}
							var Video = document.createElement("td");
							var innerVideo = document.createElement("div");
							if(training_class.TrainingClassesUser !== undefined && training_class.TrainingClassesUser.position == 'COMPLETE'){
								innerVideo.setAttribute("class", "star");
							}
							var Quiz = document.createElement("td");
							var innerQuiz = document.createElement("div");
							if(training_class.UserQuiz !== undefined){
								innerQuiz.setAttribute("class", "star");
							}
							var QuizCellId = "quiz_" + training_class.id;
							innerQuiz.setAttribute("id",QuizCellId);
							Quiz.appendChild(innerQuiz);
							var VideoCellId = "video_" + training_class.id;
							innerVideo.setAttribute("id",VideoCellId);
							Video.appendChild(innerVideo);
							NewClass.appendChild(Name);
							NewClass.appendChild(Video);
							NewClass.appendChild(Quiz);
							TrainingClasses.appendChild(NewClass);
							
							if(course.UsersTest !== undefined){
								$('#training-test-score').html(course.UsersTest.score + "%");
							}else{
								$('#training-test-score').html('0%');	
							}
							
							if(data.UsersExam !== undefined){
								$('#training-exam-score').html(data.UsersExam.score  + "%");
							}else{
								$('#training-exam-score').html('0%');
							}
						});
					});
					
				});
				showTrainOverview(this);
				return false;
			});

		
		/* IF THERE ARE MORE THAN ONE TRAINING CLASS PAGE - SHOULD REMOVE (going to AJAX) */

		if ($('.classes-page').length > 1) {
			$('#train-left').show();
			$('#train-right').show();
			
			$('#train-interface #classes').cycle({ 
				speed: 250,
				timeout: 0, 
				fx: 'scrollHorz',
				prev: '#train-left',
				next: '#train-right',
				cleartypeNoBg: true
			});
		}
		
		if ($('#default-dashboard').length) {
			var pieces = $('#default-dashboard').val().split('-');
			
			if (pieces.length == 2) {
				var main = pieces[0];
				var sub = $('#default-dashboard').val();
				$('#' + main).addClass('active');
				$('#' + sub).addClass('active');
				$('#' + main + '-sub').show();
			}

			if (pieces.length == 3) {
				var main = pieces[0];
				var sub = pieces[1];
				var subsub = $('#default-dashboard').val();
				$('#' + main).addClass('active');
				$('#' + subsub).addClass('active');
				$('#' + main + '-sub').show();
				$('#' + main + '-' + sub + '-sub').show();
			}

			if (main == "train") {
				if ($("#curriculum").length) {
					$("#show-train-interface").click();
					var i = 0;
					var link = '';
					// Loop over each page
					$("div#train-classes div#classes div.classes-page").each(function() {
						$(this).find('a').each(function() {
							if ($(this).attr('curriculum_id') == $("#curriculum").val()) {
								link = $(this);
							}
						});

						if (link == '') {
							i++;
						}
					});

					for (j = 0; j < i; j++) {
						$("#train-right").click();
					}

					$(link).click();
					$("div#train-overview a[rel='fund-sub']").click();
				}
			}
		}
		$('#show-curriculum-interface').click( function() {
			$('#show-train-interface').removeClass('active');
			$('#train-interface, #train-overview, #train-overview .train-sub-section').slideUp(250);
			$('#curriculum-interface').removeClass('active');
		
			$(this).toggleClass('active');
			$('#curriculum-interface').slideToggle(250);
		});

		$('#share').click( function() {
			$('#search-close').click();
			$('#radio-close').click();
			$('#share-interface').fadeIn(250);
		});

			$('#share-close').click( function() {
				$('#share-interface').fadeOut(250);
			});
		
		/*
		$('#online-now').click( function() {
			if ( $('#login-dropdown').length > 0 ) { 
				if ( $('#login-dropdown').css('display') != 'none' ) {
					toggleLogin();
				}
			}
			if ( $('#signup-dropdown').length > 0 ) {
				if ( $('#signup-dropdown').css('display') != 'none' ) {
					toggleSignUp();
				}
			}
			if ( $('#myaccount-dropdown').length > 0 ) {
				$('#showaccount-tab').removeClass('active');
				$('#myaccount-dropdown').slideUp(250);
			}

			$('#online-now-dropdown').slideToggle(500);
		});
		*/

		$('.post-textarea').live('focus keyup input paste', function(event) {
			limit(this, 500, 'down');
		});

		$('.comment-textarea').live('focus keyup input paste', function(event) {
			limit(this, 250, 'down');
		});

		$('.email-textarea').live('focus keyup input paste', function(event) {
			limit(this, 100, 'up');
		});

		$('textarea').live('keypress', function(event) {
			if (event.keyCode == 13) {
				return false;
			}
		});
		
	  	/* PLUGINS */
		
		$('#news-ticker #ticker').cycle({
			fx: 'scrollRight',
			timeout: 5000,
			speed: 2000,
			fit: 1,
			width: 600,
			cleartypeNoBg: true,
			pause: true,
			before: function(currSlideElement) { $(currSlideElement).fadeOut(500); },
			after: function(currSlideElement) { $(currSlideElement).fadeIn(0); }
		}).cycle('pause');
		
		/* ONLY IF A CONTENT-SLIDESHOW EXISTS */
		
		
	$("a.social-share-action").live('click',function(e){
		e.preventDefault();
		openShareWindow(this);
	});

	// share fb/twitter windows to open
	$("a.social-share, a.social-share-action").not(".action").live("click", function(){
		if($(this).hasClass('action')){ return false; }
		if($(this).attr('id') == 'fb-social-share'){
			facebookConnect();
			return;
		}else if($(this).attr('id') == 'tw-social-share'){
			twitterConnect();
			return;
		} 
		openShareWindow(this);
		return false;
	});
	
	$("a.love-ad").live("click", function(){
		var id = $(this).attr('rel').split('-')[1];
		
		if (typeof id != "undefined" && id != null) {
			$.ajax({
				url: '/like/add/like/advertisement/'+id,
				async: true,
				type: 'GET',
				dataType: 'json',
				success: function(response) {
					$("#user-ad-"+response.foreign_id+" a.love-ad span").html("("+response.likes+")");
					$("#user-ad-"+response.foreign_id+" a.hate-ad span").html("("+response.dislikes+")");
				}
			});
		}
	});
	
	$("a.hate-ad").live("click", function(){
		var id = $(this).attr('rel').split('-')[1];
		
		if (typeof id != "undefined" && id != null) {
			$.ajax({
				url: '/like/add/dislike/advertisement/'+id,
				async: true,
				type: 'GET',
				dataType: 'json',
				success: function(response) {
					$("#user-ad-"+response.foreign_id+" a.love-ad span").html("("+response.likes+")");
					$("#user-ad-"+response.foreign_id+" a.hate-ad span").html("("+response.dislikes+")");
				}
			});
		}
	});
	
	$('#main-footer .main-action').click( function(event) {
		if ($(this).hasClass('active')) {
			$('#main-footer .main-action').removeClass('active covered');
			$('#main-footer .main-pipe').removeClass('active');
			$('#main-footer #main-footer-line').removeClass().hide();
			$('#main-footer .main-footer-details').slideUp(250);
			return false;
		}
		
		var section = $(this).attr('rel');

		$(this).addClass('active');
		$('#main-footer .main-action').not($(this)).removeClass('active').addClass('covered');
		
		$('#main-footer .main-pipe').removeClass('active');
		$(this).next('.main-pipe').first().addClass('active');
		$(this).prev('.main-pipe').first().addClass('active');

		$('#main-'+section+'-details').slideDown(250);
		$('#main-footer .main-footer-details').not($('#main-'+section+'-details')).slideUp(250);
		
		$('#main-footer #main-footer-line').removeClass().addClass(section).show();
	} );
	
} );

function showBlocker(dialog) {
	$('.overlay').not($(dialog)).hide(250);
	var clone = $(dialog).clone();
	$('#page-blocker-dialog').empty().append($(clone));
	if ($('html.ie7').length > 0) {
		var w_w = $(window).width();
		var w_h = $(window).height();
		var d_w = $(clone).width();
		var d_h = $(clone).height();
		var tc = (w_h / 2) - (d_h / 2);
		var lc = (w_w / 2) - (d_w / 2);
		$(clone).css('top', tc).css('left', lc);
	}
	$('#page-blocker').fadeIn(250);
}

function hideBlocker() {
	$('#page-blocker').fadeOut(250, function() {
		$('#page-blocker-dialog').empty();
	});
}

function getAds() {
	var sessid = $("#sessid").val();
	
	var ads = $.get(
		"/ads/get/"+sessid,
		function(result) {
			$.each(result, function(i,ad) {
				$("#container_ad-"+i).html(ad);
			});
		},"json"
	);
	
	if ($("#user-ads-container").length > 0) {
		$("head").append('<link rel="stylesheet" type="text/css" href="/theme/football/css/elements/user_ad.css">');
		getUGA();
	}
}

function getUGA() {
	var sessid = $("input#sessid").val();
	
	var ads = $.get(
		"/ads/uga/"+sessid,
		function(result) {
			if (result != false) {
				$(result).each(function(i,ad) {
					$("#user-ads-container").append(ad);
				});
			}
		},"json"
	);
}

function openShareWindow(ob){
	var windowWidth = 700;
	var windowHeight = 500;
	var centerWidth = Math.floor(($(window).width() - windowWidth) / 2);
	var centerHeight = Math.floor(($(window).height() - windowHeight) / 2);
	
	newWindow = window.open(ob.href, "Share SOTL", 'resizable=0,width=' + windowWidth + 
		',height=' + windowHeight + 
		',left=' + centerWidth + 
		',top=' + centerHeight);
	
	newWindow.focus();
}

function facebookConnect(){
	$.ajax({
	  url: "/ajax/facebookConnect",
	  success: function(d){
			var windowWidth = 700;
			var windowHeight = 500;
			var centerWidth = Math.floor(($(window).width() - windowWidth) / 2);
			var centerHeight = Math.floor(($(window).height() - windowHeight) / 2);
			var windowUrl = $('#fb-social-share').attr('rel');
			newWindow = window.open(windowUrl, "Share SOTL", 'resizable=0,width=' + windowWidth + 
				',height=' + windowHeight + 
				',left=' + centerWidth + 
				',top=' + centerHeight);
			
			newWindow.focus();
	  }
	});
}

function twitterConnect(){
	$.ajax({
	  url: "/ajax/twitterConnect",
	  success: function(d){
	  	var windowWidth = 700;
			var windowHeight = 500;
			var centerWidth = Math.floor(($(window).width() - windowWidth) / 2);
			var centerHeight = Math.floor(($(window).height() - windowHeight) / 2);
			var windowUrl = $('#tw-social-share').attr('rel');
			newWindow = window.open(windowUrl, "Share SOTL", 'resizable=0,width=' + windowWidth + 
				',height=' + windowHeight + 
				',left=' + centerWidth + 
				',top=' + centerHeight);
			
			newWindow.focus();
	  }
	});
}

function limit(el, ml, d) {
	if ( $(el).val().match(/\r|\n|\t/gim) ) {
		$(el).val( $(el).val().replace(/\r|\n|\t/gim, ' ') );
	}

	if( $(el).val().length > ml ) {
		$(el).val( $(el).val().substring(0, ml) );
	}

	if ( d == 'up' ) {
		$(el).parent().parent().find('.character-count').text($(el).val().length);
	} else if ( d == 'down' ) {
		$(el).parent().parent().find('.character-count').text(ml - $(el).val().length);
	}
}

function loginSignupSlider(which) {
	var which = $('#'+which);
	
	if ( $(which).css('display') == 'none' ) {
		$(which).show(0, function() {
			$(which).animate({ 'top' : 0 }, 500);
		});
	} else {
		$(which).animate({ 'top' : -172 }, 500, function() {
			$(which).hide();
		});
	}
}

	function toggleLogin() {
		$('#showlogin-tab').toggleClass('active');

		loginSignupSlider('login-dropdown');
	}

function ajaxLogin() {
	var dat = { 'data': { 'User': { 'username':$('#UserUsername').val(),'password': $('#UserPassword').val(), 'rememberMe': $('#login-rememberMe').val() } } };
	
	var action = $("#ajaxLoginForm").attr('action');
	
	$("#ajaxLoginForm").submit(function(result) {
		console.log(result);
	});
	
	/*
	$.ajax({
		url: action,
		async: true,
		type: 'GET',
		dataType: 'json',
		data: dat,
		success: function(response) {
			//console.log(response);

			if (response == false) {
				alert("Error :\n\nSorry, but there is no match for those credentials.  Please try again.");
			} else {
				var user_type = response.toLowerCase();
				//console.log(user_type);
				if (user_type == 'legend') {
					window.location.href="/";
				} else {
					window.location.reload();
				}
			}
		}
	});
	*/
}

function toggleSubSection(link) {
	$('#train-interface, #train-overview, #train-overview .train-sub-section').slideUp(500);
	$('#train-interface #train-classes .classes-page a.active').removeClass('active');
	$('#curriculum-interface, .curriculum-sub-section').slideUp(500);
	$('#curriculum-interface').removeClass('active');
	$('#show-train-interface, #show-curriculum-interface').removeClass('active');

	var sub = $(link).attr('id') + '-sub';

	if ($(link).attr('id') == $('.main-section.active').attr('id')) {
		$(link).removeClass('active');
		$('.sub-section[rel=' + sub + ']').slideUp(500);
		return;
	}
	
	$('.main-section.active').removeClass('active');
	$(link).addClass('active');

	$('.sub-section').slideUp(500);
	$('.sub-section[rel=' + sub + ']').slideDown(500);
}

function showTrainOverview(el) {
	if ($(el).hasClass('active')) { return; }

	$('#train-interface #train-overview, #train-interface #train-overview .train-sub-section').slideUp(250);
	$('#train-interface a.train-section.active').removeClass('active');
	$('#train-interface .classes-page a.active').removeClass('active');
	
	$(el).addClass('active');
	$('#train-interface #train-overview').slideDown(250);
	return false;
}

	function toggleTrainOverviewSection(el) {
		var target = $(el).attr('rel');
		target = $('#' + target);

		if ($(el).hasClass('active')) {
			$(el).removeClass('active');
			$(target).slideUp(250);
			return;
		}

		$('#train-overview .train-section.active').removeClass('active');
		$('#train-overview .train-sub-section').slideUp(250);
		$(el).addClass('active');
		$(target).slideDown(250);
	}

function showCurriculumOverview(el) {
	if ($(el).hasClass('active')) { return; }

	$('#curriculum-interface').removeClass('active');
	$('#curriculum-interface, .curriculum-sub-section').slideUp(250);
	$(el).addClass('active');
	$('#curriculum-interface').slideDown(250);
}

	function toggleCurriculumOverviewSection(el) {
		var target = $(el).attr('rel');
		target = $('#' + target);

		if ($(el).hasClass('active')) {
			$(el).removeClass('active');
			$(target).slideUp(250);
			return;
		}

		$('#curriculum-interface .curriculum-section.active').removeClass('active');
		$('#curriculum-interface .curriculum-sub-section').slideUp(250);
		$(el).addClass('active');
		$(target).slideDown(250);
	}

function searchTimer(e) {
	var text = $('#search-text').val();

	text = $.trim(text);
	
	if (e.keyCode == 13) {
		window.location.href = '/search/index/profiles/' + text;
		return;
	}

	if (text.length >= 3) {
		clearTimeout($.dash_search.timer);
		$.dash_search.timer = setTimeout( function() {
			dashboardSearch();
		}, 500);
	} else {
		$('#search-results').slideUp(250);
	}
}

function dashboardSearch() {
	var text = $('#search-text').val();
	text = $.trim(text);

	if (text.length < 3) { return; }

	$.ajax({
		url: '/AutoComplete/searchComplete/model:AutoComplete/column:return_text/text:' + text,
		dataType: 'json',
		success: function(response) {
			if (response[0] == "No results") {
				$('#search-results').slideUp(250, function() {
					$('#results').empty();
				});
			} else {
				$('#results').empty();

				$.each(response, function() {
					var link = $('<a></a>');
						$(link).attr('id', this.id);
						$(link).attr('href', this.link);
				
					var lowerText = text.toLowerCase();
					var lowerResult = this.text.toLowerCase();
					
					var from = lowerResult.indexOf(lowerText);
					
					if (from == -1) {
						$(link).text(this.text);
					} else {
						var beginText = this.text.substr(0, from);
						var bold = this.text.substr(from, text.length);
						var endText = this.text.substr(text.length+from);
					
						//console.log('from ' + from);
						//console.log('beginText ' + beginText + ' 0 - ' + from);
						//console.log('bold ' + bold + ' ' + from + ' - ' + text.length);
						//console.log('endText ' + endText + ' ' + text.length);
						
						var boldHTML = beginText + '<span class="bold highlight">' + bold + '</span>' + endText;
						//var boldHTML = beginText + '<span class="bold highlight">' + bold + '</span>' + endText + ' ( ' + this.text + ' )';
						
						$(link).html(boldHTML);
					}

					$(link).appendTo('#results');
				});

				$('#search-term').text(text.toUpperCase());
				$('#search-showall').attr('href', '/search/index/profiles/' + text);

				$('#search-results').slideDown(250);
			}
		}
	});
}

function blink(el, sp) {
	$(el).fadeIn(sp, function() { blinkOut(el, sp) });
}

function blinkStop(el) {
	$(el).stop(true).css('opacity', 1);
}

function blinkOut(el, sp) {
	$(el).fadeOut(sp, function() { blink(el, sp) });
}

function overlay_ad(link) {
	$('.attachment.active').removeClass('active');
	
	var ad = $(link).attr('id');
	
	target = ad.split('_')[1];
	var target_overlay = $('#overlay_' + target);
	
	$('.overlay').not($(target_overlay)).hide(250);
	$(target_overlay).toggle(250);
}

function overlay_wall(link) {
	var var_top = $(link).offset().top - 175;
	if (var_top < 324) { var_top = 324; }

	var media = $(link).attr('rel').split('|');

	$('.overlay').not($('#overlay-wall')).hide(250);

	$('#overlay-wall').hide(250, function() {
		if ($(link).hasClass('video')) { 
			$('#overlay-wall-photo').hide();
			$('#overlay-wall-video').show();

			var video_src = media[0];
			/* SET UP THE VIDEO STUFF */
		}

		if ($(link).hasClass('photo')) {
			$('#overlay-wall-video').hide();
			$('#overlay-wall-photo').show();

			var image_src = media[0];
			$('#overlay-wall-photo').css('background-image', 'url(\'' + image_src + '\')');
		}

		$('#overlay-wall-details').attr('href', media[1]);

		$('#overlay-wall').css('top', var_top + 'px');
		$('#overlay-wall').show(250);
		$('html, body').animate({scrollTop: $('#overlay-wall').position().top}, 250);
	} );

	$('#overlay-wall').css('top', var_top + 'px');
	$('#overlay-wall').show(250);
}

function adevent(id, type) {
	if (type != "target-click" && type != "click" && type != "mouseover") return false;
	if (id == null) return false;
	
	id = id.split('-')[2];
	
	$.ajax({
		url: '/ads/evlog/'+type+'/'+id,
		async: true,
		type: 'GET',
		dataType: 'json'});
}

function getNotifications() {
	$.getJSON('/ajax/notificationCounts/', function(data) {
		var messages = data.messages;
		var activity = data.activity;
		var requests = data.requests;
		var total = parseInt(messages) + parseInt(activity) + parseInt(requests);
	
		$('#messages-notify').text('(' + messages + ')');
		$('#activity-notify').text('(' + activity + ')');
		$('#requests-notify').text('(' + requests + ')');
		$('#total-notify').text('(' + total + ')');

		if (total > 0) {
			$('#notifications').text(total);
			$('#notifications').removeClass('hidden');
		} else {
			$('#notifications').text(total);
			$('#notifications').addClass('hidden');
		}
	});
}

