﻿/*

Copyright (c) 2009 INGHENIA URUGUAY S.R.L
ALL RIGHTS RESERVED

Programmed by Daniel Guerriero for  http://www.inghenia.com/wordpress

Publishing or Running this script from another site is explicitly forbidden

*/

var SW_Item_Ptr = 0;
var SWOT_Groups;

var pic1= new Image(16,10); 
pic1.src="transparent.gif"; 

var pic2= new Image(9,9); 
pic2.src="plus.gif"; 

var pic3= new Image(9,9); 
pic3.src="minus.gif"; 

var pic4= new Image(380,16); 
pic4.src="gradient.png"; 

function SWOT_Init() {
	SWOT_Groups =  new Array(
	  new SWOT_Group(0, SW_TERM.IFACT, SW_TERM.WEAK, SW_TERM.STRE, new Array()),
	  new SWOT_Group(1, SW_TERM.EFACT, SW_TERM.THRE, SW_TERM.OPOR, new Array()));
}

function SWOT_Group(id, centerCaption, leftCaption, rightCaption, items) {
	this.Id = id;
	this.CenterCaption = centerCaption;
	this.LeftCaption = leftCaption;
	this.RightCaption = rightCaption;
	this.Items = items;

	this.Average = function() {
		var sum = 0;
		var count = 0;
		for (var i=0;i < this.Items.length;i++){
			if (!this.Items[i].IsCategory && this.Items[i].Value != 0) {
				count++;
				sum += this.Items[i].Value;
			}
		}
		if (count == 0) return 0;
		else return sum / count;
	
	}

	this.DrawItems = function(DIVId) {
		var html = "";
		html += "<table class='SWOTMain'  cellpadding='0' cellspacing='0'>";
		html += "<tr><td class='SWOTMainHeader'><span style='float:left'>"+this.LeftCaption+"</span><b>"+this.CenterCaption+"</b><span style='float:right'>"+this.RightCaption+"</span></td></tr>";
		for (var i=0;i < this.Items.length;i++){
			html += this.Items[i].DrawItem(this.Id);
		}
		html += "</table>";
		document.getElementById(DIVId).innerHTML = html;
	}
	
	this.setImportedValues = function() {
		for (var i=0;i < this.Items.length;i++){
			if(!this.Items[i].IsCategory) this.Items[i].setValue(this.Items[i].ImportedValue);
		}
	}
	
	this.getItem = function(itemId) {
		for (var i=0;i < this.Items.length;i++){
			if (this.Items[i].Id == itemId) return this.Items[i];
		}
	}

	this.DimensionSurvey = function() {
	    var goodMatrix = "";
	    var badMatrix = "";
	    var retData = "";

	    for (var i = 0; i < this.Items.length; i++) {
	        if (this.Items[i].Value < 0) {
	            if (badMatrix != "") badMatrix += ",";
	            badMatrix += this.Items[i].SurveyDescription();
	        } else if (this.Items[i].Value > 0) {
	            if (goodMatrix != "") goodMatrix += ",";
	            goodMatrix += this.Items[i].SurveyDescription();
	        }
	    }

	    var answers = "[1,2,3,4,5,6,7,8,9,10]";

	    if (goodMatrix != "") {
	        retData += "{B}" + this.RightCaption + "{/B}\n";
	        retData += "{I}"+SW_TERM.STEXT+"{/I}\n";
	        retData += "@MATRIX[" + goodMatrix + "]" + answers + "\n";
	        retData += SW_TERM.STEXT2+"[]@TEXT\n";
	        if (badMatrix != "") retData += "@PAGE\n";
	    }

	    if (badMatrix != "") {
	        retData += "{B}" + this.LeftCaption + "{/B}\n";
	        retData += "{I}"+SW_TERM.STEXT+"{/I}\n";
	        retData += "@MATRIX[" + badMatrix + "]" + answers + "\n";
	        retData += SW_TERM.STEXT2+"[]@TEXT\n";
	    }

	    return retData;
	}
	
	this.DimensionData = function() {
	    var retData = "{DIMENSION_" + this.Id + "}\n";
		var empty = true;
	    for (var i = 0; i < this.Items.length; i++) {
			if (this.Items[i].IsCategory) {
	            retData += "@"+this.Items[i].SurveyDescription();
	            retData += "\n";
	        } else if (this.Items[i].Value != 0 || this.Items[i].SurveyDescription().indexOf("*")!=0) {
	            retData += this.Items[i].DataDescription();
	            retData += "\n";
				empty = false;
			}
	    }
		if (empty) return "";
		
	    retData += "{/DIMENSION_" + this.Id + "}\n";
	    return retData;
	}

	this.DimensionReport = function(goodDIV, badDIV) {
	    var goodA = new Array();
	    var badA = new Array();

	    for (var i = 0; i < this.Items.length; i++) {
	        if (this.Items[i].Value < 0) badA.push(this.Items[i]);
	        else if (this.Items[i].Value > 0) goodA.push(this.Items[i]);
	    }

	    goodA.sort(
			function(a, b) {
			    return a.Value < b.Value;
			}
		);

	    badA.sort(
			function(a, b) {
			    return a.Value > b.Value;
			}
		);

	    if (goodA.length > 0) {
	        var goodHTML = "<ul>";
	        var goodTotal = 0;
	        for (var i = 0; i < goodA.length; i++) {
	            goodHTML += goodA[i].ReportDescription();
	            goodTotal += Math.abs(goodA[i].Value);
	        }

	        for (var i = goodA.length; i < badA.length; i++) goodHTML += "<li class='SWOTResultInvisible'>&nbsp;</li>";

	        goodHTML += "<li class='SWOTResultTotal'><span class='SWOTResultNumber'>" + goodTotal + "</span><b>Total</b></li>";
	        goodHTML += "</ul>";
	        document.getElementById(goodDIV).innerHTML = goodHTML;
	    }

	    if (badA.length > 0) {
	        var badHTML = "<ul>";
	        var badTotal = 0;
	        for (var i = 0; i < badA.length; i++) {
	            badHTML += badA[i].ReportDescription();
	            badTotal += Math.abs(badA[i].Value);
	        }

	        for (var i = badA.length; i < goodA.length; i++) badHTML += "<li class='SWOTResultInvisible'>&nbsp;</li>";
	        
	        badHTML += "<li class='SWOTResultTotal'><span class='SWOTResultNumber'>" + badTotal + "</span><b>Total</b></li>";
	        badHTML += "</ul>";
	        document.getElementById(badDIV).innerHTML = badHTML;
	    }
	}
	
	
}

