$(window).load(function () {
		
    /* --------- GLOBAL --------- */
    if ($('.home-page').length > 0 || $('.wizard-page').length > 0 || $('.profile-page').length > 0 || $('.content-page').length > 0 || $('.blog-page').length > 0) {
		
        $('#page').before('<div id="page-top"></div>');
        $('#page').after('<div id="page-bot"></div>');
        $('ul#nav li:first').addClass('first');
        $('ul#nav li:not(:has(a))').addClass('active').wrapInner(document.createElement('a'));
        $('#footer .links a:first').addClass('first');
        $('#footer .googlebar input.text').wrap('<div class="textfield-wrap inline-block"></div>');

		// Open all external links in new tab/window
		$('a[href*="http://"]:not([href*="' + location.hostname + '"])').attr('target', '_blank');

		setDefaultTextfieldToggle();

        $('#footer .col').equalHeight();
		$('#footer .more').toggle(function() {
			$('#footer .more').html('&laquo; less');
			$('#footer .employer-links').css('height', 'auto');
			return false;
		}, function() {
			$('#footer .more').html('more &raquo;');
			$('#footer .employer-links').css('height', '125px');
			return false;
		});
		
		var staticDomain = 'http://static.gradconnection.com.au';
		
		$('blockquote').prepend('<img src="'+staticDomain+'/img/quote.gif" align="left" style="width:39px; height:41px; margin-right:10px;" />');
		
		$('#toolbar input.text').wrap('<div class="textfield-wrap inline-block"></div>');
		
		if(!($.browser.msie && $.browser.version == '6.0')) {
			$('#industry li:first a, #profile-list li:first a').corner('#fff 7px tl');
			$('#industry li:last a, #profile-list li:last a').corner('#fff 7px br');
	        $('.block, .block-sm, #footer, #offers, #aside, blockquote').corner('#fff 10px');
		}
    }
    
	/* --------- HOME --------- */
	if ($('.home-page').length > 0) {

		// DOM Manipulation
		$('#search-main fieldset input.text, #footer .googlebar input.text, #email-results input.text').wrap('<div class="textfield-wrap inline-block"></div>');
		$('#search-main label').wrapInner('<span></span>');
		$('.other .block-sm:last').addClass('last');
		$('.wizard-intro ul li:first').addClass('first');

		//Tabs
		$('.tabs').each(function () {
			$(this).siblings('div').children('div:gt(0)').hide();
			$(this).children('a:first').addClass('active').addClass('first');
			$(this).children('a:last').addClass('last');
			$(this).children('a').click(function () {
				var current_content_div = '#' + $(this).attr('rel');
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
				$('.tabs a.last.active').addClass('last-active');
				$(current_content_div).siblings().hide();
				$(current_content_div).show();
				return false;
			});
		});
		
		// remove trailing comma from cloud links
		$('.tag-cloud').each(function() {
		    var lastTag = $(this).children('a:last');
		    var text = lastTag.text();
		    lastTag.text(text.substr(0, text.length-1));
		});
		
		// Equal Height
		//$('.intro,.tag-cloud').equalHeight();
		//$('.wizard-intro,.tabbed-content').equalHeight();
		//$('.other .block-sm').equalHeight();
		$('.other .block-sm.createCV').height(107);
		
		// search form
		var options = { 'width': '204px', 'autofill': true };
		$('#search-main .industry input.text').autocomplete('/wizard/metaindustry.htm', options);
		$('#search-main .degree input.text').autocomplete('/wizard/metasubject.htm', options);
		$('#search-main .role input.text').autocomplete('/wizard/metarole.htm', options);
		$('#search-main form').submit(function() {
			$('#search-main input.text').each(function () {
	            if (this.value == this.defaultValue) {
	                this.value = '';
	            }
            });
		});
		
		$('.job-type select').change(updateWizardLinks);
		$('.industry select').change(updateWizardLinks);
		$('.job-type select, .industry select').keypress(function(e) {
			if(e.which == 13)
				window.location = $('.select.go a').attr('href');
			return true;
		});
				
	}

	/* --------- WIZARD --------- */
	if ($('.wizard-page').length > 0) {
		
		if(!($.browser.msie && $.browser.version == '6.0')) {
			$('.pagination').corner('#fff 15px');
			$('#email-results').corner('#fff 5px');
			$('#results').corner('#f3f3f3 10px');
			$('#wizard').corner('#fff 10px');
			$('#email-popup').corner('top #eee 10px');
			$('#email-popup').corner('left #fff 10px');
			$('#email-popup').corner('bottom #fffff0 10px');
			$('.intro-text').corner('#f3f3f3 10px');
		}
		
		//heading urls
		$('ul#nav li').each(function() {
			if($(this).children('a').attr('href') == window.location.href.replace('http://' + document.domain, ''))
				$(this).addClass('active');
		});
		
		// Wizard scrolling
		$('#pr-top').click(function() {
			return goToPage(currentPage-1);
		});
		$('#nx-top').click(function() {
			return goToPage(currentPage+1);
		});
		$('#pr-bot').click(function() {
			return goToPage(currentPage-1);
		});
		$('#nx-bot').click(function() {
			return goToPage(currentPage+1);
		});
		currentPage = 0;
		goToPage(1);
		addPageNumberEventHandlers();
		
		// related searches
		setupRelatedSearchColumns('intialRelatedUrls');
		
		// email submission
		removeEmailPanelTimer = null;
		
		$('.email-button').mouseover(function() {
			overResults = true;
			var pos = $(this).offset();  
			var height = $(this).height();
			var leftOffset = $('#email-popup').width()/2 - $(this).width()/2;
			$('#email-popup').css({ 'left': (pos.left - leftOffset) + 'px', 'top': (pos.top + height + 5) + 'px' });
			$('#email-popup').show();
			if(removeEmailPanelTimer) 
				clearTimeout(removeEmailPanelTimer);
		}).mouseout(function() {
			removeEmailPanelTimer = setTimeout('removeEmailPanel()', 700);
		});
		
		$('#email-popup').mouseenter(function() {
			if(removeEmailPanelTimer) 
				clearTimeout(removeEmailPanelTimer);
		}).mouseleave(function() {
			removeEmailPanelTimer = setTimeout('removeEmailPanel()', 700);
		});
		
		//short url box
		$('#short-url-holder input').focus(function() { 
			this.select();
		});
		
	}

    /* --------- PROFILE --------- */
    if ($(".profile-page").length > 0) {
		
        $('.tabs').each(function () {
            $(this).siblings('div').children('div:gt(0)').hide();
            $(this).children('a:first').addClass('active');
            $(this).children('a').click(function () {
                var current_content_div = '#' + $(this).attr('rel');
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
                $(".tabs a.last.active").addClass('last-active');
                $(current_content_div).siblings().hide();
                $(current_content_div).show();
                return false;
            });
        });
        $('.tabs a:first').addClass("first");
        $('.tabs a:last').addClass("last");

		$('.email-submission .input-go-3').click(submitEOI);
		
		var applicationRoot = $('#applicationRoot').text();
		$('#profile a[href*="http://"]:not([href*="' + location.hostname + '"])').each(function() {
			var url = encodeURI($(this).attr('href'));
        	var newUrl = applicationRoot + '/e?link=' + url + ($(this).hasClass('no-toolbar') ? '&go' : '');
			$(this).attr('href', newUrl);
		});
    }

    /* --------- TOOLBAR --------- */
    if($('#toolbar').length > 0) {
    	if($('#toolbar .employers ul li').length > 0) {
    		window.top.showToolbar();
    	}
//    	else {
//    		window.top.$('#toolbar-frame').hide();
//    	}
    	$('#toolbar .back a').hover(function() { 
    		$(this).siblings('.icon').css({ 'background-position' : '-48px -16px' });
    	}, function() { 
    		$(this).siblings('.icon').css({ 'background-position' : '-48px 0' });
    	});
		$('.email-submission .input-go-3').click(submitEOI);
    }
    
	if($('#toolbar-frame').length > 0) {
		var initialSrc = $('#toolbar-frame').attr('src');
		var urlParts = window.location.href.split('/');
		var qStr = '?emp=' + urlParts[urlParts.length-3] + '&jt=' + urlParts[urlParts.length-2] + '&ind=' + urlParts[urlParts.length-1].replace('.dot', '');
		$('#toolbar-frame').attr('src', initialSrc + qStr);
	}
	
    /* --------- CONTACT US --------- */
    if($('#contact-area').length > 0) {
    	$('#contact-area input.submit-button').click(function() {
			$.post('wizard/contact.form', { 
				email: $('input[name=name]').val(), 
				firstName: $('input[name=city]').val(),
				lastName: $('input[name=email]').val(),
				mobile: $('input[name=phone]').val(),  
				enquiry: $('#enquiry').val()
			});
			$(this).attr('disabled', true);
			$('.email-submitted').text('Thanks! Your enquiry has been sent.');
		});
    }
	
});

