/*
Namespace: BBY

File Name: global.js

About: Version
	1.0

Description:
	global javascript functions for best buy

Requires:
	jQuery 1.3.2 <http://jquery.com>

*/

window.BBY = window.BBY || {};
BBY.OS = ""; // platform detect

/**
	Fix background image flickering in IE6
*/
try {
	document.execCommand("BackgroundImageCache",false,true);
} catch(e) {}

/**
	global site functionalities
 */
BBY.Global = function(){
	
	var $ = jQuery;

	/** set up the sub nav mouse over main nav (ie support)
	*/
	var setupSubnav = function(){
		var nav = $("#nav");
		$("li", nav).bind("mouseover", function(e){
			$("ul", this).css("display", "block");
		});
		$("li", nav).bind("mouseout", function(e){
			$("ul", this).css("display", "none");
		});
	};

	/** clear the search box on click of original term
	*/
	var setupSearch = function() {
		/**
			Search form in header
		*/
		var searchForm = $('#search'),
			search = $(".searchTerm", searchForm),
			defaultTerm = search.attr('title'),
			
			clearSearchDefault = function() {
				if (defaultTerm === search.val()) {
					search.val("");
				}
			},
			populateSearchDefault = function() {
				if ("" === search.val()) {
					search.val(defaultTerm);
				}
			};
			
			if (search.val() === "") {
				search.val(defaultTerm);
			}

			search
				.bind("focus", clearSearchDefault)
				.bind("blur", populateSearchDefault);

			searchForm
				.bind("submit", clearSearchDefault);
				
			

		/**
			More form on search page.
		*/
		var moreForm = $('#searchMore');
		
		if (!moreForm.length) {
			return;
		}
		
		var searchMore = $(".moreTerm", moreForm);
			defaultMore = searchMore.attr('title'),
			
			clearMoreDefault = function() {
				if (defaultMore === searchMore.val()) {
					searchMore.val("");
				}
			},
			populateMoreDefault = function() {
				if ("" === searchMore.val()) {
					searchMore.val(defaultMore);
				}
			};
			
			if (searchMore.val() === "") {
				searchMore.val(defaultTerm);
			}
			
		searchMore
			.bind("focus", clearMoreDefault)
			.bind("blur", populateSearchDefault);
			
		moreForm
			.bind("submit", clearMoreDefault);
	};

	/** set up the show more buttons for voices
	*/
	var setupMore = function(){
		var allMore = $(".more");
		var max = 4; // set to show 4 currently

		var findTarget = function(node) {
			return $(node).attr("rel");
		};

		var showMax = function(list){
			$("."+list+ " li").css("display", "block");
		};

		var hideMax = function(list) {
			$("."+list+ " li").css("display", "none");
			$("."+list+ " li:lt(" + max + ")").css("display", "block");
		}

		// initial state
		$(allMore).each(function(index, link){
			hideMax(findTarget(link));
		});

		// on click show or hide
		$(allMore).bind("click", function(e) {
			e.preventDefault();
			if ($("span.seeLess", this).css("display") == "none") {
				showMax(findTarget(this))
			} else {
				hideMax(findTarget(this))
			}
			$("span", this).toggle();
		})
	};
	
	/** set up printing on preview page
	*/
	var setupPrintBtn = function(){
		$(".print").bind("click", function(e) {
			e.preventDefault();
			window.print();
		});
	};

	/** set up sharing
	*/
	var setupShare = function(){
		var hitBox = $(".shareContainer");
		hitBox.bind("click", function(e) {
			e.preventDefault();
			var button = $("a", this),
				position = button.position(),
				shareBox = $(".social_bookmark", this);

			if ($(this).hasClass("up")) {
				shareBox.css("top", position.top-20-shareBox.height());
			} else {
				shareBox.css("top", position.top + button.outerHeight());
			}

			shareBox.css("left", position.left - 5);
			$(".social_bookmark", this).toggle();
		});

	};

	/** set up external links in footer
	*/
	var setupExternalLinks = function(){
		$(".external").each(function(i, n) {

			$(n).bind("click", function(e){
				e.preventDefault();
				var link = $(this).attr("href");
				window.open(link, "BBY", "width=800,height=600,resizable=1");
			})
		});
	};
	
	/** set up the home page carousel
	*/
	var setupCarousel = function(){
		$(".scrollable").scrollable({ 
		    size: 2
		 }).circular().navigator().mousewheel().autoscroll(7000);
	};
	
	/** set up the tabs on about
	*/
	var setupTabs = function(){
		$(".tabs").tabs("div.panes > div").history(); 
		
		// sifr hax for tabbed content
		$("#aboutNav a").bind("click", function(e){
			BBY.SIFR();
		});
	};
	
	/** set up the digest overlay
	*/
	var setupDigestOverlay = function(){
		
		var dform = $("#digestForm");
		var dsuccess = $("#digestSuccess");
		var errorList = $("#digestForm .errorList");
		var capArea = $(".insertCaptcha", dform);
		
		var api = $("#mediaTools a.toolEmail[rel]").overlay({ 
					expose: { 
					        color: '#333', 
					        loadSpeed: 200, 
					        opacity: 0.6 ,
							onClose: function(){
								$("li", errorList).remove();
							},
							onLoad: function(){
							//	getCaptcha(capArea);
							}
					 },
					api: true 
			});
			
		// bind close to all overlay apis 
		$("#digestOverlay .cancelDigest").bind("click", function(e){
			e.preventDefault();
			api.close();
		});	
		// set up ajax form submit
		$("#submitDigest").bind("click", function(e){
			e.preventDefault();
			var data = dform.serialize();
			var ajaxurl =  dform.attr('action');
			
		//	var sURL = unescape(window.location);
		//	console.log(sURL);
			
			$.ajax({
				url			: ajaxurl,
				type		: "POST",
				data		: data,
				cache		: false,
				dataType 	: 'json',

				success	: function(returnData) {
					if (returnData.success) {
						dform.hide();
						dsuccess.show();
					} else {
						for (var i in returnData.errors) {
							errorList.append("<li>"+returnData.errors[i]+"</li>");
						}
					}
				}
			}); // end ajax
		}); // end submit
		
	};
	
	/** set up the email article overlay
	*/
	var setupEmailOverlay = function(){
		var apis = [];
		var eform = $("#emailForm");
		var esuccess = $("#emailSuccess");
		var errorList = $("#emailForm .errorList");
		var capArea = $(".insertCaptcha", eform);
		
		$(".social_bookmark a[rel]").each(function(i, trigger){
			// set up overlay api on each click trigger
			var overlayAPI = $(trigger).overlay({ 
				expose: { 
				        color: '#333', 
				        loadSpeed: 200, 
				        opacity: 0.6 ,
						onClose: function(){
							eform.show();
							esuccess.hide();
							$("li", errorList).remove();
						},
						onLoad: function(){
							try {
								Recaptcha.reload();
							} catch(e) {}
						}
				 },
				api: true 
			});
			
			
			// bind close to all overlay apis 
			$("#emailOverlay .cancelEmail").bind("click", function(e){
				e.preventDefault();
				overlayAPI.close();
			});	
			
			apis.push(overlayAPI);
		});
		var api = apis[0]; // meh
		
		// set up ajax form submit
		$("#submitEmail").bind("click", function(e){
			e.preventDefault();
			var data = eform.serialize();
			var ajaxurl =  eform.attr('action'); 
			
			$.ajax({
				url			: ajaxurl,
				type		: "POST",
				data		: data,
				cache		: false,
				dataType 	: 'json',

				success	: function(returnData) {
					if (returnData.success) {
						$("#sendToEmail").text($("#emailForm input[name=emailTo]").val()); // send to email in message
						eform.hide();
						esuccess.show();
					} else {
						for (var i in returnData.errors) {
							errorList.append("<li>"+returnData.errors[i]+"</li>");
						}
					}
				}
			}); // end ajax
			
		});
	};
	
	var setupCollapsibleLivestream = function() {
		var $container = $('#livestream.collapsible');
		
		if (!$container.length) {
			return;
		}
		
		var closed	= "closed",
			$header = $container.find('.header'),
			$player = $container.find('.player'),
			$meta	= $container.find('.meta'),
			$news	= $('#latestNews'),
			$msg	= $('<p>Open to watch now.</p>').appendTo($header).hide(),
			$toggle	= $('<a href="#">close</a>').addClass('btn').appendTo($header);
			
		$toggle.bind('click', function(e){
			e.preventDefault();
			if ($container.hasClass(closed)) {
				// expand the player
				$player.show();
				$msg.hide();
				$news.hide();
				$meta.show();
				$toggle.text('close');
				$container.removeClass(closed);
			} else {
				// Collapse the container
				$player.hide();
				$msg.show();
				$news.show();
				$meta.hide();
				$toggle.text('open');
				$container.addClass(closed);
			}
		});
		
		$toggle.trigger('click');
	};
	
	var getCaptcha = function(area) {
		$.ajax({
			url			: "/wp-admin/admin-ajax.php?action=sch_bby_util_recaptcha_html",
			type		: "POST",
			data		: {},
			cache		: false,

			success	: function(response) {
				area.append(response);
			}
		}); // end ajax
	};
	
	var ie6HoverSupport = function() {
		try {
			$('#galleryImages .figure').ie6hover();
		} catch(e) {}
	};
	
	
	return {
		initialize : function(){
			setupSubnav();
			setupSearch();
			setupMore();
			setupPrintBtn();
			setupShare();
			setupExternalLinks();
			setupCarousel();
			setupTabs();
			setupEmailOverlay();
			setupDigestOverlay();
			setupCollapsibleLivestream();
			ie6HoverSupport();
		}
	}

}();

