var xmlHttp;
var arrGlossaryTerms = null;
var dispatcherURL = "/DesktopModules/BSWeb.QNA/Dispatcher.aspx";

function MinMax(obj,source)
{
	if ($(source).style.display == "none") {
		obj.src= "/Portals/0/media/KB/minus.png";
		$(source).style.display = "block";
	} else {
		obj.src= "/Portals/0/media/KB/plus.png";
		$(source).style.display = "none";
		
		var arr = $(source).getElementsByTagName("DIV");
		for (var i = 0; i < arr.length; i++){
			if (arr[i].id.indexOf("objDiv") != -1) {
				$(arr[i]).style.display = "none";
			}
		}
		var arr = $(source).getElementsByTagName("img");
		for (var i = 0; i < arr.length; i++){
			if (arr[i].id.indexOf("imgStatus") != -1) {
				$(arr[i]).src= "/Portals/0/media/KB/plus.png";
			}
		}
	}
}

function MinMaxFile(obj,source,fn)
{
	fn = decodeURIComponent(fn);
	if ($(source).style.display == "none") {
		obj.src= "/Portals/0/media/KB/minus.png";
		$(source).style.display = "block";
		fn = fn.replace(/'/g, "\'");
		fn = "Data" + encodeURIComponent(fn);
		var pars = "Action=GetFileContent&FileName=\'" + fn + "\'";
		useDispatcher(source, pars);
		
	} else {
		obj.src= "/Portals/0/media/KB/plus.png";
		$(source).style.display = "none";
	}
}


function useDispatcher(source, pars, fname)
{
	/*if($("imgLoading")) $("imgLoading").show();*/
	loadingON(false);
	var myAjax = new Ajax.Updater(source, dispatcherURL, {method: 'post', parameters: pars, onComplete: function(){ loadingOFF(false); }} );
}



function expandAll(source)
{
	var arr = getParent(source).getElementsByTagName("DIV");
	for (var i = 0; i < arr.length; i++)
		if (arr[i].id != "" && arr[i].id.indexOf("Content") != -1)
		{
			arr[i].getElementsByTagName("DIV")[0].style.display = "none";
		    arr[i].getElementsByTagName("IMG")[0].onclick();
		}
}

function collapseAll(source)
{
	var arr = getParent(source).getElementsByTagName("DIV");
	for (var i = 0; i < arr.length; i++)
		if (arr[i].id != "" && arr[i].id.indexOf("Content") != -1)
		{
			arr[i].getElementsByTagName("DIV")[0].style.display = "block";
			arr[i].getElementsByTagName("IMG")[0].onclick();
		}
}

function getParent(source)
{
	var obj = source;
	while (true){
		if (obj.tagName == "DIV" && obj.id.indexOf("Content") != -1) break;
		obj = obj.parentNode;
	}
	
	return obj;
}

function showTooltip(obj)
{
	var tmp = getTooltipLayer();
	
	var text = obj.title;
	
	if (!tmp)
	{
		var newlayer = document.createElement("DIV");
		newlayer.id = "TooltipLayer";
		newlayer.style.position = "absolute";
		newlayer.style.zIndex = 20;
		newlayer.style.left = 0;
		newlayer.style.top = 0;
		document.getElementsByTagName("body")[0].appendChild(newlayer);
		tmp = getTooltipLayer();
	}
	
	var x = 0;
	var y = 0;

	pageY = 0; pageX = 0;
	par = obj;
	while (par)
	{	
		pageY += par.offsetTop;
		pageX += par.offsetLeft;
		par = par.offsetParent;
	}
	
	sl = document.body.scrollLeft; 
	st = document.body.scrollTop || document.documentElement.scrollTop;
	
    //obj.oldtitle = obj.title;
	//obj.title = "";
	$("TooltipLayer").innerHTML = setTooltip(text);
	$("TooltipLayer").style.display = "block";
    
    var intX = screen.width - (sl + pageX + 250);
	   
    $("TooltipLayer").style.left = sl + pageX + ((intX < 0) ? (intX-50) : 0) + 'px';
    $("TooltipLayer").style.top = pageY + obj.offsetHeight + 'px';
}

function setTooltip(tip)
{
	var s = "";
	
    s += "<div style='background-color: #FEE7DD; width: 250px; margin: 0px; padding: 0px 5px 5px 5px; white-space: normal; vertical-align: top;border: 1px #F15D22 solid; line-height: 15px;'><font style='font-family: verdana; font-size: 11px; color: #143156;'>";
    s += tip;
    s += "</font>";
    s += "<br />" + "<a href='javascript:void(0);' onclick='hideTooltip();' style='padding-left: 100px; padding-bottom: 5px;'>Close</a>";
    s += "</div>";

	return s;
}

function hideTooltip(obj)
{
	//obj.title = obj.oldtitle;
	document.getElementById("TooltipLayer").innerHTML = "";
	document.getElementById('TooltipLayer').style.display = "none";
}

function getTooltipLayer()
{
	return document.getElementById('TooltipLayer');
}

function createTermsArray()
{
	arrGlossaryTerms = new Array();
	/*var arr = $$("DIV");*/
	var arr = document.getElementsByTagName("DIV")
	for (var i = 0, j = 0; i < arr.length; i++)
		if (arr[i].id != "" && arr[i].id.indexOf("divTermContent") != -1)
		{
			arrGlossaryTerms[j] = new Array();
			arrGlossaryTerms[j][0] = arr[i].getElementsByTagName("DIV")[0];
			arrGlossaryTerms[j][1] = arr[i].getElementsByTagName("IMG")[0];
			j++;
		}

}

function expand_collapse_AllTerms(action)
{
	if(arrGlossaryTerms == null) createTermsArray();
	for (var i = 0; i < arrGlossaryTerms.length; i++)
	{
		if(action == "expand")
		{
			arrGlossaryTerms[i][1].src= "/Portals/0/media/KB/minus.png";
			arrGlossaryTerms[i][0].style.display = "block";
		}
		else
		{
			arrGlossaryTerms[i][1].src= "/Portals/0/media/KB/plus.png";
			arrGlossaryTerms[i][0].style.display = "none";
		}
	}
}


/*
// Share witth friend
var createNewQnA;
CreateNewQnA = Class.create();

function createNewQnADialog(options)
{
    createNewQnA = new CreateNewQnA(options);
}
*/

function removeQnADialog(options)
{
	if (window.confirm("Delete record. Are you sure?"))
	{
	    var url = '/DesktopModules/BSWeb.QNA/Dispatcher.aspx';
	    var pars = 'Action=Remove';
        pars += "&RecordID=" + options.RecordID;
        pars += "&ParentID=" + options.ParentID;
	    var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars,
			onComplete: showResponse });
	}
}
    
