﻿//ExternalLinks - tracking based on http://www.iqcontent.com/blog/2007/02/tracking-documents-and-external-links-in-google-analytics/
(function($) {
    $.fn.extend({
        ExternalLinks : function() {            
            return this.each(function() {
                $(this).click(function() {                    
                    if (this.tagName != 'A') {
                        return false;
                    }
                    
                    var link = String(this);
                    var linkHost = this.hostname;
                    var siteHost = location.host;
                    
		            if (link.match(/^mailto:/i)) 
		            {
		                return HandleMailToLink(this);
		            }
		            else if (linkHost == siteHost) 
		            {
			            if(link.match(/\.(doc.aspx|pdf.aspx|xls.aspx|ppt.aspx|zip.aspx|txt.aspx|vsd.aspx|vxd.aspx|js.aspx|css.aspx|rar.aspx|exe.aspx|wma.aspx|mov.aspx|avi.aspx|wmv.aspx|mp3.aspx)$/)) 
			            {
		                    return HandleDocumentLink(this);
			            }
			            else
			            {
		                    return HandleInternalLink(this);
			            }
		            }
		            else 
		            {
		                return HandleExternalLink(this);
		            }
                });
            });
        
            function HandleMailToLink(anchor)
            {
                var email = anchor.href.substring(7);
                TrackLink('mailto', email);
                
                return true;
            }
            
            function HandleDocumentLink(anchor)
            {
                var doc = CleanURL(anchor.pathname, false);
                TrackLink('download', doc);                
                
                window.open(anchor.href);		            
                return false;
            }
            
            function HandleInternalLink(anchor)
            {             
                window.open(anchor.href);		            
                return false;
            }
            
            function HandleExternalLink(anchor)
            {
                var link = CleanURL(anchor.hostname+'/'+anchor.pathname, true);
                TrackLink('external', link);
                
                window.open(anchor.href);		            
                return false;
            }
            
            function TrackLink(type, virtualPath)
            {
                if (typeof(pageTracker) != 'undefined')
                {
	                var url = CleanURL(window.location.pathname, true);
	                if (url.length == 0)
	                {
	                    url = '/';
	                }
	                var linkStr = CleanURL('/virtual/'+type+url+'/'+virtualPath, true);
	                pageTracker._trackPageview(linkStr);
	            }
            }
            
            function CleanURL(url, end)
            {
	            var url = url.toString();
	            var urlLen = url.length;
            	
	            if (end)
	            {
		            if (url.charAt((urlLen-1))=='/') {
			            url = url.substring(0,(urlLen-1));
			        }
	            }
	            else
	            {
		            if (url.charAt(0)=='/') {
			            url = url.substring(1,urlLen);
			        }
	            }
	            return url;
            }
        }
    });
})(jQuery);

//ImageSwap
(function($) {
    $.fn.extend({
        ImageSwap : function() {                           
            return this.each(function() {
                if (this.tagName != 'IMG' || this.tagName != 'INPUT') {
                    var img = $(this);
                    var origSrc = img.attr('src');
                    var path = origSrc.substring(0, origSrc.lastIndexOf('.'));
                    var ext = origSrc.substring(origSrc.lastIndexOf('.'), origSrc.length);
                    path += '-on';
                    var swapSrc = path + ext;
                        
                    img.data('OrigSrc', origSrc);
                    img.data('SwapSrc', swapSrc); 
                    
                    var preloader = new Image();
                    preloader.src = swapSrc;
                    
                    img.hover(
                        function() {
                            $(this).attr('src', $(this).data('SwapSrc'));
                        },
                        function() {
                            $(this).attr('src', $(this).data('OrigSrc'));
                        }
                    );
                }
            });
        }
    });
})(jQuery);

