/*
 * ENABLE JS-ONLY STYLES
 */
$('html').addClass('js-enabled');
if(typeof(swfobject) !== 'undefined' && swfobject.hasFlashPlayerVersion("9.0.0")) {
	$('html').addClass('flash-enabled');
}

// For weird form pieces
$(function() {
	var beginText = $('#other-branding-label').text() + ' ' + $('#other-specify-label').text().toLowerCase();
	var $otherSpecify = $('#other-specify');
	if ($otherSpecify.val() === '') {
		$otherSpecify
			.val(beginText)
			.focus(function() {
				$otherSpecify.val('');
			})
	}
	$('li#site-nav-search p.nav-arr a').click(function(){
		$('#header-search-form').submit();
		return false;
	});
});

// This opens a SWF object in a semi-transparent blue box. It can be called by calling:
// homeBoxen('path/to/flash.swf'); // Replace the path with something real, of course.
// If there's XML associated with the SWF, use this:
// homeBoxen('path/to/flash.swf?path/to/xml_file.xml');
// Remember to return false; if you're using this on a click event!
var homeBoxen = (function(e, f) {
	if ($('#swfShadowBox').length) {
		$('#swfShadowBox').fadeOut(300, function() {
			$('#swfFeature').fadeOut(100, function() {
				$(this).remove();
			});
			$('.main').removeAttr('style');
			$('.header').css('z-index', 2).animate({opacity: 1}, 75, function() {
				$('.header, .dashboard, .footer').removeAttr('style');
			});
			$(this).remove();
		});
	}
	else {
		var $b = $('body');
		var wh = $(window).height();
		var bh = $b.height();
		if (bh > wh) {
			var sbxh = bh;
		}
		else {
			var sbxh = wh;
		}
		if (e) {
			var ba = '<div id="swfShadowBox"></div><div id="swfFeature"><div id="featureSWFBox"></div></div>';
		}
		else {
			var ba = '<div id="swfShadowBox"></div>';
			$('.header').css('z-index', 999);
			$('.main').css('z-index', 998);
		}
		$b.append(ba);
		$('.header').animate({opacity: 0.5}, 300);
		$('#swfShadowBox')
			.height(sbxh)
			.css('opacity', 0)
			.show()
			.fadeTo(300, 0.85, function() {
				$('.header').animate({opacity: 0}, 150, function() {
					$('.header, .dashboard, .footer').css('z-index', 0);
				});
				if (e) {
					$('#swfFeature').show();
					var feature_flashvars = {};
					if (f) {
						var feature_flashvars = { xmlPath: f };
					}
					var feature_params = {
						quality: 'high',
						scale: 'noscale',
						allowscriptaccess: 'always',
						bgcolor: '#fff',
						wmode: 'transparent'
					};
					var feature_attributes = false;
					swfobject.embedSWF(e, 'featureSWFBox', '990', '560', '9', '', feature_flashvars, feature_params, feature_attributes);
				}
			});
	}
});


// Prevent the hight of the "Select" box on products_suite, etc., from overflowing the parent container. This should work. Probably a better way to do this, though. --EV
// Update: float the orange box for product_suites. It'll save a ton of headaches.

var orangeBoxTooBig = (function() {	
	var $orangeBox = $('#selected-products-cart');
	var $sCCont = $('.select-and-connect-container');
	var oBH = $orangeBox.height() + 247;
	var sCCH = $sCCont.height();
	
	if (oBH > sCCH) {
		$sCCont.height(oBH);
	}
});
$(function() {
	orangeBoxTooBig();
	$('.hfeed-entries h2.entry-title + div').addClass('news-source');
	// $('.product-removal, .product-indicator, .link-showdetails').click(function(){
	// 	orangeBoxTooBig();
	// });
});



/*
 * CONTACT OVERLAY SUBMIT FUNC.
 * Adds "starred" values and the selected
 * products list to the "Connect" form.
 *
 */
