﻿/*
	Global LoveMoney Javascript
	!! This script requires jQuery	
*/

// map document as LoveMoney
var LoveMoney = $(document);

LoveMoney.Nav = {
	siteSearchUi: function() {
		topSiteSearchField = $('input.TopSiteSearch')
		topSiteSearchButton = $('input.TopSiteSearchButton')

		bottomSiteSearchField = $('input.BottomSiteSearch')
		bottomSiteSearchButton = $('input.BottomSiteSearchButton')

		userSearchField = $('input.UserSearch')

		groupsSearchField = $('input.GroupsSearch')
		
		// insert placefiller search text on load
		topSiteSearchField.val('Search lovemoney.com');
		userSearchField.val('Find a member');		

		// clear placefiller search text on focus
		topSiteSearchField.bind('focus', function() {
		if (topSiteSearchField.val() == 'Search lovemoney.com') {
			topSiteSearchField.val('');
			}
		});
		// clear placefiller user search text on focus
		topSiteSearchField.bind('focus', function() {
		if (topSiteSearchField.val() == 'Find a member') {
			topSiteSearchField.val('');
			}
		});
		// restore search text if field is empty on blur
		topSiteSearchField.bind('blur', function() {
		if (topSiteSearchField.val().length < 1) {
			topSiteSearchField.val('Search lovemoney.com');
			}
		});

		// insert placefiller search text on load
		bottomSiteSearchField.val('Search lovemoney.com');


		// clear placefiller search text on focus
		bottomSiteSearchField.bind('focus', function() {
		if (bottomSiteSearchField.val() == 'Search lovemoney.com') {
			bottomSiteSearchField.val('');
			}
		});

		// restore search text if field is empty on blur
		bottomSiteSearchField.bind('blur', function() {
		if (bottomSiteSearchField.val().length < 1) {
			bottomSiteSearchField.val('Search lovemoney.com');
			}
		});
			
		
		// restore user search text if field is empty on blur
		userSearchField.bind('blur', function() {
			if (userSearchField.val().length < 1) {
				userSearchField.val('Find a member');
			}
		});
		// clear placefiller user search text on focus
		userSearchField.bind('focus', function() {
		if (userSearchField.val() == 'Find a member') {
			userSearchField.val('');
			}
		});

        // insert placefiller search text on load
        groupsSearchField.val('Search groups');

        // restore user search text if field is empty on blur
        groupsSearchField.bind('blur', function () {
            if (groupsSearchField.val().length < 1) {
                groupsSearchField.val('Search groups');
            }
        });
        // clear placefiller user search text on focus
        groupsSearchField.bind('focus', function () {
            if (groupsSearchField.val() == 'Search groups') {
                groupsSearchField.val('');
            }
        });

		/*siteSearchField.bind('blur', function() {
		if (siteSearchField.val().length < 1) {
		siteSearchField.val('Search lovemoney.com');
		}
		});*/
	},
	compareTriggerSetup: function() {
		var cpeShow = false;
		$('a.CpeTrigger').bind('click', function() {
			if (cpeShow != true) {
				$('div.Cpe').slideDown('fast').bgiframe();
				$('a.CpeTrigger').addClass('CpeTriggered');
				cpeShow = true;
			}
			else {
				$('div.Cpe').slideUp('fast').bgiframe();
				$('a.CpeTrigger').removeClass('CpeTriggered');
				cpeShow = false;
			}
			return false;
		});
	}
}

/* LOVEMONEY UTILITY FUNCTIONS */
LoveMoney.Util = {

	/* prevent other sites iframing our pages */
	frameBuster: function() {
		// exclusion list of sites that are allowed to iframe 
		var whitelist = ['digg.com', 'www.digg.com', 'facebook.com', 'www.facebook.com'];
		if (window.top.location != window.location) {
			var match = document.referrer.match(/^https?:\/\/([^:\/\s]+)\/?.*/);
			if (match) {
				var domain = match[0];
				for (var i = 0; i < whitelist.length; i++) {
					if (domain == whitelist[i]) { return; }
				}
			}
			window.top.location = window.location;
		}
	},

	/* stripe tables by adding class 'Odd' to even-numbered rows - yes, i know that makes no sense */
	/* feed it the word 'list' as the second variable if its a list else it assumes its a table */
	stripe: function(selector, type) {
		if (type == 'list') {
			rows = $(selector + " li:odd");
		}
		else {
			rows = $(selector + " tr:even");
		}
		rows.each(function() {
			$(this).addClass("Odd");
		});
	},

	/* toggle open/close state of something */
	/* element needs to have css classes for open/closed set elsewhere */
	toggleOpenClose: function(element) {
		$(element).toggleClass("Open");
		$(element).toggleClass("Closed");
	},

	equaliseHeights: function(element) {
		var tallestElementHeight = 0;
		$(element).each(function() {
			thisHeight = $(this).innerHeight();
			if (thisHeight > tallestElementHeight) {
				tallestElementHeight = thisHeight;
			}
		});
		$(element).each(function() {
			if ($.browser.msie && $.browser.version == 6.0) {
				$(this).css({ 'height': tallestElementHeight });
			}
			$(this).css({
				'min-height': tallestElementHeight
			});
		});
	},
	highlightAuthorReplies: function(authorUid) {
		$('.UiUserPostedItem').each(function() {
			thisUid = $(this).attr('rel');
			if (thisUid == authorUid) {
				$(this).addClass('authorReply');
				if($(this).is('.Answer')) {
					$(this).children('.Unit').children('.Content').children('div.PostedBy').children('p').children('strong').append(' <span class="replyType">(Question asker)</span>');
				}
				if ($(this).is('.Comment') && $('body div#Blog').size() == 0) {
					$(this).children('.Unit').children('.Content').children('div.PostedBy').children('p').children('strong').append(' <span class="replyType"><strong>(Article author)</strong></span>');
				}
				if ($(this).is('.Comment') && $('body div#Blog').size() > 0) {
					$(this).children('.Unit').children('.Content').children('div.PostedBy').children('p').children('strong').append(' <span class="replyType"><strong>(Blog post author)</strong></span>');
				}
			}
		});
	}
}

