/**
* @fileOverview WCMC Site Specific Javascript <br/><br/>
* Copyright 2010 Weill Cornell Medical College. All rights reserved. <br/><br/>
*
* @author Brian Tobin
* @requires $
*/


"use strict";

/**
* WCMC specific functions
* @namespace
*/
var wcmc = {};
	

/**
* Truncate and format featured and slideshow articles
* @class
*/
wcmc.truncate_bigmedium_news = function(){
		
	/** 
	* Truncate featured articles and add read more buttons
	* @private
	*/
	function truncate(el, max_char_title, max_char_body){

		var featured = $(el),
			tail = '... ',
			featured_html,
			title,
			url,
			title_text,
			title_max,
			br,
			brbr,
			p_text,
			p_max,
			html;
		
		// loop through all articles in a given section	
		for (var i=0; i<featured.length; i+=1){
			
			// get rid of the wonderful &nbsp; that big medium thinks it needs
			if ($(featured[i]).html().indexOf('&nbsp;') !== -1){
				featured_html = $(featured[i]).html().substring(6, $(featured[i]).html().length);
			}
			else {
				featured_html = $(featured[i]).html();
			}
						
			// gather content
			title = $(featured[i]).find('a'),
			url = title.attr('href'),
			title_text = title.text(),
			title_max = max_char_title,
			br = WC.UTIL.is_ie ? featured_html.indexOf('<BR>') : featured_html.indexOf('<br>'),
			brbr = WC.UTIL.is_ie ? featured_html.indexOf('<BR><BR>') : featured_html.indexOf('<br><br>'),
			p_text,
			p_max = max_char_body;
			
			// truncate title
			if (title_text.length > title_max){
				title_text = title_text.substring(0, title_max);
				title_text = title_text.substring(0, title_text.lastIndexOf(' ')) + tail;
			}
			
			// look for appropriate break tag format and break paragraphs
			if (brbr !== -1)
				p_text = featured_html.substring(br + 4, brbr);
			else 
				p_text = featured_html.substring(br + 4);
			
			// truncate paragraph text is longer than declared max								
			if (p_text.length > p_max){
				p_text = p_text.substring(0, p_max);
				p_text = p_text.substring(0, p_text.lastIndexOf(' ')) + tail;
			}
			
			// build the new html, with read more button
			html = '<div><a href="' + url + '">' + title_text + '</a><br/>' + p_text + '<a href="' + url + '" class="read_more"><span>Read More</span></a></div>';
			
			// replace current html with new
			$(featured[i]).html(html);
		}
	}

	return function(){
		truncate('.featured div div', 140, 200);
		truncate('.slider div', 80, 150);
	}
}();


/**
* Show and position the department content modal.
* If ie, position a button clone
* @class
* @requires WC.UI.overlay
*/
wcmc.departments_modal = function(){
	
	var overlay = WC.UI.overlay;
		
	/** 
	* Postition the content
	* @private
	*/
	function position_it(){
	
		// get offset of guts for home page of interior page
		var guts_offset 		= $('body').hasClass('home') ? $('#home_guts').offset() : $('#guts').offset(),
			guts_left 			= guts_offset.left,
			dept_link_offset 	= $('.departments').offset(),
			dept_link_left 		= dept_link_offset.left,
			dept_link_top 		= dept_link_offset.top;
	
		// add css positioning
		$('#departments_modal').css({
			'left': guts_left,
			'top': $('body').hasClass('home') ? '20px' : '5px'
		});
	
		// position link clone if IE6 to fix zindex
		if (WC.UTIL.is_ie6){
			$('div.dept_link_clone').css({
				'left': dept_link_left,
				'top': dept_link_top,
				'z-index': '100'
			});
		}
	}
	
	return {
		/**
		* Bind click states to triggers
		* Position the modal and set resize event
		* @public
		*/
		init: function(){	

			$('li a.departments, li.departments a').bind('click', function(){
			
				// if already shown, return
				if ($('#departments_modal').css('display') == 'block' || $('#global_health').css('display') == 'block')
					return;
		
				// overlay init and bind close function
				overlay.init(function(){
					$('#departments_modal').fadeOut(300);
					$('li a.departments, li.departments a').removeClass('active');
					if (WC.UTIL.is_ie6){
						$('div.dept_link_clone').hide();
					}
				});

				// position it...
				position_it();
		
				// bind the resize function
				$(window).resize(function(){
					position_it();
				});
				
				// fade in content
				$('#departments_modal').fadeIn(300);
				if (WC.UTIL.is_ie6){
					$('div.dept_link_clone').fadeIn(300);
				}
		
				// activate the button
				WC.UI.button.activate($(this));
		
				// kill default
				return false;
			});
		
			// bind close triggers
			$('#departments_modal .close').live('click', function(){
				$(this).parent().fadeOut(300);
				if (WC.UTIL.is_ie6){
					$('.dept_link_clone').hide();
				}
				overlay.close();
				$('li a.departments, li.departments a').removeClass('active');
				return false;
			});
		}
	};
}();