$(function() {

	$('#contactOverlaySubmit').click(function() {

		var $prefProd = $('#selected-products-cart input:radio:checked');
		var preferredProduct = $prefProd.val();
		$('#contactOverlayExtraValues').html('<input type="text" name="mostImportantProduct" id="mostImportantProduct" /><input type="text" name="mostImportantProductID" id="mostImportantProductID" /><input type="text" name="productInterestList" id="productInterestList" />');
		var $mIP = $('#mostImportantProduct');
		var $mIPID = $('#mostImportantProductID');
		var $pIL = $('#productInterestList');
		var selectedProductList = new Array();

		$('#selected-products-cart label').each(function() {
			var valToAdd = $(this).text();
			var sPLLen = selectedProductList.length;
			selectedProductList[sPLLen] = valToAdd;
		});

		$pIL.val(selectedProductList.join());

		if (preferredProduct) {
			var pPName = $('label[for="' + preferredProduct + '"]').text();
			var pPID = $prefProd.attr('id');
			$mIP.val(pPName);
			$mIPID.val(pPID);
		} else {
			$mIP.val('');
			$mIPID.val('');
		}
				
	});

// removed and replaced by script below
// 	$('#select-and-connect-overlay form[name=select-form] .selected-remove').click(function() {
//         $(this).parents('li').remove();
//     });
// moved this function from product-suite-cart.js to here and modified to fit both product-suite and contact-overlay pages.
	$('.select-overlay-container a.product-removal').live('click',function () {
		var $prefProdId = $('#selected-products-cart input:radio:checked').val(); //get the val of the current preferred product

		var that = this;
		var href = this.href.substr(0,this.href.indexOf('/ru')) + '/ru/ajax'; //modify embedded to url for ajax

		$.getJSON(href, function(data){
			$('#selected-products-cart').empty(); //remove all items in cart
			//data.cart is an array of products, (eg data.cart[2].id)
			$.each(data.cart, function (){
				$('a.product-indicator[rel='+this.id+']')
				    .removeClass('alt')                     //set item to default state 'alt'
					.addClass((castStringToBoolean(this.selected))?'alt':'')   //CK: added castStringToBool, if selected then add class='alt'
				    .attr('href', this.action);
				if (castStringToBoolean(this.selected)) $('#selected-products-cart').append(
					'<li><input type="radio" name="group1" value="'+this.id+'" '+(($prefProdId == this.id)?"checked='checked'":"")+'/>'+	
						'<a href="'+this.url+'" class="selected-product" rel="'+this.id+'"><span class="move_">Remove<\/span><label for="'+this.id+'">'+this.text+'</label><\/a>'+
						'<a href="'+this.action+'" class="product-removal alt"><span class="selected-remove"><span class="move_">Remove selection<\/span><\/span><\/a>'+
					'<\/li>'				
				);

			});

			$('input:radio').checkbox(); //applies the "star" styled radio button

            //these calls are not necessary on this version of the function (see similar script on product-suite-cart.js)
            //updateCartDisplay(); //show hide appropriate containers in "1. Select" box
			//updateAddAllButton(data.suite);
 		});
 		
		return false;
	});

});


/*
 * SITEWIDE NAVIGATION / NAV-WIDGET CONTROLS
 */

$(function() {

 	$('#site-nav-meta #nav-share a').prepend('<span>+&nbsp;</span>');
 	$('.entry-tags li:not(:last)').append('<span class="li-after">&nbsp;/</span>');
 	$('#email-form textarea, #email-form input:text, #nav-customer-widget-login input:text').val(''); //reset input boxes to blank
 	$('#email-form .message').empty();

	//Fix bug in Opera where forms are not cleared on back button
	if(navigator.userAgent.indexOf('Opera')!=-1) setTimeout(function (){
		$('#email-form textarea, #email-form input:text, #nav-customer-widget-login input:text').val('');
	},100);
	$('.nav-widget, .nav-widget > div, #email-form').hide(); //on page ready, hide all the navigation

 	//user clicks 'email' in 'share' widget, hide the list and show email the form
 	$('#nav-share-widget-email a').click(function() {
 		$('#nav-share-widget #not-email-form').hide();
 		$('#email-form').fadeIn();
 		return false;
 	});

 	//user click 'X', hide form, show 'share' list, reset email form values to blank
 	$('#email-form .nav-close-this a').click(function() {
 		$('#nav-share-widget #not-email-form').fadeIn();
 		$('#email-form').hide();
 		$('#email-form input:text, #email-form textarea').val('');
		$('#email-form .message').empty();
 		return false;
 	});

 	$('#site-nav-search form').submit(function() {
 		var currValue = $(this).children('input:text').val();
 		//if the search value is blank then set message to user
 		if (!currValue) {
 			$(this).siblings('.site-results-container').empty().append('<span>Please enter a search term</span>')
 			return false;
 		}
 	});

	//show/hide background 'username' and 'password' images
	$('#site-nav input:text, #site-nav input:password')
		.addClass('formInit')
		.bind('focus keypress', function() {
			$(this).removeClass('formInit');
		})
		.blur(function() {
			var currValue = $(this).val();
			if (!currValue) { $(this).addClass('formInit'); }
		});

	$('#site-nav-main, #site-nav-meta')
		.mouseenter(function (){
			$(this).data('over', true);
		})
		.mouseleave(function (){
			var $elm = $(this);
 			$elm.data('over', false);
  			setTimeout(function(){
  				if(!$elm.data('over')) {
					$elm.find('.nav-widget:visible').slideUp('fast'); //hide all visible widgets
					$('.nav-set > li', $elm).removeClass('site-nav-hover');
  				}
  			},200);
		})
   	$('.nav-set > li')
		.mouseenter(function (){
			var $elm = $(this);
			var toShowHref = $elm.children('a').attr('href');
			var $par = $elm.parents('#site-nav-main, #site-nav-meta');
			$('.nav-set > li').removeClass('site-nav-hover'); $elm.addClass('site-nav-hover');
			$elm.data('over', true);
 			setTimeout(function(){
 				if($elm.data('over')) {
					$par.siblings().find('.nav-widget').fadeOut();
					$('.nav-widget > div', $par).not(toShowHref).hide().css('z-index',40); //hide all menus
					$(toShowHref).fadeIn('fast').css('z-index',50);
					$par.find('.nav-widget:hidden').slideDown();
				}
 			},100);
		}).mouseleave(function (){
			var $elm = $(this);
			$elm.data('over', false);
		})

 	$('.nav-set > li > a').click(function() { return false; });

 	$('#nav-products-widget > ul > li, #nav-products-widget > .nav-arr, #nav-customer-widget li:not([id]), #nav-insights-widget li, #nav-insights-widget > .nav-arr, #site-nav-search li, #nav-about-widget > div, #nav-partners-widget, #nav-share-widget').hover(
  		function() { $(this).addClass('site-nav-hover'); },
  		function() { $(this).removeClass('site-nav-hover'); }
 	);
 	
 	
 	var clickableNavListItems = [
 		'#nav-products-widget > ul > li:not(#nav-products-widget-other)',
 		'#nav-customer-widget li:not([id])',
 		'#nav-insights-widget li'
 	].join();
 	
 	$(clickableNavListItems).click(function() {
 		window.location = $(this).find('a').attr('href');
 		return false;
 	});

});


