if(typeof(EVERYZING) == 'undefined') { EVERYZING = {}; }

ezQuery.fn.truncateText = function(maxLen, postfix){
    ezQuery(this).each(function(){
        var target = ezQuery(this);
        var content = this.innerHTML;
        var text = target.text();
        
        if (text.length > maxLen){
            text = text.slice(0,maxLen);
            text = text.replace(/&amp;/g, '&');
			
            var elemLen = 0;
            var buf = content;
            buf = buf.replace(/&amp;/g, '&');
			buf = buf.replace(/>\r\n</g, '');
			
            while (buf.indexOf(text) == -1 && i != -1 && j != -1) {
                var i = buf.indexOf('<');
                var j = buf.indexOf('>');
                elemLen += j - i + 1;
                
                buf = buf.slice(0,i) + buf.slice(j+1,buf.length);
            }
            
            content = content.slice(0, maxLen + elemLen);
            
            // Remove trailing word fragment
            content = content.replace(/[a-z0-9]+$/i, '');
            content = ezQuery.trim(content);
            
            content = content + postfix;
            
            this.innerHTML = content;
        }
    });
};
// validate search
EVERYZING.validateSearch = function(form,searchStr) {
	var bool = false;
	if (ezQuery.trim(searchStr.val()).length > 0) {
		form.submit();	
		bool = true;
	}
	return bool;
};
/*
 * Initializes the baldr snippets
 */
EVERYZING.render_snippets_init = function(){
	
    /* Switch the currently displayed snippet highlight */
		var switchTextHighlights = function(highlight){
			var marker = ezQuery(highlight);
			
			var highlightText = ezQuery(".ez-box-content div[ts='"+marker.attr('ts')+"']", marker.parent().parent());
			if (highlightText.length == 0) return; // snippet bubble not included
			
			marker.unbind("mouseover");
				marker.siblings('.ez-active-highlight').bind("mouseover", function(){switchTextHighlights(this);});
			
			marker.addClass('ez-active-highlight');
				marker.siblings('.ez-active-highlight').removeClass('ez-active-highlight');
			
			highlightText.show();
			highlightText.siblings().hide();
				highlightText.bind("click", function(){
							if (location.href.indexOf('fedsearch') == -1){
					location.href = marker.attr('href');
				}else{
					parent.location.href = marker.attr('href');
				} 
		  });
	};
	
	/* Initialize the markers */
	if(ezQuery('.ez-uni-item').hasClass('ez-no-bubble')) return; //no snippet bubbles
	
	ezQuery(".ez-uni-item .ez-timeline").each(function(){
		var currentTimeline = ezQuery(this);
		var timeStamps = ezQuery('.ez-timeline-marker', currentTimeline);
		
		timeStamps.each(function(){
			var stamp = ezQuery(this);
		
			stamp.bind("mouseover", function(){
				switchTextHighlights(this);
			});
		});
		
		switchTextHighlights(timeStamps.slice(0,1));
	});
};


/* 
 * Truncates the snippets around the keyword and optionally adds prefix/postfix
 * There should only be bold tags (keywords) inside the ez-highlight elements
 */
