﻿//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() {                  
                if (this.tagName != 'A') {
                    return false;
                }
                
                var link = String(this);
                var linkHost = this.hostname;
                var siteHost = location.host;
                
	            if (link.match(/^mailto:/i)) 
	            {
                    $(this).click(function() {  
		                return HandleMailToLink(this);
                    });
	            }
	            else if (linkHost == siteHost) 
	            {
	                var parts = link.split('?');
	                var path = parts[0];
		            if(path.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|ashx)$/)) 
		            {
                        ModifyTitleAttribute(this);  
                        $(this).click(function() {  
		                    return HandleDocumentLink(this);
                        });
		            }
		            else
		            {
                        $(this).click(function() {  
	                        return HandleInternalLink(this);
                        });
		            }
	            }
	            else 
	            {
                    ModifyTitleAttribute(this); 
                    $(this).click(function() {  
		                return HandleExternalLink(this);
                    });
		        }
            });
        
            function HandleMailToLink(anchor)
            {
                var email = anchor.href.substring(7);
                TrackLink('email', email);
                
                return true;
            }
            
            function HandleDocumentLink(anchor)
            {
                var doc = CleanURL(anchor.pathname, false);
                TrackLink('documents', 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 linkStr = CleanURL('/'+type+'/'+virtualPath, true);
	                //pageTracker._trackPageview(linkStr);
	                trackGAPageview(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;
            }
            
            function ModifyTitleAttribute(anchor)
            {
                var jAnchor = $(anchor);
                var title = $(anchor).attr('title');
                if (title.length > 0)
                {
                    title += ' [opens in a new window]';
                }
                else
                {
                    title += 'Opens in a new window';
                }
                jAnchor.attr('title', title);
            }
        }
    });
})(jQuery);

//Re-assigns a couple of the ASP.NET validation JS functions to provide a more flexible approach
function ModifyASPNETValidation()
{
    //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;
    }
    
    //Add validation statuses to any validaiton controls that may be visible (i.e. visible when the page loads)
    $('span.validation:visible').each(function(){
        AddValidationStatus($(this));
    });
}

function AddValidationStatus(obj)
{
    if (obj.hasClass('validation'))
    {
        //We'll look for a validation container to set the status on
        var vc = obj.parents('div.validationContainer');
        if (vc.length == 0)
        {
            //Fall back to div.formInput
            vc = obj.parents('div.formInput');
        }
        vc.addClass('invalidInput');
    }
}

function RemoveValidationStatus(obj)
{
    if (obj.hasClass('validation'))
    {
        //We'll look for the validation container to remove the status
        var vc = obj.parents('div.validationContainer');
        if (vc.length == 0)
        {
            //Fall back to div.formInput
            vc = obj.parents('div.formInput');
        }
        vc.removeClass('invalidInput');
    }
}

//Extends the classic ASP.NET validation
function NicerValidatorUpdateDisplay(val)
{
    var $val = $(val);
    if (val.isvalid)
    {
        //Hide the validaiton control
        $val.hide();        
        
        //Remove the validation status if there are no more validaiton controls visible
        if ($val.parent().find('span.validation:visible').length == 0)
        {            
            RemoveValidationStatus($val);
        }
    }
    else
    {
        //SHow the validation control
        $val.show();
        
        //Add the validaiton status
        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('invalidInput');
    }
    else
    {
        //$(this).parent().removeClass('invalidInput');
    }
}

function CheckBoxValidatorDisableButton(chkId, mustBeChecked, btnId)
{
    var button = document.getElementById(btnId);
    var chkbox = document.getElementById(chkId);
    
    if (button && chkbox)
    {
        button.disabled = (chkbox.checked != mustBeChecked);
    }
}

function CheckBoxValidatorEvaluateIsValid(val)
{
    var control = document.getElementById(val.controltovalidate);
    var mustBeChecked = Boolean(val.mustBeChecked == 'true');

    return control.checked == mustBeChecked;
}

function CheckBoxListValidatorEvaluateIsValid(val)
{
    var control = document.getElementById(val.controltovalidate);
    var minimumNumberOfSelectedCheckBoxes = parseInt(val.minimumNumberOfSelectedCheckBoxes);

    var selectedItemCount = 0;
    var liIndex = 0;
    var currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
    while (currentListItem != null)
    {
        if (currentListItem.checked) selectedItemCount++;
        liIndex++;
        currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
    }
    
    return selectedItemCount >= minimumNumberOfSelectedCheckBoxes;
}

function GetQueryValue(name)
{
    return GetQueryValue(window.location.href, name);
}

function GetQueryValue(url, name)
{
    var urlParts = url.split('?');
    if (urlParts.length == 2)
    {
        var query = urlParts[1];
        var vars = query.split('&');
        for (var i=0;i<vars.length;i++)
        {
            var pair = vars[i].split('=');
            if (pair[0] == name)
            {
                return pair[1];
            }
        }
    }
    return '';
}

$(document).ready(function(){
    //Handle all links with rel = external
    $('a[rel="external"]').ExternalLinks();
    
    //Modify the standard .NET client validation so we can have a bit more control over presentation
    ModifyASPNETValidation();
    
    // position image at the bottom of the page (note 552 is the height of the image)
    var bot = eval($(document).height());
    if (bot > 552)
        bot = bot - 552;
    $('div.backgroundFilm').addClass('backgroundFilmShow').css('top', bot);
});


function trackGAPageview(pageName)
{
    if (typeof(_gaq) != 'undefined')
    {
        _gaq.push(['_trackPageview', pageName]);
        //alert('_trackPageview { ' + pageName + '}');
    }
}

function trackGAEvent(category, action, label, value)
{
    if (typeof(_gaq) != 'undefined')
    {
        _gaq.push(['_trackEvent', category, action, label]);
        //alert('_trackEvent { ' + category + ',  ' + action + ',  ' + label + ',  ' + value + '}');
    }
}

function trackResourceEvent(action, category)
{
    var label = $('div#nav li.jsNav a.active span').text();
    trackGAEvent(category, action, label, '');
}
