/**
 * 
 */

var Template = function(find){
	this.base = find;
};


Template.prototype.init = function(){

	this.base.html('');
	// 選択コンボ表示
	if (this.template.length > 1){
		this.base.append(
				$('<select></select>')
				.attr({
					'id': this.base[0].id + '_select_title'
				})
			);
				
		var propStr = '';
		
		for (var i=0; i<this.template.length; i++){
			propStr += '<option value="' +i+'">'+this.template[i].title+'</option>\n';
		}
		$("select#" + this.base[0].id + "_select_title").html(propStr);
		var me = this;
		$("select#" + this.base[0].id + "_select_title").change(function(event){
			me.selectTitle();
		});
	}
	this.base.append(
			$('<div></div>')
			.attr({
				'ID': this.base[0].id + '_query_label'
			})
			);
	
	this.selectTitle(0);
	
};


Template.prototype.selectTitle = function(index){
	if (index == undefined){
		index = $("select#" + this.base[0].id + "_select_title").val();
	}

	$('#' + this.base[0].id + '_query_label').html('');

	$('#' + this.base[0].id + '_query_label').append(
			this.makeLabel(this.template[index].label, index)
		);
	

};

Template.prototype.makeLabel = function(str, index){
	var ret = '';
	var strs = str.split('$');
	
	for (var i=0; i<strs.length; i++){
		if (i % 2 == 0) {
			ret += strs[i];
		} else {
			ret += this.makeValiableLabel(strs[i], index);
		}
	}
	
	return ret;
};


Template.prototype.makeValiableLabel = function(str, index){
	var ret = '';
	if (str == ''){
		return '$';
	}
	
	if (this.template[index].valiables[str] != undefined){
		ret += '<select id="' + this.base[0].id + '_' + str + '">';
		for (var i=0; i<this.template[index].valiables[str].length; i++){
			var val = this.template[index].valiables[str][i];
			ret += '<option value="' + i + '">' + val + '</option>';
		}
		ret += '</select>';
	} else {
		ret += '<input type="text" id="' + this.base[0].id + '_' + str + '">';
	}
	
	return ret;
};

Template.prototype.makeQuery = function(str, index){
	var ret = '';
	var strs = str.split('$');
	
	for (var i=0; i<strs.length; i++){
		if (i % 2 == 0) {
			ret += strs[i];
		} else {
			ret += this.makeValiableQuery(strs[i], index);
		}
	}
	
	return ret;
};

Template.prototype.makeValiableQuery = function(str, index){
	var ret = '';
	if (str == ''){
		return '$';
	}
	if (this.template[index].valiables[str] != undefined){
		return this.template[index].valiables[str][$('#'+ this.base[0].id + '_' + str).val()];
	} else {
		return $('#'+ this.base[0].id + '_' + str).val();
	}
	
};