function SWOT_Item(description,category) {
	this.Id = SW_Item_Ptr++;
	this.GroupId = 0;
	this.Name = description;
	this.Description = description;
	this.DescriptionDIV = null;
	this.Value = 0;
	this.IsCategory = false;
	this.Category = null;
	this.ImportedValue = 0;

	if (description.indexOf("@") == 0) {
		this.IsCategory = true;
		this.Description = description.substr(1);
	}
	
	if (category) this.Category = category;

	this.DrawItem = function(groupId) {
		this.GroupId = groupId;
		var html = "";
		var expr = "SW_"+this.GroupId+"_CEDIV_"+this.Id;
		
		if (this.IsCategory) {
			html += "<tr>";
			html += "<td class='SWOTSubtitle'>";
			html += "<img id='SW_IMG_CAT_"+this.GroupId+"_"+this.Id+"' src='plus.gif' width='9' height='9' onclick='SWOT_OT_Col("+this.GroupId+","+this.Id+")' style='cursor:pointer;float:right; padding-right:5px;padding-top:2px'/>";
			html += "<span class='SWOTEditableItem' id='"+expr+"' contentEditable>"+this.Description+"</span>";
			html += "</td></tr>";
		} else {
			var catExp = "SW_Category_"+this.GroupId+this.Category;
		
			if (this.Category) html += "<tr style='display:none' class='"+catExp+"'><td>";
			else html +="<tr><td>";

			html += "<div class='SWOTEditableItem' id='"+expr+"' contentEditable>"+this.Description+"</div>";
			html += "</td></tr>";
			
			if (this.Category) html += "<tr style='display:none' class='"+catExp+"'><td>"+this.DrawLine()+"</td></tr>";
			else html += "<tr><td>"+this.DrawLine()+"</td></tr>";
		}
		
		return html;
	}
	
	this.ReportDescription = function() {
		var expr = "SW_"+this.GroupId+"_CEDIV_"+this.Id;
		return "<li><span class='SWOTResultNumber'>" + Math.abs(this.Value) + "</span>" + trimCR(document.getElementById(expr).innerHTML) + "</li>";
	}

	this.SurveyDescription = function() {
		var expr = "SW_"+this.GroupId+"_CEDIV_"+this.Id;
		return BRW_getInnerText(document.getElementById(expr));
	}
	
	this.DataDescription = function() {
		var expr = "SW_"+this.GroupId+"_CEDIV_"+this.Id;
        return trimCR(document.getElementById(expr).innerHTML) + " [" + this.Value + "]";
	}
	
	this.DrawLine = function() {
		var html = "";
		var expr;
		html += "<table class='SWOT' cellpadding='0' cellspacing='0'>";
		html += "<tr>";
		for (var i=-10; i<=10;i++){
			expr = "SW_"+this.GroupId+"_TD_"+this.Id+"_"+i;
			
			var color = "white";
			if (i == 0) color = "transparent";
			html +="<td width='16' title='"+i+"' style='height:10px;font-size:10%;background:"+color+"' onclick='SWOTClick("+this.Id+","+i+","+this.GroupId+")' id='"+expr+"'>&nbsp;</td>";
		}

		html += "</tr>";
		html += "</table>";
		
		return html;
	}
	
	this.setValue = function(value) {
		this.Value = value;
		var expr;
		for (var i=-10; i<=10;i++){
			var color = "transparent";
			expr = "SW_"+this.GroupId+"_TD_"+this.Id+"_"+i;
			
			if (value >= 0 && i < 0) color = "white";
			else if (value >= 0 && i > value) color = "white";
			else if (value < 0 && i > 0) color = "white";
			else if (value < 0 && i < value) color = "white";
			
			document.getElementById(expr).style.backgroundColor=color;
		}	
	}
}