//=========================
/*
 * EXPANDING PRODUCT TABS
 * EXPANDING NAVIGATION TABS
 * This redundancy will be reduced.
 */
// Expands and hides product expanders, and toggles header style.
$(function() {
	//hide divs with expander class
	//targets: products_suite.html, accounts_foundproduct.html, about_imagelibrary.html, about_press_releases.html, blog_archive.html, blog_structure.html, search_results.html
  	$('div.expander > div:not(.product-teaser)').hide();

	//toggle first tab on and switch header class.
	//targets: about_imagelibrary.html, about_press_releases.html, blog_archive.html, blog_structure.html, search_results.html
    $('div.expander:eq(0)> div').show();

	/* REMOVED: appears to orphaned, kept for reference
	$('div.expander > h2').click(function() {
		$(this).next().slideToggle('fast');
		//If an expanding class is on, turn it off, if it's off turn it on.
		$(this).toggleClass('expanding_');
		$(this).toggleClass('expanded_');
	  });
	*/

	//targets green expander on: about_imagelibrary.html, about_press_releases.html, blog_archive.html, search_results.html
	//targets gray expander on products_suite.html, accounts_foundproduct.html, blog_structure.html
	//WAS: $('div.expander > h3') NOW: targets just green expander (#nav-insights)
	$('#nav-insights .nav-product-links').hide();
	$('#nav-insights .nav-product-links:eq(0), #nav-insights div.hasSelections').show();
	$('#nav-insights.expander > h3:eq(0), #nav-insights.expander > h3.hasSelections').removeClass('expanding_');
	$('#nav-insights.expander > h3:eq(0), #nav-insights.expander > h3.hasSelections').addClass('expanded_');
	$('#nav-insights.expander > h3').addClass('expanding_').click(function() {
		$(this).next('div.expanding_').slideToggle('fast');
		//If an expanding class is on, turn it off, if it's off turn it on.
		$(this).toggleClass('expanding_');
		$(this).toggleClass('expanded_');
	});

});


//targets Contact First Data Support expander in navigation-secondary on
//accounts_extranets.html
//accounts_findproduct.html
//accounts_foundproduct.html
//accounts_qa.html
//accounts_youraccount.html
$(function() {
  $('div.contact-content').hide();
  $('div#contact-account-actions > h3.related-tagline').click(function() {
    $(this).next().slideToggle('fast');
    //If an expanding class is on, turn it off, if it's off turn it on.
    $(this).toggleClass('expanding_');
    $(this).toggleClass('expanded_');
  });
});


//accounts_foundproduct.html
// $(function() {
//   	$('div.products-foundproducts div.product-content').hide();
//   	// $('div.products-foundproducts div.has-form-errors a.link-showdetails').addClass('expanded_')
//   	// $('div.products-foundproducts div.has-form-errors div.product-intro').addClass('expanded_');
//   	$('div.products-foundproducts a.link-showdetails').click(function() {
// 		$(this).text(($(this).is(".expanded_"))?'View Details':'Hide Details');
// 		$(this).parents('div.product-intro').toggleClass('expanded_');
//   		var selectedcontent = this.rel;
//     	$('#'+selectedcontent).slideToggle('fast');
// 	    //If an expanding class is on, turn it off, if it's off turn it on.
// 	    $(this).toggleClass('expanded_');
// 	});
// 
// });


//accounts_extranets
$(function() {
  	$('div.accounts_extranets div.product-content').hide();
});



//investor_questions.html
$(function() {
  	$('div.products-foundproducts a.link-faqdetails').click(function() {
  	$(this).text(($(this).is(".expanded_"))?'View Answer':'Hide Answer');
	$(this).parents('div.product-intro').toggleClass('expanded_');
  	var selectedcontent = this.rel;
    $('#'+selectedcontent).slideToggle('fast');
    //If an expanding class is on, turn it off, if it's off turn it on.
    $(this).toggleClass('expanded_');
  });

});

