/* 
	jQuery Library Needed
	RiverBed Main JavaScript File
*/

// Avoid conflicts with prototype $().
var $ = jQuery.noConflict()


/**********************************************/
//	  Stopping all Clicks Before Page Loads
/**********************************************/
$().bind('click.noclick', function(){
	return false;
});

/**********************************/
//	   jQuery JS Calls
/**********************************/
$(document).ready(function() {
						   
	var tab = $('div.tabs > div');
		tab.hide().filter(':first').show();
		
		$('div.tabs ul.tab a').click(function () {
			tab.hide();
			tab.filter(this.hash).show();
			$('div.tabs ul.tab a').removeClass('selected');
			$(this).addClass('selected');
			return false;
		}).filter(':first').click();
						  
/**********************************/
//	   Home Page Tabs Rotation
/**********************************/
	var stopper = false;
	
	numTabs = $(".tabbed-box .tabs li a").length;
	
	//Stop Rotation when TAB is clicked
	$(".tabbed-box .tabs li a").click(function() {
		$f("*").each(function() { 
			this.unload();
		});
		if (stopper){
			$(".tabbed-box").unbind('mouseover');
			$(".tabbed-box").unbind('mouseout');
		}
		stopper = true;
		openTab($(this)); return false;
	});
	
	//Stop rotation when "PLAY" is clicked
	$(".tabbed-box .tabbed-content .innerLeft a").click(function() {
		if (stopper){
			$(".tabbed-box").unbind('mouseover');
			$(".tabbed-box").unbind('mouseout');
		}
		stopper = true;
	});
	
	$(".tabbed-box").mouseover(function(){clearInterval(autoRotate)})
	.mouseout(function(){autoRotate = setInterval("rotateTabs()", rotateSpeed)});
		
	$(".tabbed-box .tabs li a:eq("+currentTab+")").click()
	$(".tabbed-box").mouseout();

	
/**********************************/
//		Mega Menu Dropdown
/**********************************/
	//On Hover Over
	function megaHoverOver(){
	    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in    
	}
	
	//On Hover Out
	function megaHoverOut(){
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
	      $(this).hide();  //after fading, hide it
	  });
	}
	
	//Set custom configurations
	var config = {
		sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
		interval: 0, // number = milliseconds for onMouseOver polling interval
		over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
		timeout: 0, // number = milliseconds delay before onMouseOut
		out: megaHoverOut // function = onMouseOut callback (REQUIRED)
	};
	
	$("#topnav li.large_dropdown").each(function (i) {
		var pos = $(this).position().left;
		pos = pos + 19;
		$(this).find('.sub').css("left", "-" + pos + "px");
	});
	
	$("#topnav li.medium_dropdown").each(function (i) {
		var pos = $(this).position().left;
		pos = pos - 458;
		$(this).find('.sub').css("left", "-" + pos + "px");
	});
	
	$("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
	$("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations

/***************************
	Browser Bookmark
***************************/
$("a.bookmark").click(function(e) {
	if ($.browser.opera == false) {
			e.preventDefault();
			var url = this.href;  
			var title = this.title;
	
			if ($.browser.mozilla == true) {
					window.sidebar.addPanel(title, url, '');
					return false;
			} else if($.browser.msie == true) {  
					window.external.AddFavorite( url, title);
					return false;
			} else {
					alert('Please use CTRL + D to bookmark this website.');
			}
    }
});

/**********************************/
//		Share Module
/**********************************/
	if ($('#share').length) {
		$("#mailto").attr('href', $("#mailto").attr('href').replace('{articleUrl}', window.location.href));
		$("#mailto").attr('href', $("#mailto").attr('href').replace('{articleTitle}', document.title));
		$("#digg").attr('href', $("#digg").attr('href').replace('{articleUrl}', window.location.href));
		$("#digg").attr('href', $("#digg").attr('href').replace('{articleTitle}', document.title));
		$("#del").attr('href', $("#del").attr('href').replace('{articleUrl}', window.location.href));
		$("#del").attr('href', $("#del").attr('href').replace('{articleTitle}', document.title));
		$("#facebook").attr('href', $("#facebook").attr('href').replace('{articleUrl}', window.location.href));
		$("#facebook").attr('href', $("#facebook").attr('href').replace('{articleTitle}', document.title));
		$("#twitter").attr('href', $("#twitter").attr('href').replace('{articleUrl}', window.location.href));
		$("#stumbleupon").attr('href', $("#stumbleupon").attr('href').replace('{articleUrl}', window.location.href));
		$("#stumbleupon").attr('href', $("#stumbleupon").attr('href').replace('{articleTitle}', document.title));
		$("#reddit").attr('href', $("#reddit").attr('href').replace('{articleUrl}', window.location.href));
		$("#reddit").attr('href', $("#reddit").attr('href').replace('{articleTitle}', document.title));
		$("#bookmark").click(function() {
				bookmark_us(window.location.href, document.title);
			});
	}

/**********************************/
//		Country Selection
/**********************************/
	$('#nav li').hover(
		function () {
			//show its submenu
			$('ul', this).slideDown(100);

		},
                function () {
			//hide its submenu
			$('ul', this).slideUp(600);			
		}

);

/**********************************/
//		JS Column List (Customer Stories Landing Page)
/**********************************/
	$('#alphaList').columnizeList({cols:3,constrainWidth:0});
	

/**********************************/
//		jQuery Accordion
/**********************************/
	$('ul').accordion();
	
/**********************************/
//		Equal Heights Calls
/**********************************/
	equalHeight($(".column"));
	equalHeight($(".equal"));

/**********************************/
//		JQuery Tabs
/**********************************/
	//$(".tab-set").tabs();
	
	$(function() {
	    $('.tab-set').tabs();
	    $("a.openTab").click(function() {
	        $('.tab-set').tabs('select', this.hash);
	        return false;
	    });
	});
	
	
/**********************************/
//		Remove No-Click Event
/**********************************/	
	$(function(){
		$().unbind('click.noclick');
	});

/*End of Document.Ready*/
});