// handlers
function SWOTClick(LineId,Col,GroupId) {
	SWOT_Groups[GroupId].getItem(LineId).setValue(Col);
}

function SWOT_OT_Col(GroupId,LineId) {
	if (document.getElementsByClassName) {
		var child = document.getElementsByClassName("SW_Category_"+GroupId+SWOT_Groups[GroupId].getItem(LineId).Name);
		for (var i=0;i<child.length;i++) {
			child[i].style.display = (child[i].style.display == "none"?"":"none");
		}
	} else {
	    // the slow way for IE...
	    var child = document.getElementsByTagName("tr");
		for (var i=0;i<child.length;i++) {
			if (child[i].className == "SW_Category_"+GroupId+SWOT_Groups[GroupId].getItem(LineId).Name)
				child[i].style.display = (child[i].style.display == "none"?"":"none");
		}		
	}
	var img = document.getElementById("SW_IMG_CAT_"+GroupId+"_"+LineId);
	if (img.src.indexOf("plus") != -1) img.src = "minus.gif";
	else img.src = "plus.gif";
}

function SWOT_GenerateSWOT() {
	SWOT_Groups[0].DimensionReport("SWOT_S","SWOT_W");
	SWOT_Groups[1].DimensionReport("SWOT_O","SWOT_T");
}

// data i/o

function SWOT_GenerateDATA() {
    document.getElementById("SWOT_DataData").value = SWOT_Groups[0].DimensionData() + SWOT_Groups[1].DimensionData();
	if (document.getElementById("SWOT_DataData").value == "") document.getElementById("SWOT_DataData").value="-"+SW_TERM.NODATA+"-";
}

