$(function() {
	menuNav.init();
	search.init();
	textAreas.init();
	poll.init();
	affiliateTrack.init();
	//basket.init();
	//ads.init();
	
	$('a.styleswitch').click(function(e) {
		this.blur();
		switchStylesheet($(this).attr('rel'));
		e.preventDefault();
		return false;
	});
	
	$('.comments :input').click(
		function() {
			$('.comments label[for="'+this.id+'"]').animate({ opacity: 0, marginTop: -10 }, 150, function() { $(this).hide(); });
		}
	);
	
	var c = $.cookie('style');
	if (c == 'default' || c == 'large' || c == 'largest') {
		switchStylesheet(c);
	} else {
		$('a#styleswitcher_default').addClass('chosen');
	}
	
	/**
	 * Track an event, e.g.:
	 * 
	 *   $('a.twitter').click(function() {
	 *     $.geekGaTrackEvent('feed', 'click', 'Twitter', 'willemvzyl');
	 *   });
	 */
	$.geekGaTrackEvent = function(category, action, label, value) {

		if (typeof pageTracker != undefined) {
		  //the pageTracker was defined, track the event:
		  pageTracker._trackEvent(category, action, label, value);
		} else {
		  //the pageTracker wasn't defined:
		  throw "Unable to track event; pageTracker has not been defined";
		}

	};
	
	// do the actual tracking
	$.geekGaTrackPage('UA-16262376-1');
	$.geekGaTrackPage('UA-5532417-7');
});

var menuNav = {
	navTop:'',
	navTopArticles:'',
	navLHArticles:'',
	
	init:function() {
		this.navTop = $('#nv');
		this.navLHArticles = $('#lh-nav-articles');
		
		if (this.navTop.length) {
			this.navTop.find('li.drop').addClass('drop-image');
			this.navTop.find('#lo-nojs').hide();
			
			this.navTop.find('li.drop').children('a').click(function(e){
				this.blur();
				e.preventDefault;
				var $item = $(this).toggleClass('menuopen').parent('li.drop');
				$('ul.mp', $item).data('clicked', true);
				menuNav.navTop.find('li.drop').children('ul.mp').each(function(){
					if ($(this).data('isShown') && !$(this).data('clicked')) {
						$(this).data('isShown', false).hide().siblings('a').removeClass('menuopen');
					}
				});
				$('ul.mp', $item).data('clicked', false).data('isShown', !$('ul.mp', $item).data('isShown')).toggle();
				return false;
			});
			$(document).click(function(){
				menuNav.navTop.find('li.drop').children('ul.mp').each(function(){
					if ($(this).data('isShown')) $(this).data('isShown', false).hide().siblings('a').removeClass('menuopen');
				});
			});
			this.navTop.find('ul.mp').click(function(e){
				// this cancels the above $(document) event handler
				if (!$(e.target).is('A')){
					e.preventDefault();
					return false;
				}
			});
			this.navTop.find('a').each(function(){
				$(this).attr('title', $(this).html());
			});
		}
		
		if (this.navLHArticles.length) {
			this.navLHArticles.find('li.drop').children('a').click(function(e) {
				this.blur();
				var item = $(this).parent('li.drop');
				if (item.hasClass('open')) {
					item.children('ul').slideUp(200);
					item.removeClass('open')
				} else {
					item.children('ul').slideDown(200);
					item.addClass('open')
				}
				e.preventDefault();
				return false;
			});
			
			var list = this.navLHArticles.children('div.nav-block2').children('ul');
			list.find('li.drop').removeClass('open').children('ul').hide();
			list.find('li.current').parent('ul').parent('li.drop').addClass('open').children('ul').show();
			list.find('li.current.drop').addClass('open').children('ul').show();
		}
	}
};

var inputBox = {
	textonfocus:function(field, defaultText) {
		if (field.value == defaultText) field.value = '';
	},
	
	textonblur:function(field, defaultText) {
		if (field.value == '') field.value = defaultText;
	}
};

