/**
 *
 */

String.prototype.htmlEscape = function() {
	var obj = document.createElement('pre');
    if (typeof obj.textContent != 'undefined') {
        obj.textContent = this;
    } else {
        obj.innerText = this;
    }
    return obj.innerHTML;

};

String.prototype.replaceAll = function(target, replacement) {
	return this.split(target).join(replacement);
};


$(window).load(function() {
});

var Sparql = function(){
	this.index = 0;
	this.sessionid = "";
};

Sparql.prototype.init = function(){


	$('#container').append(
			$('<div></div>')
			.attr({
				'id': 'popup_process',
				'width': '400px',
				'height': '200px'
			})
	);
	$('#popup_process').html('検索中です');
	$('#popup_process').hide();




	// 左ペイン初期化
	if (sparql.menuCondition instanceof Array){

		var propStr = '';
		for (var d in sparql.menuCondition){
			propStr += '<h3 id="menu_'+d+'" class="left_menu">' + sparql.menuCondition[d].label+'</h3>\n';
		}
		$("#left").html(propStr);

		for (var d in sparql.menuCondition){
			$('#menu_'+d).click(function(event){
				var id = event.target.id;
				var index = id.lastIndexOf('_');
				id = id.slice(index+1);
				var query = sparql.menuCondition[id].query;
				sparql.findMenuQuery(query);
			});
		}

	} else {
		$("#right").removeClass('rightonly');
		$("#right").addClass('rightonly');
	}

	// データを整形する
	for (var d in sparql.predicates){
		if (typeof sparql.predicates[d].subject != 'undefined'){
			sparql.predicates[d].pred = 'subject';
		}
	}
	for (var d in sparql.viewPreds.data){
		if (typeof sparql.viewPreds.data[d].label != 'undefined'){
			if (typeof sparql.viewPreds.data[d].pred == 'undefined'){
				sparql.viewPreds.data[d].valiable = 's';
			}
		}
	}


	// 初期処理
	var cmd = sparql.endpoint;

	var server = sparql.server + "/SparqlFinder/Initialize?callback=?";
	if (sparql.sessionid != ""){
		server = sparql.server + "/SparqlFinder/Initialize;jsessionid=" + sparql.sessionid + "?callback=?";
	}

	sparql.process(true);
	$.getJSON(
			server,
			cmd).then(
			function(result, status){
				sparql.getResponse(result);
				sparql.process(false);
			},
			function(result, status, error){
				sparql.process(false);
			}
		);

};

Sparql.prototype.clearCondition = function(){};

Sparql.prototype.addCondition = function(){

	var index = sparql.index++;

		var id = "condition_"+index;
		$('#find_condition').append(
			$('<span></span>').attr({
				'id': id
			})
		);
		if (index != 0){
			$('#'+id).prepend('<br/>');
		}

		if (index != 0){
//		{
			var mix_id = "mix_list_"+index;
			$('#'+id).append(
					$('<select></select>')
					.attr({
						'id': mix_id,
						'size': 1
					})
			);
			var propStr = '<option value="and">かつ</option><option value="or">あるいは</option>';
			$("select#"+mix_id).html(propStr);

		}

		var text_id = "find_text_"+index;
		$('#'+id).append(
				$('<input>')
				.attr({
					'id': text_id,
					'type': 'text'
				})
		);
		var text_select_id = "find_select_"+index;
		$('#'+id).append(
				$('<select>')
				.attr({
					'id': text_select_id
				})
		);

		$('#'+id).append('が');
		var pred_id = "predicate_list_"+index;
		$('#'+id).append(
				$('<select></select>')
				.attr({
					'id': pred_id,
					'name': 'predicate'
				})
		);
		$('select#'+pred_id).change(function(event){
			var id = event.target.id;
			var index = id.slice(id.lastIndexOf('_')+1);

			sparql.updateFindWordBox(index);

		});
		sparql.updateCB(sparql.predicates, $("select#"+pred_id));

		$('#'+id).append('に');
		var select_id = "type_list_"+index;
		$('#'+id).append(
				$('<select></select>')
				.attr({
					'id': select_id,
					'size': 1
				})
		);
		var propStr = '<option value="part">含まれる</option><option value="full">一致する</option>';
		$("select#"+select_id).html(propStr);

		if (index != 0){

			var del_id = "del_"+index;
			$('#'+id).append(
					$('<input>')
					.attr({
						'id': del_id,
						'type': 'button',
						'value': 'del'
					})
			);
			$('#'+del_id).click(function(event){
				var id = event.target.id;
				var index = id.lastIndexOf('_');
				var i = id.slice(index+1);
				i = parseInt(i);

				var del_id = "condition_"+i;
				$('span#'+del_id).remove();

			});
		}

		sparql.updateFindWordBox(index);


};

