jQuery.noConflict();

function clone(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed (twice)
    for(var key in obj)
        temp[key] = clone(obj[key]);

    return temp;
}

function deselect(me) {
	// show the notice
	into_sight_left("#selectionnotice");
	// reset the similarity box
	jQuery("#startmcs").text('Load MCS');
	out_of_sight_left("#similarity");
	jQuery("#mcs-result").empty();
	jQuery("#mcssimilarities").hide();
	if (selection[0] == me) {selection = selection.slice(1);};
	if (selection[1] == me) {selection = selection.slice(0, 1);};
	update_count();
	jQuery(me.parentNode).removeClass('selectedcompound');
}

var count_text;
function update_count() {
	jQuery("#selectionnotice").html(count_text);
	jQuery("#num_selection").text(2 - selection.length);
	if (selection.length == 2) {
		out_of_sight_left(jQuery("#selectionnotice"));
		// calc similarity here
		document.forms['compoundsel'].cmp1.value = selection[0].name.substring("check".length);
		document.forms['compoundsel'].cmp2.value = selection[1].name.substring("check".length);
		jQuery("#compoundsel").ajaxSubmit(ajax_similarity_option);
		return;
	}
	jQuery("#selectionnotice").html(count_text);
	jQuery("#num_selection").text(2 - selection.length);
}
function auto_arrange() {
	pos = jQuery("#compoundarea").offset();
	jQuery(".compound").each(function() {
		jQuery(this).css('left', pos.left).css('top', pos.top);
		pos.left += 275;
		if (pos.left > jQuery(window).width() - 275) {
			pos.left = jQuery("#compoundarea").offset().left;
			pos.top += 310;
		}
	});
}
var similarity_left = -370;
function process_compound(cmp) {
	jQuery(cmp).addClass('compoundnew');
	setTimeout("jQuery('" + cmp + "').removeClass('compoundnew')", 5000);
	jQuery(cmp).draggable();
	jQuery(cmp).mouseover(function() {
		jQuery(this).addClass("compoundhover");
	});
	jQuery(cmp).mouseout(function() {
		jQuery(this).removeClass("compoundhover");
	});
	jQuery(cmp).children('.compoundcheck').click(function() {
		if (! this.checked) {
			deselect(this);
			return true;
		}
		if (selection.length == 2) {alert("You can only select two compounds to perform similarity calculation!"); return false;}
		else {
			selection.push(this);
			update_count();
			jQuery(this.parentNode).addClass('selectedcompound');
		}
	});
	jQuery(cmp).children("a.deletecompound").click(function() {
		if (confirm('Delete this compound?')) {
			jQuery(this).parent().hide();	
			var checkbox = jQuery(this).parent().children("input.compoundcheck").get(0);
			if (checkbox.checked)
				checkbox.click();
		}
		return false;
	});
	jQuery(cmp).show();
}
var template = "";
var next_compound_id = 0;
var selection = new Array();
var ajax_option = {
	dataType : 'json',
	error : function(req, status, err) {alert("Error: I was not able to submit the data to the server or the SDF you supplied is not valid.");},
	timeout : 120000,
	beforeSubmit : function(x) {
		out_of_sight_top("#uploadarea", 1000);
		into_sight_top("#uploadareactrl");
	},
	success : function(x) {
		all_status = x.status;
		failed = x.failed;
		for (var i = 0; i < failed.length; i ++)
			alert('compound #' + failed[i] + ' cannot be processed and is ignored');
		for (var i = 0; i < all_status.length; i ++) {
			xx = all_status[i];
			var cls = 'even';
			if (i % 2) cls = 'odd';
			if (xx['url'] == undefined)
				jQuery("#compoundarea").append(
					template
					.replace(/@url/, xx.img)
					.replace(/@id/, next_compound_id)
					.replace(/@md5/g, xx.md5)
					.replace(/@name/, xx.title)
				);
			else
				jQuery("#compoundarea").append(
					template
					.replace(/@url/, xx.img)
					.replace(/@id/, next_compound_id)
					.replace(/@md5/g, xx.md5)
					.replace(/@name/, '<a href="' + xx.url + '">' + xx.title + '</a>')
				);
			process_compound("#compound" + next_compound_id);
			next_compound_id ++;
		}
		auto_arrange();
		if (all_status.length)
			jQuery.scrollTo(jQuery("#compound" + (next_compound_id - 1)), 2000);
		jQuery("<span>" + all_status.length + " loaded; </span>").appendTo(jQuery("#loadstatus")).hide().fadeIn('slow').animate({'opaque':1}, 3000, function() {jQuery(this).remove()});
	}
}