/** Print plugin for articles
*/
jQuery.fn.popupwindow = function(p)
{

	var profiles = p || {};

	return this.each(function(index){
		var settings, parameters, mysettings, b, a;
		
		// for overrideing the default settings
		mysettings = (jQuery(this).attr("rel") || "").split(",");
		
		settings = {
			height:600, // sets the height in pixels of the window.
			width:600, // sets the width in pixels of the window.
			toolbar:0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			resizable:1, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			left:0, // left position when the window appears.
			top:0, // top position when the window appears.
			center:0, // should we center the window? {1 (YES) or 0 (NO)}. overrides top and left
			createnew:1, // should we create a new window for each occurance {1 (YES) or 0 (NO)}.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0 // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
		};

		// if mysettings length is 1 and not a value pair then assume it is a profile declaration
		// and see if the profile settings exists

		if(mysettings.length == 1 && mysettings[0].split(":").length == 1)
		{
			a = mysettings[0];
			// see if a profile has been defined
			if(typeof profiles[a] != "undefined")
			{
				settings = jQuery.extend(settings, profiles[a]);
			}
		}
		else
		{
			// overrides the settings with parameter passed in using the rel tag.
			for(var i=0; i < mysettings.length; i++)
			{
				b = mysettings[i].split(":");
				if(typeof settings[b[0]] != "undefined" && b.length == 2)
				{
					settings[b[0]] = b[1];
				}
			}
		}

		// center the window
		if (settings.center == 1)
		{
			settings.top = (screen.height-(settings.height + 110))/2;
			settings.left = (screen.width-settings.width)/2;
		}
		// NOTE: modified the scrollbar property to be on. Should come back later to set it up properly later on.
		parameters = "location=" + settings.location + ",menubar=" + settings.menubar + ",height=" + settings.height + ",width=" + settings.width + ",toolbar=" + settings.toolbar + ",scrollbars=1" /* + settings.scrollbars */  + ",status=" + settings.status + ",resizable=" + settings.resizable + ",left=" + settings.left  + ",screenX=" + settings.left + ",top=" + settings.top  + ",screenY=" + settings.top;
		
		jQuery(this).bind("click", function(){
			var name = settings.createnew ? "PopUpWindow" + index : "PopUpWindow";
			window.open(this.href, name, parameters).focus();
			return false;
		});
	});

};