/** 
* Show and position global health content modal
* @class
* @requires WC.UI.overlay
*/
wcmc.global_health = function(){
	
	var overlay = WC.UI.overlay;

	/** 
	* Position modal content
	* @private
	*/
	function _position_it(){
	
		// get offset of guts for home page of interior page
		var guts_offset = $('body').hasClass('home') ? $('#home_guts').offset() : $('#guts').offset(),
			guts_left = guts_offset.left,
			gh_link_offset = $('.global_health').offset(),
			gh_link_left = gh_link_offset.left,
			gh_link_top = gh_link_offset.top;
		
		// add css positioning
		$('#global_health').css({
			'left': guts_left,
			'top': $('body').hasClass('home') ? '20px' : '5px'
		});
	
		// if ie, position the link clone to fake the z-index bug	
		if (WC.UTIL.is_ie){
			$('div.gh_link_clone').css({
				'left': gh_link_left,
				'top': gh_link_top,
				'z-index': '100'
			});
		}
	}
				
	/** 
	* Control Map rollover popups
	* @private
	*/
	function _pop_up(location){
		
		// grab id off location and collect proper hidden popup
		var id = location.attr('id'),
			popup = $('.global_map .' + id),
			height = $('.global_map .' + id).innerHeight(),
			width = $('.global_map .' + id).innerWidth();
		
		// if the requested popup is not showing already, clear all
		if (popup.css('display') == 'block'){
			return;
		}
		else {
			$('.popup').fadeOut(100);
			$('.pointer').remove();
			$('.popup .close').remove();
		}
		
		// get position
		var position = location.position(),
			left = position.left,
			top = position.top;
		
		// create quandrants
		var half_width = Math.floor(775 / 2),
			half_height = Math.floor(350 / 2),
			pointer_type;
		
		// based on quandrant, assign pointer type, left and top positions	
		if (left <= half_width && top <= half_height){
			pointer_type = 'top_left';
			top = (top + 31) + 3;
			left = left + 9;
		}
		else if (left <= half_width && top >= half_height){
			pointer_type = 'bottom_left';
			top = (top - 31) - height + 4;
			left = left + 9;
		}
		else if (left > half_width && top < half_height){
			pointer_type = 'top_right';
			top = (top + 31) + 3;
			left = left - width - 1;
		}
		else if (left > half_width && top > half_height){
			pointer_type = 'bottom_right';	
			top = (top - 31) - height + 4;
			left = left - width;
		}	
		
		// position and show appropriate hidden popup
		popup
			// append appropriate pointer type
			.append('<div class="pointer ' + pointer_type + '"></div>')
			// append close btn
			.append('<div class="close"><a href="">x</a></div>')
			// position it with final left and right
			.css({
				'left': left + 'px',
				'top': top + 'px'
			})
			.fadeIn(300);
	}
	
	/** 
	* Close parent
	* @function
	* @private
	*/
	function _close(btn){
		var parent = btn.parent();
		
		// if closing out the global health modal, then remove the active off the btn
		if (parent.attr('id') == 'global_health'){
			// clear any open popups that might be lingering
			$('.popup').hide();
			// deactivate link
			$('li a.global_health, li.global_health a').removeClass('active');
			// close overlay
			overlay.close();
		}
		// close which ever parent div
		parent.fadeOut(300);
	}
	
	return {
		/**
		* Init global health map
		* @function
		*/
		init: function(){
			
			// bind click init function to links
			$('li a.global_health, li.global_health a').bind('click', function(){
				
				// if either global health or department modals are showing, hide
				if ($('#global_health').css('display') == 'block' || $('#departments_modal').css('display') == 'block'){
					return;
				}
			
				// show overlay and bind callback function
				overlay.init(function(){
					$('#global_health').fadeOut(300);
					$('li a.global_health, li.global_health a').removeClass('active');
					if (WC.UTIL.is_ie6){
						$('div.gh_link_clone').hide();
					}
				});

				// position it...
				_position_it();
			
				// activate link
				WC.UI.button.activate($(this));
			
				// fade it in and then activate the button
				$('#global_health').fadeIn(300);
				
				// if ie, bring in the link clone to fake the z-index bug	
				if (WC.UTIL.is_ie){
					$('div.gh_link_clone').fadeIn(100);
				}	
			
				// bind the resize function
				$(window).bind('resize', function(){
					_position_it();
				});			
			
				// kill default
				return false;
			});
		
			// bind mouseover for popups to map locations
			$('.global_map .location').mouseover(function(){
				_pop_up($(this));
			});
		
			// bind click function for close button
			$('#global_health .close').live('click', function(){
				_close($(this));
				return false;
			});
		}
	};
}();