function showResponse(originalRequest)
{
	alert(originalRequest.get_responseData());
	if(originalRequest.getResponseHeader("redirect"))
	{
		location.href=originalRequest.getResponseHeader("redirect");
		return;
	}
}

CreateNewQnA = function(options)
{
	//this.window = new PopupWindow('createNewQnAPopUp', {className: " realtymind", title: "Create new QnA", width:450, height:495});
	var me = this;
	this.options = options;
	this.window = new PopupWindow('/DesktopModules/BSWeb.QNA/html/createnewqna.html', { width: 450, height: 330, className: 'window_modal', title: 'Create new QnA"', cancelId: "cancelbtn", bindData: function() { me.onWindowLoad() } });
	// add hide window observer 
	//Windows.addObserver({ onDestroy: function(){ WindowUtilities.enableScreen('overlay_modal'); } });
	// block all now
	//WindowUtilities.disableScreen(this.window.options.className, 'overlay_modal', this.window.getId());
	//var div_with_features = document.createElement("DIV")
	//div_with_features.className = "realtymind_misc"
	//$("createNewQnAPopUp").appendChild(div_with_features)
	//this.window.setAjaxContent("/DesktopModules/BSWeb.KnowledgeBaseM/html/createnewqna.html?"+Math.random(),{method: 'get'});
	//this.window.setDestroyOnClose();
	//this.window.showCenter();
	
	//this.options = $H(options);
	//if (window.htUI) this.options = this.options.merge($H(window.htUI));
}