/*
Namespace: ie6hover
	A jQuery plugin that adds hover support to any element in IE6
*/

(function($) {
	
	// ie6? 
	var ie6 = $.browser.ie6 || !!($.browser.msie && parseInt($.browser.version, 10) === 6);
	
	/**
	 * @constructor
	 */
	$.ie6hover = function(el, opts) {
		
		this.$el	= $(el);
		this.opts	= $.extend({}, $.fn.ie6hover.defaults, opts || {});
		
		this.initialize();
	};

	$.ie6hover.fn = $.ie6hover.prototype;
	$.ie6hover.fn.extend = $.extend;
	
	/**
		Extend the constructor with private methods
	 */
	$.ie6hover.fn.extend({
		
		/**
		 * Binds hover events to the elements passed in, adding a class on hover.
		 * @private
		 * @returns nothing
		 */
		initialize : function() {
			
			var self = this;
			
			this.$el.hover(
				function(){
					$(this).addClass(self.opts.hoverClass);
				},
				function(){
					$(this).removeClass(self.opts.hoverClass);
				}
			);
			
		}
		
	});
	
	/**
	 * @name ie6hover
	 * @type jQuery
	 * @param Hash options A set of key/value pairs to set as configuration properties.
	 * @cat Plugins/ie6hover
	 */
	$.fn.ie6hover = function(options) {
		
		if (!ie6) {
			return;
		}
		
		return this.each(function() {
			new $.ie6hover(this, options);
		});
	};

	/**
		Defaults
	*/
	$.fn.ie6hover.defaults = {
		hoverClass			: "hover"
	};

})(jQuery);

