﻿//javascript File
var sQuestionTextBeforeKeyPress = "";
var sPreviousQuestionText = "";
var sHTTPPrefix = "http://";
if (location.host.substr(0, 3) == "www") sHTTPPrefix += "www.";
var sSitePrefix = sHTTPPrefix + "genon.ru/";
var sGetSimilarQuestionsFile = sSitePrefix + "GetSimilarQWithA.aspx";
var isSwitchToQuestionText = false;
var iFrameReloadRequests = 0;
var SuggestedQuestionsDivTop = 0;
var SuggestedQuestionsDivLeft = 0;
var SuggestedQuestionsSelectHasFocus = false;
var SpanWithScript = null;
var SpanTag = null;
var QuestionsArray = [];
var oQuestionText = null;
var randOfRequest = "";
var randOfResponse = "";
var selectListDependedObject = null;
var _selectedQuestionIndex = -1;
var DefaultQuestionText = "Задайте вопрос";

window.onresize = function ()
{
    RefreshSuggestedQuestionsDiv(document.getElementById("SuggestedQuestionsDiv").innerHTML);
}

window.onload = function ()
{
    oQuestionText = document.forms[0].QuestionText;
    try
    {
        oQuestionText.focus();
    }
    catch(ex) {}
}

function GetListStyleName(index, selected)
{
	if (selected)
   		return "questionSelected";
	else
	{
   		if (QuestionsArray[index][3] < 2)
   			return "questionList";
   		else return "questionListGrey";
	}
}

function HighlightMatches(text, expr)
{
    var words = expr.split(" ");
    var copy = text;
    for (var i = 0; i < words.length; i++)
        copy = copy.replace(RegExp("(" + words[i] + ")", "i"), "<B>$1" + "</B>");

    return copy;
}

