/**
 * Stolen from baseJS
 * http://paularmstrongdesigns.com/projects/basejs/
 */
$.extend(Function.prototype, {
    /**
     * Override scope of a function.
     * @param oScope     {object}      Object to override the scope of the function.
     * @param arguments  {*}           Any additional arguments to pass.
     */
    use: function() {
		var method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
		return function() {
			return method.apply(object, args.concat(Array.prototype.slice.call(arguments)));
		}
    },
    /**
     * Override scope of a callback function on an event.
     * @param oScope     {object}      Object to override the scope of the function.
     * @param arguments  {*}           Any additional arguments to pass.
     */
    useEL: function() {
        var method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
        return function(event) {
            return method.apply(object, [event || window.event].concat(Array.prototype.slice.call(arguments)));
        }
    }
});
$.extend(jQuery.Event.prototype, {
    stop: function() {
        this.stopPropagation();
        this.preventDefault();
    }
});

$(document).ready(function() {
	
	$('#search').data('default', $('#search').val('')).focus(function() { 
	    if($(this).val() == $(this).data('default')) {
    	    $(this).val(''); 
	    }
	}).blur(function() { 
	    if($(this).val() == '') {
    	    $(this).val($(this).data('default')); 
	    }
	});
	
	$('.filterList h2').append('<span class="toggle">+</span>');
	$('.filterList .list ul').each(function() {
	    $(this).data('height', $(this).height())
	    if(!$(this).find('.selected').length) {
	        $(this).css({ height: '0' }).removeClass('open');
	    } else {
	        $(this).parents('.list').prev('h2').children('.toggle').addClass('open').html('&ndash;');
	    }
	});
	$('.filterList h2').click(function(event) {
	    var list = $(this).parents('.filterList').find('.list ul');
	    var toggle = $(this).find('.toggle');
	    if(toggle.hasClass('open')) {
	        toggle.removeClass('open').text('+');
	        list.animate({ height: '0' }, 500, 'easeInBack');
	    } else {
	        toggle.addClass('open').html('&ndash;');
	        list.animate({ height: list.data('height')+'px' }, 700, 'easeOutBack');
	    }
	});
	
	/**
	 * Open links to other sites in the #content section in a new window
	 */
	$('#content a, .copy a').each(function() {
	    var a = new RegExp('/' + window.location.host + '/');
	    if(!a.test(this.href)) {
	        $(this).click(function(event) {
	            event.stop();
	            window.open(this.href, '_blank');
	        });
	    }
	});
	
	
   function filterPath(string) {
       return string
               .replace(/^\//,'')
               .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
               .replace(/\/$/,'');
   }
   
   var locationPath = filterPath(location.pathname);
   
   var scrollElement = 'html, body';
   $('html, body').each(function () {
       var initScrollTop = $(this).attr('scrollTop');
       $(this).attr('scrollTop', initScrollTop + 1);
       if ($(this).attr('scrollTop') == initScrollTop + 1) {
           scrollElement = this.nodeName.toLowerCase();
           $(this).attr('scrollTop', initScrollTop);
           return false;
       }    
   });
   
   $('a[href*=#]').each(function() {
       var thisPath = filterPath(this.pathname) || locationPath;
       if(locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
           if ($(this.hash).length) {
               $(this).click(function(event) {
                   event.stop();
                   
                   var targetOffset = $(this.hash).offset().top;
                   var target = this.hash;
                   
                   $(scrollElement).animate({ scrollTop: targetOffset }, 800, 'easeOutSine', function() {
                       location.hash = target;
                   });
               });
           }
       }
   });
   
   $('td.features ul').each(function() {
       var l = $(this).find('li').length;
       if(l > 4) {
           $(this).after('<a class="more" href="#more">more</a>');
           for(var i = 4; i < l; i++) {
               $($(this).find('li').get(i)).hide();
           }
       }
   });
   $('td.features a.more').bind('click', function(event) {
       event.stop();
       if(!$(this).hasClass('less')) {
           $(this).addClass('less').text('less').prev('ul').children('li').show();
       } else {
           var l = $(this).prev('ul').children('li').length;
           var i = 0;
           $(this).removeClass('less').text('more').prev('ul').children('li').each(function() {
               if(i >= 4 && i <= l) {
                   $(this).hide();
               }
               i++;
           });
       }
   });
   
   $('.tooltipContent').hide().addClass('js');
   $('.tooltip').prepend('<a class="tooltipHelp" href="#tooltip" title="More Info">?</a>').find('a.tooltipHelp').click(function(event) {
       event.stop();
       var tooltip = $(this).next('.tooltipContent');
       if(!tooltip.data('visible')) {
           tooltip.stop().fadeIn(500).data('visible', true);
           $(document).trigger({ type: 'showTooltip', reserved: tooltip.get(0) });
       } else {
           tooltip.stop().fadeOut(500).data('visible', false);
       }
   });
   $('.tooltipContent').click(function() {
       $(this).fadeOut(300);
   });
   $(document).bind('showTooltip', function(event) {
       var reserved = event.reserved;
       $('.tooltipContent').each(function() {
           if(this != reserved) {
               $(this).fadeOut(300);
           }
       });
   });
   
   
   $('object, embed').each(function() {
       var maxWidth = $(this).parent().innerWidth();
       var ratio = $(this).width() / $(this).height();
       var newHeight = maxWidth / ratio;
       
       $(this).width(maxWidth);
       $(this).height(newHeight);
   });
   
   // auto append file extensions as a class on links
   // Track Downloads
   $('a[href]').each(function() {       
       if((C = $(this).attr('href').match(/[.](docx|ppt|doc|xls|pdf|rtf|txt)$/))) { 
           $(this).addClass('file').addClass(C[1]); 
           $(this).bind('click', function(event) {
               // Track as category: 'Downloads', label: link of file, optional_label: text of link
               pageTracker._trackEvent('Downloads', $(this).attr('href'), $(this).text());
           });
       }
   });

    // Track PPC downloads differently
    $('div.whitepaper-download a[href]').each(function() {       
        if((C = $(this).attr('href').match(/[.](docx|ppt|doc|xls|pdf|rtf|txt)$/))) { 
            $(this).addClass('file').addClass(C[1]); 

            // remove the default tracker
            $(this).unbind('click');
            // add the special PPC tracker            
            $(this).bind('click', function(event) {
                console.log('PPC Campaign Download', window.location.href, $(this).attr('href'))
                //pageTracker._trackEvent('PPC Campaign Download', window.location.href, $(this).attr('href'));
                // (pageTracker moved to layout file)
            });
        }
    });
    
   
   // Track Outbound Links
   $('a').each(function() {
       var href = $(this).attr('href');
       // verify that the href includes an http or https protocol 
       // and also require that the href includes the hostname of the current page
       if( href.match('http://|https://') && href.indexOf(window.location.hostname) == -1) {
           $(this).bind('click', function() {
               // Track as category: 'Outbound Link', label: link, optional_label: the current page
               pageTracker._trackEvent('Outbound Link', $(this).attr('href'), window.location.pathname);
           });
       }
   });

   // Track Browser Dimensions
   /*
   pageTracker._trackEvent('Browser Dimensions', 'load', $(window).width() + 'x' + $(window).height(), $(window).width());
   $(window).resize(function () {
       if ($(this).data('gatimer')) {
           clearTimeout($(this).data('gatimer'));
           $(this).data('gatimer', null);
       }

       $(this).data('gatimer', 
       setTimeout(function () {
           pageTracker._trackEvent('Browser Dimensions', 'resize', $(window).width() + 'x' + $(window).height(), $(window).width());
           }, 500)
       );
   });   
   */
   
});