/********************************************/
//		Rotating Banner On Home Page
/********************************************/
var rotateSpeed = 5000; // Milliseconds to wait until switching tabs.
var currentTab = 0; // Set to a different number to start on a different tab.
var numTabs; // These two variables are set on document ready.
var autoRotate;

function openTab(clickedTab) {
	var thisTab = $(".tabbed-box .tabs a").index(clickedTab);
	$(".tabbed-box .tabs li a").removeClass("active");
	$(".tabbed-box .tabs li a:eq("+thisTab+")").addClass("active");
	$(".tabbed-box .tabbed-content").hide();
	$(".tabbed-box .tabbed-content:eq("+thisTab+")").show();
	currentTab = thisTab;
}

	
function rotateTabs() {
	var nextTab = (currentTab == (numTabs - 1)) ? 0 : currentTab + 1;
	openTab($(".tabbed-box .tabs li a:eq("+nextTab+")"));
	
}
/********************************************/
//		jQuery Equal Heights
/********************************************/

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/********************************************/
//		jQuery Accordions
/********************************************/
(function($){ 
     $.fn.extend({  
         accordion: function() {       
            return this.each(function() {
				if($(this).data('accordiated'))
					return false;									
				$.each($(this).find('ul, li>div'), function(){
					$(this).data('accordiated', true);
					$(this).hide();
				});
				$.each($(this).find('a:not(.foo)'), function(){
					$(this).click(function(e){
						activate(e.target);
						return void(0);
					});
				});
				
				var active = false;
				if(location.hash)
					active = $(this).find('a[href=' + location.hash + ']')[0];
				else if($(this).find('li.current'))
					active = $(this).find('li.current a')[0]; 
				
				if(active){
					activate(active, 'toggle','parents');
					$(active).parents().show();
				}
				
				function activate(el,effect,parents){
					$(el)[(parents || 'parent')]('li').toggleClass('active').siblings().removeClass('active').children('ul, div').slideUp('fast');
					$(el).siblings('ul, div')[(effect || 'slideToggle')]((!effect)?'fast':null);
				}
				
            });
        } 
    }); 
})(jQuery);

/********************************************/
//		jQuery Sliding Panel
/********************************************/
$(function(){
	
	$("#openBtn").click(function(){
		$("#panel").animate({height: "135px"}, "swing").animate({height: "135px"}, "fast");
		$(".panelBtn").toggle();
		return false;
	});
	
	$("#closeBtn").click(function(){
		$("#panel").animate({height: "135px"}, "swing").animate({height: "0px"}, "fast");
		$(".panelBtn").toggle();
		return false;
	});
	
});