$.fn.autoResize = function(options) {
	
	// Just some abstracted details,
	// to make plugin users happy:
	var defaults = {
		onResize : function(){},
		animate : true,
		animateDuration : 1500,
		animateCallback : function(){},
		extraSpace : 20,
		limit: 300
	};
	
	var settings = $.extend(defaults, options);
	
	// Only textarea's auto-resize:
	this.filter('textarea').each(function(){
		// Get rid of scrollbars and disable WebKit resizing:
		var textarea = $(this).css({'height':'20px','resize':'none','overflow-y':'hidden'}),
			// Cache original height, for use later:
			origHeight = (textarea.css('display')=='block')?textarea.height:20,
			
			// Need clone of textarea, hidden off screen:
			clone = (function(){
				// Properties which may effect space taken up by chracters:
				var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
					propOb = {};
				
				// Create object of styles to apply:
				$.each(props, function(i, prop){
					propOb[prop] = textarea.css(prop);
				});
				
				// Clone the actual textarea removing unique properties
				// and insert before original textarea:
				return textarea.clone().removeAttr('id').removeAttr('name').css({
					position: 'absolute',
					top: 0,
					left: -9999
				}).css(propOb).attr('tabIndex','-1').insertBefore(textarea);
			})(),
			lastScrollTop = null,
			updateSize = function() {
				// Prepare the clone:
				clone.height(0).val($(this).val()).scrollTop(10000);
				
				// Find the height of text:
				var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
					toChange = $(this).add(clone);
				
				// Don't do anything if scrollTip hasen't changed:
				if (lastScrollTop === scrollTop) { return; }
				lastScrollTop = scrollTop;
				
				// Check for limit:
				if ( scrollTop >= settings.limit ) {
					$(this).css('overflow-y','');
					return;
				}
				// Fire off callback:
				settings.onResize.call(this);
				
				// Either animate or directly apply height:
				settings.animate && textarea.css('display') === 'block' ?
					toChange.stop().animate({height:scrollTop}, settings.animateDuration, settings.animateCallback)
					: toChange.height(scrollTop);
			};
		
		// Set the height of the text area to fit it's contents
		clone.height(0).val($(this).val()).scrollTop(10000);
		var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace;
		lastScrollTop = scrollTop;
		textarea.height(scrollTop);
		
		// Bind namespaced handlers to appropriate events:
		textarea
			.unbind('.dynSiz')
			.bind('keyup.dynSiz', updateSize)
			.bind('change.dynSiz', updateSize)
			.bind('focus.dynSiz', updateSize);
	});
	
	// Chain:
	return this;
};
//bodytext
var textAreas={
	init:function(){
		// this code mostly works in IE6 and IE7, except when page is loading and textarea has content...
		// it won't expand the textareas to fit content as the clone textarea hasn't been rendered yet and
		// IE6 and 7 can't figure out the height of it...
		if (!($.browser.msie && $.browser.version < 8)) {
			$('textarea:not(.bodytext)').autoResize({
				animate : false
			});
		}
	}
};

var search = {
	searchRefineArea:'',
	searchRefineLink:'',
	searchRefineTaxonomyArea:'',
	
	init:function() {
		this.searchRefineArea = $('#refine-search-section');
		this.searchRefineLink = $('#refine-search-toggle');
		this.searchRefineTaxonomyArea = $('#refine-search-taxonomy');
		
		if (this.searchRefineLink.length) {
			this.searchRefineLink.toggle(function(e){
				search.searchRefineArea.show();
				search.searchRefineLink.blur();
				search.searchRefineLink.fadeOut('fast', function(){
					search.searchRefineLink.html('Hide the refine search section');
					search.searchRefineLink.fadeIn('fast');
				});
				e.preventDefault();
				return false;
			},function(e){
				search.searchRefineArea.hide();
				search.searchRefineLink.blur();
				search.searchRefineLink.fadeOut('fast', function(){
					search.searchRefineLink.html('Refine your search');
					search.searchRefineLink.fadeIn('fast');
				});
				e.preventDefault();
				return false;
			});
		}
		
		if (this.searchRefineTaxonomyArea.length) {
			this.searchRefineTaxonomyArea.find('li.drop').click(function() {
				var link = $(this);
				if (link.hasClass('open')) {
					link.removeClass('open')
				} else {
					link.addClass('open')
				}
			});
		}
	}
};