/* --------- general --------- */
function setupRelatedSearchColumns(containerId) {
	var colHeight = $('#'+containerId+' .col ul li').height() * 4;
	var $columns = $('#'+containerId+' .col ul');
	$columns.equalHeight();
	if($columns.height() > colHeight) {
		$columns.height(colHeight).css('min-height', colHeight+'px');
		$('#'+containerId+' .more a').toggle(function() {
			$(this).show().html('&laquo; less');
			$('.col ul', $(this).parent().parent()).css('height', 'auto');
			$('.col ul', $(this).parent().parent()).equalHeight();
			return false;
		}, function() {
			$(this).show().html('more &raquo;');
			$('.col ul', $(this).parent().parent()).height(colHeight).css('min-height', colHeight+'px');
			return false;
		});
	}
	else {
		$('#'+containerId+' .more a').hide();
	}
}

function setDefaultTextfieldToggle() { 
    $('input.text').focus(function () {
        if (this.value == this.defaultValue) {
            this.value = '';
            $(this).css('color', '#333');
        }
	    return true;
    });
    $('input.text').blur(function () {
        if (this.value === '') {
            this.value = this.defaultValue;
            $(this).css('color', '#777');
        }
	    return true;
    });
}

/* --------- wizard --------- */
function updateWizardLinks() {
	var jobType = 'jobs';
	var industry = null;
	var jobTypeSelect = $('.job-type select');
	var industrySelect = $('.industry select');
	
	if(jobTypeSelect.attr('selectedIndex') != 0) 
		jobType = jobTypeSelect.val().replace(/\s/g, '-').toLowerCase();
	else
		jobType = 'jobs';
	if(industrySelect.attr('selectedIndex') != 0) 
		industry = industrySelect.val().replace(/\s/g, '-').toLowerCase();
	else
		industry = null;
			
	var href = '/' + jobType + '/';
	if(industry)
		href += industry + '/';
	href += 'index.htm';
	$('.select.go a').attr('href', href);
}