var ajax_query_option = clone(ajax_option);
ajax_query_option.beforeSubmit = null;
ajax_query_option.error = function(req, status, err) {alert("Error: The server was not able to perform the requested calculation.");},
ajax_query_option.success = function(x) {
	jQuery("#mcssize").text(x.m_size);
	jQuery("#mcsmin").text(x.sim_min);
	jQuery("#mcsmax").text(x.sim_max);
	jQuery("#mcstanimoto").text(x.sim_tanimoto);
	jQuery("#mcssimilarities").slideDown(500);
	jQuery("#compoundarea").append(
		template
		.replace(/@url/, x.img)
		.replace(/@id/, next_compound_id)
		.replace(/@md5/g, x.md5)
		.replace(/@name/, x.title)
	);
	jQuery("#mcs-result")
	.hide()
	.html(
		mcs_template
		.replace(/@url/, x.img)
	).slideDown(500);
	jQuery("#startmcs").text('Loaded');
	// let "add to workspace" work
	var last_loaded_mcs = next_compound_id;
	jQuery("#mcs-result #addmcsresult").unbind('click');
	jQuery("#mcs-result #addmcsresult").click(function(){
		jQuery(this).hide();
		var _offset = jQuery("#mcs-result").offset();
		jQuery("#compound" + last_loaded_mcs).css('left', _offset.left).css('top', _offset.top);
		process_compound("#compound" + last_loaded_mcs);
		jQuery("#compound" + last_loaded_mcs).animate({left: (_offset.left + 270) + 'px'}, 600);
		return false;
	});
	next_compound_id ++;
}

var ajax_similarity_option = clone(ajax_option);
ajax_similarity_option.beforeSubmit = null;
ajax_similarity_option.url = '/ChemMineV2/mcs/ap_sim';
ajax_similarity_option.error = function(req, status, err) {alert("Error: The server was not able to calculate the similarity.");},
ajax_similarity_option.success = function(x) {
	jQuery("#mcs-result").hide();
	jQuery("#mcssimilarities").hide();
	into_sight_left(jQuery("#similarityvalue").text(x.sim).parent());
	out_of_sight_left("#selectionnotice");
}

jQuery(document).ready(function() {
	similarity_left = jQuery("#similarity").offset().left;
	count_text = jQuery("#selectionnotice").html();
	template = jQuery("#compoundarea").html();
	mcs_template = jQuery("#mcs-result").html();
	jQuery("#compoundarea").empty().show();
	jQuery("#mcs-result").empty();
	jQuery("#mcssimilarities").hide();
	jQuery('#compoundsel, #uploadform, #uploadform2').ajaxForm(ajax_option);
	out_of_sight_top("#uploadarea", 10);
	//into_sight_top("#uploadarea");
	jQuery("#closeuploadbtn").click(function() {
		out_of_sight_top("#uploadarea");
		into_sight_top("#uploadareactrl");
		return false;
	});
	jQuery("#uploadareactrl, #showuploadform").click(function() {
		out_of_sight_top(this);
		into_sight_top("#uploadarea");
		return false;
	});
	jQuery("a#startmcs").click(function() {
		if (selection.length != 2) {
			alert("You must select exactly 2 compounds to start MCS calculation");
			return false;
		}
		jQuery("#compoundsel").ajaxSubmit(ajax_query_option);
		return false;
	});
	jQuery(document).bind("ajaxStart", function() {
		jQuery("#ajaxstatus div").text("Working...");
		jQuery("#ajaxstatus div").show();
	});
	jQuery(document).bind("ajaxStop", function() {
		jQuery("#ajaxstatus div").text("Done");
		setTimeout("jQuery(\"#ajaxstatus\ div\").hide()", 2000);
	});
	jQuery("a#closesimilarity").click(function() {
		out_of_sight_left("#similarity");
		return false;
	});
	jQuery("a.loadsample").click(function() {
		document.forms['uploadform'].dbimport.value = 'default';
		document.forms['uploadform'].Upload.click();
		return false;	
	});
	jQuery("a.loadstarred").click(function() {
		document.forms['uploadform'].dbimport.value = 'starred';
		document.forms['uploadform'].Upload.click();
		return false;	
	});
	jQuery("a.loadworkbench").click(function() {
		document.forms['uploadform'].dbimport.value = 'workbench';
		document.forms['uploadform'].Upload.click();
		return false;	
	});
	jQuery("a").click(function() {
		jQuery("#landing").hide();
	});
	jQuery("input").click(function() {
		jQuery("#landing").hide();
	});
	jQuery("a.resetworkspace").click(function() {
			if (confirm("Are you sure you want to clear all compounds in the workspace?")) {
			if (selection.length) deselect(selection[0]);
			if (selection.length) deselect(selection[0]);
			jQuery("#compoundarea").empty();
		}
		return false;
	});
});

function out_of_sight_top(elem, duration) {
	if (duration == undefined) duration = 300;
	if (! jQuery(elem).hasClass('outofsight'))
		jQuery(elem).animate({top: '-=' + jQuery(elem).outerHeight() + 'px'}, duration).addClass('outofsight');
}

function into_sight_top(elem, duration) {
	if (duration == undefined) duration = 300;
	if (jQuery(elem).hasClass('outofsight'))
		jQuery(elem).show().animate({top: '+=' + jQuery(elem).outerHeight() + 'px'}, duration, 'swing').removeClass('outofsight');
}

function out_of_sight_left(elem, duration) {
	if (duration == undefined) duration = 300;
	if (! jQuery(elem).hasClass('outofsight'))
		jQuery(elem).animate({left: '-=' + jQuery(elem).outerWidth() + 'px'}, duration).addClass('outofsight');
}

function into_sight_left(elem, duration) {
	if (duration == undefined) duration = 300;
	if (jQuery(elem).hasClass('outofsight'))
		jQuery(elem).show().animate({left: '+=' + jQuery(elem).outerWidth() + 'px'}, duration).removeClass('outofsight');
}