$.fn.makeAbsolute = function(rebase) {
    return this.each(function() {
        var el = $(this);
        var pos = el.position();
        el.css({ position: "absolute",
            marginLeft: 0, marginTop: 0,
            top: pos.top, left: pos.left });
        if (rebase) el.remove().appendTo("body");
    });
}

var ads = {
	adArea:'',
	layout:'',
	layoutOffset:'',
	
	init:function() {
		this.adArea = $('#rhadverts');
		
		if (this.adArea.length) {
			this.layout = $('#layout');
			this.layoutOffset = this.layout.offset();
			
			$(window).scroll(function(){
				var offset = ads.adArea.offset();
				var newTop = 20;
				
				if ((offset.top - 20) < $(window).scrollTop()) {
					var newLeft = ads.layoutOffset.left + ads.layout.width() - ads.adArea.width();
					if (newLeft.toString().indexOf('.') > 0) newLeft = 1 + (newLeft.toString().substring(0, newLeft.toString().indexOf('.')) * 1);
					
					ads.adArea.css('position', 'fixed');
					ads.adArea.css('top', newTop + 'px');
					ads.adArea.css('left', newLeft + 'px');
				} else if ($(window).scrollTop() < (175 - 20) && ads.adArea.css('position') != 'relative') {
					ads.adArea.css('position', 'relative');
					ads.adArea.css('top', '0px');
					ads.adArea.css('left', '0px');
				}
			});
		}
	}
};

function switchStylesheet(styleName) {
	$('link[rel*=style]').each(function(i) {
		var thisTitle = $(this).attr('title');
		if (thisTitle.length > 0) {
			this.disabled = true;
			$('a#styleswitcher_' + thisTitle).removeClass('chosen');
			if (thisTitle == styleName) {
				this.disabled = false;
				$('a#styleswitcher_' + thisTitle).addClass('chosen');
			}
		}
	});
	$.cookie('style', styleName, {expires: 365, path: '/'});
}

function setDBDate(dateId, setToDate) {
	if (setToDate.length > 0) {
		var dateBox = $('#' + dateId);
		var d = new Date(setToDate);
		dateBox.val(d.getFullYear() + '-' + zeroPad(d.getMonth()+1) + '-' + zeroPad(d.getDate()));
		$('#' + dateId + '-d option[value=' + d.getDate() + ']').attr('selected', 'selected');
		$('#' + dateId + '-m option[value=' + (d.getMonth()+1) + ']').attr('selected', 'selected');
		$('#' + dateId + '-y option[value=' + (d.getFullYear()) + ']').attr('selected', 'selected')
	}
}

function zeroPad(inVal) {
	var val = inVal.toString();
	if (val.length == 1) val = '0' + val;
	return val
}

function updateDBDate(dateId) {
	var dateBox = $('#' + dateId);
	var day = $('#' + dateId + '-d').val();
	var month = $('#' + dateId + '-m').val()-1;
	var year = $('#' + dateId + '-y').val();
	var d = new Date(year, month, day);
	if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day)
		dateBox.val(d.getFullYear() + '-' + zeroPad(d.getMonth()+1) + '-' + zeroPad(d.getDate()))
	else {
		d = new Date(year, month+1, 0);
		setDBDate(dateId, d.getFullYear() + '-' + zeroPad(d.getMonth()+1) + '-' + zeroPad(d.getDate()))
	}
}

