/*
 * viewperson_pubselect.js
 *
 * Copyright (c) 2009 Bo Gao (elivoa|gmail.com)
 *
 * $Date: 2010-05-05 $
 */

/*********************
 * pub select page
 *********************/
var loading_img = '<div style="text-align: center;"><img src="images/loading[0].gif" /></div>';
var _naid = -1;

/** init naid */
function init_publist(naid){
	_naid = naid;
}

$(document).ready(function() {
	var pub_changed = false;

	$('#disambiguation_btn').toggle(function() {
		pub_changed = true;
		/* Disambiguation Mode */
		$(this).text('[BACK]');
		$('#pub_select_area').fadeIn();
		$('#pub_area').hide();
		$('#pub_select_area').load("ajaxpage.do?m=inc_person_publist_edit_1list&naid="+_naid);
	}, function() {
		/* Publication View */
		$(this).text('[Edit disambiguation Result]');
		if (pub_changed == false) {
			$('#pub_area').fadeIn();
			$('#pub_select_area').hide();
		} else {
			pub_changed = false;
			var pub_area_obj = $('#pub_area');
			//pub_area_obj.html(loading_img);
			pub_area_obj.fadeIn();
			$('#pub_select_area').hide();
			pub_area_obj.load("ajaxpage.do?m=inc_person_publist_show&naid="+_naid);
		}
	});
});



var others_in_one_list = false;
function setInOneList(onelist){
	others_in_one_list = onelist;
}

/**
 * Create Publication Node
 * side: 0 - left side.
 * 		 1 - right side.
 */
function createPubNode(side, from_person_id, to_person_id, pub_id, idx, pub_str, year){
	// if in_one_list mode and create right side node.
	if(others_in_one_list && side == 1){
		var person_div_obj = $('#publist_-5');
	} else {
		var person_div_obj = $('#publist_'+from_person_id);
	}
	var insertLocation = foundInsertPosition(person_div_obj, year);
	//alert(from_person_id+'-'+to_person_id)
	// Add PubElement
	var html = '<div year="'+year+'" class="pub">';
	html += '<div class="idx">['+idx+']</div>';
	html += '<div class="text">'+pub_str+'</div>';
	if(side==0){ // left side, button is remove
		html += generateOperationLink('remove', 'Remove', from_person_id, to_person_id, pub_id, year);
	} else { // right side, button is remove
		html += generateOperationLink('get', 'Get', from_person_id, to_person_id, pub_id, year);
	}
	html += '</div>';
	var htmlObj = $(html);
	htmlObj.hover(onMouseIn, onMouseOut);// hover
	insertLocation.after(htmlObj);
}

function onMouseIn(){
	$(this).css('border','solid 1px #6fbee7');
	$(this).css('background-color','#2587b9');
	var btn = $(this).find('.function_area');
	btn.css('visibility','visible');
}

function onMouseOut(){
	$(this).css('border','solid 1px #999');
	$(this).css('background-color','');
	var btn = $(this).find('.function_area');
	btn.css('visibility','hidden');
}

// generate method call used on operation link
function generateOperationLink(action, display_name, from_person_id, to_person_id, pub_id ,year){
	var html = '<input type="button" class="function_area" value="' + display_name + '" onclick=\'';
	html += 'onPubMove("' + action + '", $(this).parent() , ' + from_person_id + ', ' + to_person_id + ', ' + pub_id + ', ' + year + ' )';
	html += '\' />';
	return html;
}

// find a year banner to insert pub node into.
function foundInsertPosition(container, year){
	// Find position and add year bar.
	var isFoundEqual = false;
	var equalBanner = undefined;
	var isNeighborFound = false;
	var banner = undefined;
	var invalidYear = false;
	var intYear = Number(year);
	if(intYear < 1700 || 2212 < intYear){
		intYear = 0
		invalidYear = true;
	}
	container.children().each(function(){
		var loopyear = Number($(this).attr('year'));
		var type = $(this).attr('class');
		if(type == "year_banner"){
			// alert("compare ---- "+loopyear+" .compareWith "+intYear+"?");
			if(loopyear == intYear){
				isFoundEqual = true;
				equalBanner = $(this);
				return;
			}else if(loopyear < intYear){
				banner = $(this);
				isNeighborFound = true;
				return;
			}else if(loopyear > intYear){
				banner = $(this);
			}
		}
	});

	// create year if needed
	if(isFoundEqual == true){
		return equalBanner;
	} else if(invalidYear == true){
		var year_banner = $('<div year="'+ year +'" class="year_banner"> - </div>');
		$(year_banner).appendTo(container);
		return year_banner
	} else if(isNeighborFound == true){
		var year_banner = $('<div year="'+ year +'" class="year_banner">' + year + '</div>');
		banner.before(year_banner);
		return year_banner;
	} else {
		var year_banner = $('<div year="'+ year +'" class="year_banner">' + year + '</div>');
		$(year_banner).appendTo(container);
		return year_banner;
	}
}