function SWOT_Import() {
    var toImport = document.getElementById("SWOT_DataData").value;
	SW_Item_Ptr = 0;
	try {
		SWOT_Import_Dimension(0,GetElementValue(toImport,"DIMENSION_0").split("\n"),"SWOT_SW_DIV");
		SWOT_Import_Dimension(1,GetElementValue(toImport,"DIMENSION_1").split("\n"),"SWOT_OT_DIV");
		SWOT_OptionSelected("SWO_Input");
	} catch(ex) {
		alert(ex);
	}
}

function SWOT_Category_Exists(catName,items) {
    for (var i = 0; i < items.length; i++) {
        if (items[i].IsCategory && items[i].Name == catName) throw (SW_TERM.SDUPL+": " + catName);
    }

}

function SWOT_Import_Dimension(group,dimData,div) {
	try {
		document.getElementById(div).innerHTML = "";
		SWOT_Groups[group].Items = new Array();
		var LastCat = "";
		for (var i=0;i<dimData.length;i++) {
			if (trim(dimData[i]) != "") {
				if (trim(dimData[i]).indexOf("@") == 0) {
					if (document.getElementById("SWOT_AddBlank").checked && LastCat != "") {
						for (var j=0;j<4;j++) SWOT_Groups[group].Items.push(new SWOT_Item("*",LastCat));
					}
					LastCat = trim(dimData[i]);
					SWOT_Category_Exists(LastCat, SWOT_Groups[group].Items);
					SWOT_Groups[group].Items.push(new SWOT_Item(LastCat));
				} else {
				    if (LastCat == "") throw (SW_TERM.NOCAT);
				    var desc;
				    var value;
				    if (dimData[i].indexOf("[") == -1) {
				        desc = trim(dimData[i]);
				        value = 0;
				    } else {
				        desc = trim(dimData[i].substr(0, dimData[i].lastIndexOf("[")));
				        if (desc == "") throw (dimData[i]);
				        value = trim(dimData[i].substr(dimData[i].lastIndexOf("[") + 1));
				        value = value.substr(0, value.indexOf("]"));
				        if (isNaN(value)) {
				            throw (dimData[i]);
				        } else if (new Number(value) > 10 || new Number(value) < -10) {
				            throw (dimData[i]);
				        }
				    }

					var item = new SWOT_Item(desc,LastCat);
					item.ImportedValue = new Number(value);
					SWOT_Groups[group].Items.push(item);
				}
			}
		}
		if (document.getElementById("SWOT_AddBlank").checked && LastCat != "") {
			for (var j=0;j<4;j++) SWOT_Groups[group].Items.push(new SWOT_Item("*",LastCat));
		}

		SWOT_Groups[group].DrawItems(div);
		SWOT_Groups[group].setImportedValues();
	} catch(ex) {
		throw(SW_TERM.INVALID+" - "+ex);
	}
}

function SWOT_Load() {
	if (!supports_local_storage()) {
		alert(SW_TERM.NOFILE5);
		return;
	}

	var sValue = window.localStorage.getItem("SWOTData");
	if (!sValue) alert(SW_TERM.NOLOCAL);
	else {
		document.getElementById("SWOT_DataData").value = sValue;
		SWOT_Import();
	}
}

function SWOT_Save() {
	if (!supports_local_storage()) {
		alert(SW_TERM.NOFILE5);
		return;
	}
	var sValue = window.localStorage.getItem("SWOTData");
	
	if (sValue) {
		if (!confirm(SW_TERM.OVERWRITE)) return;
	}
	
	var toImport = document.getElementById("SWOT_DataData").value;
	window.localStorage.setItem("SWOTData",toImport);
	alert(SW_TERM.STORED);
}