/**
* Footer Modal Functions
* @class
* @requires WC.UI.overlay
*/
wcmc.footer_modal = function(){
	
	var guts = '#guts_wrapper',
		overlay = WC.UI.overlay;;
	
	/** 
	* Open modal and selected content in page
	* If content is too tall compared to page height
	* Increase content div height
	* @private 
	*/
	function show_modal_content(event){
		
		// kill default
		var event 			= event || window.event,
			self 			= $(this),
			button_width 	= self.outerWidth(),
			button_height 	= self.outerHeight(),
			button_class	= self.attr('class').split(' ')[1],
			modal_element 	= $('#' + button_class),
			modal_height 	= modal_element.outerHeight(),
			modal_width 	= modal_element.outerWidth(),
			
			// page content size change
			header_height	= 160,
			guts_height 	= ($(guts).length > 0) ? $(guts).height() : 'undefined',
			height_dif 		= ($(guts).length > 0) ? (guts_height + header_height) - modal_height : 'undefined',
			is_height_dif 	= height_dif ? height_dif < 0 : false;
					
		event.preventDefault();
			
		// if this modal already exists, then the second click is to close	
		if (modal_element.css('display') == 'block'){
			close();
			return false;
		}

		// activate the button
		WC.UI.button.activate(self);
		// show modal and bind close function
		overlay.init(function(){
			$(modal_element).fadeOut(300);
			WC.UI.button.deactivate(self);
			$(guts).css('height', 'auto');
		});
		
		function _show_modal(){
			var button_offset = self.offset();

			modal_element
				.append(
					$('<div class="close"><a href="">x</a></div>').click(function(){ 
						close();
						return false;
					})
				)
				.css({
					'left': ((button_offset.left + button_width) - modal_width),
					'top': (button_offset.top - modal_height)
				})
				.fadeIn(300);
		}
		
		// if page is not high enough to fit modal content, grow the guts wrapper
		// Modal is positioned and shown after growth wraps up
		if (is_height_dif){
			// scroll to top of page
			$('html, body').animate({ scrollTop: 0 }, 800);	
			// if not home page
			// TODO: provide grow method for home page
			if (!$('body').hasClass('home')){
				$(guts).animate({ 'height': (modal_height - header_height) + 'px' }, 200, function(){
					_show_modal();
				});
			}
		}
		else {
			_show_modal();
		}
	
		// bind the resize function to just close the modal on page resizing
		$(window).resize(function(){
			close();
		});
	}
	
	/** 
	* Pass the overlay close function, which 
	* also closes content and deactivates triggers  
	* @private 
	*/
	function close(){
		overlay.close();
		// TODO: check if this is necessary
		$(guts).css('height', 'auto');
	}

	return {
		/**
		* Bind click event
		* @public
		*/
		init: function(){
			
			// bind click to select boxes
			$('.select_box').bind('click', show_modal_content);
		}
	};
}();


