var undefined;

var ASMEarticle = function(options) {
   
	var self = this;
	
	this.defaults = {
		overlayTriggers:$JQ.ASME.mainContentDiv.find('.view-larger'),
		rightColAccordions:$JQ.ASME.mainContentDiv.find('.right-col .accordion')
	};
	
	this.settings = $JQ().extend({}, this.defaults, options);
	
	function _init() {
		console.log("starting ASME Article JS...");	
		
		//determine title, description, and author for later use. Used in Addthis inline JS on the article page
		$JQ.ASME.pageTitle = $JQ.ASME.mainContentDiv.find('h1').text();
		
		//instead of grabbing description from article, grabbing a hidden field supplied by the CMS, as per internal request
		// first make sure it isn't an empty string, if it is, we will just use the default description from main.js
	    //$JQ.ASME.pageDesc = $JQ.ASME.mainContentDiv.find('.middle-col h2').siblings('p:first').text();
		var descText = $JQ.ASME.mainContentDiv.find('.share-description').text();
		if(descText != '')
			$JQ.ASME.pageDesc = $JQ.ASME.mainContentDiv.find('.share-description').text();
		$JQ.ASME.pageAuthor = $JQ.ASME.mainContentDiv.find('#author').text();
		
		$JQ.ASME.pubDate = $JQ.ASME.mainContentDiv.find('.date p').text();
		
		$JQ.ASME.pageMediaType = 'Article';
				
		if($JQ.ASME.pageDesc.length > 140)
			$JQ.ASME.pageDesc = $JQ.ASME.pageDesc.slice(0,140);
			
		$JQ.ASME.pageThumbnail = site_url + $JQ.ASME.mainContentDiv.find('#thumbnail-url').text();
			
		//actions for non-pressrelease pages
		if(!$JQ.ASME.mainContentDiv.hasClass('press-release')) {
			//check length of article title to see if font size should be reduced NOTE:do it before cufoning. it might still work, but not a good idea
			_headlineLengthCheck();
			
			$JQ.ASME.cufon.headers();
			
			$JQ.ASME.pageType = 'Article Page';
			
		} else {
			$JQ.ASME.mainContentDiv.find('.header h1').show();	
			$JQ.ASME.pageAuthor = 'ASME.org';
			$JQ.ASME.pageType = "press_release";
		}
		
		//media type changes based on podcast or video
		if($JQ.ASME.mainContentDiv.find('#podcast-container').get(0)) {
			$JQ.ASME.pageMediaType = 'Video';
			$JQ.ASME.pageType = "multimedia_page";
			$JQ('body').addClass('addThisFix');
		}
		
		if($JQ.ASME.mainContentDiv.find('.podcast-menu').get(0)) {
			$JQ.ASME.pageMediaType = 'Podcast';
			$JQ.ASME.mainContentDiv.find('.podcast-menu a').bind('click', function(e) {
				//e.preventDefault();
				var podcastTitle = $JQ.ASME.pageTitle;
				podcastTitle = $JQ.ASME.string.stripWhiteSpace(podcastTitle);
				podcastTitle = $JQ.ASME.string.replaceWhiteSpace(podcastTitle, '_');
				podcastTitle = podcastTitle.toLowerCase();
				ntptAddPair('podcast_name', encodeURIComponent(podcastTitle));
				ntptEventTag('ev=podcast_signup');
																					   
			});
		}
		
		//check images
		//NOTE: crop images is no longer being used per client request, leaving just in case it's needed later
		//self.cropImages();
		
		//check to see if article is high touch
		self.highTouch();

		//check to see if first module in right col has class top, if not, add it (we need this for the top border)
		var $module = $JQ.ASME.mainContentDiv.find('.right-col .module:eq(0)');
		
		if(!$module.hasClass('top'))
			$module.addClass('top');

		//add ME logo to header, this logo is only needed for article pages
		//_addMELogo();
		
		//actions for tracking
		$JQ.ASME.trackingValues = ',author=' + encodeURIComponent($JQ.ASME.pageAuthor) + ',publication_date=' + encodeURIComponent($JQ.ASME.pubDate);
		var trackingAuthor = $JQ.ASME.string.replaceWhiteSpace($JQ.ASME.pageAuthor.toLowerCase(), '_');
		console.log(trackingAuthor);
		ntptAddPair('author', encodeURIComponent(trackingAuthor));
		var pubDate = $JQ.ASME.formatDate($JQ.ASME.pubDate);
		ntptAddPair('publication_date', encodeURIComponent(pubDate));
		self.setPrimaryTopic();
		self.enableTracking();

	};
	
	
	//private functions
	function _getBlockQuotes() {
		console.log("pulling quotes...");
		/*
			grabs all block quotes from the articles's main content area, then uses them to build the pullquotes and places them in the articles right column
			finds the quotes relative position and uses that to place the quote nearby NOTE TO SELF: Add some checks here to make sure quotes won't be on top of existing right column modules, if they are present, just append it to the right column without absolute positioning
		*/
		var $blockquotes = $JQ.ASME.mainContentDiv.find('.middle-col blockquote');
		
		var $lastDiv = $JQ('#main-content .right-col div:last');
		if($lastDiv.get(0) != undefined) {
			var lastDivTop = $lastDiv.position();
			lastDivTop = lastDivTop.top;
			lastDivTop += $lastDiv.height();
			lastDivTop = $JQ.ASME.math.roundNumber(lastDivTop, 0);
		}
		else {
			var lastDivTop = 0;
		}
		
		var lastY = 0;
		
		$blockquotes.each(function() {
		  var $this = $JQ(this);
		  var position = $this.position();
		  
		  var quote = $this.find('em').html();
		  var author = $this.find('cite').text();
		  
		  if(quote == '')
		  	quote = $this.text();

		  if (author == '')
            //removed because they want to display no author if doc type field is blank
		  	//author = $JQ.ASME.mainContentDiv.find("#author").text();
			
		  quote = $JQ.ASME.string.stripWhiteSpace(quote);	
			
		  if(quote == '' || quote == '<br>' || quote == '&nbsp;')
		  	return false;
		  
		  var html = [
				  '<blockquote><p><strong>"</strong>' + quote + '</p>',
				  '<cite>' + author + '</cite></blockquote>'
		  ];
		  
		  
		  
		  console.log('quote is ' + quote);
		  
		  html = html.join('');
		  
		  var $div = document.createElement('div');
		  $div = $JQ($div);
		  $div.addClass('pullquote').addClass('module');
		  
		  $div.html(html);
		  
		  $JQ('.right-col').append($div);
		  
		  var top = position.top - 150;
		  top = $JQ.ASME.math.roundNumber(top, 0);
		  
		  if((top < lastY) && (lastY != 0)) {
			top += $div.height(); 
		  }
		  
		  lastY = top + $div.height();
		  
		  if(0) {
		  	$div.css({'top':(top),'left':0,'position':'absolute',zIndex:1});
		  }
		  else {
		  	//we are positioning the quote 100px down for short articles, and 600 for long articles
			//using the height of the main content div to determine article length
			var mainContentHeight = $JQ.ASME.mainContentDiv.height();
			var rightColHeight = $JQ.ASME.mainContentDiv.find('.right-col').height();
			
			if(mainContentHeight > (rightColHeight + 2000)) {
				$div.css({'float':'left','margin':'600px 0px 34px 0px'});		
			} else {
				$div.css({'float':'left','margin':'100px 0px 34px 0px'});	
			}
			
			$div.css('border-top', '3px solid #000');
			
			lastDivTop = lastDivTop + $div.height();
		  }
		  
		});
		
	}
	
	function _addMELogo() {
		var html = '<div id="me-logo"><p class="float-left">ME Magazine</p> <a href="http://memagazine.asme.org/"><img src="/wwwasmeorg/media/images/logo-me.gif" alt="Mechanical Engineering Magazine" border="0" /></a></div>';
		$JQ.ASME.headerDiv.append(html);	
	}
	
	function _headlineLengthCheck() {
		var length = $JQ.ASME.pageTitle.length;
		
		if(length > 69) {
			$JQ.ASME.mainContentDiv.find('h1').css('font-size', '36px');	
		}
			
	}
	
	//public functions
	this.getPullQuotes = function() {
		_getBlockQuotes();	
	}
	
	this.buildToolTips = function() {
		self.journalTooltips = new tooltip();	
	}
	
	/*
		builds image overlays using overlay.js, creates a new overlay object and set's it content to the img in the link's url NOTE: depending on .net implentation, this might change later
	*/
	this.setOverlays = function() {
		console.log("setting overlays...");
		self.settings.overlayTriggers.bind('click', function(e) {
			e.preventDefault();
			
			var $this = $JQ(this);
			
			var fullURL = $this.attr('href');
			
			var caption = $this.parents().find('.caption').html();
			
			var imageHTML = '<img id="overlay-img" />';
			
			var overlay = $JQ.ASME.newOverlay();
			overlay.setContent(imageHTML);
			var $overlayImg = $JQ('#overlay-img');
			
			$overlayImg.attr('src', fullURL).load(function() {  
    			overlay.show(); 
				
				var imageWidth = overlay.div.find('img').width();
				
				imageWidth = imageWidth.toString();
				//if caption exists, append it
				console.log(caption);
				if((caption != '') && (caption != '<br>')) {
					caption = '<div class="caption" style="width:' + imageWidth + 'px"><p>' + caption + '</p></div>';
					overlay.appendContent(caption);
				}
				//overlay.div.find('.caption').css('width', imageWidth);
			}); 
			
			
			var pictureName = $JQ.ASME.string.replaceWhiteSpace(caption.toLowerCase(), '_');
			ntptAddPair('picture_name', encodeURIComponent(pictureName));
			ntptEventTag('ev=enlarge_picture');
			
		});
	}
	
	/*
		builds vertical accordions in the right column.
		
		goes through all elements that have the accordion class(stored in this object's default settings), finds number of child elements
		
		if child elements are greater than 5, hides items beyond 5
		
		then it builds a new ul and populates it with clone of hidden elements, this is because sliding down a new ul looks smoother than sliding down lis themselves
		
		then builds the trigger that will be used to slide up/slide down to show/hide remaining elements
		
		binds trigger to those actions
		
	*/
	this.buildModuleAccordions = function() {
		console.log("building accordions...");
		self.settings.rightColAccordions.each(function(index) {
			var $this = $JQ(this);
			var size = $this.find('li').size();
			
			if(size < 6)
				return false
			else {
				var $hiddenItems = $this.find('li:gt(4)');
				$hiddenItems.hide();
				
				var $newUL = document.createElement('ul');
				$newUL = $JQ($newUL);
				$newUL.append($hiddenItems.clone().show());
				$newUL.hide();
				$this.parent('.module').append($newUL);
				
				var $trigger = document.createElement('div');
				$trigger = $JQ($trigger);
				$trigger.addClass('accordion-trigger').addClass('bg-beige');
				$trigger.attr('id', 'accordion-' + index);
				
				var triggerHTML = [
					'<a href="javascript:void(0)">Reveal all ',
						size,
					'</a>'
				];
				
				triggerHTML = triggerHTML.join('');
				
				$trigger.html(triggerHTML);
				
				$this.parent('.module').append($trigger);
				
				$trigger.bind('click', function(e) {
					if(!$trigger.hasClass('open')) {
					  $newUL.slideDown(1000, function(){$trigger.find('a').text('Hide');});
					  $trigger.addClass('open');
					  //$trigger.removeClass('bg-beige').addClass('bg-light-blue');
					} else {
						$trigger.removeClass('open');
						$newUL.slideUp(1000);
						$trigger.html(triggerHTML);	
						//$trigger.removeClass('bg-light-blue').addClass('bg-beige');
					}
				});
				
				//hover state for triggers, blue background and blue arrow
				$trigger.bind('mouseover', function(e){
					  $trigger.removeClass('bg-beige').addClass('bg-light-blue');
				});
				
				$trigger.bind('mouseout', function(e){
					  $trigger.removeClass('bg-light-blue').addClass('bg-beige');
				});
				
			}
			
		});
		
	}
	
	/*
		check and see if author is being covered up by image in article layout II
		
		checks to see if layout II is being used, if so, checks height of primary image
		if it's greater than 125, it adjusts the author div to have a top margin that will put it line with the
		first sub header
		
	*/
	
	this.authorCheck = function() {
		if(!$JQ.ASME.mainContentDiv.hasClass('alternate'))
			return false	
			
		console.log("fixing author...");	
			
		var $img = 	$JQ.ASME.mainContentDiv.find('.primary-image .image-container img');
		var src = $img.attr('src');
		
		
		if($img.get(0).complete) {
		
			var height = $img.height();
			
			if(height > 125) {
			  $JQ.ASME.mainContentDiv.find('.author').css('margin-top', (height + 20));
			  
			}	
		
		} else {
			$img.load(function() {
					var height = $img.height();
			  
					if(height > 125) {
						
						
						$JQ.ASME.mainContentDiv.find('.author').css('margin-top', (height + 20));
						
					}	  
			  
			  });	
			
		}

	}
	
	/*
		checks images to see if they are beyond the desired dimensions, then moves the image around inside the containing div to "crop" them
	*/
	this.cropImages = function() {
		var primaryImage = $JQ.ASME.mainContentDiv.find('.primary-image .image-container img');
		if(primaryImage.length) {
			primaryImage.load(function() {
			  var imageHeight = primaryImage.height();
			  var maxHeight = $JQ.ASME.mainContentDiv.hasClass('alternate')?155:276;
			  if(imageHeight > maxHeight) {
				  //if the height is too big, move it up the difference divided by two
				  var difference = imageHeight - maxHeight;
				  difference = (difference/2);
				  difference = $JQ.ASME.math.roundNumber(difference, 0);
				  //move it up equal to the negative value of the difference
				  primaryImage.css('margin-top',(-1*difference));				
			  }
			});
		}
	}
	
	/*
		put high-touch class in proper place. Because of templating limitations backend can't put class on the container div we need, so we are moving it
	*/
	this.highTouch = function() {
		if($JQ.ASME.mainContentDiv.hasClass('hightouch'))
			$JQ('#asme').addClass('high-touch');
	}
	
	
	//getting primary topic for article page, var provided by .NET backend
	this.setPrimaryTopic = function() {
		if(primaryTopic != undefined) {
			primaryTopic = $JQ.ASME.string.replaceWhiteSpace(primaryTopic.toLowerCase(), '_');
			$JQ.ASME.primaryTopic = primaryTopic;
			console.log($JQ.ASME.primaryTopic);
		}
			
	}
	
	
	//enables article specific tracking events
	this.enableTracking = function() {
		var $rightColLinks = $JQ.ASME.mainContentDiv.find('.right-col ul li a');
		$rightColLinks.bind('click', function(e) {								  
			var $this= $JQ(this);
			var moduleTitle = $this.parents('.module').find('h3').text();
			moduleTitle = $JQ.ASME.string.replaceWhiteSpace(moduleTitle, '_');
			moduleTitle = moduleTitle.toLowerCase();
			ntptAddPair('content_module', encodeURIComponent(moduleTitle));
			ntptEventTag('ev=click_event');
		});
		
		var $moreTopicsLinks = $JQ.ASME.mainContentDiv.find('.more-topic a');
		$moreTopicsLinks.bind('click', function(e) {
			ntptAddPair('content_module', 'more_on_this_topic');
			ntptEventTag('ev=click_event');											
		});
		
		var $relatedTopics = $JQ.ASME.mainContentDiv.find('.related-topics a');
		
		$relatedTopics.bind('click', function(e) {
			var $this = $JQ(this);
			var text = $this.text();
			text = $JQ.ASME.string.replaceWhiteSpace(text.toLowerCase(), '_');
			ntptAddPair('content_module', 'related_topic');
			ntptEventTag('ev=click_event');	
		});
		
	}

	_init();
	
};
  
