//-------------------------------
// Redirect to secure host
//-------------------------------
var securl = 'https://asmguides.worldsecuresystems.com',
	usecurl = 'http://climbingadventures.com.au',
	securls = /\/book\/|BookingRetrieve\.aspx|FormProcessv2\.aspx/i;

if ( securls.test( document.location.toString() ) ) {
	// Rediect to secure host
	if (document.location.protocol == 'http:') {
		var segs = document.location.toString().split('/');
		segs.splice(0,3); // delete protocol & domain
		window.location = securl + '/' + segs.join('/');
	}
} else {
	if (document.location.protocol == 'https:') {
		// Rediect to unsecure host
		var segs = document.location.toString().split('/');
		segs.splice(0,3); // delete protocol & domain
		window.location = usecurl + '/' + segs.join('/');
	}
}

//-------------------------------
// SEO Domain Name Redirect
//-------------------------------
var patt = /asmguides\.com/i
if ( patt.test(window.location.hostname) ) window.location = window.location.toString().replace(patt, 'climbingadventures.com.au');

//-------------------------------
// Makes Div equal the same height
//-------------------------------
$.fn.equalCols = function() {
	// Array Sorter
	var sortNumber = function(a,b) {return b - a;},
		heights = [];
	// Push each height into an array
	$(this).each(function() {
		$(this).css('height', 'auto'); // reset to natural height for recall
		heights.push( $(this).height() );
	});
	heights.sort(sortNumber);
	var maxHeight = heights[0];
	return this.each(function() {
		// Set each column to the max height unless highest
		if ( $(this).height() != maxHeight ) {
			$(this).css({'height': maxHeight});
		}
	});
};

//-------------------------------
// Adds class name to body based on URL
//-------------------------------
function setBodyClass() {
	var urlroot = '/', // Set to the root URL of the site
		url = window.location.pathname,
		dir = url.split(urlroot);
	dir = dir[1].toLowerCase();
	if (dir) {
		var file = dir.split('.'); // removes file extentions
		if (file[0]) {
			dir = file[0];
		}
	} else {
		dir = 'home';
	}
	$('body').addClass(dir);
}

//-------------------------------
// Stops elements getting covered by sidebars. Works with CSS
//-------------------------------
$.fn.overlapCheck = function() {
	return this.each(function() {
		var i = $(this),
			iposy = i.offset().top,
			s = $('#sidebar > :last-child');
		if (i.hasClass('alt')) {
			s = $('#extra > :last-child');
		}
		var sendy = s.offset().top + s.innerHeight();
		if (iposy < sendy) {
			i.removeClass('img');
		}
	});
};

//-------------------------------
// Adds title to images from alt
//-------------------------------
function imgTitle() {
	$('img').each(function() {
		if (!$(this).attr('title') && $(this).attr('alt')) {
			$(this).attr('title', $(this).attr('alt'));
		}
	});
}

//-------------------------------
// Makes entire booking listing clickable and link to secure page
//-------------------------------
function bookLink() {
	$('#content  ul.events li a').each(function() {
		var pathfixed = (this.pathname.charAt(0) != '/') ? ('/' + this.pathname) : this.pathname; // IE and Opera miss the leading slash. Need to test and add

		$(this).parents('li').wrapInner('<a href="' + ( securls.test( this.pathname ) ? securl : '') + pathfixed + this.search + '"></a>').end().remove();
	});
}

//-------------------------------
// Position the element in the middle of the viewport
//-------------------------------
$.fn.positionIt = function() {
	return this.each(function() {
		$(this).css({marginLeft: '-' + parseInt(($(this).width() / 2),10) + 'px'});
		if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // IE6
			$(this).css({marginTop: '-' + parseInt(($(this).height() / 2),10) + 'px'});
		}
	});
};

//-------------------------------
// Break lists into 2 columns
//-------------------------------
$.fn.columnEvents = function() {
	return this.each(function() {
		// Better no booking text
		if ( $.trim( $(this).text() ) == 'No bookings found.') {
			$(this).after('<p>No dates set for this course. Please <a href="/contact">contact <strong>ASM</strong></a> to make a booking.</p>').remove();
		}

		var datelist = $(this).find('li'),
			minitems = 5;
		if (datelist.length > minitems) {
			var remainder = datelist.eq(Math.ceil(datelist.length/2) - 1).nextAll().remove();
			$('<ul class="events alt"></ul>').append(remainder).insertAfter(this);
		}
	});
};

//-------------------------------
// Show the hide div with faded bg and close button
//-------------------------------
$.fn.popSame = function() {
	return this.each(function() {
		$(this).click(function() {
			var upcoming = $(this).siblings('.upcoming');
			if (upcoming.length < 1) { return true; } // test for event list
			var closeOver = function() {	
						background.remove();
						close.remove();
						$(window).unbind('scroll resize');
						upcoming.attr('id', '').hide();
					},
					background = $('<div></div>')
						.attr('id', 'background')
						.appendTo('body')
						.click(closeOver),
					close = $('<div id="close"></div>')
						.click(closeOver)
						.appendTo(upcoming);
						
					upcoming
						.show()
						.attr('id', 'upcoming')
						.positionIt();

				$(document).keyup(function(event) {
					if (event.keyCode == 27) { // Esc key
						closeOver();
					}
				});
			$(this).find('a').blur();
			return false;
		});	
	});
};

function equalPageHeight() {
	$('#content, #extra, #sidebar').equalCols();
}
$(document).bind('fontresize', equalPageHeight);

$(function() {
	$('#newsletter').validate();
	setBodyClass();
	imgTitle();
	bookLink();
	if ($(window).width() > 600) { // only for wider screens
		$('.upcoming').hide();
		$('.upcoming ul').columnEvents();
		$('.cta').popSame();
	}
	equalPageHeight(); // do after height effecting mods are done
	$('.brand').attr('title', 'Australian School of Mountaineering');
});

$(document).ready(function() {
	$('.img').overlapCheck();
});