/**
* Build and control interior secondary nvavigation 
* Author: Philip Forget
* @class
*/
wcmc.content_navigation = function(){
	//Private vars
	var _navigation_div,
		_primary_navigation,
		_tertiary_nav = {},
		_body_classes = [];

	//Private functions
	function _init(primary_navigation, navigation_div){
		_navigation_div = navigation_div;
		_primary_navigation = primary_navigation;

		// get the body classes and assign them to an array
		_body_classes = $('body').attr('class').split(' ');

		// Shift the array to get the first elemend and add current class to primary nav
		_primary_navigation.find('#'+_body_classes.shift()).addClass('current');;

		// Populate the li's with classes based on the text in the wrapped <a> tag
		_navigation_div.find('li').find('a:first').each(function(){
			var temp_link = $(this),
				temp_link_li = temp_link.parent();
			temp_link_li.addClass(WC.UTIL.string_to_class(temp_link.text()));
		});

		// If there is only one body tag, apply it to the first item
		if (_body_classes.length === 1){
			_navigation_div.find("."+_body_classes[0]+":first a:first").addClass('current');
		}
		// If there are two body tags, the first tag gets a current_parent tag, the second a current
		else if (_body_classes.length === 2){
			_navigation_div.find("."+_body_classes[0]+":first a:first").addClass('current_parent');
			_navigation_div.find("."+_body_classes[1]+":first a:first").addClass('current');
		}
		else if(_body_classes.length === 3){
			_navigation_div.find("."+_body_classes[0]+":first a:first").addClass('current_parent');
			_navigation_div.find("."+_body_classes[1]+":first a:first").addClass('current_parent');
			_navigation_div.find("."+_body_classes[2]+":first a:first").addClass('current');
		}

		// Find all the more buttons and show them if there are child navigational elements
		_navigation_div.find('a.more_button').each(function(){
			if(!$(this).parent().find('a.current').length){
				var more_button = $(this);
				more_button.addClass('js_override');
				more_button.click(function(){

					if(more_button.text()=="MORE"){
						// Close any other open secondary navs
						_navigation_div.find('.secondary_nav.unfolded').slideUp().addClass('folded').parent().find('a.more_button').text('MORE');

						more_button.text('LESS');
						more_button.parent().find('.secondary_nav').slideDown().removeClass('folded').addClass('unfolded');
					}
					else{
						more_button.text('MORE');
						more_button.parent().find('.secondary_nav').removeClass('unfolded').slideUp().addClass('folded');
					}
					return false;
				});

			}
		});

		_navigation_div.find("."+_body_classes[0]+":first div.secondary_nav").addClass('unfolded_main');

		// For each secondary nav, do some magic
		_navigation_div.find(".secondary_nav").each(function(){
			var secondary_nav = $(this),
				tertiary_nav_array = [];

			secondary_nav.append($('<div class="tertiary_nav_jsoverride"></div>'));
			var tertiary_wrapper = secondary_nav.find('.tertiary_nav_jsoverride');

			secondary_nav.addClass('js_override');
			secondary_nav.find(".tertiary_nav").each(function(){
				var temp_nav = $(this);
				temp_nav.addClass(temp_nav.parent().attr('class'));
				tertiary_nav_array.push(temp_nav);
			});

			// Cache the initial height of the secondary nav (hack for webkit)
			secondary_nav.height(secondary_nav.find('ul:first').height());

			// Apply the magic to each tertiary nav
			//
			var override_height = 0;
			for(var i in tertiary_nav_array){
				var temp_nav = tertiary_nav_array[i],
					temp_nav_class = temp_nav.attr('class').split(' ')[1],
					temp_nav_height = temp_nav.find('ul:first').height();


				if( temp_nav_height > override_height ){
					override_height = temp_nav_height;
				}

				// Hide the tertiary nav to see if it's taller or shorter than the secondary nav
				temp_nav.hide();
				secondary_nav.height(secondary_nav.find('ul:first').height());
				// If it is taller, set the height of the container
				if(secondary_nav.height() < override_height){
					secondary_nav.height(override_height);
				}
				tertiary_wrapper.append(temp_nav);

				// Add the active_override class if the state is active but not moused over
				if(temp_nav_class == _body_classes[1]){
					temp_nav.show().addClass('active_override').addClass('active').hover(function(){
						$(this).removeClass('active_override');
						_navigation_div.find('li.'+_body_classes[1]+' a').addClass('active');
						},
						function(){});
				}
			}
			
			// For each secondary nav with children, add has_children class and assign hover actions
			secondary_nav.find('ul:first li a').each(function(){
				var temp_link = $(this);
				if(tertiary_wrapper.find("."+temp_link.parent().attr('class')).length){
					temp_link.addClass('has_children');
				}
				temp_link.hover(
					function(){
						secondary_nav.find('a.active').removeClass('active');
						temp_link.addClass('active');
						tertiary_wrapper.find('div.active').removeClass('active').hide();
						tertiary_wrapper.find("."+temp_link.parent().attr('class')).addClass('active').removeClass('active_override').show().hover(function(){},function(){
						});
					},
					function(){
						if(!tertiary_wrapper.find("."+temp_link.parent().attr('class')).length){
							temp_link.removeClass('active');
						}
					}
				);
			});
			secondary_nav.hover(function(){},function(){
				tertiary_nav_rollout(secondary_nav, tertiary_wrapper);
			});
		});
		// Initially fold up all the secondary navs except the main one if it exists
		_navigation_div.find(".secondary_nav").each(function(){
			var secondary_nav = $(this);
			if(!secondary_nav.hasClass('unfolded_main')){
				secondary_nav.addClass('folded');
			}
		});
		// Reusable function for turning off the tertiary_nav divs on mouseout
		function tertiary_nav_rollout(secondary_nav, tertiary_wrapper){
			secondary_nav.find('a.active').removeClass('active');
			tertiary_wrapper.find('div.active').removeClass('active').hide();
			tertiary_wrapper.find('.'+(secondary_nav.find('.current_parent').parent().attr('class'))).addClass('active').addClass('active_override').show();
			tertiary_wrapper.find('.'+(secondary_nav.find('.current').parent().attr('class'))).addClass('active').addClass('active_override').show();
		}
	};
	//Public vars and functions!
	return {
		init : _init
	};
}();


