var TASK_BUTTON_RELOAD = 1;
var TASK_BUTTON_HELP = 2;
var TASK_BUTTON_ANSWER = 4;
var TASK_BUTTON_RIGHT = 8;

var TASK_PANEL_BUTTON_HELP = 16;
var TASK_PANEL_BUTTON_START = 32;

var TASK_BUTTON_ALL = 63;

var inputToBeFocused = null;



function Task_Module_Abstract(taskId, panel) 
{
	Task_Module_Abstract.superclass.constructor.call(this);
	
	var mode = panel.mode; // mode==0 - без кнопок, mode==1 - с кнопками "справка" и "подсказки"
	this.panel = panel;
	//this.link = link;
	
	this._taskType = 0;
	
	this._params = {};
	this._params.taskId = taskId;
	
	this._setBaseElement(Rup.create('div'));
	
	this._elements = {
		loading: Rup.create('div'),
		//title: Rup.create('div'),
		text: Rup.create('div'),
		question: Rup.create('div'),
		variants: Rup.create('div'),
		result: Rup.create('div')
	};
	
	this._elements.loading.innerHTML = 'Загрузка...';
	
	//this._elements.title.className = 'EduTaskTitle';
	this._baseElement.className = 'edutask';
	this._elements.text.className = 'tasktext';
	this._elements.question.className = 'taskquestion';
	this._elements.variants.className = 'taskvariant';
	this._elements.result.className = 'taskresult';
	this._elements.result.style.display = 'none';
	
	this._variantElement = this._elements.variants;
	
	//this.buttons = 0;
	
	this._loaded = false;
	
	this._hideLoading();
	
	this._baseElement.appendChild(this._elements.loading);
	//this._baseElement.appendChild(this._elements.title);
	this._baseElement.appendChild(this._elements.text);
	this._baseElement.appendChild(this._elements.question);
	this._baseElement.appendChild(this._elements.variants);
	if (mode == 1)
	{
		this._elements.buttons = Rup.create('div');
		this._elements.buttons.className = 'taskbuttons';
		this.addButtons(mode);
		this._baseElement.appendChild(this._elements.buttons);
		
		this._elements.hints = Rup.create('div');
		this._elements.hints.className = 'taskhints';
		this._baseElement.appendChild(this._elements.hints);
		this._elements.hints.style.display = 'none';
	}
	this._baseElement.appendChild(this._elements.result);
	
	this._variants = [];
	this._helpItems = [];
}

Rup.extend(Task_Module_Abstract, Element_Abstract);

Task_Module_Abstract.prototype._showLoading = function()
{
    this._elements.loading.style.display = 'block';
}

Task_Module_Abstract.prototype._hideLoading = function()
{
    this._elements.loading.style.display = 'none';
}

Task_Module_Abstract.prototype.load = function( /*buttons*/ )
{
	if( !this._loaded )
	{
		this._load();
		//this.showButtons( buttons );
	}
}

Task_Module_Abstract.prototype._load = function()
{
	var instance = this;
	
	this._showLoading();
	var fname = this._params.taskId + ".xml";
	ProcessAjax({
		url: fname,
		callback: function(respXML){
			var aObjects = respXML.getElementsByTagName('task');
			var aErrors = respXML.getElementsByTagName('error');
			instance._hideLoading();
			
			if( aErrors.length && aErrors[0].getAttribute('level') )
			{
				var oError = aErrors[0];
				
				var iLevel = oError.getAttribute('level');
				
				if( iLevel == 1 )
				{
					instance.showContentMessage(oError.getAttribute('title'), oError.getAttribute('content'));
					instance.showButtons(TASK_BUTTON_RELOAD);
					instance.link.setError();
				}
				else
				{
					Error.Show( oError );
				}
			}
			else
			{
				var oData = aObjects[0];
				instance._createHtml(respXML /*oData*/);
			}
		}
	});
}


Task_Module_Abstract.prototype.addButtons = function(mode)
{
	if (this._elements.buttons && mode == 1)
	{
		var instance = this;
		//this._elements.buttons.appendChild(Rup.GetButton("Справка", function(){ instance.showHelp(); }));
		//this._elements.buttons.appendChild(Rup.GetButton("Показать подсказки", function(){ instance.toggleHint(this); }));
	}
}