function removeEmailPanel() {
	$('#email-popup').hide();
}

function addPageNumberEventHandlers() {
	$('#wizard-page-links-top a').click(function() {
		return goToPage($(this).text());
	});
	$('#wizard-page-links a').click(function() {
		return goToPage($(this).text());
	});
	
	//disable next button if only 1 page
	maxPage = $('#wizard-page-links a').length;
	if(maxPage <= 1) {
		maxPage = 1;
		$('#wizard .pagination .nx').addClass('disabled');
		$('#wizard-page-links a, #wizard-page-links-top a').removeClass('active').addClass('disabled');
	}
	else 
		$('#wizard .pagination .nx').removeClass('disabled');
}

function goToPage(page) {

	maxPage = $('#wizard-page-links a').length;
	if(maxPage < 1) {
		maxPage = 1;
		return false;
	}
	
	if(!window.currentPage)
		currentPage = 0;
	
	if(page < 1 || page > maxPage || page == currentPage)
		return false;
	
	currentPage = parseInt(page);
	
	$('#wizard .pagination .pr , #wizard .pagination .nx').removeClass('disabled');
	if(currentPage <= 1) {
		currentPage = 1;
		$('#wizard .pagination .pr').addClass('disabled');
	}
	else if(currentPage >= maxPage) {
		currentPage = maxPage;
		$('#wizard .pagination .nx').addClass('disabled');
	}
	
	$('#wizard-page-links a, #wizard-page-links-top a').each(function() {
		$(this).removeClass('active');
		$(this).removeClass('disabled');
		if($(this).text() == currentPage)
			$(this).addClass('active');
	});
	$('#wizard-current-page, #wizard-current-page-top').text('Page ' + currentPage + ' of ' + maxPage);

	$('.wizard-results-page').hide();
	$('#wizard-page-'+currentPage).show();
	
	return false;
}