/**
* Controlls the three search fields on homepage
* @function
*/
wcmc.home_search = function(){
	function _init() {
		
		if ($('.search_selector').length > 0) {
			var search_items_default_string = new Array();
			var search_items = new Array($("#page_search"), $("#people_search"), $("#physician_search"));
			var radio_items = new Array($(".search_selector input[value='pages']"), $(".search_selector input[value='people']"), $(".search_selector input[value='physician']"));

			for (var i = 0; i < search_items.length; i++) {
				$(".search_selector").css("display","block"); // show radio selectors
				if (i != 0) { // hide all but the first input field
					search_items[i].css("display","none");
				}

				// Grab the default value of each form's text field
				search_items_default_string.push(search_items[i].children("input[type='text']")[0].defaultValue);

				radio_items[i].bind('click', function(e) {
					// hide all forms
					search_items[0].css('display','none');
					search_items[1].css('display','none');
					search_items[2].css('display','none');

					// show the selected form and reset it's value to the default
					switch (e.target.value) {
						case 'pages':
							search_items[0].css('display','block');
							search_items[0].children("input[type='text']")[0].value = search_items_default_string[0];
							break;
						case 'people':
							search_items[1].css('display','block');
							search_items[1].children("input[type='text']")[0].value = search_items_default_string[1];
							break;
						case 'physician':
							search_items[2].css('display','block')
							search_items[2].children("input[type='text']")[0].value = search_items_default_string[2];
							break;
					}
				});
			}
			
			if ($('#page_search').length > 0) {
				switch (location.host) {
					// set the page search to search the current 1st level folder of the current domain
					case "www":
					case "new.weill.cornell.edu":
					case "weill.cornell.edu":
						
						switch (location.pathname.split("/")[1]) {
							case "diversity":
							case "vascular":
								$('#page_search input[name="sitesearch"]').attr('value', "weill.cornell.edu/" + location.pathname.split("/")[1]);
								break;
							
							default:
								$('#page_search input[name="sitesearch"]').attr('value','');
						}
						break;
						
					case "intranet.med.cornell.edu":
					case "intranet":
						// Edit the page_search to use the intranet GSA
						$('#page_search').attr('action', 'http://search-int.med.cornell.edu/search');
						$('#page_search input[name="proxystylesheet"]').attr('value', 'intranet_new');
						
						// Edit the people_search to use the intranet GSA
						$('#people_search').attr('action', 'http://weill.cornell.edu/cgi-bin/phf');
						break;
						
					// set the page search to search the current domain
					default:
						$('#page_search input[name="sitesearch"]').attr('value',location.host);
				}
			}
			
			$('#search-submit').click(function(){
				selected = document.physician_search.wcpsearch.value;

				if ((selected != null && selected.length > 0)) {
					document.physician_search.any.value = selected;
				} else {
					return false;
				}

				document.physician_search.submit();
			});
		}
		
		// Set the height of .bleed_right
		$('.bleed_right').css('height', $('.global_search').outerHeight());
	};
	
	return {		
		init: _init
	}
}();