/********************************************/
//		jQuery Accordion (Multiple)
/********************************************/
(function($) {
$.fn.expandAll = function(options) {
    var defaults = {
         trigger1 : 'Expand All',
         trigger2 : 'Collapse All',
         container : '.sliderWrap div.sliderContent',
         ref : 'h4.expand',
         showMethod : 'slideDown',
         hideMethod : 'slideUp',
         speed : ''
    };
    var o = $.extend({}, defaults, options);   
    return this.each(function() {
        $(o.container + ':eq(' + $(o.container).index(this) + ') ' + o.ref + ':first').before('<p class="switch"><a href="#">' + o.trigger1 + '</a></p>');
        $(this).find('p.switch a').click(function() {
        var $cllps = $(this).closest(o.container).find('.collapse'),
            $exp = $(this).closest(o.container).find(o.ref);
        if ($(this).text() == o.trigger1) {
          $(this).text(o.trigger2);
          $exp.addClass('open');
          $cllps[o.showMethod](o.speed);
        } else {
          $(this).text(o.trigger1);
          $exp.removeClass('open');
          $cllps[o.hideMethod](o.speed);
        }
        return false;
    });
});};
})(jQuery);
////////////////////////////
$(function() {
    // --- Initially hide collapsible sections. Generate <a>-tags wrapping the elements that handle the toggle action. --- //
    $('.sliderWrap').find('div.collapse').hide().end()
    .find('h4.expand').wrapInner('<a style="display:block" href="#" title="expand/collapse" />');
    
    // --- Expand All/Collapse All --- //
    $('.sliderWrap div.sliderContent').each(function(index) {
        var $thisDemo = $('.sliderWrap div.sliderContent:eq(' + index + ')');
        if (index == 2) {
          $thisDemo.expandAll({
            trigger1 : '[Show]', 
            trigger2 : '[Hide]', 
            ref : 'div', 
            showMethod : 'show', 
            hideMethod : 'hide', 
            speed: 'slow'});
        } else {
        $thisDemo.expandAll();
        }
    });
    
    // --- Toggle --- //
    $('.sliderWrap div.sliderContent h4.expand').click(function() {
        $(this).toggleClass('open')
        .next('.collapse').slideToggle();
        return false;
    });
    
});

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);



/**********************************/
//	Form Select Dropdown
/*********************************/
	
function showHide(obj)
{
  $("#" + obj).siblings().hide();
  $("#" + obj).show();
}
	
/***************************

A validator for the Registration form

***************************/

function Validator(form){
	error=0;

	if(form.first_name.value==""){
		error=1;
		alert("Please enter your first name!");
		form.first_name.focus();	
	}else if(form.last_name.value==""){			
		error=1;
		alert("Please enter your last name!");
		form.last_name.focus();	
	}else if(form.title.value==""){		
		error=1;
		alert("Please enter your title!");
		form.title.focus();
	}else if(form.company.value==""){
		error=1;
		alert("Please enter the company name!");
		form.company.focus();
	}else if(form.email.value==""){
		error=1;
		alert("Please enter your email address!");
		form.email.focus();	
	}else if(form.phone.value==""){		
		error=1;
		alert("Please enter your telephone number!");
		form.phone.focus();
	}else if(form.state.value==""){		
		error=1;
		alert("Please enter your state or province!");
		form.state.focus();
	}else if(form.country.value==""){		
		error=1;
		alert("Please enter your country!");
		form.country.focus();
	}

	if(error==1)
		return false;
	else
		return true;
}
			

/***************************
	JavaScript Columns
***************************/
(function($){
  $.fn.columnizeList = function(settings){
    settings = $.extend({
      cols: 3,
      constrainWidth: 0
    }, settings);
    // var type=this.getNodeType();
    var container = this;
    if (container.length == 0) { return; }
    var prevColNum = 10000; // Start high to avoid appending to the wrong column
    var size = $('li',this).size();
    var percol = Math.ceil(size/settings.cols);
    var tag = container[0].tagName.toLowerCase();
    var classN = container[0].className;
    var colwidth = Math.floor($(container).width()/settings.cols);
    var maxheight = 0;
    // Prevent stomping on existing ids with pseudo-random string
    var rand = Math.floor(Math.random().toPrecision(6)*10e6);
    $('<ul id="container'+rand+'" class="'+classN+'"></ul>').css({width:$(container).width()+'px'}).insertBefore(container);
    $('li',this).each(function(i) {
      var currentColNum = Math.floor(i/percol);
      if(prevColNum != currentColNum) {
        if ($("#col" + rand + "-" + prevColNum).height() > maxheight) { maxheight = $("#col" + rand + "-" + prevColNum).height(); }
        $("#container"+rand).append('<li class="list-column-processed"><'+tag+' id="col'+rand+'-'+currentColNum+'"></'+tag+'></li>');
      }
      $(this).attr("value",i+1).appendTo("#col"+rand+'-'+currentColNum);
      prevColNum = currentColNum;
    });
    $("li.list-column-processed").css({
      'float':'left',
      'list-style':'none',
      'margin':0,
      'padding':0
    });
    if (settings.constrainWidth) {
      $(".list-column-processed").css({'width':colwidth + "px"});
    };
    $("#container"+rand).after('<div style="clear: both;"></div>');
    $("#container"+rand+" "+tag).height(maxheight);
    // Add CSS to columns
    this.remove();        
    return this;
  };
})(jQuery);