// chart
function SWOT_GenerateGRAPH() {
	var dim0 = SWOT_Groups[0].Average();
	var dim1 = SWOT_Groups[1].Average();
	SWOT_drawChart(dim0,dim1,450,'SWOT_Chart');
}

  function SWOT_drawChart(dimension0Avg,dimension1Avg, width, canvasEl){
	var canvas = document.getElementById(canvasEl);
	var ctx = canvas.getContext('2d');
	var w=width; var h=width;
	
	var xValue=dimension1Avg;
	var yValue=dimension0Avg;
	
	ctx.save();
	try {
		ctx.clearRect(0,0,w,h);
		
		var stepX = w/20;
		var stepY = h/20;

		ctx.fillStyle = "rgba(255,255,0, .2)";
		ctx.fillRect(0,0,w/2,h/2);
		ctx.fillRect(w/2,h/2,w/2,h/2);
		
		ctx.fillStyle = "rgba(255,0,0, .2)";
		ctx.fillRect(0,h/2,w/2,h/2);

		ctx.fillStyle = "rgba(0,255,0, .2)";
		ctx.fillRect(w/2,0,w/2,h/2);

		ctx.strokeStyle = "rgba(0, 0, 0, 1)";
		ctx.beginPath();
			ctx.moveTo(w/2,0);
			ctx.lineTo(w/2,h);
		
			for (var i=0; i <= h; i+=stepX) {
				ctx.moveTo(w/2-5,i);
				ctx.lineTo(w/2+5,i);
			
			}
		
			ctx.moveTo(0,h/2);
			ctx.lineTo(w,h/2);
			for (var i=0; i <= w; i+=stepY) {
				ctx.moveTo(i, h/2-5);
				ctx.lineTo(i, h/2+5);
			}
		ctx.stroke();

		ctx.translate(w/2, h/2);
		var xTValue = (xValue*stepX); 
		var yTValue = (yValue*stepY)*-1;
		var OxTValue = (10*stepX); 
		var OyTValue = (10*stepY)*-1;

		ctx.beginPath();
			ctx.strokeStyle = "rgba(128, 128, 128, 1)";
			ctx.moveTo(0,yTValue);
			ctx.lineTo(xTValue,yTValue);
			ctx.moveTo(xTValue,0);
			ctx.lineTo(xTValue,yTValue);
		ctx.stroke();
		
		var xDisp = -24;
		if (xValue < 0) xDisp = 24;
		
		var yDisp = -14;
		if (yValue > 0) yDisp = 20;
		
		ctx.textAlign = "center";
		ctx.font = "bold 11px verdana,arial";
		ctx.fillStyle = "rgba(255, 255, 255, .6)";
		ctx.strokeRect(xTValue-15,-12+yDisp,30,16);
		ctx.fillRect(xTValue-15,-12+yDisp,30,16);
		ctx.fillStyle = "rgba(0, 0, 0, 1)";
		if (xValue < 0) ctx.fillStyle = "rgba(255, 0, 0, 1)";
		ctx.fillText(Math.round(xValue*10)/10,xTValue,0+yDisp);
		
		ctx.fillStyle = "rgba(255, 255, 255, .6)";
		ctx.strokeRect(-15+xDisp,yTValue-12,30,16);
		ctx.fillRect(-15+xDisp,yTValue-12,30,16);
		ctx.fillStyle = "rgba(0, 0, 0, 1)";
		if (yValue < 0) ctx.fillStyle = "rgba(255, 0, 0, 1)";
		ctx.fillText(Math.round(yValue*10)/10,0+xDisp,yTValue);


		ctx.beginPath();
			ctx.fillStyle = "rgba(255, 255, 0, .9)";
			ctx.strokeStyle = "rgba(0, 0, 0, .6)";
			ctx.arc(xTValue, yTValue, 10, 0, Math.PI*2, true); 
		ctx.fill();
		//ctx.stroke();

		ctx.beginPath();
			ctx.fillStyle = "rgba(255, 255, 0, .9)";
			ctx.strokeStyle = "rgba(0, 0, 0, .6)";
			ctx.arc(xTValue, yTValue, 10, 0, Math.PI*2, true); 
		//ctx.fill();
		ctx.stroke();

		
		ctx.beginPath();
			ctx.lineWidth = 1;
			ctx.fillStyle = "rgba(0, 255, 0, .6)";
			ctx.strokeStyle = "rgba(0, 0, 0, .6)";
			ctx.arc(OxTValue, OyTValue, stepX, 0, Math.PI*2, true); 
		ctx.fill();
		ctx.stroke();
		
		ctx.beginPath();
			ctx.strokeStyle = "rgba(0, 0, 0, .1)";
			ctx.lineWidth = 1;
			var radio = stepX;
			for (var i=1;i<=30;i++) {
				ctx.arc(OxTValue, OyTValue, radio+=stepX*2, 0, Math.PI*2, true); 
			}
		ctx.stroke();
		
		var arrowEnd = 9.8;
		if (xValue > 9 || yValue > 9) arrowEnd = 10;
		
		var FxTValue = (arrowEnd*stepX); 
		var FyTValue = (arrowEnd*stepY)*-1;

		ctx.beginPath();
			ctx.strokeStyle = "rgba(0, 0, 255, .9)";
			ctx.lineWidth = 2;
			ctx.moveTo(xTValue, yTValue);
			ctx.lineTo(FxTValue, FyTValue);
		ctx.stroke();

		var ady = xValue*-1+arrowEnd;
		var opo = yValue*-1+arrowEnd;
		var angle =Math.atan(ady/opo);

		ctx.save();
		ctx.translate(FxTValue, FyTValue);
		ctx.rotate(angle);
		ctx.beginPath();
			ctx.strokeStyle = "rgba(0, 0, 255, .9)";
			ctx.fillStyle = "rgba(0, 0, 255, .9)";
			ctx.moveTo(0, 0);
			ctx.lineTo(8,15);
			ctx.lineTo(-8,15);
			ctx.lineTo(0, 0);
		ctx.fill();
		ctx.restore();
	} catch(ex) {
	;
	}
	
	ctx.restore();

}