/* --------- expression of interest --------- */
function submitEOI() {
	var success = true;
	
	if(!$('input[name=email]').val().match(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i )) {
		success = false;
		$('input[name=email]').css({ 'border' : 'solid 1px #d77' });
	} else {
		$('input[name=email]').css({ 'border' : '' });
	}
	
	if($('input[name=firstName]').val() == '') {
		success = false;
		$('input[name=firstName]').css({ 'border' : 'solid 1px #d77' });
	} else {
		$('input[name=firstName]').css({ 'border' : '' });
	}
	
	if($('input[name=lastName]').val() == '') {
		success = false;
		$('input[name=lastName]').css({ 'border' : 'solid 1px #d77' });
	} else {
		$('input[name=lastName]').css({ 'border' : '' });
	}
	
	/*
	if(!$('input[name=terms]').attr('checked')) {
		success = false;
		$('label[for=gwt-uid-1] a').css({ color: '#d77' });
	} else {
		$('label[for=gwt-uid-1] a').css({ color: '#333' });
	}
	*/
	
	if(success) {
		$.post("/wizard/eoi.form", { 
			email: $('input[name=email]').val(), 
			firstName: $('input[name=firstName]').val(),
			lastName: $('input[name=lastName]').val(),
			mobile: $('input[name=mobile]').val(),
			university: $('input[name=university]').val(),
			twitter: $('input[name=twitter]').val(),
			jobType: $('input[name=jobType]').val(),
			industry: $('input[name=industry]').val(),
			company: $('input[name=company]').val() });
		$('.email-submitted').show();
	}
	return false;
}

/* --------- toolbar --------- */
function goToProfile(url) {
	window.top.location = url;
}

function toggleToolbarFrameHeight() {
	if($('#toolbar-frame').height() < 300) {
		$('#toolbar-frame').animate({'height': '330px'}, 'fast');
	} else {
		$('#toolbar-frame').animate({'height': '30px'}, 'fast');
	}
}

function toggleToolbarExpand() {
	if(window.self != window.top) {
		$('#toolbar-expanded').show();
		window.top.toggleToolbarFrameHeight();
	}
	else {
    	$('#toolbar-expanded').slideToggle('fast');
	}
	$('#toolbar a.icon.d, #toolbar a.icon.u').toggleClass('d').toggleClass('u'); 
}

function showToolbar() {
	if(!readCookie('toolbarClosed')) {
		$('#toolbar-frame').show();
		$('#page-top').css('margin-top','40px');
	}
}

function closeToolbar() {
	if(window.self != window.top) {
		window.top.$('#toolbar-frame').slideUp('fast');
		window.top.setCookie('toolbarClosed', 'true', 1);
	}
	else {
		setCookie('toolbarClosed', 'true', 1);
		window.location.href = $('#external-frame').attr('src');
	}
}

/* --------- yum --------- */
function setCookie(name, value, expiration) {
	if (expiration) {
		var date = new Date();
		date.setTime(date.getTime()+expiration);
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name, '', -1000000);
}