//products_suite.html
//about_imagelibrary.html
//about_press_releases.html
//accounts_youraccount.html
//blog_archive.html
//blog_structure.html
//careers_landing.html (doesn't work)
//company_bio_detail.html (doesn't work)
//products_merchants_landing.html (doesn't work)
//search_results.html
$(function() {
	//Turn 'on' the folder icon when clicked.  Product class '.product-indicator' is currently the folder icon.
	$('.nav-suite').click(function () {
		$(this).toggleClass('alt');
	});
	$('.landing .headline').find('b').parents('.precis').children('p').addClass('makeThisWhite');
});

//accounts_foundproduct.html
//products_suite.html
$(function() {
	$('.product-intro').hover(function() {
	  $(this).addClass('hoverstate');
	}, function() {
	  $(this).removeClass('hoverstate');
	});
});

//products_allproducts.html
$(function() {
	$('.allproducts-byalpha li').hover(function() {
		$(this).addClass('alpha-hover');
	}, function() {
		$(this).removeClass('alpha-hover');
	});

	$('.supplementary-entry').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
});

//company_bio_landing.html
$(function() {
	$('.leadership').hover(function() {
	  $(this).addClass('leadership-hover');
	}, function() {
	  $(this).removeClass('leadership-hover');
	});
});

//accounts_youraccount.html
$(function() {
	$('.links .status-update').hover(function() {
	  $(this).addClass('status-update-hover');
	}, function() {
	  $(this).removeClass('status-update-hover');
	});
});


//accounts_youraccount.html
$(function() {
	$('.links .status-update').click(function() {
		var url = this.href;
		var el = $(this);
		$.ajax({
			url: url,
			success: function (){
				el.fadeOut(function (){el.addClass('cleared')});
			},
			error: function (){
				location.href = url;
			}
		});
		return false;
	});
});

//blog_article.html
$(function() {
	$('.blog-email-close').hover(function() {
	  $(this).addClass('blog-email-close-hover');
	}, function() {
	  $(this).removeClass('blog-email-close-hover');
	});
});

/*
 * Puff Rollover Tooltips for the navigation
 * EV_NOTE: removed for now, due to implementation issues. (10/30/2009)
 
$(function () {
  $('.bubbleInfo').each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 100;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;

    var trigger = $('.trigger', this);
    var popup = $('.popup', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: -100,
          left: -33,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});
*/
/* Basic bloggy stuff for share-this functionality. */
$(function() {
	$('.entry-share a').each(function() {
		var theTitle = $(this).text();
		$(this).attr('title', theTitle);
	});
});

/********************
 *
 *  "share" functions
 *
 ********************/