LoveMoney.Tagging = {
	setupAutocomplete: function() {
		$('.TagPredictiveTextBox').each(function() {
			tagPattern = $(this).val();
			tagAjaxUrl = "/controls/tagging/autocompletetagaction.aspx";
			$(this).autocomplete(tagAjaxUrl,
				{
					autoFill: true,
					delay: 300,
					scroll: false,
					matchContains: 1,
					minChars: 3,
					width: 250
				}
			);
		});
	},

	setupAddTagAjax: function() {
		$(".AddTagContainer input[type='submit']").bind('click', function() {
			// disable button until call has returned
			$(this).attr("disabled", "disabled");
			$('#FindTags').fadeTo("fast", 0.33);
			// get input value
			var text = $(".AddTagContainer input.TagPredictiveTextBox").val();
			// get AddTagUrl
			var addTagUrl = $("input[id*='hdnAddTagUrl']").val();
			// deliberately break AddTagUrl so we get json back from the request instead of redirected page
			nonReturnAddTagUrl = addTagUrl.replace('returnUrl', 'borkedReturnUrl');
			// get address
			var address = $("input[id*='hdnAddress']").val();
			// send the request
			$.get(nonReturnAddTagUrl + text, function(data) {
				returnedJson = $.evalJSON(data);
				$.post("/controls/tagging/tagcloudaction.aspx", { show: "content", address: encodeURI(address) }, function(data1) {
					$('#FindTags').empty();
					$('#FindTags').append(data1);
					// respond if tag is dead
					if (returnedJson[0].isDead == false && (returnedJson[0].cleanedTo.length > 0)) {
						$('#FindTags').prepend('<div class="UiSuccess"><span class="HrefList TickGreen">Successfully tagged as <strong>' + returnedJson[0].cleanedTo + '</strong></span></div>');
					}
					else if (returnedJson[0].isDead == false) {
						$('#FindTags').prepend('<div class="UiSuccess"><span class="HrefList TickGreen">Successfully tagged as <strong>' + text + '</strong></span></div>');
					}
					else {
						$('#FindTags').prepend('<div class="UiFailed"><span class="HrefList Report"><strong>' + text + '</strong> is a banned tag</span></div>');
					}

					$('#FindTags').fadeTo("fast", 1);
				});
				// reenable button
				$(".AddTagContainer input[type='submit']").attr("disabled", "");
			});
			return false;
		});
	},
	setupAddTagPlusButtonAjax: function() {
		$("ul.TagList a.TickGrey").bind('click', function() {
			thelink = $(this);
			$.ajax({
				beforeSend: function() {
					thelink.removeClass('TickGrey');
					thelink.addClass('Loading');
				},
				cache: false,
				fail: function() {
					thelink.removeClass('Loading');
				},
				type: "GET",
				url: $(this).attr('href').replace('returnUrl', 'borkedReturnUrl'),
				success: function(msg) {
					thelink.removeClass('Loading');
					thelink.addClass('TickGreen');
				}
			});
			return false;
		});
	}
}

/* LOVEMONEY ADMIN FUNCTIONS */
LoveMoney.Admin = {
	toggleAdminBoxes: function() {
		$('.AdminBox').toggle();
		if ($('a.ShowAdmin').html() == "Show admin boxes") {
			$('a.ShowAdmin').html("Hide admin boxes");
		}
		else {
			$('a.ShowAdmin').html("Show admin boxes");
		}
	}
}