(function($) {
    $.fn.DefaultValue = function(options) {
        //Build main options before element iteration
        var opts = $.extend({}, $.fn.DefaultValue.defaults, options);
        
        return this.each(function() {
            SetDefault(this, opts);
        });
        
        function SetDefault(obj, opts)
        {
            //We only want to set a default on textboxes, textareas and passwords
		    if(obj.type != 'text' && obj.type != 'password' && obj.type != 'textarea')
		    {
			    return;
			}
			    
            var $obj = $(obj);
            
			//Get the text we are going to use as the default
			var text = opts.Text;
			if (text.length == 0)
			{
			    text = $obj.attr('title');
			    $obj.attr('title', '');
			}
			
			if (text.length > 0)
			{    		
		        //Set value initially if none are specified
                if(obj.value == '' || obj.value == text)
                {
			        obj.value = text;
		        }
		        else
		        {
			        //Other value exists - ignore
			        return;
		        }
        		
		        //Remove values on focus
		        $obj.focus(function() {
			        if(this.value == text || this.value == '')
			        {
				        this.value = '';
				    }
		        });
        		
		        //Place values back on blur
		        $obj.blur(function() {
			        if(this.value == text || this.value == '')
			        {
				        this.value = text;
				    }
		        });
        		
		        //Capture parent form submission
		        //Remove field values that are still default
		        //$(this).parents("form").each(function() {
			        //Bind parent form submit
		        //	$(this).submit(function() {
		        //		if(fld_current.value==text) {
		        //			fld_current.value='';
		        //		}
		        //	});
		        //});
		    }
        }
    };
  
    //Plugin defaults
    $.fn.DefaultValue.defaults = {
        Text: ''
    };
})(jQuery);

//Re-assigns a couple of the ASP.NET validation JS functions to provide a more flexible approach
function UpgradeASPNETValidation()
{
    // Hi-jack the ASP.NET error display only if required
    if (typeof(Page_ClientValidate) != "undefined")
    {
        ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
        AspPage_ClientValidate = Page_ClientValidate;
        Page_ClientValidate = NicerPage_ClientValidate;
    }
    
    $('span.EditingFormErrorLabel:visible').each(function(){
        AddValidationStatus($(this));
    });
}

function AddValidationStatus(obj)
{
    //if (obj.hasClass('validation'))
    //{
        var vc = obj.parents('div.validationContainer');
        if (vc.length == 0)
        {
            vc = obj.parents('div.formInput');
        }
        vc.addClass('invalid');
    //}
}

function RemoveValidationStatus(obj)
{
    //if (obj.hasClass('validation'))
    //{
        var vc = obj.parents('div.validationContainer');
        if (vc.length == 0)
        {
            vc = obj.parents('div.formInput');
        }
        vc.removeClass('invalid');
    //}
}

//Extends the classic ASP.NET validation
function NicerValidatorUpdateDisplay(val)
{
    var $val = $(val);
    if (val.isvalid)
    {
        $val.hide();        
        if ($val.parent().find('span.EditingFormErrorLabel:visible').length == 0)
        {            
            RemoveValidationStatus($val);
        }
    }
    else
    {
        $val.show();
        AddValidationStatus($val);
    }
}

//Extends classic ASP.NET validation to include parent element styling
function NicerPage_ClientValidate(validationGroup)
{
    var valid = AspPage_ClientValidate(validationGroup);
    if (!valid)
    {
        //$(this).parent().addClass('Invalid');
    }
    else
    {
        //$(this).parent().removeClass('Invalid');
    }
}

(function($) {
    $.fn.slideReveal = function(options) {    
        //Build main options before element iteration
        var opts = $.extend({}, $.fn.slideReveal.defaults, options);
    
        //Iterate through each object
        return this.each(function() {
            var container = $(this);
            var cover = container.find(opts.coverSelector);
            
            if (!cover.hasClass('noSlide'))
            {
                container.addClass(opts.containerCssClass);            
                createSlideReveal(container, opts);
            }
        });
    };
  
    ////Private functions
    function createSlideReveal(container, opts) { 
        var cover = container.find(opts.coverSelector);
        var outParams = getOutParams(container, opts);
        var inParams = getInParams(container, opts);
        
        container.hoverIntent(function(e) {
            cover.stop().animate(
                outParams,
                {
                    queue:false,
                    duration:opts.outDuration,
                    easing:opts.outEasing
                }
            );
        }, function() {  
            cover.stop().animate(
                inParams,
                {
                    queue:false,
                    duration:opts.inDuration,
                    easing:opts.inEasing
                }
            );  
        });
    };
    
    function getOutParams(container, opts)
    {
        var width = container.outerWidth();
        var height = container.outerHeight();
        
        switch(opts.direction)
        {
            case 'up':
                return {top: '-' + height + 'px'}
            case 'down':
                return {top: height + 'px'}
            case 'left':
                return {left: '-' + width + 'px'}
            default:
                //The default is to slide right
                return {left: width + 'px'}
        }
    };
    
    function getInParams(container, opts)
    {        
        switch(opts.direction)
        {
            case 'up':
            case 'down':
                return {top: '0px'}
            case 'left':
            default:
                return {left: '0px'}
        }
    };
  
    ////Plugin defaults
    $.fn.slideReveal.defaults = {
        direction: 'right',
        coverSelector: 'div.cover',
        containerCssClass: 'slideReveal',
        outDuration: 500,
        inDuration: 500,
        outEasing:'swing',
        inEasing:'swing'
    };
})(jQuery);

