
function analyzeDocuments(doc) {
	
	wait($(doc), 'analyzing documents');

	invokeLink($(doc).children('a:first'), function(obj) { replaceAndRun(obj, $(doc), function(res) { hidePassages(res); }); });
	
}

function analyzeComplex(rel) {
	
	wait($(rel), 'analyzing ' + $(rel).children('h3').html());
	
	invokeLink($(rel).children('a:first'), function(obj) { 
		
		replaceAndRun(obj, $(rel), function(res) {
			
			hideFactItems(res);
			
			clickableTooltipWithPic($('.item-atomic > [title]'));		
			
			standardTooltip($(':not(.item-atomic):not(.more):not(.browse-next):not(.browse-prev)>[title]'));
			
		}); 
		
	});
	
}

function setAnchor(link) {
	
	document.location.hash = "#" + $(link).attr('id');
	
}



function hintSearchField(field, hint) {
	$(field).click(function() {
		if($(this).val() == hint) {
			$(this).val('');
		}
	});
	$(field).blur(function() {
		if($(this).val() == '') {
			$(this).val(hint);
		}
	});
	$(field).trigger('blur');
}

function hidePassages(set) {
	standardTooltip($(set).children('div.passages').find('[title]'));
	if($(set).children('div.passages').length > 3) {
		$(set).prepend($('<a class="toggle"></a><div class="tooltip" />'));
		$(set).append($('<a class="toggle"></a><div class="tooltip" />'));

		$(set).children('a.toggle').click(function() {
			if($(this).siblings('div.passages:gt(2)').length > 0) {
				$(this).css('cursor', 'pointer');
				$(this).siblings('div.passages:gt(2)').toggle();
				$(this).toggleClass('hide');
				$(this).siblings('a.toggle').toggleClass('hide');
				if($(this).hasClass('hide')) {
					$(this).next('.tooltip').html('Show ' + $(this).siblings('div.passages:gt(2)').length + ' other documents...');
					$(this).siblings('.passages').find('p.text').css({ maxHeight: '12em', overflowY: 'auto' });
				} else {
					$(this).next('.tooltip').html('Hide ' + $(this).siblings('div.passages:gt(2)').length + ' documents...');
					$(this).siblings('.passages').find('p.text').css({ maxHeight: '', overflowY: 'show' });
				}
				if($(this).siblings('a.toggle').hasClass('hide')) {
					$(this).siblings('a.toggle').next('.tooltip').html('Show ' + $(this).siblings('div.passages:gt(2)').length + ' other documents...');
				} else {
					$(this).siblings('a.toggle').next('.tooltip').html('Hide ' + $(this).siblings('div.passages:gt(2)').length + ' documents...');
				}
			};
			return false;
		});
		standardTooltip($(set).children('a.toggle'));
		$(set).children('a.toggle:first').trigger('click');
	}
}

function hideFactItems(set) {
	if($(set).find('td.edit').length > 0) hide=false;
	else hide=true;
	updateHiddenFactItems(set,hide);
}

function updateHiddenFactItems(set,hide) {
	if($(set).find('tbody tr:not(.doc)').length > 1) {
		
		var isCompareView = $(set).parent('td').length > 0;

		if(isCompareView) {
			// compare view 

			$(set).find('th:first').css('padding-left', '18px').prepend('<a href="#" class="toggle"></a><div class="tooltip" />');
			
		} else {
			// analyze view
			
			$(set).children('h3').css('padding-left', '18px').before('<a href="#" class="toggle"></a><div class="tooltip" />');
			
		}
		
		var toggle = (isCompareView ? $(set).find('th:first').children('.toggle') : $(set).children('.toggle') );
		
		toggle.click(function() {
			
			var toFold = (isCompareView ? $(this).parents('table:first').find('tbody tr:not(.doc):gt(0)') : $(this).parents('.relateds').find('tbody tr:not(.line_edit):not(.doc):not(.line_new):gt(0)') );
			
			if(toFold.length > 0){
				$(this).css('cursor', 'pointer');
				toFold.toggle();
				$(this).siblings('.browse').toggle();
				$(this).toggleClass('hide');
				var howMany = toFold.length;
				if($(this).hasClass('hide')) {
					$(this).next('.tooltip').html('Show ' + howMany + ' other item' + (howMany > 1 ? 's' : '') + '...');
				} else {
					$(this).next('.tooltip').html('Hide ' + howMany + ' item' + (howMany > 1 ? 's' : '') + '...');
				}
			}
			return false;
		});
		if (hide) {
			toggle.trigger('click');
		} else {
			toggle.each(function() {
					var howMany = toFold.length;
					if (howMany > 0) {
						$(this).next('.tooltip').html('Hide ' + howMany + ' item' + (howMany > 1 ? 's' : '') + '...');
					}
			});
		}
	}
	standardTooltip(toggle);

	var index = 0;
	if(isCompareView) {
		$(set).find('.more a').each(function() {
			/* removed because we now have icons
			var link = $(this).html();
			$(this).html(link.substring(link.length - 1));*/
			standardTooltip($(this));
		});
//		seeMore(set, '#seemore', false );
	} else {
//		seeMore(set, '#seemore', false );
		standardTooltip($(set).find('.more a'));
	}
	agreeLinks(set);
	editLinks(set);
	clickLinks(set);
	browseComplex(set);
}