EVERYZING.render_snippets_truncate = function(maxLen, prefix, postfix){
	maxLen = parseInt(maxLen, 10);
	if (isNaN(maxLen)){
		maxLen = 160;
	}
	
    if (prefix == null || prefix.length == 0){
        prefix = "&#8220;&#8230;";
    }
    if (postfix == null || postfix.length == 0){
        postfix = "&#8230;&#8221;";
    }
	
	ezQuery(".ez-uni-item .ez-highlight").each(function(){
		var content = this.innerHTML;
		content = content.replace(/<B/g, '<b');
		content = content.replace(/<\/B>/g, '</b>');
		
		var text = ezQuery(this).text();
		
		if (text.length > maxLen) {
			var i = content.indexOf('<b');
			var j = content.indexOf('</b>');
			
			var pre = content.slice(0, i);
			pre = pre.slice(-1 * maxLen / 2);
			pre = pre.replace(/^[a-z0-9.]* /i, '');
			
			var post = content.slice(i, content.length);
			
			var targetPostLen = maxLen - pre.length;
			var targetPostText = text.slice(i, targetPostLen + i);
			targetPostText = targetPostText.replace(/&amp;/g, '&');
			
			var elemLen = 0;
			var buf = post;
			buf = buf.replace(/&amp;/g, '&');
			
			while (buf.indexOf(targetPostText) == -1) {
				var i = buf.indexOf('<');
				var j = buf.indexOf('>');
				elemLen += j - i + 1;
				
				buf = buf.slice(0, i) + buf.slice(j + 1, buf.length);
			}
			
			post = post.slice(0, targetPostLen + elemLen);
			post = post.replace(/[a-z0-9<>]+$/i, '');
			
			var newContent = pre + post;
			newContent = ezQuery.trim(newContent);
			
			this.innerHTML = newContent;
		}
		
		this.innerHTML = prefix + this.innerHTML + postfix;
	});
	ezQuery(".ez-uni-item .ez-snippet").slideDown('800');
};
// Render IE6 compliant seach boxes
EVERYZING.drawSelectBoxes = function(el) {
		if(EVERYZING.boxesDrawn == true) return; //dont run this function if its been run once already
		EVERYZING.boxesDrawn = true;
		var container = ezQuery('#ez-advanced-search');
		var theForm = ezQuery('#ez-advanced-search-form');
  var selectBoxes = ezQuery(el);
		
  ezQuery(el).each(function(){
				var box = ezQuery(this);
				var name = box.attr('name');
				var advancedSearchBox = ezQuery('#ez-advanced-search');
				// Give the select box an id
				box.attr('id','ez-select_'+name+'_hidden');
				// Set up the new select boxes
				var boxValue = box.find('option:selected') != null ? box.find('option:selected').text() : name;

				advancedSearchBox.prepend('<div id="ez-select_'+name+'_dropdown" class="ez-select_dropdown"></div>');
				var dropdown = ezQuery('#ez-select_'+name+'_dropdown');
				dropdown.append('<a id="ez-select_'+name+'_trigger" href="javascript:void(0);" title="'+boxValue+'">'+boxValue+'</a>');
				var listInputTrigger = ezQuery('#ez-select_'+name+'_trigger');
				listInputTrigger.addClass('ez-advanced-search-select-trigger');
				
				ezQuery('#ez-select_'+name+'_trigger').after('<ul id="ez-select_'+name+'_list"></ul>');
				var optionList = ezQuery('#ez-select_'+name+'_list');
				optionList.addClass('ez-advanced-search-input-list');
				var optionName = 'ez-select_'+name+'_option';
				
				box.find('option').each(function(){
					var index = ezQuery('option',box).index(this);
					ezQuery(this).attr('id',optionName+'_'+index);
					optionList.append('<li><a href="javascript:void(0);" id="'+optionName+'_'+index+'">'+ezQuery(this).text()+'</a></li>');
				});
				optionList.find('li').each(function(){
					ezQuery(this).find('a').click(function(){													 
						var index = ezQuery(this).attr('id');
						listInputTrigger.text(ezQuery(this).text());
						listInputTrigger.attr('title',ezQuery(this).text());
						box.find('option').removeAttr('selected').filter('#'+index).attr({selected:'selected'});
						ezQuery(this).parents('.ez-advanced-search-input-list').hide();
					});											
				});

				listInputTrigger.click(function(){
					var el = ezQuery(this);
					el.next().toggle().css({
						left: listInputTrigger.position().left	 
					});
					ezQuery('.ez-advanced-search-input-list').not(el.next('.ez-advanced-search-input-list')).hide();
				});
				
				optionList.hide();
   });
/* Moved to search.xsl as it overlaps with timeline code		
		ezQuery('#ez-advanced-search-submit').click(function(){
			theForm.submit();																					 
		});
		ezQuery('#ez-advanced-search-clear').click(function(){
			ezQuery('.ez-select_dropdown').each(function(){
				ezQuery('ul li:first a', this).trigger('click');
			});
			//selectBoxes.find('option').removeAttr('selected');
			//selectBoxes.find('option:first').attr({selected:'selected'});
			theForm.submit();																					 
		});
*/		
}
EVERYZING.clearSelectBoxes = function(el) {
	el.find('option').removeAttr('selected');
	el.find('option:first').attr({selected:'selected'});
	ezQuery('#ez-advanced-search-form').submit();
}

// Add frameset for external links
EVERYZING.ChangeUrls = function() {
    var base = "http://www.newsweek.com/frameset.aspx?url=";
    ezQuery("a").click(function() {
        var href = ezQuery(this).attr("href");      
        if(href.search("newsweek.com") == -1) {
            ezQuery(this).attr(
            {
            	"href" : base + encodeURIComponent(href), "target" : "_blank"
            });
		}
	})
} 