/* LOVEMONEY ADS FUNCTIONS */
LoveMoney.Ads = {
	drawLabels: function(target) {
		$(target).each(function() {
			var adHeight = $(this).height();
			if (adHeight > 240 && adHeight < 260) {
				// it's an MPU
				$(this).addClass('AdMpu');
			}
			else if (adHeight > 590 && adHeight < 610) {
				// it's a Skyscraper
				$(this).addClass('AdSkyscraper');
			}
			else if (adHeight > 80 && adHeight < 100) {
				// it's a Leaderboard
				$(this).addClass('AdLeaderboard');
			}
			else {
				$(this).removeClass('AdMpu');
				$(this).removeClass('AdSkyscraper');
				$(this).removeClass('AdLeaderboard');
				$(this).removeClass('Module');
			}
		});
	},
	drawDartLabels: function(adInstanceName, adSize) {
		try {
			noAd = true;

			// find any images within the ad call
			adCallImages = $('div#' + adInstanceName + ' img');
			// find any embeds within the ad call
			adCallEmbeds = $('div#' + adInstanceName + ' embed');
			// find any objects within the ad call
			adCallObjects = $('div#' + adInstanceName + ' object');
			// find any iframes within the ad call
			adCallIframes = $('div#' + adInstanceName + ' iframe');
			// find any form inputs (for emcap ads) within the ad call
			adCallInputs = $('div#' + adInstanceName + ' input');

			// check for iframes that dart sends for html ads
			// also check for embeds that dart sends for flash ads	
			if ((adCallIframes.size() > 0) || (adCallEmbeds.size() > 0) || (adCallInputs.size() > 0) || (adCallObjects.size() > 0)) {
				noAd = false;
			}
			else {
				// check for ad images that aren't the default grey.gif image
				// that Dart sends when no ad is returned
				$(adCallImages).each(function() {
					if (this.src.endsWith('grey.gif')) {
						noAd = true;
						// alert(adInstanceName+'\nEMPTY: '+n.src);
					}
					else {
						noAd = false;
						// alert(adInstanceName+'\nFULL: '+n.src);
					}
				});
			}


			// if there is a real ad being served by Dart
			// draw the correct div class around ads based on their size
			if (noAd == false) {
				switch (adSize) {
					case "728x90":
						// alert('lb');
						$(adInstanceName).addClass('AdLeaderboard');
						break;
					case "300x250":
						// alert('mpu');
						$(adInstanceName).addClass('AdMpu');
						break;
					case "120x600":
						// alert('skyscraper');
						$(adInstanceName).addClass('AdSkyscraper');
						break;
					default:
						break;
				}
			}
			else {
				// $(adInstanceName).addClassName('HideMe');
			}
		}
		catch (err) {
			// do nothing
		}
	},
	clickBackground: function(targetUrl) {
		var clickableAreas = 'body, form#aspnetForm, div.Middle, div.HomepageIntro';
		// bind the clicks
		$('body').bind('click', function(e) {
			var originalElement = e.srcElement;
			if (!originalElement) { originalElement = e.originalTarget; }
			if ($(originalElement).is(clickableAreas)) {
				window.open(targetUrl, 'ad');
			}
		});
		// bind the mouseover
		$('body').bind('mouseover', function(e) {
			var originalElement = e.srcElement;
			if (!originalElement) { originalElement = e.originalTarget; }
			if ($(originalElement).is(clickableAreas)) {
				$(this).css('cursor', 'pointer');
			}
			else {
				$(this).css('cursor', 'inherit');
			}			
		});
	}
}

LoveMoney.Dev = {
	// alert where a page has no meta keywords/description
	metaAlerts: function(targetUrl) {
		description = $("meta[name=description]").attr("content");
		keywords = $("meta[name=keywords]").attr("content");
		if (description == void 0) {
			alert('No meta description');
		}
		if (keywords == void 0) {
			alert('No meta keywords');
		}
	}
}

/* things that need to fire on page load */
$(document).ready(function() {
	// wire-up flip lists 
	var triggers = $('ul.FlipList li span.Status');
	triggers.each(function() {
		$(this).click(function() {
			LoveMoney.Util.toggleOpenClose($(this).parent())
		});
	});
	LoveMoney.Util.frameBuster();
	LoveMoney.Nav.siteSearchUi();
	LoveMoney.Nav.compareTriggerSetup();
	LoveMoney.Util.stripe('.Stripey');
	LoveMoney.Tagging.setupAutocomplete();
	LoveMoney.Tagging.setupAddTagAjax();
	LoveMoney.Tagging.setupAddTagPlusButtonAjax();
	// $('a[rel*=facebox]').facebox();

	$('a.ShowAdmin').bind('click', function() {
		LoveMoney.Admin.toggleAdminBoxes();
		return false;
	});

	// run ad label drawing 2secs after document.ready
	setTimeout("LoveMoney.Ads.drawLabels('div.OpenXAd')", 2000);
});