/**
* Init all homepage specific functions
* @function
*/
wcmc.home_init = function(){
	wcmc.truncate_bigmedium_news();
	WC.UI.multi_menu.init( 'ul.mission_nav', { 'speed': 300, 'custom': 'div.hover_menu' } );
	
	var news_home_slideshow = WC.UI.slideshow.create_slideshow('#slideshow', slideshow_options, '#slideshow_controller');
		WC.UI.slideshow.add_slideshow(news_home_slideshow);
		news_home_slideshow.go_to_slide(0);
		
};


$(function(){
	$(document).pngFix();
	
	function size_red_ie(){
		var bleed = $('.bleed_left_ie'),
			height = 472 + 23,
			window_width = $(window).width(),
			width = ( window_width - 970 ) / 2;
		if (window_width < 970){ 
			bleed.css('display','none');
			return;
		}
		bleed.css({
			'height': height + 'px',
			'display': 'block',
			'width': width + 'px'
		});
	}
	
	try {
		wcmc.home_search.init();
		
		// init navigation
		wcmc.content_navigation.init($('#menu'), $('#sidebar ul.section_nav'));
		
		WC.UI.multi_menu.init( 'ul.header_navigation', { 'speed': 300, 'custom': 'div.hover_menu' });
		WC.UI.clear_field('.search_field');
		WC.UI.bleed_element('.bleed_right', '.global_search');	
		
		var department_filter = WC.UI.content_filter.init('#dept_filter_input', '.modal_list_column a');
		var sitemap_filter = WC.UI.content_filter.init('#sitemap_filter_input', '.modal_list_column a');
		
		// if not IE6, init page modals
		if (!WC.UTIL.is_ie6){
			wcmc.global_health.init();
			wcmc.departments_modal.init();
			wcmc.footer_modal.init();
		}
		
		// add red bleed to news in IE6
		if (WC.UTIL.is_ie6){
			size_red_ie();
			$(window).resize(size_red_ie);
		}
	} catch(e){}
	
	// hide "home" links in sitemap modal
	$('.sitemap_modal ul li:eq(0)').hide();
});