$(function() {
	// Delicious
	$('#nav-share-widget-delicious a, #on-delicious a').click(function() {
		window.open('http://delicious.com/save?v=5&noui&jump=close&url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent(document.title), 'delicious', 'toolbar=no,width=550,height=550');
		return false;
	});

	// Twitter
	$('#nav-share-widget-twitter a, #on-twitter a').click(function() {
		var makeTweet = 'http://twitter.com/home?status=Checking out ' + encodeURIComponent(document.title) + '. ' + encodeURIComponent(location.href);
		$(this).attr('target', '_blank').attr('href', makeTweet);
	});

	// Digg
	$('#nav-share-widget-digg a, #on-digg a').click(function() {
		var diggThis = 'http://digg.com/submit?url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent(document.title);
		$(this).attr('target', '_blank').attr('href', diggThis);
	});

	// Facebook
	$('#nav-share-widget-facebook a, #on-facebook a').click(function() {
		var facebookIt = 'http://www.facebook.com/share.php?u=' + encodeURIComponent(location.href) + '&t=' + encodeURIComponent(document.title);
		$(this).attr('target', '_blank').attr('href', facebookIt);
	});

	// LinkedIn
	$('#nav-share-widget-linkedin a, #on-linkedin a').click(function() {
		var linkIn = 'http://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent(document.title);
		$(this).attr('target', '_blank').attr('href', linkIn);
	});

	// Technorati
	$('#nav-share-widget-technorati a, #on-technorati a').click(function() {
		var tNut = 'http://www.technorati.com/faves?add=' + encodeURIComponent(location.href);
		$(this).attr('target', '_blank').attr('href', tNut);
	});
});


//==============
//cklanac 6/9/2009
//wrap functions in namespace to avoid name collissions
//EX: http://www.dustindiaz.com/namespace-your-javascript/
var iBlog = function() {
	var _url = "_data/wordpress_wpx.xml";
	var _type = "GET";
	var _dataType = "XML";

	var _dateFormat = {
			dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",],
			monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",]
	};

	return {
		load : function()
		{
			return $.ajax(
			{
				type: _type,
				url: _url,
				dataType: _dataType,
				success: function(data){
					var oBlog = iBlog.get($.xml2json(data)); //xml2json is a jquery plugin
					return iBlog.show(oBlog);
				},
				error: function(e){
					//TODO: implement error condition display
				}
			})
		},
		get: function(jRss)
		{
			if (!jRss.channel || !jRss.channel.item || !jRss.channel.item.length)
			{
				//TODO: show no blog entry available error?
				//call same function as ajaxError()
				return;
			}
			var rePat = new RegExp(iBlog.page(),'i'); //caseinsensitve regex
			var blogEntry;

			//loop thru blog entries - find first category match
			for (i in jRss.channel.item)
			{
				blogEntry = jRss.channel.item[i];
				if (rePat.test(blogEntry.category)) break;
			}
			return blogEntry;
		},
		page: function()
		{
			//TODO: verify that the blog category will be stored in the meta tag
			var pageCat = $('meta[name=category]').attr('content')
			return pageCat;
		},
		show: function(obj)
		{
			var target = $('#uniqueID-X');

			$('a[rel=bookmark]',target).attr('href',obj.link).text(obj.title);

			$('a.entry-full',target).attr('href',obj.link)
				.find('span.move_').text(obj.title) //hidden text for 'continue reading' link

			$('address.vcard.author',target)
				.find('a.url.fn').text(obj.author).end()
				.find('span.title').text(obj.author_title).end();

			var thisDate = new Date(obj.pubDate);
			var strISODate = thisDate.getFullYear()+'-'+thisDate.getMonth()+'-'+thisDate.getDate();
			var strLocDate = thisDate.getDate()+' '+_dateFormat.monthNames[thisDate.getMonth()]+'. '+thisDate.getFullYear();
			$('ul.entry-meta li.published abbr.value', target).attr('title',strISODate).text(strLocDate)

			$('ul.entry-meta li.category a[rel=tag]',target).text(obj.category);

			var strComments;
			if (obj.comment_count == 0) strComments = 'no comments';
			else if (obj.comment_count == 1) strComments = obj.comment_count + ' comment';
			else strComments = obj.comment_count + ' comments';

			$('ul.entry-meta li.comments a',target).text(strComments);

			$('div.entry-summary',target).empty().append('<p>'+obj.description+'</p>');
			//cklanac: the following line just is alternate code for convience.
			//if lead-in has embedded links then use 'conent' node since it supports CDATA encoded html
			//$('div.entry-summary',target).empty().append('<p>'+obj.content+'</p>');
			return true;
		},
		error: function()
		{
			$('div.box div.content.hfeed').empty().append('<p>No blog entry was found for this category</p>');
		}

	};
}();

$(function () {
	//TODO: verfiy the 'if-then' logic will hold on other pages
	//if meta tag name=category exists then page must be product landing so load blog info
	if ($('meta[name=category]').length) iBlog.load();
})



/**
 * LIVE SEARCH FUNCTIONALITY
 */
$(function() {
    //set these value before each section to customize for different searches
    jQuery.fn.liveSearch.before = '/nonjs';
    jQuery.fn.liveSearch.after = '/ajax';
    jQuery.fn.liveSearch.maxRows = 5;
    $('#site-nav-search input[name=txtSearch]')
    .val('')
    .focus(function()
    {
        $('#site-nav-main > .nav-widget, #site-nav-meta  > .nav-widget').hide();
        //ensure other dropdown navs are hidden
        if ($('#site-nav-search-widget ul.site-results-container').is(':not(:empty)')) $('#site-nav-search-widget').slideDown('fast')
    })
    .blur(function()
    {
        setTimeout(function() {
            $('#site-nav-search-widget').slideUp('fast');
        },
        250);
        //allow clicks to bubble before closing dropdown
    })
    .keyup(function()
    {
        $('#site-nav-search-widget').slideDown('fast');
    })
    .liveSearch($('#site-nav-search input[name=txtSearch]').parents('form').attr('action'),
      function(xhr, status)
      //fetching callback
      {
          $('#site-nav-search-widget ul.site-results-container').empty().append('<li class="searchload">Fetching Results</li>');
      },
      function(xhr, status, err)
      //error callback
      {
          $('#site-nav-search-widget ul.site-results-container').empty().append('<li>There was an error</li>');
          xhr.handled = true;
      },
      function(obj)
      //results callback
      {
          var thisElm = $('#site-nav-search-widget ul.site-results-container').empty();
          $.each(obj,
          function(i) {
              thisElm.append(
                $('<li></li>').append(
                  $('<h3></h3>').append(
                    $('<a></a>').attr('href', obj[i].link).html(obj[i].title)
                  ).append(
                    /** TODO: Maybe add a conditional here as a fix to issue #580 */
                    $('<span></span>').addClass('category').html(' in ' + obj[i].category)
                  ).append(
                    $('<p></p>').addClass('description').html(obj[i].description)
                  )
                )
              );
          });
      }
    );

    $('#accounts-nav-search input[name=txtSearch]')
    .val('')
    .focus(function()
    {
        if ($('#accounts-nav-search ul.search-results-container').is(':not(:empty)')) {
			$('#links-container:not(.ie7negZIndex)').addClass('ie7negZIndex');
			$('#accounts-nav-search .search-results-container-wrapper').slideDown('fast');
		}
    })
    .blur(function()
    {

        setTimeout(function() {
            $('#accounts-nav-search .search-results-container-wrapper').slideUp('fast', function() { $('#links-container').removeClass('ie7negZIndex'); });
        },
        250);
   })
    .keyup(function()
    {
        if ($('#accounts-nav-search .search-results-container-wrapper').children().length) {
			$('#links-container:not(.ie7negZIndex)').addClass('ie7negZIndex');
			$('#accounts-nav-search .search-results-container-wrapper').slideDown('fast');
		}
    })
    .liveSearch(
      $('#accounts-nav-search input[name=txtSearch]').parents('form').attr('action'),
      function(xhr, status)
      //fetching callback
      {
          $('#accounts-nav-search ul.search-results-container').empty().append('<li class="searchload">Fetching Results</li>');
      },
      function(xhr, status, err)
      //error callback
      {
          $('#accounts-nav-search ul.search-results-container').empty().append('<li>There was an error</li>');
          xhr.handled = true;
      },
      function(obj)
      {
          var thisElm = $('#accounts-nav-search ul.search-results-container').empty();

          $.each(obj, function(i) {
              thisElm.append($('<li></li>').append($('<a></a>').attr('href', obj[i].link).html(obj[i].title)));
          });
      }
    );

    $('#products-nav-search input[name=txtSearch]')
    .val('')
    .focus(function()
    {
        if ($('#products-nav-search ul.search-results-container').is(':not(:empty)')) {
		  $('#links-container:not(.ie7negZIndex)').addClass('ie7negZIndex');
          $('#products-nav-search .search-results-container-wrapper').slideDown('fast');
        }
    })
    .blur(function()
    {
        setTimeout(function() {
            $('#products-nav-search .search-results-container-wrapper').slideUp('fast', function() { $('#links-container').removeClass('ie7negZIndex'); });
        },
        250);
    })
    .keyup(function()
    {
        if($('#products-nav-search .search-results-container-wrapper').children().length) {
			$('#links-container:not(.ie7negZIndex)').addClass('ie7negZIndex');          
			$('#products-nav-search .search-results-container-wrapper').slideDown('fast');
        }
    })
    .liveSearch($('#products-nav-search input[name=txtSearch]').parents('form').attr('action'),
    function(xhr, status)
    //fetching callback
    {
        $('#products-nav-search ul.search-results-container').empty().append('<li class="searchload">Fetching Results</li>');
    },
    function(xhr, status, err)
    //error callback
    {
        $('#products-nav-search ul.search-results-container').empty().append('<li>There was an error</li>');
        xhr.handled = true;
    },
    function(obj)
    {
        var thisElm = $('#products-nav-search ul.search-results-container').empty();

        $.each(obj, function(i) {
            thisElm.append($('<li></li>').append($('<a></a>').attr('href', obj[i].link).html(obj[i].title)));
        });
    });
});


//"LiveSearch" is a completely refactored/reworked version of the original liveSearch/liveUpdate
//this version loads, scores and sorts the data in memory (2 arrays), then inserts matched items in the DOM
//Also added a timeout for the keyup event so searches are a more efficient.
//src=path to json file
//elm=UL element to hold results
//display = callback to display results

jQuery.fn.liveSearch = function(_src, _fetchFn, _errorFn, _displayFn){
	_maxRows = (jQuery.fn.liveSearch.maxRows) ? jQuery.fn.liveSearch.maxRows : 10;
	var _results; //storage for ajax search results
	var _search;
	var _delay = 200; // 1/5 second
	var _request = null;  // Instance variable for xmlhttprequest pointer
	var _input = this;    // Instance variable to store the input we're doing all this stuff on.
  // _src = _src ? _src.replace(jQuery.fn.liveSearch.before,jQuery.fn.liveSearch.after) : _src;
  // _src = _src ? _src.replace('/search/productsQuery','/search/ajaxProduct') : _src;
  _src = _src ? _src.replace('/search/all','/search/ajaxAll') : _src;
  
  // MTS: Adding a hook here to re-load after a few keyups
  // this.focus(load);
  this.keyup(function () {
    if(_request != null) {
      _request.abort();
      _request = null;
    }
    load();
  });
  var _keyup_timer = null;
	return this;

	function load()
	{
    // Don't bother with the AJAX call if there's nothing to search for.
    if($(_input).val().length == 0) {
      return;
    }
    
		_request = $.ajax({
			type: 'GET',
			url: _src,
			data: "txtSearch=" + $(_input).val(),
			dataType: 'json',
			beforeSend: _fetchFn,
			error:  _errorFn,
			success: function(json)
			{
				_results = json;
				_displayFn(_results.root.item.slice(0, _maxRows));
				//build array of 'searchable' strings used for the quicksilver process
				_search = $.map(_results.root.item, function(item){
					var str = '';
					for (prop in item) {
					  str += item[prop].toLowerCase() + ' ';
					} //CK added toLowerCase()
					return str;
				});
				
				_request = null;  // XMLHttpRequest is finished so it can be reset to null now
			} //end success
		}); //end ajax
	}
};

$(function(){
	//define the elements to be boxed, pass in options to override defaults
	//css, overlayCSS and message are options
	$('a[type=video/x-flv], a[type=image/jpeg]').boxer({
		height:265,
		width:470,
		css: {
			height:'290px',
			width:'480px',
			padding: 5,
			border: '1px solid black',
			backgroundColor: '#fff',
			cursor: 'default'
		},
		overlayCSS:  {
			backgroundColor: '#000',
			opacity:         0.8,
			cursor:         'default'
		},
	 	params : {
	 		bgcolor: "#F00"
	 	}
	});

//appears to be product suite specific, move to product-suite-cart.js
// 	$('#select-and-connect-overlay').hide()
//
 	$('#by-email').click(function ()
 	{
 		$.blockUI({
 			css: {
 				height: '367px',
 				width: '325px',
 				cursor:'default',
 				border: '0px solid black'
 			},
 			overlayCSS: {
 				cursor:'default',
 				opacity: '0.8'
 			},
 			message: $('#blog-email')
 		});
 		return false;
 	})

 	$('.blog-email-close').click(function()
 	{
 		$.unblockUI();
 		return false;
 	})


	$('#myemailform').submit(function (){
		$.ajax({
			type: $(this).attr("method"),	//get method from form
			url: $(this).attr("action"),	//get action (destination) from form
			data: $(this).serialize(),		//serialize form data for submission
			dataType: 'json',				//the response type
			beforeSend: function (){
				$('#email-form input[name=btnEmailSendButton]').addClass('progress').val('Sending');
				$('#email-form .message').empty();
			},
			error: function (xhr, opt){  //non-200 server error (eg timeout function)
				//CK: removed direct location reset and replaced with form submit.
				//var jsDiabledHref = $('#nav-share-widget-email a').attr('href');
				//location.href = jsDiabledHref;	//on any error go to the javascript disabled version of the page and display the error
				//xhr.handled = true;
				//NOTE do not use $(this).submit() it will trigger infinite loop of submits - use .click() instead
				$('#myemailform input[name=btnEmailSendButton]').click(); //force a standard form submit by clicking the button
			},
			success: function(res)	//non-200 server error (eg timeout function)
			{
				if (res.success) {
					//on success, show message for 3 seconds then revert button to "send email" and close dropdown menu
					$('#email-form input[name=btnEmailSendButton]').removeClass('progress').val(res.success);
					setTimeout(function (){
						$('#email-form input[name=btnEmailSendButton]').fadeOut(function (){
							$(this).val('Send Email').fadeIn(function (){
								$('#site-nav-meta').mouseleave();
								$('#email-form textarea, #email-form input:text').val(''); //reset input boxes to blank
								$('#email-form input[name=btnEmailSendButton]').val('Send Email');
							})
						});
					},3000)
				} else if (res.error) {
					//on success, show message for 3 seconds then revert button to "send email" and close dropdown menu
					$('#email-form input[name=btnEmailSendButton]').removeClass('progress').val('Error').after('<span class="message">'+res.error+'</span>');
					setTimeout(function (){
						$('#email-form input[name=btnEmailSendButton]').fadeOut(function (){
							$(this).val('Send Email').fadeIn(function (){
								$('#email-form input[name=btnEmailSendButton]').val('Send Email');
							})
						});
					},3000)				
				} else {
					//if neither a success message nor an error message exist, then force a standard submit to the js-disabled page 
					$('#myemailform input[name=btnEmailSendButton]').click(); //force a standard form submit by clicking the button
				}
				
				
			}
		})
		return false;	//prevent default action and stop bubble propogation
	});

});

// LOGIN and REGISTRATION form stuff.
$(function() {
	var $loginFormStart = $('#user-login-init');
	var $loginFormNext = $('#user-login-forgot');
	var $loginFormThx = $('#user-login-reset-yes');
	var $registerForm = $('.user-registration-form-content');
//	$loginFormNext.load('login_password.html #user-pwd-get-form-content > div');
//	$loginFormThx.load('login_register_confirm_pwd.html #pwd-sent-confirm > div');
	$('.i-forgot a').click(function() {
		$loginFormStart.hide();
		$loginFormNext.show();
		return false;
	});
	$('#reset-login-form').click(function() {
		$loginFormNext.hide();
		$loginFormStart.show();
		return false;
	});
});


//checks the user-login-forgot div for the class "validation-error"
// if it exists then hide the normal login and show the password retrieval div and validation error
// EXAMPLE: <div id="user-login-forgot" class="validation-error">

$(function (){
	if($('#user-login-forgot.login-registration-errors-notice').length) {
		$('#user-login-init').hide();
		$('#user-login-forgot').show();
		$('#user-login-forgot .login-registration-error').show();
	}
});

//BOXER: A CUSTOM VIDEO/IMAGE LIGHTBOX CLONE
(function($) {
	$.fn.boxer = function(options) {
		return this.each(function(){
			var $el = $(this);
			$el.click(function() {
				var _isVideo = $el.attr('type') === 'video/x-flv';
				$('<div class="overlay-container"/>')
				.append($('<span class="selected-remove"><span class="move_">Close</span></span>').click(function()
					{
						$(this).parent().empty().remove();
						$.unblockUI();
						return false;
					})).append('<div id="player" />').appendTo($el)

				var hw = $.extend({height:100,width:100}, options);
				var defaults = {
					height:hw.height,
					width:hw.width,
					message: $('.overlay-container',this),
					css: {
						width: hw.width + 'px',
						height: hw.height + 'px',
						cursor: 'wait',
						padding: 10
					},
					overlayCSS: {
						opacity: '0.8',
						cursor: 'wait'
					},
					flashvars: {
						playSt: $(this).attr('href'),
						flvPath: $(this).attr('href')
					},
					params: {
						bgcolor: "#000000",
						menu: "false",
						allowfullscreen: "true"
					},
					attributes: {
						id: "video-object"
					}
				}
				var opts = $.extend(true, defaults, options); //combine defaults and options
				$.blockUI(opts);
				if(_isVideo) {
					//delay loading the flash until the shadow box is finished loading/displaying
					setTimeout(function(){
						swfobject.embedSWF("_flash/video_player.swf", "player", opts.width, opts.height, "9.0.28", null, opts.flashvars, opts.params, opts.attributes);
					},$.blockUI.defaults.fadeIn)
				} else {
					$('#player').html('<img src="'+ $(this).attr('href') +'" />');
				}
				return false;
			});
		});
	};
})(jQuery);

$(function() {
  // Expands and hides product expanders
  // (accounts_extranets.html), and toggles header style. uses
  // addressing to saves "state" of page. allows for
  // bookmarking and fluid navigation hide divs with expander
  // class targets: products_suite.html,
  // accounts_foundproduct.html,
  
  $.address.history(false);
  //toggle this to change back/forward button behavior
  //attach addressing functionality to the expander, fires onclick
  $('a.link-showdetails')
  .address(function() {
    $(this).toggleClass('expanded_');
    //$(this).text(($(this).is(".expanded_"))?'Hide Details':'View Details'); //moved to url.change handler
    //set the has values in the URL to allow back/forward buttons and bookmarking
    //get all expanded divs and join them 'slash-separate', if there are no expanded divs, then return a space ' ' to prevent window jump to top
    return (sHash = $('a.link-showdetails.expanded_').map(function() {
      return $(this).attr('rel');
    }).get().join('/')) ? sHash: ' ';
  });
  
  $("a.link-showdetails")
  .click(function () {
    if(!$(this).parents('.product-intro').hasClass("expanded_")) {
      qContainer = $(this).parents('.product-entry').children('.content-product-container, .product-content')
      
      $(this).text("Hide details");
      $(this).parents('.product-intro').addClass("expanded_");
      
      // Some of these accordions don't have their content yet, so this loads 'em.
      if(qContainer.is(':empty')) {
        qContainer.hide().load(this.href + ' #content-product-' + this.rel, function() {
          $(this).slideDown('fast');
        });
      }
      else {
        qContainer.slideDown('fast');
      }
    }
    else {
      $(this).text("View details");
      $(this).parents('.product-intro').removeClass("expanded_");
      $(this).parents('.product-intro').siblings('.content-product-container, .product-content')
      .slideUp();
    }
  });
  //attach handler to address.onChange, the URL hash is passed to the function
  //since we don't receive the clicked object from addressing, we need to loop thru all divs and set the state
  $.address.change(function(sHash) {
    //$('div.expander-addr > .expander-header')
  });
});

/*
 * Handler for the address change. If there's something in the URL hash, it's
 * gotta get handled once at startup. After that, the links can change address
 * state but should have their own expanding onclick functions.
 */
$(function () {
  sHash = {};
  if(document.location.href.match(/#/)) {
    sHash.pathNames = document.location.href.split(/#/)[1].split('/').slice(1);
  }
  else {
    sHash.pathNames = [];
  }

  $('a.link-showdetails').each(function() {
    var qThis = $(this);
    //container for the content which is loaded from 'external' pages
    //CK: var qContainer = qThis.parents('.product-entry').children('.content-product-container');
    var qContainer = qThis.parents('.product-entry').children('.content-product-container, .product-content');

    /** Added by mstahl */
    // Determine if any of the pieces of sHash match this.rel. If they do, set a flag that's
    // tested in the following conditional block.
    is_in_hash = false;
    for (i in sHash.pathNames) {
      if (this.rel === sHash.pathNames[i]) {
        is_in_hash = true;
        break;
      }
    }
    /* 
     * EV: This seems to lock .has-form-errors and .isCurrentProduct divs
     * in their expanded states. What we need is something that only evaluates
     * those classes on page load, maybe by finding them & appending their hashes.
     * Needs research.
     */

    /** /mstahl */
    if($(this).parents('.product-entry').is('.has-form-errors') || $(this).parents('.product-entry').is('.isCurrentProduct') || is_in_hash) {
      $(this).addClass('expanded_').removeClass("has-form-errors");
      $(this).parents('div.product-intro').addClass('expanded_');
      qThis.text('Hide Details');
      // if the container is empty (initial state) then load content, else just show it...
      // this saves multiple calls to the external product pages
      if (qContainer.is(':empty')) {
        qContainer.load(this.href + ' #content-product-' + this.rel, function() {
          $(this).slideDown('fast');
        });
      }
      else {
        qContainer.slideDown('fast');
      }
    }
    else {
      $(this).removeClass('expanded_');
      $(this).parents('div.product-intro').removeClass('expanded_');
      //hide section and reset display
      qThis.text('View Details');
      qThis.parents('div.product-intro').removeClass('expanded_');
      qContainer.slideUp('fast');
    }
    // orangeBoxTooBig();
  });
});