function feedbackSave() {
	var $feedbackform = $('#feedbackMsg');
	var $fbm = $('#fbm').val();
	var $fbu = $('#fbu').val();
	var $fbe = $('#fbe').val();
	var $fbr = $('#fbr').val();
	var $strCAPTCHA = $('#strCAPTCHA').val();
	var data_1;
	
	if ($fbm.length == 0) {
		data_1 = 'Error<br />Please enter any comments or suggestions before submitting.<br />';
		dialogError('#feedback-popup', data_1);
	} else if ($strCAPTCHA.length == 0) {
		data_1 = 'Error<br />Please enter a value in the number challenge box at the bottom before submitting.<br />';
		dialogError('#feedback-popup', data_1);
	} else {
		var postString = { fbm: $fbm, fbu: $fbu, fbe: $fbe, fbr: $fbr, fbjs: '1', fbajax: '1', strCAPTCHA: $strCAPTCHA };
		
		$.post('/feedback_save.asp', postString, function(data) {
			if(data == 'success'){
				dialogClose('#feedback-popup');
				$('#fbm').val('');
				dialogOpen('#feedback-thanks');
			}else if(data == 'captcha'){
				reSetCaptcha();
				var data_1 = 'Error<br />The number at the bottom of the form doesn\'t match the displayed number to the left of it.<br />';
				dialogError('#feedback-popup', data_1);
			}else{
				var data_1 = 'Error<br />Could not submit your feedback. Please try again or email us at <a href=""mailto:support@mylastsong.com"">support@mylastsong.com</a><br />';
				dialogError('#feedback-popup', data_1);
			}
		});
	}
}

function feedbackCancel() {
	reSetCaptcha();
	dialogClose('#feedback-popup');
	$('#fbm').val('');
}

function feedbackThanksClose() {
	dialogClose('#feedback-thanks');
}

function dialogOpen(item) {
	dialogReset(item);
	if ($(item)) $(item).dialog('open');
	if ($('object')) $('object').css('visibility', 'hidden');
}

function dialogClose(item) {
	if ($(item)) $(item).dialog('close');
	dialogReset(item);
	if ($('object')) $('object').css('visibility', 'visible');
}

function dialogClick(button) {
	var $button = $(button);
	if ($button) {
		var buttonContainer = $button.parent().parent();
		buttonContainer.hide().siblings('.ui-dialog-buttons-working').show();
	}
}

function dialogReset(item) {
	if ($(item)) {
		$(item).find('.ui-dialog-buttons-working').hide().siblings('.ui-dialog-buttons').show().find(':hidden').show();
		if ($(item).find('.error')) $(item).find('.error').html('').hide();
	}
}

function dialogError(item, error) {
	dialogReset(item);
	if ($(item)) {
		if ($(item).find('.error')) $(item).find('.error').html(error).show();
	}
}

var basket = {
	basketClassAdd: 'basket_add',
	basketClassRemove: 'basket_remove',
	basketClassCheckout: 'basket_checkout',
	basketClassView: 'basket_view',
	
	init: function() {
		//var basketAddLinks = $('.' + this.basketClassAdd);
		
		//if (basketAddLinks.length) {
		//	basketAddLinks.click(function(e) {
		//		e.preventDefault();
		//		this.blur();
		//		return false;
		//	});
		//}
	}
}

var poll = {
	container: '',
	form: '',
	pollTimeout: 0,
	
	init: function() {
		poll.container = $('#poll-container');
		poll.form = $('#poll-form');
		if (poll.container.length) {
			poll.container.css('overflow', 'hidden');
			poll.container.animate({
				height: 82
			}, 2000);
		}

		poll.container.mouseover(function(){
			clearTimeout(poll.pollTimeout);
			poll.container.stop().animate({
				height: '100%'
			}, 500);
		});

		// add click event to handle touch screens
		poll.container.find('.question').css({'text-decoration':'underline','cursor':'pointer'}).click(function(){
			clearTimeout(poll.pollTimeout);
			poll.container.stop().animate({
				height: '100%'
			}, 500);
		});

		poll.container.mouseout(function(){
			clearTimeout(poll.pollTimeout);
			poll.pollTimeout = setTimeout(function(){
				poll.container.stop().animate({
					height: 82
				}, 2000);
			}, 8000);
		});
		
		poll.form.find('#poll-submit').hide();
		poll.form.find(':radio').change(function(e){
			e.preventDefault;
			poll.vote();
			return false
		})
	},
	
	vote: function(){
		poll.form.find('.choices').hide().siblings('.choices-waiter').show();
		poll.form.find('#isajax').val('1');
		$.get('dopoll.asp', poll.form.serialize(),function(data){
			poll.response(data)
		})
	},
	
	response: function(data){
		var answer = '';
		var pollId = '';
		if(data.indexOf('|') > 0){
			var items = data.split('|');
			answer = items[0];
			pollId = items[1];
		}
		switch(answer) {
		case 'success':
			poll.form.find('.choices-waiter').hide().siblings('.choices-complete').addClass('positive').html('Thank you for voting').show();
			$.get('/getPollResults.asp', { pollid: pollId }, function(data) {
				if (data.length > 0) $('#poll-results').html(data);
			});
			break;
		case 'ipoverlimit':
			poll.form.find('.choices-waiter').hide().siblings('.choices-complete').addClass('information').html('We cannot record your choice. Too many choices have been recorded from your IP address.').show();
			break;
		default:
			poll.form.find('.choices-waiter').hide().siblings('.choices-complete').addClass('error').html('There was a problem recording your choice for the poll.').show();
			break;
		}
	}
}