Sparql.prototype.updateFindWordBox = function(index){
	var predicate_index = $('select#predicate_list_'+index).val();
//	var predicate_val = sparql.predicates[predicate_index].pred;
	var select_id = "find_select_"+index;
	var text_id = "find_text_"+index;
	var type_id = "type_list_"+index;

	for (var i=0; i<sparql.predicates.length; i++){
//		if (sparql.predicates[i].pred == predicate_val){
		if (i == predicate_index){
			if (typeof sparql.predicates[i].types != 'undefined'){
				var obj = $("select#"+select_id);
				var propStr = '';

				for (var d in sparql.predicates[i].types){
					propStr += '<option value="' +(sparql.predicates[i].types[d])+'">'+sparql.predicates[i].types[d].htmlEscape()+'</option>\n';
				}
				obj.html(propStr);
				$('select#'+select_id).show();
				$('input#'+text_id).hide();
			} else {
				//
				$('select#'+select_id).hide();
				$('input#'+text_id).show();
			}
		}
	}
};


Sparql.prototype.find = function(){

	var param = new Array();

	for (var i=0; i<sparql.index; i++){
		var word = $('#find_text_'+i).val();
		if ($('#find_text_'+i).is(':visible')){
			word = $('#find_text_'+i).val();
		} else if ($('#find_select_'+i).is(':visible')){
			word = $('select#find_select_'+i).val();
		}

		var and_or = $('select#mix_list_'+i).val();
		var type = $('select#type_list_'+i).val();
		var target = $('select#predicate_list_'+i).val();

		if (target != undefined){
			target = sparql.predicates[target].pred;
		}
		if (word != '' && word != undefined && word != null){
			var p =	{"word": encodeURI(word), "predicate":encodeURI(target), "type":type, "and_or": and_or };
			param.push(p);
		}
	}



	if (param.length > 0){
		sparql.find_(param);
	}

};


Sparql.prototype.find_ = function(param){

	var param;
	var limit = $('select#limit').val();

	if (typeof sparql.sparqlConditionHead == 'undefined'){
		param = {"target":JSON.stringify(sparql.viewPreds.data), "param":encodeURI(JSON.stringify(param)), "limit":limit, "offset":"0" };
	} else {
		param = {"target":JSON.stringify(sparql.viewPreds.data), "head":encodeURI(sparql.sparqlConditionHead), "param":encodeURI(JSON.stringify(param)), "limit":limit, "offset":"0" };
	}

	sparql.process(true);

	$.getJSON(
			sparql.server + "/SparqlFinder/FindByCondition;jsessionid=" + sparql.sessionid + "?callback=?",
			param).then(
				function(result, status){
					//
					result = JSON.parse(sparql.getResponse(result));

					sparql.update(result);
					sparql.process(false);
				},
				function(result, status, error){
					sparql.process(false);
				}
		);



};

Sparql.prototype.viewCondition = function(){

	var param = new Array();

	for (var i=0; i<sparql.index; i++){
		var word = $('#find_text_'+i).val();
		if ($('#find_text_'+i).is(':visible')){
			word = $('#find_text_'+i).val();
		} else if ($('#find_select_'+i).is(':visible')){
			word = $('select#find_select_'+i).val();
		}
		var and_or = $('select#mix_list_'+i).val();
		var type = $('select#type_list_'+i).val();
		var target = $('select#predicate_list_'+i).val();
		target = sparql.predicates[target].pred;
		if (word != '' && word != undefined && word != null){
			var p =	{"word": encodeURI(word), "predicate":encodeURI(target), "type":type, "and_or": and_or };
			param.push(p);
		}
	}



	if (param.length > 0){
		sparql.viewCondition_(param);
	}

};