function analyzeMoreComplex(rel) {
	wait($(rel), 'browsing ' + $(rel).children('h3').html());
	invoke($(rel).children('form:first'), 'analyzeComplex', function(obj) {
		replaceAndRun(obj, $(rel), function(res) {
			updateHiddenFactItems(res,false);
			ajaxifyA(res, '?analyze=');
			clickableTooltipWithPic($('.item-atomic > [title]'));		
			standardTooltip($(':not(.item-atomic):not(.more):not(.browse-next):not(.browse-prev)>[title]'));
		});
	});
}

function browseComplex(rel) {
	/*$(rel).find('.browse').css("border", "1px solid red");*/
	$(rel).find('.browse-next a,.browse-prev a').each(function() { $(this).after($('<div class="tooltip" />').html($(this).attr('title'))).attr('title', ''); standardTooltip($(this)); });
	$(rel).find('.browse-next a').click(function() {
		offset = $(rel).children('form:first').find('input[name=factSetOffset]');
		offset.val((offset.val()*1)+15);
		analyzeMoreComplex(rel);
		$(this).remove();
		return false;
	});
	$(rel).find('.browse-prev a').click(function() {
		offset = $(rel).children('form:first').find('input[name=factSetOffset]');
		offset.val(Math.max(offset.val()-15,0));
		analyzeMoreComplex(rel);
		$(this).remove();
		return false;
	});
}

function seeMore(rel, doc, hidden) {
	/*alert(hidden);*/
	$(rel).find('.more a.smallicon.seemore').click(function(e) {
		if($(doc).length == 0) {
			if(documents == null || documents.closed) {
				documents = window.open($(this).attr('href'), 'documents', 'screenX=' + (e.screenX + 10) + ',screenY=' + (e.screenY + 10) + ',width=800,height=600,scrollbars=yes');
			} else {
				documents.wait(doc, 'analyzing documents');
				documents.invokeLink($(this), function(obj) {
					documents.replaceAndRun(obj, doc, function(res) { 
						documents.hidePassages(res); 	
					}); 
				});
			}
		} else {
			wait($(doc), 'analyzing documents');
			var link = $(this);
			invoke($(this).siblings('form:first'), 'analyzeDocuments', function(obj) { 
				setAnchor(link);
				replaceAndRun(obj, $(doc), function(res) { 
					hidePassages(res); 	
				}); 
			});
		}
		if(hidden == true) {
//			alert($(this).parents('div.relateds').length);
			$('.relateds tr.doc').removeClass('doc');
			$(this).parents('div.relateds').find('tr:eq('+$(this).parent('div.tooltip').attr('id').split('_')[3] +')').each(function() {
				$(this).addClass('doc');
			});
		}else {
			$('.relateds tr.doc').removeClass('doc');
			$(this).parents('tr:first').addClass('doc');
		}
		return false;
	});
}