/**
	sifr set up replacement
 */
BBY.SIFR = function(){
	var ua = navigator.userAgent.toLowerCase();
	BBY.OS = {
	  mac: /mac/.test(ua),
	  win: /win/.test(ua),
	  linux: /linux/.test(ua)
	};

	if (BBY.OS.linux) {
		return false; // skip sifring if its on linux
	}

	var futura = { src: '/cmn/swf/futura.swf' };

	sIFR.activate(futura);

	sIFR.replace(futura, {
		wmode: 'transparent',
		selector: '#voicesHeaderSpecial, .homeModule .homeHeader h2, #twitterVoices h2',
		css: [
		'.sIFR-root { color: #333333 }'
	 	,'a { text-decoration: none; color: #333 }'
		,'a:link { color: #333333 }'
		,'a:hover { color: #333333; text-decoration: underline }'
		 ]
	});

	sIFR.replace(futura, {
		wmode: 'transparent',
		selector: '#needHelp h2, #mediaTools h2, .stockInitial, #footerContent h3, h2.latest, .sectionHeaderMain, h2.header2, #sectionRail h3, #sectionRail h2, #peoplesVoice h2, #article .rail h3, .search h1, .notFound h1, .paneRail h3',
		css: [ '.sIFR-root { color: #333333;}' ]
	});

	sIFR.replace(futura, {
		wmode: 'transparent',
		selector: '#sectionColumn .voicesColumn h2, .news #sectionColumn h2, .sustain #sectionColumn h2,  .world #sectionColumn h2, #voicesAd p.adHeader',
		css: [ '.sIFR-root { color: #ffffff;}' ]
	});

	sIFR.replace(futura, {
		wmode: 'transparent',
		selector: '.latestHeader, #featureTitle, #feature2Title',
		css: [
        '.sIFR-root { color: #ffffff; text-transform: uppercase }'
                ,'a { text-decoration: none; color: #fff }'
		,'a:link { color: #ffffff }'
		,'a:hover { color: #ffffff; text-decoration: none }'
		,'.sIFR-root {leading: 2;}' 
		 ]
	});

};

BBY.SIFR(); // call sifr immediately

/**
	Fire up the global initialization.
*/
jQuery(document).ready(BBY.Global.initialize);