(function($) {
    $.fn.eventCalendar = function() {
        return this.each(function() {
            var eventTable = $(this);
            var eventList = eventTable.find('+ div.eventList');
            
            //Check if we have any events on the page to show
            if (eventList.length > 0)
            {
                //By default we want to hide all groups unless the current page url requests to show one specifcally via a hash
                var eventGroups = eventList.find('div.eventGroup');
                eventGroups.hide();
                if (window.location.href.indexOf('#') > 0)
                {
                    var eventGroupId = GetEventGroupId(window.location.href);
                    eventList.find('div#' + eventGroupId).show();
                }
                
                //For each event date link in the table we want to add a function that toggles the event list to only display events belonging to the selected date
                var eventDates = eventTable.find('td.eventDate');
                eventDates.each(function() {
                    var link = $(this).find('a');
                    link.click(function() {
                        var eventGroupId = GetEventGroupId(this.href);
                        eventGroups.hide();
                        eventList.find('div#' + eventGroupId).show();
                    });
                });
            }
        });
        
        ////Private functions
        function GetEventGroupId(href)
        {
           return (href.split('#'))[1];
        }
    };
})(jQuery);

(function($) {
    $.fn.mediaImageGallery = function(options) {
        //Build main options before element iteration
        var opts = $.extend({}, $.fn.mediaImageGallery.defaults, options);
        
        return this.each(function() {
            var container = $(this);
            var thumbs = container.find('div.thumbnails');
            
            //Set a class on the container so we can tell this js has been applied
            container.addClass('hasFilmstrip');
            
            //Set the width of the thumbs list so it is just one big strip
            var thumbsList = thumbs.find('ul');
            var thumbsListItems = thumbsList.find('li');
            var thumbsLinks = thumbsList.find('a');
            var thumbWidth = $(thumbsListItems[0]).outerWidth(true);
            var thumbHeight = $(thumbsListItems[0]).outerHeight(true);
            var totalThumbsWidth = thumbWidth * thumbsListItems.length;            
            thumbsList.css('width', totalThumbsWidth);
            
            //Create the move left and right controls, caption area and the filmstrip
            var moveLeft = $('<div class="moveLeft"><a href="#" class="control">' + opts.moveLeftContent + '</a></div>');
            var moveRight = $('<div class="moveRight"><a href="#" class="control">' + opts.moveRightContent + '</a></div>');
            var filmstrip = $($('<div class="filmstrip"></div>').append(thumbsList));
            var captionArea = $('<div class="caption"></div>');
            
            //Add the filmstrip and controls to the container
            thumbs.empty().append(moveLeft).append(filmstrip).append(moveRight);
            container.prepend(captionArea);            
            
            //Set up the colorbox, but unbind the click event because we want the colorbox to be controlled by a different link
            thumbsLinks.colorbox({photo:true});
            thumbsLinks.unbind('click.colorbox');
            
            //Add functions to move the filmstrip and display caption when a thumb or control is clicked
            thumbsLinks.addClass('thumb').click(function(){
                SelectThumbnail(captionArea, thumbsList, filmstrip, $(this), opts);
                return false;
            });
            
            moveLeft.click(function(){
                var selectedItem = thumbsList.find('li.selected');
                var selectedItemIndex = thumbsListItems.index(selectedItem);
                
                //If we're looking at the first thumb then we can't go left
                var newItemIndex = 0;
                if (selectedItemIndex > 1)
                {
                    newItemIndex = (selectedItemIndex - 1);
                }
                
                SelectThumbnail(captionArea, thumbsList, filmstrip, $(thumbsListItems[newItemIndex]).find('a'), opts);
                return false;
            });
            
            moveRight.click(function(){
                var selectedItem = thumbsList.find('li.selected');
                var selectedItemIndex = thumbsListItems.index(selectedItem);
                
                //If we're looking at the last thumb then we can't go right
                var newItemIndex = (thumbsListItems.length - 1);
                if (selectedItemIndex < (thumbsListItems.length - 1))
                {
                    newItemIndex = (selectedItemIndex + 1);
                }
                
                SelectThumbnail(captionArea, thumbsList, filmstrip, $(thumbsListItems[newItemIndex]).find('a'), opts);
                return false;
            });
            
            //'Click' on the first thumb to make it selected
            $(thumbsLinks[0]).click();
        });
    };
    
    ////Private functions
    function SelectThumbnail(captionArea, thumbsList, filmstrip, thumbLink, opts)
    {
        var totalThumbsWidth = thumbsList.width();            
        var filmstripWidth = filmstrip.outerWidth(true);
        var filmstripCenter = filmstripWidth / 2;
        var listItem = thumbLink.parent();
        var pos = listItem.position();
        var itemCenterPos = pos.left + (listItem.outerWidth(true) / 2);
        var maxLeft = -totalThumbsWidth + filmstripWidth;                              
        var leftPos = 0;        
        var thumbsListItems = thumbsList.find('li');
        var selectedItemIndex = thumbsListItems.index(listItem);
        
        //If the selected item is past the centre point of the filmstrip, scroll it
        if (itemCenterPos > filmstripCenter)
        {
            leftPos = filmstripCenter - itemCenterPos;            
        }
        //But make sure that the new left position will not move the thumbs past the right hand edge of the filmstrip
        if (leftPos < maxLeft)
        {
            leftPos = maxLeft;
        }
        
        //Show the caption
        var image = listItem.find('img');
        var caption = image.attr('title');
        var viewLargeLink = $('<a href="#">' + opts.viewLargerImage + '</a>').click(function(){
            $.fn.colorbox({
                rel: 'gallery',
                photo: true,
                open: true,
                href: thumbLink.attr('href'),
                title: thumbLink.attr('title')
            });
            return false;
        });
        captionArea.empty().append($('<p>' + caption + '. </p>').append(viewLargeLink));
        
        //Scroll the film strip
        thumbsList.stop();
        thumbsList.animate(
            { left: leftPos + 'px'},
            {
                queue: false,
                duration: opts.animTime,
                easing: opts.animEasing
            }
        );
        
        //Set the item as selected and set the controls
        thumbsList.find('li.selected').removeClass('selected');
        listItem.addClass('selected');
        
        SetControls(filmstrip, selectedItemIndex, thumbsListItems.length);
    }
            
    function SetControls(filmstrip, selectedItemIndex, totalItems)
    {
        var moveLeft = filmstrip.parent().find('div.moveLeft');        
        var moveRight = filmstrip.parent().find('div.moveRight');
        
        if (totalItems == 1)
        {
            moveLeft.hide();
            moveRight.hide();
        }
        else if (selectedItemIndex == 0)
        {
            moveLeft.hide();
            moveRight.show();
        }
        else if (selectedItemIndex == (totalItems - 1))
        {
            moveLeft.show();
            moveRight.hide();
        }
        else
        {
            moveLeft.show();
            moveRight.show();
        }
    }
  
    ////Plugin defaults
    $.fn.mediaImageGallery.defaults = {
        moveLeftContent: '<',
        moveRightContent: '>',
        animTime: 1000,
        animEasing: 'swing',
        viewLargerImage: 'View larger image'
    };
})(jQuery);

function SetRegisterFormsTab()
{    
    var formContainer = $('div#registerForms');
    formContainer.tabs( { cookie: { expires: 30 } } );
    
    if (formContainer.length > 0)
    {
        if (formContainer.find('div#candidateRegistration div.formInput.invalid').length > 0)
        {
            formContainer.tabs('option', 'selected', 0);
        }
        else if (formContainer.find('div#employerRegistration div.formInput.invalid').length > 0)
        {
            formContainer.tabs('option', 'selected', 1);
        }
    }
}

$(document).ready(function() { 
    UpgradeASPNETValidation();
    
    $('a[rel="external"]').ExternalLinks();
    
    $('div#features div.feature').slideReveal({
        direction: 'up',
        outEasing: 'easeOutSine',
        inEasing: 'easeOutSine'
    });
    
    $('table.eventCalendar').eventCalendar();
    
    $('div.mediaGallery').mediaImageGallery();
    
    $('div#features div.newsletterFeature').DefaultValue();
    
    SetRegisterFormsTab();
});