function standardTooltip(elem) {
	$(elem).each(function(){
		if($(this).next('.tooltip').length > 0) $(this).attr('title', '');
		$(this).tooltip({
			predelay: 250,
			delay: 0,
			position: 'top left',
			events: {
			  def:     "mouseover,mouseout click unload blur",
			  input:   "focus,blur",
			  widget:  "focus mouseover,blur mouseout",
			  tooltip: ",mouseover mouseout click"
			},
			onBeforeShow: function(evt, pos) {
				this.getConf().offset = [evt.pageY - this.getTrigger().offset()['top'] + this.getTip().height() + 25, evt.pageX - this.getTrigger().offset()['left'] + this.getTip().width() + 25];
	//			alert(this.getConf().offset);
				var tip = this.getTip();
			},
			effects: 'slide'
		});
	});
}
function standardTooltipPositioned(elem) {
	$(elem).each(function(){
		if($(this).next('.tooltip').length > 0) $(this).attr('title', '');
		$(this).tooltip({
			predelay: 250,
			delay: 150,
			position: 'top left',
			relative: 'true',
			events: {
			def:     "mouseover,mouseout click unload blur",
			input:   "mouseover,blur mouseout",
			widget:  "mouseover,blur mouseout",
			tooltip: ", mouseover mouseout click"
		},
		onBeforeShow: function(evt, pos) {
			this.getConf().offset = [evt.pageY - this.getTrigger().offset()['top'] + this.getTip().height() + 25, evt.pageX - this.getTrigger().offset()['left'] + this.getTip().width() + 25];
			var tip = this.getTip();
			var length = $(this.getTrigger()).next('.tooltip').html().length;
			$(this.getTrigger()).next('.tooltip').css('width', length + 'ex');
		},
		effects: 'slide'
		});
	});
}

function clickableTooltip(elem, ident) {
	$(elem).each(function(){
		if($(this).next('.tooltip').length > 0) $(this).attr('title', '');
		$(this).tooltip({
			tip: ident,
			predelay: 250,
			delay: 450,
			position: 'top left',
			onBeforeShow: function(evt, pos) {
				this.getConf().offset = [evt.pageY - this.getTrigger().offset()['top'] + this.getTip().height() + 25, evt.pageX - this.getTrigger().offset()['left'] + this.getTip().width() + 25];
	//			alert(this.getConf().offset);
			},
			effects: 'slide'
		});
	});
}

function clickableTooltipWithPic(elem) {
	$(elem).each(function(){
		if($(this).next('.tooltip').length == 0) $(this).after('<div class="tooltip top"></div>');
		if($(this).filter('[title]').length > 0)  {
			if($(this).next('.tooltip').filter(':not(.no-replace)').length > 0) $(this).next('.tooltip').append($(this).attr('title'));
			$(this).attr('title', '');
		}
		$(this).tooltip({
			predelay: 250,
			delay: 450,
			position: 'top left',
			onBeforeShow: function(evt, pos) {
				var val = this.getTrigger().html();
				var tip = this.getTrigger().next('.tooltip');
				if($(tip).children('.images').length == 0)
				$.getJSON("http://ajax.googleapis.com/ajax/services/search/images?q=" + val + "&v=1.0&callback=?&hl=en",
						
						// on search completion, process the results
						function (data) {
							$(tip).append('<div class="images" />');
							if (data.responseData.results &&
									data.responseData.results.length > 0) {
								var results = data.responseData.results;
								for (var i=0; i < results.length; i++) {
									if(i==1) return true;
									$('<a/>').addClass('img').attr('href', results[i].originalContextUrl).append($('<img/>').attr('src', results[i].tbUrl).attr('width', results[i].tbWidth).attr('height', results[i].tbHeight)).appendTo($(tip).children('div.images')).after($('<div/>').html('<span class="info">' + results[i].visibleUrl + '</span>'));
						}    
					}
					
				});
				this.getConf().offset = [evt.pageY - this.getTrigger().offset()['top'] + this.getTip().height() + 25, evt.pageX - this.getTrigger().offset()['left'] + this.getTip().width() + 25];
			},
			effects: 'slide'
		});
	});
}

var documents = null;
$(document).ready(function() {

	$.get($('#home').attr('href') + '?ajax', null, function() { });

//	$('.search #analyze').attr('title', '');
//	$('.search #analyze').after('<div id="analyze-tooltip" style="height: 1em; text-align: center;" class="tooltip">Analyze the object on the left</div>');
//	standardTooltipPositioned($('.search #analyze'));
	
	standardTooltip($('#header a.img').attr('title',''));
	standardTooltip($(':not(.item-atomic):not(.more):not(.browse-next):not(.browse-prev)>[title]'));
	
	standardTooltip($('.entity-counts a'));
	
	clickableTooltipWithPic($('.item-atomic > [title]'));
	
	$('.button input').click(function() { $(this).blur(); }); //IE Fix for the buttons

	proposeField();
	
});