function createNewQnADialog(options)
{
    new CreateNewQnA(options);
}

CreateNewQnA.prototype = {

	onWindowLoad: function(){
	
		if(this.options.Title != null) $("txtRecordTitle").value = unescape(this.options.Title);
		if(this.options.Tag != null) $("txtTag").value = this.options.Tag;
		if(this.options.Description != null) $("txtRecordDescription").value = unescape(this.options.Description);
		if(this.options.ID  != null)
		{
		    var url = '/DesktopModules/BSWeb.QNA/Dispatcher.aspx';
			var pars = 'Action=Edit';
			pars += "&RecordID=" + this.options.ID;
			pars += "&ParentID=" + this.options.ParentID;
			var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars,
				onComplete: this.setValues });
		}
		
		var me = this;
        $("savebtn").onclick = function(){me.save();return false;}
        //$("cancelbtn").onclick = function(){me.destroy();return false; }
	},
    
    destroy: function(){
        hideValidationMessage(document);
        this.window.destroy();
    },
    
    save: function(){
        var strResult = validateForm();
        if (strResult != "")
        {
            PopupWindow.alert(strResult);
            return false;
        }
        hideValidationMessage(document);
        var url = '/DesktopModules/BSWeb.QNA/Dispatcher.aspx';
	    var pars = 'Action=Create';
        var inputs = { RecordTitle: "txtRecordTitle", RecordDescription: "txtRecordDescription", RecordTag: "txtTag"  };
        for(var i in inputs){
            pars += "&" + i + "=" + encodeURIComponent($(inputs[i]).value);
        }
        if(this.options.ParentID != null) pars += "&ParentID=" + this.options.ParentID;
        if(this.options.PreviousID != null) pars += "&PreviousID=" + this.options.PreviousID;
        if(this.options.ID != null) pars += "&RecordID=" + this.options.ID;
        
	    $("button_saving").style.display = 'inline';
        //console.log(pars)
		var me = this;
	    var myAjax = new Ajax.Request( url, { method: 'post', parameters: pars,
			onComplete: function(originalRequest){ me.showResponse(originalRequest); }});
    },
    
	/*showError: function(originalRequest,ex){
		var s = ""
	    for(var i in ex){
	        s+=i + ": " + ex[i] + "; ";
	    }
	    alert("Script error while saving:" + s);
		this.window.destroy();
	},*/
    
    showResponse: function(originalRequest){
        $("button_saving").style.display = 'none';        
	    //alert(originalRequest.responseText);
		if(originalRequest.get_responseData() == 'ok'){
            alert("ok");
			if(originalRequest.getResponseHeader("redirect"))
			{
				location.href=originalRequest.getResponseHeader("redirect");
				return;
			}
			this.window.close();
	    }else{
	        alert("Error while saving: " + originalRequest.get_responseData());
	    }
	},
	
	setValues: function(originalRequest){
		if(originalRequest.get_responseData() == 'ok'){
			if(originalRequest.getResponseHeader("RecordTitle"))
			{
				$("txtRecordTitle").value = originalRequest.getResponseHeader("RecordTitle");
			}
			if(originalRequest.getResponseHeader("RecordDescription"))
			{
				$("txtRecordDescription").value = originalRequest.getResponseHeader("RecordDescription");
			}
			if(originalRequest.getResponseHeader("RecordTag"))
			{
				$("txtTag").value = originalRequest.getResponseHeader("RecordTag");
			}
	    }else{
	        alert("Error while saving: " + originalRequest.get_responseData());
	    }
	}
}