// survey

function SWOT_GenerateSURVEY() {
	var isokey = SWOT_Groups[0].DimensionSurvey();
	if (isokey != "") isokey += "@PAGE\n";
	
	isokey += SWOT_Groups[1].DimensionSurvey();
	if (isokey != "") {
		isokey = "@NONUMBER\n"+isokey;
		document.getElementById("SWOT_DataSurvey").value = isokey;
	} else document.getElementById("SWOT_DataSurvey").value="-"+SW_TERM.NODATA+"-";
	
}

// util

function supports_local_storage() {
	return (typeof window.localStorage != 'undefined');
}
function trim(str) {
	return str.replace(/^\s*|\s*$/g, "");
} 
function GetElementValue(InStr, Tag) {
	var pattern = "{" + Tag + "}(([^{]|\n)*){/" + Tag + "}";
	var re = new RegExp(pattern, "m");
	var arr = re.exec(InStr);

	if (arr != null) return arr[1];
	else throw(SW_TERM.INVALID2);
}

function BRW_getInnerText(obj) {
    var str = (obj.innerText) ? obj.innerText : (obj.textContent) ? obj.textContent : "";
    str = str.replace(String.fromCharCode(160), ' ');
	str = str.replace(/\r\n/g, " ");
	return str;
}

function trimCR(str) {
	str = str.replace(/\r\n/g, " ");
	return str;
}

// menu

function SWOT_OptionSelected(option) {
	var MenuOptions = new Array("SWO_Input","SWO_Table","SWO_Graph","SWO_Data","SWO_Survey","SWO_About");
	
	for (var i=0;i < MenuOptions.length; i++ ) {
		document.getElementById(MenuOptions[i]).className = "";
		document.getElementById(MenuOptions[i]+"_Panel").style.display = "none";
	}

    document.getElementById(option).className = "selected";
    document.getElementById(option + "_Panel").style.display = "";

    if (option == "SWO_Table") SWOT_GenerateSWOT();
    if (option == "SWO_Data") SWOT_GenerateDATA();
	if (option == "SWO_Survey") SWOT_GenerateSURVEY();
	if (option == "SWO_Graph") SWOT_GenerateGRAPH();

}