Task_Module_Abstract.prototype.hideButtons = function()
{
	//if (this._elements.buttons) this._elements.buttons.firstChild.style.display = 'none';
}

Task_Module_Abstract.prototype.toggleHint = function(btn)
{
	if (this._elements.hints.style.display == 'none')
	{
		this._elements.hints.style.display = 'block';
		btn.value = 'Скрыть подсказки';
	}
	else
	{
		this._elements.hints.style.display = 'none';
		btn.value = 'Показать подсказки';
	}
}

/*Task_Module_Abstract.prototype.showButtons = function( buttons )
{
	this.buttons = buttons;
	this._elements.buttons.innerHTML = '';
	
	var instance = this;
	
	if( buttons & TASK_BUTTON_ANSWER )
	{
		this._elements.buttons.appendChild(Rup.GetButton("Ответить", function(){ instance.answer(); }));
	}
	
	if( buttons & TASK_BUTTON_HELP )
	{
		this._elements.buttons.appendChild(Rup.GetButton("Справка по заданию", function(){ Rup.app.task.goWindow({taskId: instance._params.taskId}); }));
	}
	
	if( buttons & TASK_BUTTON_RIGHT )
	{
		this._elements.buttons.appendChild(Rup.GetButton("Правильный ответ", function(){ instance.getRightAnswer(); }));
	}
	
	if( buttons & TASK_BUTTON_RELOAD )
    {
        this._elements.buttons.appendChild(Rup.GetButton("Попробовать снова", function(){ instance._load() }));
    }
    
    if( buttons & TASK_PANEL_BUTTON_START )
    {
        this._elements.buttons.appendChild(Rup.GetButton("Начать тест", function(){ instance.panel.startTest(); }));
    }
    
    if( buttons & TASK_PANEL_BUTTON_HELP )
    {
        this._elements.buttons.appendChild(Rup.GetButton("Справка по тесту", function(){ Rup.app.task.goWindow({taskId: instance.panel.testId}); }));
    }
}*/

Task_Module_Abstract.prototype.showContentMessage = function(title, content)
{
    this._elements.text.innerHTML = title;
    this._elements.question.innerHTML = content;
}

Task_Module_Abstract.prototype.showHelp = function()
{
	window.open(this._params.taskId + '.xml', 'taskhelp');
}

Task_Module_Abstract.load = function( buttons )
{
	if( !this._loaded )
	{
		this._load();
	}
}

Task_Module_Abstract.prototype._createHtml = function( respXML )
{
	var aObjects = respXML.getElementsByTagName('task');
	var taskXml = aObjects[0];
	
	this._loaded = true;
	//this._elements.title.innerHTML = taskXml.getAttribute('name');
	this._elements.question.innerHTML = taskXml.getAttribute('task');
	this._params.ranswer = taskXml.getAttribute('rightanswer');
	
	this._createVariants( taskXml );
	replaceroot(this._elements.text);
	replaceroot(this._elements.question);
	replaceroot(this._elements.variants);
	if (this.panel.mode == 1)
	{ //alert('hints begin');
		var hintnodes = respXML.getElementsByTagName('node');
		//debugger;
		var hnum = 0;
		for (var i = 0; i < hintnodes.length; i++)
		{ //alert('i = ' + i);
			var nd = hintnodes[i];
			if (nd.getAttribute('type') == 'hint')
			{ 
				//alert('type == nint');
				var txt = nd.getAttribute('content');
				if (txt == '') continue;
				hnum++; 
				//alert('txt != null');
				
				var hcont = Rup.create('div');
				hcont.className = 'hintcont';
				this._elements.hints.appendChild(hcont);
				
				var hcapt = Rup.create('div');
				hcapt.className = 'hintcapt';
				hcapt.onclick = function(){var ht = this.nextSibling; ht.style.display = (ht.style.display == 'none') ? 'block' : 'none';};
				hcont.appendChild(hcapt);
				hcapt.innerHTML = 'Шаг ' + hnum;
				
				var htext = Rup.create('div');
				htext.className = 'hinttext';
				htext.style.display = 'none';
				hcont.appendChild(htext);
				
				var htextinner = Rup.create('div');
				htextinner.className = nd.getAttribute('style');
				htext.appendChild(htextinner);
				htextinner.innerHTML = txt;
			}
		}
		if (hnum > 0)
		{
			var instance = this;
			this._elements.buttons.appendChild(Rup.GetButton("Показать подсказки", function(){ instance.toggleHint(this); }));
		}
		
		replaceroot(this._elements.hints);
	}
}

