/**
 * ----------------------------------------------
 * ---         object tree for humana         ---
 * ----------------------------------------------
 * humana
 *		.init(options)
 *		.replaced_el
 *		.replacement_el
 *		.selectify(arr,context,orig_caller)
 *		.overlay_labels(inputs)
 *		.pw_input(hidden_input,password_input)
 *		.rounder(arr)
 *		.equalize(options)
 *		.modal
 *			.init(options)
 *			.screen()
 *			.create_dialog()
 *		.compare_table
 *			.init(elem)
 *			.equalize(th)
 *			.add_x(elem)
 *			.remove_col(elem)
 *		.nav
 *			.init()
 *		.mastnav
 *			.init(arr,obj)
 *			.dropdown(index)
 *		.slideshow
 *			.timer
 *			.init(options)
 *			.control_check()
 *			.play()
 *			.fade_slide_out(elem)
 *			.fade_slide_in(elem)
 *		.tabs
 *			.init(options)
 *			.switcher(outer, nav, active, id)
 *		.carousel
 *			.init(arr)
 *			.next(trig)
 *			.prev(trig)
 *		.twitter
 *			.init(argConfig)
 *			.remove_entities(str)
 *			.linkify(str)
 *			.search(container, query)
 *		.video()
 *		.query_string(str)
 *		.maps
 *		.prepare_gmaps
 * ----------------------------------------------
 */