Sparql.prototype.viewCondition_ = function(param){

	var param =	{"param":JSON.stringify(param) };

	sparql.process(true);
	$.getJSON(
			sparql.server + "/SparqlFinder/GetMenuCondition;jsessionid=" + sparql.sessionid + "?callback=?",
			param).then(
				function(result, status){
					//
					result = JSON.parse(sparql.getResponse(result));

					$('#popup_condition').html((result.query).htmlEscape());
					$('#popup').dialog({
						draggable:true
					});
					sparql.process(false);
				},
				function(result, status, error){
					sparql.process(false);
				}
		);



};

Sparql.prototype.getViewQuery = function(){

	var param = new Array();

	for (var i=0; i<sparql.index; i++){
		var word = $('#find_text_'+i).val();
		if ($('#find_text_'+i).is(':visible')){
			word = $('#find_text_'+i).val();
		} else if ($('#find_select_'+i).is(':visible')){
			word = $('select#find_select_'+i).val();
		}
		var and_or = $('select#mix_list_'+i).val();
		var type = $('select#type_list_'+i).val();
		var target = $('select#predicate_list_'+i).val();
		target = sparql.predicates[target].pred;
		if (word != '' && word != undefined && word != null){
			var p =	{"word": encodeURI(word), "predicate":encodeURI(target), "type":type, "and_or": and_or };
			param.push(p);
		}
	}



	if (param.length > 0){
		sparql.getViewQuery_(param);
	}

};

Sparql.prototype.getViewQuery_ = function(param){


	var limit = $('select#limit').val();

	if (typeof sparql.sparqlConditionHead == 'undefined'){
		param = {"target":JSON.stringify(sparql.viewPreds.data), "param":encodeURI(JSON.stringify(param)), "limit":limit, "offset":"0" };
	} else {
		param = {"target":JSON.stringify(sparql.viewPreds.data), "head":encodeURI(sparql.sparqlConditionHead), "param":encodeURI(JSON.stringify(param)), "limit":limit, "offset":"0" };
	}

	sparql.process(true);

	$.getJSON(
			sparql.server + "/SparqlFinder/GetViewQuery;jsessionid=" + sparql.sessionid + "?callback=?",
			param).then(
				function(result, status){
					result = JSON.parse(sparql.getResponse(result));
					//
					$('#popup_query').html((result.query).htmlEscape().replaceAll('\n','<br/>'));
					$('#popup_2').dialog({
						draggable:true
					});
					sparql.process(false);
				},
				function(result, status, error){
					sparql.process(false);
				}
		);



};




Sparql.prototype.findMenuQuery = function(menuQuery){

	var param;
	var limit = $('select#limit').val();

	if (typeof sparql.sparqlConditionHead == 'undefined'){
//		param =	{"target":JSON.stringify(sparql.viewPreds.data), "menuquery":encodeURI(menuQuery), "limit":limit, "offset":"0" };
		param =	{"target":JSON.stringify(sparql.viewPreds.data), "param":encodeURI(menuQuery), "limit":limit, "offset":"0" };
	} else {
//		param =	{"target":JSON.stringify(sparql.viewPreds.data), "head":encodeURI(sparql.sparqlConditionHead), "menuquery":encodeURI(menuQuery), "limit":limit, "offset":"0" };
		param =	{"target":JSON.stringify(sparql.viewPreds.data), "head":encodeURI(sparql.sparqlConditionHead), "param":encodeURI(menuQuery), "limit":limit, "offset":"0" };
	}

	sparql.process(true);

	$.getJSON(
			sparql.server + "/SparqlFinder/FindByCondition;jsessionid=" + sparql.sessionid + "?callback=?",
			param).then(
				function(result, status){
					result = JSON.parse(sparql.getResponse(result));
					//
					sparql.update(result);
					sparql.process(false);
				},
				function(result, status, error){
					sparql.process(false);
				}
		);



};