Task_Module_Abstract.prototype.setDisabled = function()
{
	for( var i = 0; i < this._variants.length; i++ )
	{
		this._variants[i].setDisabled();
	}
}

Task_Module_Abstract.prototype.checkAnswer = function()
{
	if (this.setDisabled)
	{
		this.setDisabled();
	}
	if (this.compareAnswers)
	{
		var res = this.compareAnswers();
		this._elements.result.innerHTML = 'Результат: ' + res + '%';
		this._elements.result.style.display = 'block';
	}
	this.hideButtons();
	return res;
}

/*Task_Module_Abstract.prototype.getRightAnswer = function()
{
	var instance = this;
	
    ProcessAjax({
        method: "GET",
        data: "guid=" + this._params.taskId,
        url: "/tests.asmx/GetRightAnswer",
        //url: "GetRightAnswer.xml",
        callback: function(respXml){
        	var aAnswers = respXml.getElementsByTagName("answer");
        	var oAnswer = aAnswers[0];
        	instance.setAnswer(oAnswer);
        }
    });
}*/

Task_Module_Abstract.prototype.setAnswer = function(answerXml)
{
	alert("Возможность не реализована для этого типа задания");
}

/*Task_Module_Abstract.prototype.answer = function()
{
    var instance = this;
    
    this._showLoading();
    
    ProcessAjax({
        method: "GET",
        data: 'answer=' + this._getAnswerString() + "&taskId=" + this._params.taskId + "&typeId=" + this._taskType,
        url: "/tests.asmx/CheckAnswer",
        //url: "/CheckAnswer.xml",
        callback: function(respXml){
        	instance._hideLoading();
        	instance.setDisabled();
            instance.panel.showAnswer( respXml );
        }
    });
}*/

Task_Module_Abstract.prototype._createAnswerXml = function(right)
{
    var sXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><answer right=\"" + right + "\" /></root>";
    
    // Mozilla and Netscape browsers
    if (document.implementation.createDocument) 
    {
        var parser = new DOMParser();
        doc = parser.parseFromString(sXml, "text/xml");
    // MSIE
    } else if (window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(sXml);
    }
    
    return doc;
}

/*Task_Module_Abstract.prototype._showClientHelp = function(variantNums)
{
	oClientHelpWindow = new Help_Client_Window();
	
	var oTitle = Rup.create("h3");
	oTitle.innerHTML = "Ваш ответ неправильный";
	
	oClientHelpWindow.appendChild(oTitle);
	
	var sHelpId = this._dataXml.getAttribute("helpid");
	var aHelpId = sHelpId.split("|");

	var aShowHelpItems = [];

	for( var j = 0; j < variantNums.length; j++ )
	{
		var variantNum = variantNums[j];
		
		var aVariantId = aHelpId[ variantNum ].split(";");
		
		for( var i = 0; i < aVariantId.length; i++ )
		{
			if( aShowHelpItems.indexOf(aVariantId[i]) == -1 )
			{
				aShowHelpItems.push(aVariantId[i]);
			}
		}
	}
	
	for (var idNum = 0; idNum < aShowHelpItems.length; idNum++)
	{ // именно так - наружный цикл пробегает по aShowHelpItems, а внутренний по _helpItems. Наоборот нельзя - будет неверный порядок блоков
    	for( var i = 0; i < this._helpItems.length; i++ )
	    {
		    sCurId = this._helpItems[i].getAttribute("helpid");
    		if( aShowHelpItems[idNum] == sCurId )
	    	{   
		    	oClientHelpWindow.appendChild(Node_Factory.get(this._helpItems[i]));
		    	// без break т.к. может быть несколько узлов с одинаковым helpid
		    }
	    }
	}
}*/