var humana = {
	
	config : {
		
		nohash : false
		
	},
	
	/* perform utility actions */ 
	init : function(options){
		if(options.overlay){
			humana.overlay_labels(options.overlay);
		}
		if(options.round){
			humana.rounder(options.round);
		}
		if(options.equalize){
			$(options.equalize).each(function(){
				humana.equalize(this);
			});
		}
		
		/* onload handlers */
		humana.link_handler.init();
		
		// product list expandable
		$('.product_list').delegate('.items>li', 'hover', function(e){
			e.preventDefault();
			$(this).toggleClass('hover');
		});
		$('.product_gallery').delegate('.items>li', 'hover', function(e){
			e.preventDefault();
			$(this).toggleClass('hover');
		});
		
		/* Initialize Tab Navigation */
		humana.tabnav.init();
		
		/* Initialize ShowHide Boxes */
		humana.showhide.init();
		
		// medicare zip code search binding
		$('body').delegate('#medicare_plans_search', 'submit', function(e) {
			e.preventDefault();
			window.open($(this).attr('action')+'?'+$(this).serialize());
		});
		
		// humana one state dropdown binding
		$('body').delegate('#individual_plans_search', 'submit', function(e) {
			e.preventDefault();
			window.open($(this).attr('action')+'?'+$(this).serialize());
		});
		
		// alternating table.data row classes
		if($('table.data').length > 0){
			$('table.data tr:even').addClass('alt');
		}
		
	},
	
	
	/* global storage for element replacements using selectify */
	replaced_el : '',
	replacement_el : '',
	
	/* utility method for transforming list(s) into select(s)
	 * - arr = array of jQuery collections containing lists to be selectified.
	 * - context should be passed as null
	 * - origCaller should be passed as arguments.callee from a calling function.
	 * - EXAMPLE OF HOW TO CALL:
	 * - if($('.pulldown').length > 0){ humana.selectify([$('.pulldown')], null, arguments.callee); }
	 */
	selectify : function(arr, context, origCaller){
		var tmpAttrs = [],
			tmpClone,
			newEl;

		$(arr).each(function(){

			// store the original element so we can extract its stuff later
			tmpClone = $(this).clone();

			// perform element arrangement, based on where in the list's node tree we are
			if(tmpClone.is('ul') || tmpClone.is('ol') || tmpClone.is('dl')){
				newEl = $('<select></select>');
				humana.replaced_el = $(this);
				humana.replacement_el = newEl;
			} else {
				if(context !== undefined && context.is('select')) {
					context.append('<option></option>');
					newEl = context.find('option:last');
					if(tmpClone.get(0).firstChild.nodeType == 3){ /* 3 == Node.TEXT_NODE - babysit IE */
						newEl.text(tmpClone.text());
					}
				} else if(context !== undefined && context.is('option')) {
					if(tmpClone.is('a')){
						context.text(tmpClone.text());
						context.val(tmpClone.attr('href'));
					} else {
						context.append(tmpClone);
					}
					newEl = tmpClone;
				}
			}

			if(tmpClone !== newEl){
				// dump list's attributes to a tmp var
				tmpAttrs = tmpClone.get(0).attributes;

				$(tmpAttrs).each(function(){
					if(this.nodeName == 'class'){
						newEl.addClass(this.nodeValue);
						if(this.nodeValue == 'heading'){
							newEl.attr('disabled','disabled');
						} else if(this.nodeValue == 'current'){
							newEl.attr('selected','selected');
						}
					} else {
						if(this.nodeValue !== null && this.nodeValue !== '') {
							newEl.attr(this.nodeName, this.nodeValue);
						}
					}
				});

				// artificially limit depth of traversal by cutting context off after <option> el's in the node tree
				if(!newEl.is('select') && !newEl.is('option')){
					newEl = undefined;
				}
				// recursively call selectify, passing array of list children to process and current new element for context
				if(tmpClone.children().length > 0){
					humana.selectify(tmpClone.children(), newEl);
				}
			}

		});

		// if we're done with all the recursion, perform the actual replacement.
		if(humana.selectify.caller === origCaller){
			humana.replaced_el.replaceWith(humana.replacement_el);
			// select box binding for triggering page change
			// - using .change() here rather than .delegate() in global init due to ie6 weirdness
			$('.pulldown, .condense').change(function(e){
				location.href = $(this).val();
			});
		}
	},
	
	/**
	 * Label overlay util method
	 * @param {Object} inputs
	 */
	overlay_labels : function(inputs) {
		
		inputs.each(function() {
			$(this).prev('label')
				.hide()
				.end()
				.val($.trim($(this).prevAll('label:first').text()));
		});
		
		inputs.bind('focus', function() {
			if($.trim($(this).val().toLowerCase()) == $.trim($(this).prevAll('label:first').text().toLowerCase())) {
				$(this).val('');
			}
		}).bind('blur', function() {
			if($(this).val() == '') {
				$(this).val($.trim($(this).prevAll('label:first').text()));
			}
		});
		
	},
	
	///* facebook-style password input switcher */
	pw_input : function(hidd, pass){
		
		pass.hide();
		hidd.show();
		humana.overlay_labels(hidd);
		
		$(hidd).focus(function(){
			$(this).hide();
			$(pass).show()
				.focus();
		});
		
		$(pass).blur(function(){
			if(this.value == ''){
				$(hidd).show();
				humana.overlay_labels(hidd);
				$(this).hide();
			}
		});
		
	},
	
	/* corner rounding util method */
	rounder : function(arr){
		
		$(arr).each(function(){
			$(this).addClass('rounded')
				.before('<span class="left"></span>')
				.after('<span class="right"></span>');
		});
		
	},
	
	/**
	 * equalize column heights for display util method
	 *
	 * cols - jQuery collection containing column elements to equalize
	 * type - String value either 'simple' or 'multi'
	 *	- if 'simple', two cols, set height to taller value
	 *	- if 'multi', multiple rows in each column, combine and then set height to tallest
	 * example options object: {cols:$('#mycols),type:'simple'}
	 */
	equalize : function(options){
		var cols = options.cols,
			type = options.type,
			tallest = 0,
			totalLeftHeight = 0,
			totalRightHeight = 0,
			heightExtras = 0,
			filterFloat,
			newHeight;
			
		if(type == 'simple'){
		
			cols.each(function(){
				if(parseInt($(this).height(), 10) > tallest){
					tallest = parseInt($(this).height(), 10);
				}
			});
			cols.css('height', tallest);
			
		} else if(type == 'multi'){		
				
			cols.each(function(cnt, elem){
				if($(this).css('float') == 'left'){
					if(cnt === 0){
						heightExtras += parseInt($(this).css('margin-bottom'), 10);
						totalLeftHeight += heightExtras;
					}
					totalLeftHeight += parseInt($(this).height() +
									parseInt($(this).css('padding-bottom'), 10) +
									parseInt($(this).css('border-bottom-width'), 10), 10);
				} else if($(this).css('float') == 'right'){
					totalRightHeight += parseInt($(this).height(), 10);
				}
			});

			if(totalLeftHeight > totalRightHeight){
				filterFloat = 'right';
				newHeight = totalLeftHeight;
			} else if(totalRightHeight > totalLeftHeight){
				filterFloat = 'left';
				newHeight = totalRightHeight;
			} else {
				filterFloat = 'right';
				newHeight = totalLeftHeight;
			}

			cols.each(function(){
				if($(this).css('float') == filterFloat){
					$(this).css('height', newHeight);
				}
			});
		}
	},
	
	/**
	 * modal dialog utility
	 *
	 * simple modal dialog popper.  for accessibility uses existing inline elements on page
	 * via provided jQuery collection to populate the dialog.
	 * - these elements should be hidden via JS in their own handlers, so that modern clients don't see the originals.
	 * - we clone the hidden original and populate the dialog with the copy.  the original is untouched.
	 */
	modal : {
	
		// initialize modal dialog window
		// - we do a bit more work here than normal to make sure that everything needed is in 
		// - place and kosher, to keep from popping empty windows or grinding and causing poor responsiveness.
		// - as a bonus, the function handles most predictable input-type scenarios.
		init : function(options){
			var tmp;
		
			if(typeof(options) != "object" && $(options).length < 1) {
				
				// fail silently (but with honor), like a ninja.
				return false;
			
			} else if( typeof(options) == "object" && options.jquery === undefined ){
			
				// parse out options object
				// - if options is expanded in the future, here is the spot to process it.
				// - for now, options.elem is all we're using.  see associated conditionals below.
				
				if(options.elem !== undefined && options.elem.jquery !== undefined){
				
					// we've been given a jQuery object.  ideal!
				
				} else if(options.elem !== undefined){
				
					if($(options.elem).length < 1){
						return false;
					} else {
						options.elem = $(options.elem);
					}
					
				}
				
			} else if(options.jquery !== undefined){
				
				// jquery in the house
				if(options.elem === undefined){
					tmp = options;
					options = {};
					options.elem = tmp;
				}
				
			} else if($(options).length < 1){
				
				return false;
			
			} else {
				tmp = options;
				options = {};
				options.elem = $(tmp);
			}
			
			// if we made it here, we know that by hook or by crook... options.elem is now a valid jQuery object.
			humana.modal.create_dialog(options.elem);
		},
		
		// utility for toggling transparent overlay behind modals
		screen : function(){
			// bind event for removal
			$('#modal_screen').live('click', function(e){
				e.preventDefault();
				$('#dialog').remove();
				$(this).remove();
			});
				
			// check for existing, render out
			if($('#modal_screen').length < 1){
				$('body').append('<div id="modal_screen"></div>');
				$('#modal_screen').animate({opacity:0.75,height:$(window).height()}, 600);
			} else if(!$('#modal_screen').is(':visible')){
				$('#modal_screen').animate({opacity:0.75,height:$(window).height()}, 600);
			} else {
				$('#modal_screen').fadeOut();
			}
		},
		
		// create dialog box
		create_dialog : function(elem){
			humana.modal.screen();
			
			if($('#dialog').length < 1){
				$('body').append('<div id="dialog"><div class="content"></div></div>');
			} else if(!$('#dialog').is(':visible')){
				$('#dialog').fadeIn();
			}

			// initialize with 1/20th viewport-width margin on all sides
			var xGap = Math.floor($(window).height() / 20),
				yGap = Math.floor($(window).width() / 20),
				widthTmp = parseInt(yGap * 18, 10),
				heightTmp = parseInt(xGap * 18, 10);
			$('#dialog').css({
				'left':yGap,
				'top':xGap,
				'width':widthTmp,
				'height':heightTmp
			});
			
			// populate dialog
			elem.clone().appendTo('#dialog .content');
			
			// trick to help compare_table dialogify function
			return $('#dialog .content');
		}
	
	},
	
	/* compare table utility */
	compare_table : {
		
		// initialize table functionality using provided element
		init : function(elem){
			var th = elem.find('th');
			
			// hide table so we can modalize it
			elem.hide();
			
			humana.compare_table.equalize(th);
		},
		
		// equalize column widths
		equalize : function(th){
			var width = Math.floor(100 / parseInt(th.length, 10));
			th.css('width',width+'%');
		},
		
		// add 'x' buttons to provided column(s)
		add_x : function(elem){
			elem.prepend('<a class="x_btn" href="#" title="Close">X</a>')
				.find('.x_btn')
				.live('click', function(){
					humana.compare_table.remove_col(elem);
				});
		},
		
		// remove column given provided TH element
		remove_col : function(elem){
			var col = elem.index(),
				table = elem.closest('table'),
				tmpEl;
				
			elem.remove();
			table.find('tr').each(function(){
				tmpEl = $(this).find('td')
					.get(col);
				$(tmpEl).remove();
			});
			
			humana.compare_table.equalize(table.find('th'));
		},
		
		// perform the functions necessary to pop a dialog and put our table into it
		dialogify : function(elem){
			var table = humana.modal.create_dialog(elem).find('table'),
				th;
			
			table.show();
			th = table.find('th');
			th.each(function(){
				humana.compare_table.add_x($(this));
			});
		}
		
	},
	 
	/* nav object */
	nav : {
		
		// initializes the nav submenus
		init : function(){
			$('#nav_primary').find('.submenu .content')
				.css({'border-bottom':'0'})
				.after('<img class="submenu_btm" src="/library/images/nav_menu_btm.png" alt="" width="639" height="43" />');
		}
		
	},
	
	/**
	 * mastnav object
	 * - initialize with object containing index of mastnav elements to activate dropdown for,
	 * - as well as object containing dropdown data in format like:
	 * - {0:[{title:item1title,url:item1url},{title:item2title,url:item2url}],2:[{title:item1title,url:item1url}]}
	 */
	mastnav : {
	
		// initialize dropdowns
		init : function(arr, obj){
			// attach data to DOM elements for activated items so we can find them later
			var linkArr = $('#masthead ul li a');
			$(arr).each(function(){
				linkArr.eq(parseInt(this)).data('mastnav', this);
			});
			
			// store active item array and dropdown object for later use
			humana.mastnav.activeArr = $(linkArr);
			humana.mastnav.dropdownData = obj;

			// event handler for dropdowns
			$('#masthead').delegate('ul li a', 'click', function(e){
				if ($(this).text() == 'Log In') {
					e.preventDefault();
				}
				if ($(this).data('mastnav')) {
					e.preventDefault();
					humana.mastnav.dropdown(parseInt($(this).data('mastnav')));
				}
			});
			$('#masthead').delegate('ul li div.mastdrop', 'mouseleave', function() {
				// hide dropdown if it exists
				$(this).hide();
			});
		},
		
		// trigger dropdown menu for given index
		dropdown : function(index) {
			var
        self = humana.mastnav.activeArr.eq(index),
				dropDiv = '<div id="mastdrop-' + index + '" class="mastdrop"></div>';
			
			if (self.next('div').length == 0) {
				self.after(dropDiv);
				var thisDrop = self.next('div');

				if ($.trim(thisDrop.prev('a').text()) !== 'Log In') {
					// append links from data object unless we're dealing with LogIn link
					thisDrop.append('<ul></ul>');
					var itemMarkup;
					for (var i = 0; i < humana.mastnav.dropdownData[index].length; i++) {
						if (i == 0) {
							itemMarkup = '<li class="first"><a href="' + humana.mastnav.dropdownData[index][i].url+'">'+humana.mastnav.dropdownData[index][i].title+'</a></li>';
						} else if (i == humana.mastnav.dropdownData[index].length - 1) {
							itemMarkup = '<li class="last"><a href="'+humana.mastnav.dropdownData[index][i].url+'">'+humana.mastnav.dropdownData[index][i].title+'</a></li>';
						} else {
							itemMarkup = '<li><a href="'+humana.mastnav.dropdownData[index][i].url+'">'+humana.mastnav.dropdownData[index][i].title+'</a></li>';
						}
						thisDrop.find('ul').append(itemMarkup);
					}
					thisDrop.show();					
				} else {
					// build out login form
					var loginFormMarkup = '<form action="https://securedlogons.humana.com/common/scripts/PreLogin.asp" id="mast_login" method="post">' +
            '<fieldset>' +
						'<legend>log in</legend>' +
						'<label for="mast_uid">User ID</label>' +
						'<input id="mast_uid" type="text" name="Userid" />' +
						'<label for="mast_password">Password</label>' +
						'<input id="mast_password" name="" type="text" />' +
						'<input id="mast_password-actual" name="txtPassword" type="password" />' +
						'<input type="hidden" name="launchURL" />' +
						'<input type="hidden" name="slstylesheet" />' +
						'<input type="hidden" name="portoforigin" value="0" />' +
						'<input type="hidden" name="sourcesite" value="1" />' +
						'<button name="login" type="submit"><span>Log In</span></button>' +
						'<a href="https://securedlogons.humana.com/common/scripts/UserIDPasswordHelp.asp" id="mast_forgot_password" title="Forgot ID/Password?">Forgot ID/Password?</a>' +
						'</fieldset>' +
						'</form>';
					thisDrop.append(loginFormMarkup);
					humana.pw_input($('#mast_password'),$('#mast_password-actual'));
					humana.overlay_labels($(thisDrop).find('input[type="text"]'));
					thisDrop.show();
				}
			} else {
				self.next('div').show();
			}
		}
		
	},
	
	showhide : {
		
		init : function() {
			
			// Force all open showhide items to close. We don't support multiple open items
			$('div.showhide .info').slideUp();
			
			// Bind the click event to the showhide link on each item
			$('div.showhide a.showhide_link').click( function(e) {
				
				// Since the showlink links are anchor tags, we prevent them from acting like real anchors
				e.preventDefault();
				
				// Determine if the current item is shown by checking for the .show class
				var is_shown = false;
				if ($(this).hasClass('show'))
					is_shown = true;
				
				// Check if current item is a nested showhide
				var nested = false;
				if ($(this).parent().parent().hasClass('info'))
					nested = true;
				
				// Close all open showhide items to close if they are siblings or children. Also, remove the .show class from .info divs and showhide links
				$(this).parent().parent().find('div.showhide .info').removeClass('show').slideUp();
				$(this).parent().parent().find('a.showhide_link').removeClass('show');
				
				// Is this item is not shown, then show it and add .show class
				if (!is_shown)
					$(this).addClass('show').siblings('div.info').addClass('show').slideDown();
				
			});
			
		}
		
	},
	
	/* slideshow object */
	slideshow : {
		
		timer : '',
		
		// initializes the slideshow and its methods
		init : function(options){
			humana.slideshow.id = options.id;
			if(options.controls === true){
				humana.slideshow.controls = true;
				var html_controls = '<p id="slideshow_nav">';
				var counter = 1;
				$(humana.slideshow.id+" .slide").each( function() {
					if (counter == 1)
						html_controls += '<a id="slide'+counter+'_link" href="#slideshow" class="active">'+counter+'</a>';
					else
						html_controls += '<a id="slide'+counter+'_link" href="#slideshow">'+counter+'</a>';
					counter++;
				});
				html_controls += '<span id="control" href="#slideshow">></span></p>';
				$(humana.slideshow.id).append(html_controls);
			} else {
				humana.slideshow.controls = false;
			}
			
			// bind control elements
			$('#slideshow_nav #control').click(function(e){
				e.preventDefault();
				if($(this).hasClass('active')) {
					humana.slideshow.play();
				}	else {
					$.clearTimer(humana.slideshow.timer);
				}
			});
			$('#slideshow_nav a').click(function(e){
				e.preventDefault();
				if(!$(this).hasClass('active')){
					var curr = $(humana.slideshow.id + ' > .active');
					humana.slideshow.fade_slide_out($(curr));
					humana.slideshow.fade_slide_in($('#' + $(this)[0].id.replace('_link', '')));
					if(!$('#slideshow_nav #control').hasClass('active')){
						$.clearTimer(humana.slideshow.timer);
					}
				}
			});
			
			// kickoff slideshow
			if($(humana.slideshow.id).length > 0){
				humana.slideshow.timer = $.timer(6000, function(){
					humana.slideshow.play();
				}, function(){
					if(humana.slideshow.control_check()){
						$('#slideshow_nav #control').toggleClass('active');
					}
				});
			}
		},
		
		// checks if the control elements have been enabled
		control_check : function(){
			return humana.slideshow.controls ? true : false;
		},
		
		
		// triggers the slideshow
		play : function(){
			var controller = $('#slideshow_nav #control'),
				curr;
			
			if(humana.slideshow.control_check()){
				if(controller.hasClass('active')){
					controller.toggleClass('active');
				}
			}
			
			curr = $(humana.slideshow.id + ' > .active');
			
			humana.slideshow.fade_slide_out(curr);
			
			if($(curr).next('.slide').length > 0){
				humana.slideshow.fade_slide_in($(curr).next('.slide'));
			} else {
				humana.slideshow.fade_slide_in($(humana.slideshow.id + ' .slide:first'));
			}
			
			humana.slideshow.timer = $.timer(8000, function(){
				humana.slideshow.play();
			}, function(){
				if(humana.slideshow.control_check()){
					$('#slideshow_nav #control').toggleClass('active');
				}
			});
		},
		
		// fade out current slide
		fade_slide_out : function(elem){
			$(elem).fadeOut(1200)
				.toggleClass('active');
			if(humana.slideshow.control_check()){
				$('#' + elem[0].id + '_link').toggleClass('active');
			}
		},
		
		// fade in new slide
		fade_slide_in : function(elem){
			$(elem).fadeIn(1200)
				.toggleClass('active');
			if(humana.slideshow.control_check()){
				$('#' + elem[0].id + '_link').toggleClass('active');
			}
		}
		
	},
	
	/* tabs object
	 * - init with object containing id, like {id:'#tabset'}
	 */
	tabs : {
	
		// enable tab behaviors on provided outer id
		init : function(options){
			var outer = $(options.id),
				nav = $(options.id + '_nav'),
				active = $(nav).find('li.active'),
				visible = $(active.find('a').attr('href'));
			
			outer.find('.tab').css({'position':'absolute','top':'0'});
			outer.find('.tab').not(visible).hide();
			
			// bind tab-switching behaviors for tab nav
			nav.find('li').bind('click', {outer:outer,nav:nav}, function(e){
				e.preventDefault();
				var active = $(nav).find('li.active'),
					id = parseInt($(this).find('a').attr('href').replace('#tab', ''), 10) - 1;
				humana.tabs.switcher(outer, active, nav, id);
			});
		},
		
		// switch away from provided active tab, to tab in provided outer container's tabset_nav with provided id
		switcher : function(outer, active, nav, id){
			active.toggleClass('active');
			
			if (window.location.pathname != '/' && window.location.pathname != '/default.aspx')
				window.location.hash = $(this).attr('href');
		
			var curr = nav.find('li').eq(id),
				visible = curr.find('a').attr('href');
			
			curr.toggleClass('active');
			
			outer.find('.tab').not(visible).fadeOut(600);
			$(visible).fadeIn(600);
		}
	
	},
	
	/**
	 * TABNAV is a reusable function that allows you to dynamically set the navigation and collection
	 * 	containers to create a tabbed, in-page navigation. 
	 */
	tabnav : {
		
		settings : {
			navigation: 'ul.tabs li',
			container: 'div.tabs_container',
			hashtag: ''
		},
		
		init : function(options) {
			$.extend(humana.tabnav.settings, options);
			
			if (window.location.hash) {
				humana.tabnav.settings.hashtag = window.location.hash;
			}
			
			$(humana.tabnav.settings.navigation).each( function() {
				if ($(this).find('a').attr('href') == window.location.hash) {
					$(this).addClass('active').siblings().addClass('hidden').removeClass('active');
				}
			});
			
			$(humana.tabnav.settings.navigation).each( function() {
				
				$(this).not('.active').each( function() {
					$($(this).find('a').attr('href')).hide();
				});
				
				$(this).not('.hidden').bind('click', function(e) {
					e.preventDefault();
					$(this).toggleClass('active').siblings().removeClass('active');
					humana.tabnav.showtab($(this).find('a').attr('href'));
					humana.tabnav.set_hash($(this).find('a').attr('href'));
				});
				
				if ($(this).hasClass('hidden')) 
					$(this).hide();
					
			});
			
			$(humana.tabnav.settings.container).find('a.showtab').each( function() {
				
				$(this).click( function(e) {
					e.preventDefault();
					humana.tabnav.showtab($(this).attr('href'));
				});
				
			});
			
		},
		
		showtab : function(tab) {
			$(tab).show().siblings().hide();
		},
		
		set_hash : function(element_id) {
			
			var element_id = element_id.replace(/^.*#/, '');
			var element = $('#'+element_id);
			
			$(element).removeAttr('id');
			window.location.hash = element_id;
			$(element).attr('id',element_id);
			
		}
		
	},
	
	/* carousel object */
	carousel : {
	
		// enable carousel behaviors on supplied jQuery objects
		init : function(arr){
			$(arr).each(function(){
				$(this).before('<a class="carousel_left_arrow" href="#">prev</a>')
					.after('<a class="carousel_right_arrow active" href="#">next</a>');

				$(this).prev()
					.bind('click', function(e){
						e.preventDefault();
						humana.carousel.prev($(this));
					})
					.end()
					.next()
						.bind('click', function(e){
							e.preventDefault();
							humana.carousel.next($(this));
						});
			});
		},
		
		// advance the carousel one slide, triggering button passed in for context
		next : function(trig){
			var curr = trig.prev().find('.carousel_item.active'),
				nxt = curr.next('.carousel_item');

			if(nxt.length == 0){ 
				nxt = $('.carousel_item:first');
			}
							
			curr.hide().toggleClass('active');
			nxt.show().toggleClass('active');
		},
		
		// retreat the carousel one slide, triggering button passed in for context
		prev: function(trig){
			var curr = trig.next().find('.carousel_item.active'),
				prv = curr.prev('.carousel_item');
			
			if (prv.length == 0) {
				prv = $('.carousel_item:last');
			}
			
			curr.hide().toggleClass('active');
			prv.show().toggleClass('active');
		}
		
	},
	
	video : {
		
		init : function() {
		
			var video_plugins = humana.video.loadCaptions();
			var video = $f("player", {src: "/library/players/flowplayer.commercial-3.2.5.swf", wmode: 'opaque'}, {
				clip: {
					captionUrl: $("#player").attr("rev")
				},
				//plugins: video_plugins,
				key: '#@fb98ecf80dc977e6402',
				logo: null
			});
		
		},
		
		loadCaptions : function() {
		
			var video_plugins = {};
			if ($("#player").attr("rev") != "") {
				video_plugins = {
					captions: {
						url: '/library/players/flowplayer.captions-3.2.2.swf',
						captionTarget: 'content'
					},
					content: {
						url: "/library/players/flowplayer.content-3.2.0.swf",
						bottom: 10,
						height: 40,
						backgroundColor: 'transparent',
						backgroundGradient: 'none',
						border: 0,
						textDecoration: 'outline',
						style: {
							body: {
								fontSize: 14,
								fontFamily: 'Arial',
								textAlign: 'center',
								color: '#ffffff'
							}
						},
						display: 'none' // Required to hide captions by default
					}
				};
			}
			return video_plugins;
			
		}
		
	},
	
	/* querystring parsing utility */
	query_string : function(str) {
		var qsd = {},
			tmp = [],
			qs,
			pairs = [];
		
		tmp = str.split('?');
		qs = decodeURI(tmp[1]);
		
		if (!qs) {
			return;
		}
		
		qs = qs.substring(1);
		pairs = qs.split('&');
		
		for(var i=0; i<pairs.length; i++){
			var kvp = pairs[i].split('=');
			qsd[kvp[0]] = kvp[1];
		}
		
		return qsd;
	},
	
	/* define object global for maps array */
	maps : [],
	
	prepare_gmaps : function() {
		$(".gmap").each(function(i) {
			$(this).after('<div id="gmap'+i+'" class="gmap" style="width: 330px; height: 220px;"></div>');
			var coords = $.getAllQueryStrings({URL: $(this).attr("href")}).sll.split(',');
			var latlng = new google.maps.LatLng(coords[0],coords[1]);
	    var myOptions = {
	      zoom: 16,
	      center: latlng,
				mapTypeControl: true,
				mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    var map = new google.maps.Map(document.getElementById('gmap'+i), myOptions);
			var marker = new google.maps.Marker({
				position: latlng, 
				map: map
			});
			$(this).remove();
		});
		
	},
	
	/**
	 * This sub-class is used for scanning all links and applying the required functionality. 
	 */
	link_handler : {
		
		init : function() {
			
			// Must use $.live() for dynamically changed content.
			$('a').live("click", function(e) {
				
				var relLink;
				var revLink;
				var linkPath;
				
				humana.link_handler.check_external(this);
				humana.link_handler.check_file(this);
				
				if (humana.link_handler.rel_link(this) || humana.link_handler.rev_link(this)) {
				
					e.preventDefault();
					
					relLink = humana.link_handler.rel_link(this);
					revLink = humana.link_handler.rev_link(this);
					linkPath = $(this).attr('href');
						
					if (relLink == true && revLink == false) {
						window.open(linkPath);
					}
					else if (relLink == true && revLink != false) {
						window.open(revLink);
					}
					else if (relLink == false && revLink != false) {
						document.location = revLink;
					}
					else {
						document.location = $(this).attr('href');
					}
					
				}
				
			});
			
		},
		
		/**
		 * Check if the supplied link is to an external source.
		 * @param {Object} link
		 */
		check_external : function(link) {
			
			var intLinkRE = /^\/|^http\:\/\/www.humana.com|^http\:\/\/humana.com|^\s*#|^https\:\/\/securedlogons.humana.com|^.*espanol.humana.com|^http\:\/\/dev-www.humana.com|^http\:\/\/test-www2.humana.com|^http\:\/\/qa-www2.humana.com/i;
			if (!intLinkRE.test($(link).attr('href'))) {
				$(this).attr('rel', 'external');
			}
			
		},
		
		/**
		 * Check if the supplied link contains a 'file' variable in the querystring.
		 * @param {Object} link
		 */
		check_file : function(link) {
			
			var docLinkRE = /\?file=/;
			if (docLinkRE.test($(link).attr('href'))) {
				$(this).addClass('pdf');
			}
			
		},
		
		/**
		 * Check if the supplied link has the 'rel="external"' attribute set.
		 * @param {Object} link
		 * @return {Boolean}
		 */
		rel_link : function(link) {
		
			var attrRel = $(link).attr('rel').toLowerCase();
			if (attrRel != "" && attrRel == "external") {
				return true;
			}
			return false;
			
		},
		
		/**
		 * Check if the supplied link has the 'rev=""' attribute and if TRUE return the conbined 'href' and 'rev' values.
		 * This function is used to reduce  duplicate links to certain portals where the only difference is the link querystring.
		 * Test looks for class="revlink" or rev attribute not blank, but requires the first character to be the '?' of the querystring.
		 * @param {Object} link
		 * @return {String, Boolean}
		 */
		rev_link : function(link) {
		
			var attrRev = $(link).attr('rev');
			if ($(link).hasClass('revlink') || attrRev != "" && attrRev.match(/^\?/) == "?") {
				return $(link).attr('href') + attrRev;
			}
			return false;

		},
		
		/**
		 * Modifies the spanish link in the masthead to include onclick code supplied by motion point.
		 */
		spanish_link : function() {
	
			$('#spanish_link').click( function(e) 
			{
				e.preventDefault();
				MP.SrcUrl = unescape('mp_js_orgin_url');
				MP.UrlLang = 'mp_js_current_lang';
				MP.init(); 
				MP.switchLanguage(MP.UrlLang == 'es' ? 'en' : 'es');
			});
		
		}
		
	},
	
	pagination : {
		
		settings : {
		
			pageContainer: 'div.viewport',
			pagerType: 'spinner',
			showAll: true
			
		},
		
		article : function() {
			
			var
				breakTag = 'PAGE_BREAK',
				currentPage = 0,
				totalPages = 0,
				nodeCount = 0;
			
			var viewport = document.createElement('div');
			$(viewport).addClass('viewport');
			viewport.id = "page_top";
			
			var article = $('div.module.article').contents();
			$(article).each( function(i) {
				if (currentPage == totalPages) {
					pageContainer = document.createElement('div');
					$(pageContainer).addClass('page page'+(currentPage+1));
					$(pageContainer).attr('id','page'+(currentPage+1));
					if (currentPage == 0)
						$(pageContainer).addClass('active');
					totalPages++;
				}
				
				if (this.nodeType != 8) {
					$(pageContainer).append($(this).clone());
					nodeCount++;
				}
				
				if (this.nodeType == 8 || i == (article.length - 1)) {
					if (this.nodeType == 8 && false)
						alert(this);
					$(viewport).append(pageContainer);
					pageContainer = '';
					currentPage++;
				}
				
				$(this).remove();
			});
			
			$('div.module.article').append(viewport);
			
			if (totalPages > 1)
				humana.pagination.pager(totalPages, 'article');
			
		},
		
		video_list : function() {
			
			var
				settings = { max: 6 },
				container = 'div.module.video_gallery ul.items',
				totalItemCount = $(container).children().length;
			
			if (totalItemCount > settings.max) {
				
				var pageCount = 1;
				var pageItemCount = 0;
				
				var paginatedContentContainer = document.createElement("div");
				paginatedContentContainer.id = "paginated_content";
				$(container).after(paginatedContentContainer);
				
				$(container).children().each( function(i) {
					if (pageItemCount == 0) {
						var page = document.createElement("ul");
						$(page).addClass("page page" + pageCount + " items " + $(container).attr("class"));
						$('#paginated_content').append(page);
					}
	
					pageItemCount++;
					
					$('#paginated_content .page' + pageCount).append($(this).clone());
					$(this).remove();
					
					if (pageItemCount == settings.max) {
						pageCount++;
						pageItemCount = 0;
					}
				});
				
				//$(container).remove();
				$('#paginated_content .page1').addClass('active').show();
				
				humana.pagination.settings.pageContainer = '#'+paginatedContentContainer.id;
				humana.pagination.pager(pageCount,'video_list');
			}
	
		},
		
		pager : function(pageCount, content_type) {
			
			// Create pager box
			$(humana.pagination.settings.pageContainer).parent().after($('<div></div>').attr('id','pager').addClass('pager spinner'));
			
			// Append 'previous' link and build functionality
			$('#pager').append(
				$('<a></a>').text('Previous').attr('href','#previous').addClass('previous').hide().click( function(e) {
					
					if (content_type == 'video_list')
						e.preventDefault();
					
					$("#pager span.currentPage").text(parseInt($("#pager span.currentPage").text()) - 1);
					
					if ($("#pager span.currentPage").text() == 1)
						$(this).hide();
					
					if ($("#pager span.currentPage").text() < $("#pager span.lastPage").text())
						$('#pager a.next').css("display","inline-block");
					
					$(humana.pagination.settings.pageContainer + ' .page' + $("#pager span.currentPage").text()).addClass('active').siblings().removeClass('active');
				
				}
				
			));
			
			// Append 'show all' functionality if setting is 'true'
			if (humana.pagination.settings.showAll) {
				$('#pager').append(
					$('<a></a>').text('Show All').attr('href','#showall').addClass('showall').click( function (e) {
						e.preventDefault();
						$(humana.pagination.settings.pageContainer).children().show();
						$('#pager').hide();
					})
				);
			}
			
			// Append counter information
			$('#pager').append($('<span></span>').text('1').addClass('currentPage'));
			$('#pager').append(" of ");
			$('#pager').append($('<span></span>').text(pageCount).addClass('lastPage'));
			
			// Append 'next' link and build functionality
			$('#pager').append(
				$('<a></a>').text('Next').attr('href','#next').addClass('next').click( function(e) {
					if (content_type == 'video_list')
						e.preventDefault();
						
					var thisPage = $("#pager span.currentPage").text();
					
					$("#pager span.currentPage").text(parseInt(thisPage) + 1);
					
					if ($("#pager span.currentPage").text() == $("#pager span.lastPage").text())
						$(this).hide();
					
					if ($("#pager span.currentPage").text() > '1')
						$('#pager a.previous').css("display","inline-block");
					
					$(humana.pagination.settings.pageContainer + ' .page' + $("#pager span.currentPage").text()).addClass('active').siblings().removeClass('active');
				}
			));
			
		}
		
	},
	
	debug : {
		
		log : function(msg) {
			
			setTimeout(function() {
				throw new Error(msg);
			}, 0);
			
		}
		
	},
	
	tools : {
		
		window_close : function() {
			window.close();
		},
		
		set_hash : function() {
			window.location.hash = url_hash;
		}
		
	}
		
};