function PrepareQuestionText(sQuestionText)
{
	sQuestionText = sQuestionText.replace(/\s/g, " ");
	sQuestionText = sQuestionText.replace("</genon_var>", "")
	sQuestionText = sQuestionText.replace("<genon_var id=\"VarTitle\">", "")
	sQuestionText = sQuestionText.replace(/<genon_var id=\"VarId\" value=\"[^\"]*\"\/>/i, "");
	sQuestionText = sQuestionText.replace(/ +/g, " ");
	sQuestionText = sQuestionText.replace(/^ +/g, "");
	sQuestionText = sQuestionText.substr(0, 500);
	return sQuestionText;
}

function getCursorPosition(oInput) {
    if (typeof(oInput.selectionStart) != "undefined")
        return oInput.selectionStart;
    else if (document.selection)
        return Math.abs(document.selection.createRange().moveStart("character", -1000000));
}

function setCursorPosition(oInput, iStart, iEnd) {
	if (oInput.setSelectionRange)
	{
		oInput.setSelectionRange(iStart, iEnd);
	} 
	else if (oInput.createTextRange)
	{
		range = oInput.createTextRange();
		range.collapse(true);
		range.moveEnd('character', iStart);
		range.moveStart('character', iEnd);
		range.select();
	}
}

function SaveQuestionTextBeforeKeyPress(event, oQuestion)
{
	sQuestionTextBeforeKeyPress = oQuestion.value;
	if (event.keyCode == 13) //enter key
	{
	    document.forms[0].onsubmit = function ()
        {
            return false;
        }
    }
}

function SuggestSimilarQuestions(event, oQuestion) {
	var sQuestionText = oQuestion.value;
	if (sQuestionText == DefaultQuestionText) return;
	if (event.keyCode == 40) //down key
	{
		isSwitchToQuestionText = false;
	    var suggestedQuestionsSelect = document.getElementById("SuggestedQuestionsSelect");
	    if (!suggestedQuestionsSelect && oQuestionText.value != "")
	    {
	    	SimilarQuestionsFrameLoad(1);
	    	suggestedQuestionsSelect = document.getElementById("SuggestedQuestionsSelect");
	    }

	    if (suggestedQuestionsSelect)
	    {
			suggestedQuestionsSelect.childNodes[0].focus();
			SetSelectedQuestion(event, 0);
		}

		return false;
	}
	if (event.keyCode == 27) oQuestionText.value = ""; // esc key
	if (event.keyCode == 13) //enter key
	{
	    GetAnswer(oQuestionText.value, document.forms[0].QuestionId.value, document.forms[0].AnswerId.value);
	}
	var sUrl = "about:blank";
	var qtl = sQuestionText.length;
	sQuestionText = PrepareQuestionText(sQuestionText);
	if (sQuestionText == "") {
	    QuestionsArray = [];
		RefreshSuggestedQuestionsDiv("");
		return false;
	}
	if (sQuestionText == sQuestionTextBeforeKeyPress) return false;
	document.forms[0].QuestionId.value = "";
	document.forms[0].AnswerId.value = "";
	var cp = getCursorPosition(oQuestion);
	oQuestion.value = sQuestionText;
	setCursorPosition(oQuestion, cp - (qtl - sQuestionText.length), cp - (qtl - sQuestionText.length));
	if (sQuestionText.length > 1) {
		sPreviousQuestionText = sQuestionText;
		sQuestionText = escape(sQuestionText);
		var exactMatch = false;
		if (document.forms[0].ExactMatch) exactMatch = document.forms[0].ExactMatch.checked;
		var searchOnlyInPersonal = false;
		if (document.forms[0].SearchOnlyInPersonal) searchOnlyInPersonal = document.forms[0].SearchOnlyInPersonal.value;
	    randOfRequest = Math.random() + "";
		sUrl = sGetSimilarQuestionsFile + "?qt=" + sQuestionText + "&soip=" + searchOnlyInPersonal + "&em=" + exactMatch + "&rand=" + randOfRequest;
		iFrameReloadRequests++;
		window.setTimeout("UpdateSimilarQuestionsFrame('" + sUrl + "')", 500);
	}
}

function OnQuestionList_KeyDown(event, listItem)
{
	if (event.keyCode == 40 && _selectedQuestionIndex >= 0 && _selectedQuestionIndex < QuestionsArray.length - 1)
	{
		SetSelectedQuestion(event, _selectedQuestionIndex + 1);
	}

    if (event.keyCode == 38 && _selectedQuestionIndex >= 0) //up key
    {
    	if (_selectedQuestionIndex == 0)
    	{
    		if (selectListDependedObject != null) selectListDependedObject.disabled = "disabled";
    		isSwitchToQuestionText = true;
    	}

    	SetSelectedQuestion(event, _selectedQuestionIndex - 1);

    	if (_selectedQuestionIndex == -1)
    	{
    		SuggestedQuestionsSelectHasFocus = false;
    		oQuestionText.focus();
    	}
    }

    if (event.keyCode == 13 && _selectedQuestionIndex >= 0) //enter key
    {
	    oQuestionText.focus();
	    GetAnswer(oQuestionText.value, document.forms[0].QuestionId.value, document.forms[0].AnswerId.value);
	    return false;
	}

	if (event.keyCode == 38 || event.keyCode == 40)
	{
	    CancelEvent(event);
	    return false;
	}
}

function SetSelectedQuestion(event, index)
{
	_selectedQuestionIndex = index;
	if (index > -1)
	{
		document.forms[0].QuestionId.value = QuestionsArray[_selectedQuestionIndex][1];
		document.forms[0].AnswerId.value = QuestionsArray[_selectedQuestionIndex][2];
		oQuestionText.value = PrepareQuestionText(QuestionsArray[_selectedQuestionIndex][0].replace(/\?+$/g, ""));
		SuggestedQuestionsSelectHasFocus = true;
		SuggestedQuestionsSelect_Change(event, document.getElementById("SuggestedQuestionsSelect"));
	}
	else
	{
		document.forms[0].QuestionId.value = "";
		document.forms[0].AnswerId.value = "";

		var list = document.getElementById("SuggestedQuestionsSelect");
		for (var i = 0; i < list.childNodes.length; i++)
			list.childNodes[i].className = GetListStyleName(i, false);

		oQuestionText.value = sQuestionTextBeforeKeyPress;
		oQuestionText.focus();
	}
}

function SuggestedQuestionsSelect_Click(event, listItem) 
{
    oQuestionText.value = listItem.title;
    SetSelectedQuestion(event, listItem.value);
}

function SuggestedQuestionsSelect_DblClick(event, listItem)
{
	oQuestionText.value = listItem.title.replace(/\?+$/g, "");
	SetSelectedQuestion(event, listItem.value);
    GetAnswer(oQuestionText.value, document.forms[0].QuestionId.value, document.forms[0].AnswerId.value);
}

function SuggestedQuestionsSelect_Change(event, list)
{
    if (selectListDependedObject != null) selectListDependedObject.disabled = "disabled";
    if (!isSwitchToQuestionText) 
    {
        if (_selectedQuestionIndex >= 0)
        {
            for (var i = 0; i < list.childNodes.length; i++)
            {
                if (list.childNodes[i].value != _selectedQuestionIndex)
                	list.childNodes[i].className = GetListStyleName(i, false);
                else
                {
                	list.childNodes[i].className = GetListStyleName(i, true);
                	list.childNodes[i].focus();
                }
            }
            //event.cancelBubble = true;
            if (selectListDependedObject != null)
            {
                if (qText != "") {
                	if (document.getElementById("_searchInPublished")) {
                		if (document.getElementById("_searchInPublished").checked) {
                			selectListDependedObject.disabled = null;
                			selectListDependedObject.style.visibility = "visible";
                		}
                	}
                }
			}
        }
    }
    else
    {
        SetSelectedQuestion(event, -1);
        isSwitchToQuestionText = false;
    }
}

function UpdateSimilarQuestionsFrame(sHref)
{
    if (iFrameReloadRequests == 1)
    {
        with (document) {
            SpanTag = createElement("SPAN");
            SpanTag.style.display = "none";
            body.appendChild(SpanTag);
            SpanTag.innerHTML = "&nbsp;<s" + "cript></" + "script>";
            setTimeout(
                function() {
                    var ScriptTag = SpanTag.getElementsByTagName("script")[0];
                    ScriptTag.language = "JavaScript";
                    if (ScriptTag.setAttribute) ScriptTag.setAttribute("src", sHref);
                    else ScriptTag.src = sHref;
                }, 20);
            SpanWithScript = SpanTag;
        }
    }
    iFrameReloadRequests--;
}

function SimilarQuestionsFrameLoad(oFrame)
{
    if (randOfRequest != randOfResponse) return false;
    var SpanTag = SpanWithScript;
    if (SpanTag) {
        SpanWithScript = null;
        setTimeout(
            function() {
                SpanTag.parentNode.removeChild(SpanTag);
            }, 50);
    }
	var sInnerHTML = "";
	var SaveSuggestedQuestionsSelectHasFocus = SuggestedQuestionsSelectHasFocus;
	if (oFrame.src != "about:blank" && oQuestionText.value.length > 1)
	{
		if (QuestionsArray.length > 0)
		{
			sInnerHTML  = "<div><ul id=\"SuggestedQuestionsSelect\">";
			for(var i = 0; i < QuestionsArray.length; i++)
			{
				var text = PrepareQuestionText(QuestionsArray[i][0]);
			    styleColor = "";
			    //if (QuestionsArray[i][3] == 2) styleColor = "style=\"color: #999999\"";
			    sInnerHTML += "<li hidefocus=\"false\" value=\"" + i + "\" " + styleColor
                + "title=\"" + text + "\" "
                + "onclick=\"SuggestedQuestionsSelect_Click(event, this)\" "
			    + "ondblclick=\"SuggestedQuestionsSelect_DblClick(event, this)\" "
			    + "onkeydown=\"OnQuestionList_KeyDown(event, this)\" "
			    + "onkeypress=\"PreventScroll(event, this)\" "
			    + "tabindex=\"" + (200 + i) + "\" "
			    + "onfocus=\"SuggestedQuestionsSelectHasFocus = true\" "
			    + "onblur=\"SuggestedQuestionsSelectHasFocus = false\" "
				+ "class=\"" + GetListStyleName(i, false) + "\" " + ">" + HighlightMatches(text, oQuestionText.value) + "?</li>";
			}
			sInnerHTML += "</ul></div>";
		}
	}
	RefreshSuggestedQuestionsDiv(sInnerHTML);
	var suggestedQuestionsSelect = document.getElementById("SuggestedQuestionsSelect");
	if (suggestedQuestionsSelect && SaveSuggestedQuestionsSelectHasFocus && _selectedQuestionIndex >= 0)
	    suggestedQuestionsSelect.children[_selectedQuestionIndex].focus();
	return true;
}

function RefreshSuggestedQuestionsDiv(sInnerHTML)
{
    var obj = document.getElementById("SuggestedQuestionsDiv");
    obj.style.display = "none";
	obj.innerHTML = sInnerHTML;
	var suggestedQuestionsSelect = document.getElementById("SuggestedQuestionsSelect");
	obj.style.display = "block";
}

function DisableUnneededFields()
{
    var suggestedQuestionsSelect = document.getElementById("SuggestedQuestionsSelect");
    if (suggestedQuestionsSelect) 
        suggestedQuestionsSelect.disabled = true;
	return true;
}

function CancelEvent(event)
{
	if (event.cancelBubble != null)
		event.cancelBubble = true;
	if (event.stopPropagation)
		event.stopPropagation();
	if (event.preventDefault)
		event.preventDefault();
	event.returnValue = false;
	if (event.cancel != null)
		event.cancel = true;
}

// For Opera
function PreventScroll(event, listItem)
{
	if ((event.keyCode == 38 || event.keyCode == 40) && event.preventDefault)
		event.preventDefault();
}

