// SeCo
// Teppo Känsälä
// beta
// (C) 2007

/*
Copyright (c) 2007 Semantic Computing Research Group (SeCo) - www.seco.tkk.fi/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

dojo.provide("seco.widget.Recommend");
dojo.provide("seco.widget.RecommendItem");
dojo.provide("seco.widget.RecommendGroup");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.io.script");

var seco_semlink_server = "http://demo.seco.tkk.fi/leijuke/";
var seco_default_service = "/semlink/info";

function seco_hover_hide()
{
    document.getElementById('seco_hover_img').style.display = 'none';
}

function seco_hover(img)
{
    document.getElementById('seco_hover_img').src = img;
    document.getElementById('seco_hover_img').style.display = 'block';
    //document.getElementById('seco_hover_div').innerHTML = img;
}

var seco_option_templates = {

plain:
{ item_html: '' },

images:
{ item_html: '<div class="secoBookmark"><a href="${data.url}">${data.title}</a><br/><a href="${data.url}"><img src="http://www.kulttuurisampo.fi/${data.thumbnail}"/></a></div>' },

hover:
{ item_html: '<div class="secoBookmark"><a href="${data.url}" onMouseOver="javascript:seco_hover(\'${data.thumbnail}\')">${data.title}</a></div>' },

hover_act:
{ item_html: '<div class="secoBookmark"><a href="${data.url}" onMouseOver="javascript:seco_hover(\'${data.thumbnail}\')">${data.title}</a></div>', preprocess_data: function(data) { var img = data[0].thumbnail; if (img) { document.getElementById('seco_hover_img').src = img; document.getElementById('seco_hover_img').style.display = 'block'; } return data; } },

description:
{ item_html: '<div class="secoBookmark"><a href="${data.url}">${data.title}</a><br/>${data.description}</div>' },

plain:
{ }

};

// -------------------------------------------
// GENERAL helpers
// -------------------------------------------

function isArray(a)
{
  return isObject(a) && a.constructor == Array;
}

 function isObject(a)
 {
     return (typeof a == 'object' && !!a) || isFunction(a);
 }

 function isFunction(a)
 {
      return typeof a == 'function';
 }

function ltrim(str) { 
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str) {
	return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

// -------------------------------------------
// DATA manipulation
// -------------------------------------------

function do_o(data) // helps debugging
{
	alert(data.title);
}

function do_flatten_arr(array, i, data)
{
	var j = 0;
	for (j = 0; j < data.length; ++j)
	{
		i = do_flatten_obj(array, i, data[j]);
	}
	return i;
}

function do_flatten_obj(array, i, data)
{
	var aval = data['children'];


	if (aval)
 	{
		i = do_flatten_obj(array, i, aval);
	}
	else if (isArray(data))
	{
		i = do_flatten_arr(array, i, data);
	}
	else
	{
//		do_o(data); // helps debugging
		array[i] = data;
		++i;
	}

	return i;
}

function flatten(data)
{
	var array = new Array();
	var i = 0;

	i = do_flatten_arr(array, i, data);

	return array;
}
// -------------------------------------------
// -------------------------------------------

function seco_pretty_name(data)
{
 var i = data.title.indexOf(" ("); if (i == -1) return data; data.title = data.title.substr(0,i); return data;
}

function for_each_recursive(data, dfunc)
{
	var aval = data['children'];
	if (aval)
 	{
	    for_each_recursive(aval, dfunc);
	}
	else if (isArray(data))
	{
	    for (var j = 0; j < data.length; ++j)
			for_each_recursive(data[j], dfunc);
	}
	else
	{
	 dfunc(data);
	}
}

// -------------------------------------------
// DOJO widget
// -------------------------------------------

//RecommendItem
//RecommendGroup
//Recommend

dojo.declare(
	"seco.widget.RecommendItem",
	[dijit._Widget, dijit._Templated],
	{
	data: '',
	templateString: '<div class="secoRecommendItem"><a href="${data.url}">${data.title}</a></div>'
});

dojo.declare(
	"seco.widget.RecommendGroup",
	[dijit._Widget, dijit._Templated],
	{
	data: '',
	templateString: '<div class="secoRecommendGroup">${data.title}</div>'
});


dojo.declare(
	"seco.widget.Recommend",
	[dijit._Widget, dijit._Templated],
	{
	
	preamble: function() {

	// 'temp variables'
	// Required for Opera to work correctly
	this.groups = new Array(10);
	this.status_node = null;

	},
	
	style: "",
	wstyle: "",
	service_url: "",
	service: "",
	source: "",
	item_uri: "",
	item: "",
	concepts: [],
	lang: "fi",
	data: "",
	item_widget: "",
	group_widget: "",
	noresponse_html: "<strong>Server didn't respond to our request!</strong>",
	results_header_html: "",
	noresults_html: "<strong>No results</strong>",
	loading_html: "<strong>Loading</strong>",
	breaks: true,
	break_html: "<br>",
	break_last: false,
	timeout_in_seconds: 10,
	limit: 666,
	limit_group: 10,
	hard_limit: 666,
	keywords: "",
	item_html: "",
	group_html: "",
	item_html_file: "",
	group_html_file: "",
	flatten: false,
	item_widget: "seco.widget.RecommendItem",
	group_widget: "seco.widget.RecommendGroup",
	encoding: "",
	fullnames: false,

	templateString: '<div class="secoRecommend" dojoAttachPoint="domNode"><div class="secoStatus"></div>',


	createGroup: function(/* JSON-node */ n) {
		if (this.group_html_file != "")
		{
			var w = new seco.widget.RecommendItem({ data: n, templatePath: this.group_html_file });
			return w.domNode;
		}
		if (this.group_html != "")
		{
			var w = new seco.widget.RecommendGroup({ data: n, templateString: this.group_html });
			return w.domNode;
		}

		var node = document.createElement("div");
		var cl = document.createAttribute("class");
		cl.nodeValue = "secoBookmarkGroup"+this.level;
		node.setAttributeNode(cl);

		var anode = document.createElement("span");
		var cl2 = document.createAttribute("class");
		cl2.nodeValue = "secoBookmarkGroupLabel"+this.level;
		anode.setAttributeNode(cl2);
		node.appendChild(anode);

		var text = document.createTextNode(n.title);
		anode.appendChild(text);
/*		if (this.breaks)
		if (!this.last_item || (this.last_item && this.break_last))
		{
			var bnode = document.createElement("span");
			bnode.innerHTML = this.break_html;
			node.appendChild(bnode);
		}
*/		return node;
	}
	,

	createChild: function(/* JSON-node */ n) {
		if (this.item_html_file != "")
		{
			var w = new seco.widget.RecommendItem({ data: n, templatePath: this.item_html_file });
			return w.domNode;
		}
		if (this.item_html != "")
		{
			var w
			if (n.thumbnail==undefined && this.item_html.indexOf('${data.thumbnail}')>0)
				w = new seco.widget.RecommendItem({ data: n, templateString: "" });
			else
				w = new seco.widget.RecommendItem({ data: n, templateString: this.item_html });
			return w.domNode;
		}
	
		var node = document.createElement("div");
		var cl = document.createAttribute("class");
		cl.nodeValue = "secoBookmark";
		node.setAttributeNode(cl);

		var anode = document.createElement("a");
		var href = document.createAttribute("href");
		href.nodeValue = n.url;
		anode.setAttributeNode(href);

		node.appendChild(anode);

		var text = document.createTextNode(n.title);
		anode.appendChild(text);
		if (this.breaks)
		if (!this.last_item || (this.last_item && this.break_last))
		{
			var bnode = document.createElement("span");
			bnode.innerHTML = this.break_html;
			node.appendChild(bnode);
		}
		return node;
	}
	,
	timeout: function()
	{
		this.domNode.innerHTML = this.noresponse_html;
		//this.status_node.innerHTML = this.noresponse_html;
	}
	,
	receive: function(data)
	{
		//alert("foo"+data);
		//this.domNode.innerHTML = "<h1>Received!</h1>"+data;
		
		if (!this.fullnames)
				for_each_recursive(data, seco_pretty_name);
		
		this.setData(data);
	}
	,
	request: function()
	{
		if (this.service_url == "")
		   this.service_url = this.service;
		if (this.service_url == "")
		   this.service_url = seco_default_service;
		var surl = this.service_url;
	   if (this.service_url.length > 7 && this.service_url.substr(0,7) == "http://")
	   {
	   }
	   else
	   {
		 surl = seco_semlink_server + surl;
	   }
		surl += "?lang="+this.lang;
		surl += "&limit="+this.limit;
		surl += "&limit_group="+this.limit_group;
		if (this.source != "" && this.source != "auto")
		{
			surl += "&source="+escape(this.source);
			has_q = true;
		}
		if (this.encoding != "")
		{
			surl += "&encoding="+escape(this.encoding);
			has_q = true;
		}
		if (this.item_uri != "")
		{
			surl += "&item="+escape(this.item_uri);
			has_q = true;
		}
		else if (this.item != "")
		{
			surl += "&item="+escape(this.item);
			has_q = true;
		}
		if (this.concepts.length)
		{
			for (var i = 0; i < this.concepts.length; ++i)
			{
				surl += "&cat="+escape(this.concepts[i]);
			}
		}
		if (this.keywords.length)
		{
			for (var i = 0; i < this.keywords.length; ++i)
			{
				surl += "&key="+escape(this.keywords[i]);
			}
		}
//		alert(surl);
		var mywidget = this;
		var deferred = dojo.io.script.get({
	        url: surl, 
		handleAs: "json",
		timeout: 5000,
		load: function(data, ioArgs)
		{
			dojo.hitch(mywidget, "receive")(data);
		},
		error: function(data, ioArgs)
		{
			dojo.hitch(mywidget, "timeout")();
		},
		callbackParamName: "callback"
		});
	}
	,
	postCreate: function()
	{
	 	if (this.style != "")
		   this.wstyle = this.style;
	    if (this.wstyle != "")
		{
		    this.setWStyle(this.wstyle);
		 	//var pre = seco_option_templates[this.wstyle];
			//if (pre)
			//    dojo.lang.mixin(this, pre);
		}
	
	    if (!isArray(this.concepts))
		   this.concepts = this.concepts.split(';');
		for (var j = 0; j < this.concepts.length; ++j)
			this.concepts[j] = trim(this.concepts[j]);
	    if (!isArray(this.keywords))
		   this.keywords = this.keywords.split(';');
		for (var j = 0; j < this.keywords.length; ++j)
			this.keywords[j] = trim(this.keywords[j]);
			if (this.keywords.length == 1 && this.keywords[0] == '')
			   this.keywords.length = 0;
			if (this.concepts.length == 1 && this.concepts[0] == '')
			   this.concepts.length = 0;
		this.level = 0;
		this.groups = new Array(10);
		if (this.domNode)
				this.groups[0] = this.domNode;

		this.domNode.innerHTML = this.loading_html;

		this.inherited("postCreate", arguments);

		this.request();
	}
	,
	appendChild: function(/* Widget */ w) {
		this.groups[this.level].appendChild(w);
	}
	,

	setDataObject: function(data) {
		var aval = data['children'];
		
		if (aval)
		{
			if (!this.flatten)
			{
				var ng = this.createGroup(this.group_manipulator(data));
				this.groups[this.level].appendChild(ng);
				++this.level;
				this.groups[this.level] = this.groups[this.level-1];
				this.groups[this.level] = ng;
			}
			this.setDataObject(aval);
			if (!this.flatten)
			{
				--this.level;
			}
			//this.setDataArray(aval);
		}
		else if (isArray(data))
		{
//			++this.level;
//			this.groups[this.level] = this.groups[this.level-1];
			this.setDataArray(data);
//			--this.level;
		}
		else
		{
			this.groups[this.level].appendChild(this.createChild(this.manipulator(data)));
		}
	}
	,
	setDataArray: function(data) {
		var j = 0;
		
		this.last_item = false;
		var l = data.length-1;
		if (l > this.hard_limit)
		   l = this.hard_limit;
		for (var j = 0; j < data.length-1; ++j)
		{
			this.setDataObject(data[j]);
		}
		if (data.length > 0)
		{
			if (!this.flatten)
				this.last_item = true;
			this.setDataObject(data[data.length-1]);
			this.last_item = false;
		}
	}
	,
	manipulator: function(data)
	{
	 return data;
	}
	,
	group_manipulator: function(data)
	{
	 return data;
	}
	,
	preprocess_data: function(data)
	{
	 return data;
	}
	,
	clear: function(data) {
	}
	,
	setWStyle: function(wstyleq) {
		if (wstyleq == "plain")
		{
		 this.item_html = "";
		}
	    if (wstyleq != "")
		{
		 	var pre = seco_option_templates[wstyleq];
			if (pre)
			    dojo.mixin(this, pre);
		}
	},
	setHeaderExtra: function(data) {
	}
	,
	setData: function(org_data) {
		var data = org_data;
		var type_test = data['items'];
		if (type_test)
		   data = type_test;
		this.data = this.preprocess_data(data);

		this.level = 0;
		this.groups[0] = this.domNode; // Opera fix

		if (data.length == 0)
		{
			this.domNode.innerHTML = this.noresults_html;
			return;
		}
		
		this.domNode.innerHTML = ""; // hmm
		this.domNode.innerHTML = this.results_header_html;
		this.setHeaderExtra(data);
		this.setDataObject(data);
	}
	,
	redraw: function() {
		this.domNode.innerHTML = "";
		this.setData(this.data);
	}
});