var affiliateTrack = {
	init: function() {
		$('a.affiliate').click(function(e){
			e.preventDefault();
			var url = $(this).attr('href');
			affiliateTrack.open(url);
			return false;
		});
	},
	
	open: function(url) {
		var $form = $('#affiliateLinkMsg');
		var $html = $form.html();
		$form.html($html.replace(/\[LINK\]/, url));
		dialogOpen('#affiliatelink-popup');
	},
	
	go: function(url) {
		var $form = $('#affiliateLinkMsg');
		var $aln = $('#aln').val();
		var $ale = $('#ale').val();
		var $all = $('#all').val();
		var $alr = $('#alr').val();
		
		if ($ale.length > 0) {
			var postString = { aln: $aln, ale: $ale, alr: $alr, all: $all, aljs: '1', alajax: '1' };
			
			$.post('/affiliatelink_save.asp', postString, function(data) {
				if (data == 'success') {
					dialogClose('#affiliatelink-popup');
					document.location = $all;
				} else {
					var data_1 = 'Error<br />Could not submit the form. Please try again or email us at <a href=""mailto:support@mylastsong.com"">support@mylastsong.com</a><br />';
					dialogError('#affiliatelink-popup', data_1);
				}
			});
		} else {
			var data_1 = 'Error<br />Please enter the requested details before submitting.<br />';
			dialogError('#affiliatelink-popup', data_1);
		}
	},
	
	stop: function() {
		dialogClose('#affiliatelink-popup');
		return false;
	}
}

/* jQuery Google Analytics replacement 20091223 JJW */
/*
 * jquery.geekga.js - jQuery plugin for Google Analytics
 * 
 * Version 1.1
 * 
 * This plugin extends jQuery with two new functions:
 * 
 *   - $.geekGaTrackPage(account_id)
 *       Track a pageview.
 * 
 *   - $.geekGaTrackEvent(category, action, label, value)
 *       Track an event with a category, action, label and value.
 * 
 * 
 * This code is in the public domain.
 * 
 * Willem van Zyl
 * willem@geekology.co.za
 * http://www.geekology.co.za/blog/
 */

var pageTracker;

/**
 * Track a pageview, e.g.:
 * 
 *   $.geekGaTrackPage('UA-0000000-0');
 */
$.geekGaTrackPage = function(account_id) {
	//check whether to use an unsecured or a ssl connection:
	var host = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	var src = host + 'google-analytics.com/ga.js';

	//load the Google Analytics javascript file:
	$.ajax(
	  {
		type:      'GET',
		url:       src,
		success:   function() {
								//the ga.js file was loaded successfully, set the account id:
								pageTracker = _gat._getTracker(account_id);
								
								//track the pageview:
								pageTracker._trackPageview();
							  },
		error:     function() {
								//the ga.js file wasn't loaded successfully:
								throw "Unable to load ga.js; _gat has not been defined.";
							  },
		dataType:  'script',
		cache:     true
	  }
	);
};