/***************************
	Validator for Press Resource form
***************************/

function validate(expr)
	{
		if(document.verify.comply[1].checked) //if disagree is checked, skip validation
		{
			return true;
		}
		else if(document.verify.comply[0].checked==false && document.verify.comply[1].checked==false)
		{
			return true; //if neither agree or disagree is checked, skip validation
		}
		else
		{
		
		if(check_name(document.verify.FirstName.value)==false){
			alert("Please enter your first name!");
			document.verify.FirstName.focus();
			return false;
		}
		else if(check_name(document.verify.LastName.value)==false){
			alert("Please enter your last name!");
			document.verify.LastName.focus();
			return false;
		}
		else if(trim(document.verify.Company.value)==""){
			alert("Please enter your Company!");
			document.verify.Company.focus();
			return false;
		}
		else if(check_WorkPhone(document.verify.WorkPhone.value)==false){
			alert("Please enter a valid WorkPhone number!\n(ex. xxx-xxx-xxxx, xxxxxxxxxx)");
			document.verify.WorkPhone.focus();
			return false;
		}
		else if(check_EmailAddress(document.verify.EmailAddress.value)==false){
			alert("Please enter a valid Email address!");
			document.verify.EmailAddress.focus();
			return false;
		}
	
		
		else if(trim(document.verify.Region.value)==""){
			alert("Please enter your state/province!");
			document.verify.Region.focus();
			return false;
		}
		else if(check_zip(document.verify.zip.value)==false){
			alert("Please enter a valid zip or postal code!");
			document.verify.zip.focus();
			return false;
		}
		else if(trim(document.verify.Country.value)==""){
			alert("Please select your country!");
			document.verify.Country.focus();
			return false;
		}
		
		else {
		//document.verify.submit(this.verify);
		return true;
		}
	 	//not requiring zip code b/c not all countries use them
		
	}
}		
	function trim(stringValue)
	{
		return stringValue.replace(/(^\s+|\s+$)/g,"");
	}
	
	function check_EmailAddress(EmailAddress)
	{
		var EmailAddress = trim(EmailAddress);
		var EmailAddressReg = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		var matches =  EmailAddress.match(EmailAddressReg);
		
		if ((EmailAddress == "") || (!matches))
		{
		return false
		}
		return true
	}
	
	
	function check_WorkPhone(WorkPhone) 
	{
		var WorkPhone_number = trim(WorkPhone);
		var WorkPhoneReg = /^[0-9\-]*$/;
		var matches = WorkPhone_number.match(WorkPhoneReg);
		if ((WorkPhone_number=="") || (!matches))
		{
		//alert ('invalid WorkPhone #');
   		return false
		}
		//alert ('valid WorkPhone #');
		return true
	}
	
	function check_name(name) 
	{
		var name = trim(name);
		var nameReg = /^[a-zA-Z]{2,20}$/;
		var matches = name.match(nameReg);
		if ((name=="") || (!matches))
		{
		//alert ('invalid WorkPhone #');
   		return false
		}
		//alert ('valid WorkPhone #');
		return true
	}
	
	function check_zip(zip) 
	{
		var zip = trim(zip);
		var zipReg = /^[0-9]{0,3}?[a-zA-Z]{0,3}?[0-9]{1,10}$/;
		var zipRegAU = /^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$/;
		var zipRegCA = /^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/;
		var zipRegDE = /^([0124678][0-9]{4})$/;
		var zipRegUK = /^(([A-Z]{1,2}[0-9][0-9A-Z]{0,1})\ ([0-9][A-Z]{2}))|(GIR\ 0AA)$/;
		var zipOther = /^[0-9]{0,3}?-[0-9]{0,5}$/;
		
		
		var matches = zip.match(zipReg);
		var matchesAU = zip.match(zipRegAU);
		var matchesCA = zip.match(zipRegCA);
		var matchesDE = zip.match(zipRegDE);
		var matchesUK = zip.match(zipRegUK);
		var matchesOther = zip.match(zipOther);
		
		
		if ((zip=="") || ((!matches) & (!matchesUK) & (!matchesCA) & (!matchesDE) & (!matchesAU) & (!matchesOther) )) {
		//alert ('invalid zip #' + zip);
   		return false
		}
		//alert ('valid zip #' + zip);
		return true
		}