// Animation and ajax call of move publication.
// @param action 'get' / 'remove'
function onPubMove(action, pubNode, from_person_id, to_person_id, pid, year){
	var function_area = pubNode.find('.function_area');
	function_area.val("Loading...");
	function_area.attr('disabled', true);
	pubNode.fadeTo('slow', 0.4, function(){
		$.ajax({
			url: "/ajaxpage.do?m=na_pub_move",
			dataType: 'text',
			data: ({
				na_action : action,
				from_person_id : from_person_id,
				to_person_id: to_person_id,
				pid : pid,
				year : year,
				jsessionid : Math.round(Math.random()*10000)
			}),
			success: function(data){
				if(data == 'error'){
					movePubFailed(action, pubNode, 'Unknown Error');
				} else if (data == 'PubMoveStateChangedException'){
					movePubFailed(action, pubNode, 'PubMoveStateChangedException');
				} else {
					var pieces = data.split(',');
					var result = pieces[0];
					if(result == 'success' || result== 'PubMoveStateAlreadyException'){
						to_person_id = pieces[1];
						movePub(action, pubNode, from_person_id, to_person_id, pid, year);
					}else{
						movePubFailed(action, pubNode);
					}
				}
	    	},
			error: function(){
	        	$(this).addClass("error");
	        	movePubFailed(action, pubNode);
	    	}
		})
	});

}
// Restore animation
function movePubFailed(action, pubNode, msg){
	if(msg == 'PubMoveStateChangedException'){
		alert('Some one already move this publication to another person, please refresh and retry.');
	} else {
		alert('Error occured when move publication. '+ msg);
	}
	pubNode.fadeTo('fast', 1);
	var function_area = pubNode.find('.function_area');
	if(action=='remove'){
		function_area.html('Remove');
	} else {
		function_area.html('Get');
	}
	function_area.attr('disabled', true);
}

// move pub animation, part 2.
function movePub(action, pubNode, from_person_id, to_person_id, pub_id, year){
	var speed = 500;
	// if in_one_list mode and create right side node.
	if(others_in_one_list && action == "remove"){
		var container = $('#publist_-5');
	} else{
		var container = $('#publist_'+to_person_id);
		// create person if not valid
		if(container == undefined || container.html()==null){
			createPersonContainer(1, to_person_id, 'Others', null);
			container = $('#publist_'+to_person_id);
		}
	}
	var insertLocation = foundInsertPosition(container, year);

	var newPubNode = pubNode.clone();
	//newPubNode.detach()
	newPubNode.css('position', 'absolute');
	newPubNode.hover(onMouseIn, onMouseOut);
	newPubNode.offset({
		left: pubNode.offset().left + $(window).scrollLeft(),
		top: pubNode.offset().top + $(window).scrollTop()
	});
	var fixed = $('<div class="fixedwrapper" style="height:0;width:0;margin:0;padding:0;border:0;" ></div>')
	pubNode.after(fixed);
	fixed.after(newPubNode);
	//pubNode.after(newPubNode);

	var placeholder2 = $('<div class="pub">');
	placeholder2.height(0);
	placeholder2.css('opacity', 0);
	insertLocation.after(placeholder2);

	pubNode.css('border', '0')
	pubNode.css('margin', '0')
	pubNode.css('padding', '5px')
	pubNode.animate({
		opacity: 0.1,
		height: '-' + pubNode.height(),
		margin:0,
		padding:0
	}, speed, function(){
		pubNode.remove();
	});

	placeholder2.animate({
		opacity: 0.8,
		height: '+' + newPubNode.height()
	}, speed);

	newPubNode.animate({
		opacity: 0.25,
		left: [insertLocation.offset().left - 1, 'linear'],
		top:  [insertLocation.offset().top + 18, 'linear']
	}, speed, function() {
		newPubNode.fadeTo('fast', 1, function(){
			newPubNode.css('position', 'static');
			placeholder2.replaceWith(newPubNode);

			// rebuild all indexes
			rebuildIndex(from_person_id)
			if(others_in_one_list){
				rebuildIndex(-5)
			} else {
				rebuildIndex(to_person_id)
			}
			//newPubNode.height(120);
		});

		// update link button
		var btn = newPubNode.find('.function_area');
		if(action=='remove'){
			btn.replaceWith(generateOperationLink('get', 'Get', to_person_id, from_person_id, pub_id, year));
		} else {
			btn.replaceWith(generateOperationLink('remove', 'Remove', to_person_id, from_person_id, pub_id, year));
		}

		// update index
		var indexSpan = newPubNode.find('.idx');
		indexSpan.html('[-]');
	});
}

/**
 * rebuild index number in one container
 */
function rebuildIndex(container_person_id){
	var container = $('#publist_' + container_person_id);
	var all_indexes = container.find(".idx");
	var count = all_indexes.length;
	all_indexes.each(function(){
		$(this).html('['+count+']');
		count -= 1;
	});
}

/**
 * Create Person Profile Info and publication list container.
 * side: 0 - left side.
 * 		 1 - right side.
 */
function createPersonContainer(side, person_id, person_name, person_affilation){
	var profile_html = '<div class="profile">';
	profile_html += '<span class="name" onclick=\"window.location.href=\'viewperson.do?naid='+ person_id + '\'\">' +person_name+'</span>';
	if(person_affilation != undefined && person_affilation != 'null' && person_affilation != '' ){
		profile_html += '<span class="aff" > (' + person_affilation + ')</span>';
	}
	profile_html += '<div id="publist_' + person_id + '" class="publist"></div>';
	var newProfileNode = $(profile_html);
	if(0==side){
		newProfileNode .appendTo('#pub_select_main');
	} else {
		newProfileNode .appendTo('#pub_select_others');
	}
	return newProfileNode;
}

/**
 * Switch between PerPerson/AllOthersInOne View
 */
function toggleView(m, person_id){
	var container = $('#pub_select_area');
	var loaded=false;
	container.fadeOut('fast', function(){
		if(!loaded){
			container.html(loading_img)
		}
		container.show();
	});
	container.load('ajaxpage.do?m='+m+'&naid='+person_id, function(){
		loaded=true;
	});
}