Sparql.prototype.find_offset = function(type){

	var param =	{"type":type };

	$.getJSON(
			sparql.server + "/SparqlFinder/OffsetFind;jsessionid=" + sparql.sessionid + "?callback=?",
			param).then(
				function(result, status){
					result = JSON.parse(sparql.getResponse(result));
					//
					sparql.update(result);
				},
				function(result, status,error){
					//
//					sparql.update($.parseJSON(result.responseText));//TODO error
				}
		);

};


Sparql.prototype.history = function(historyType){
	var param =	{"history": historyType};

	sparql.process(true);

	$.getJSON(
			sparql.server + "/SparqlFinder/SparqlFinder;jsessionid=" + sparql.sessionid + "?callback=?",
			cmd).then(
				function(result, status){
					result = JSON.parse(sparql.getResponse(result));
					//
					sparql.update(result);
					sparql.process(false);
				},
				function(result, status, error){
					sparql.process(false);
				}
		);


};


Sparql.prototype.updateCB = function(data, obj){
	if (data instanceof Array){
		var propStr = '';

		for (var d in data){
//			propStr += '<option value="' +data[d].pred+'">'+data[d].label+'</option>\n';
			propStr += '<option value="' +d+'">'+data[d].label+'</option>\n';
		}
		obj.html(propStr);

	}

};


Sparql.prototype.update = function(data){


	history = data;

	if (data.hasNext){
		$('#next_offset').show();
	} else {
		$('#next_offset').hide();
	}

	if (data.hasPrev){
		$('#prev_offset').show();
	} else {
		$('#prev_offset').hide();
	}

	if (data.results instanceof Array){
		sparql.updateTable(data.results);
	}
};

Sparql.prototype.updateTable = function(data){
	var table = $("#result_list")[0];

	while(table.rows.length > 0){
		table.deleteRow(0);	// 行を追加
	}

	if (data instanceof Array){
		$('#result_div').show();
		// ヘッダ
		var header = table.createTHead();	// 行を追加
		var row = header.insertRow(0);

		var th = document.createElement('th');
		th.innerHTML = ''; // ID
		row.appendChild(th);
		for (var i=0; i<sparql.viewPreds.data.length; i++){
			var th = document.createElement('th');
			th.innerHTML = sparql.viewPreds.data[i].label;
			row.appendChild(th);
		}

		id = 1;
		for (var d=0; d<data.length; d++){
			var row1 = table.insertRow(d+1);	// 行を追加

			// ID
			var cell = row1.insertCell(0);	// １つ目のセルを追加
			var subject = data[d].s;
			if (subject == "<same>same</same>"){
				subject = '<span class="same">〃</span>';
			} else {
				if (sparql.viewPreds.link){
					cell.innerHTML = '[<a href="' + subject + '" target="_blank">' + (id++ )+'</a>]';
				} else {
					cell.innerHTML = '[' + (id++ )+']';
				}
			}

			for (var i=0; i<sparql.viewPreds.data.length; i++){
				var cell = row1.insertCell(i+1);	// ２つ目以降のセルを追加
				var value = data[d][sparql.viewPreds.data[i].valiable];
				if (value == null){
					value = '';
				}

				if (value == "<same>same</same>"){
					cell.style.textAlign = 'center';
					value = '<span class="same">〃</span>';
				}
				if (sparql.viewPreds.data[i].link != false){
					if (value != null && value.indexOf("http://") == 0){
						value = '<a href="'+value+'" target="_blank">'+value+'</a>';
					}
				}
				cell.innerHTML = value;
			}
		}
	}
};

Sparql.prototype.getResponse = function (response){
	this.sessionid = response.sessionid;

	return response.response;
};

Sparql.prototype.process = function (processing){
	if (processing){
		$('#popup_process').dialog({
			closeOnEscape: false,
			modal:true,
			draggable:true,
			open:function(event, ui){ $(".ui-dialog-titlebar-close").hide();}
		});
	} else {
		$('#popup_process').dialog('close');
	}
};


