$(function() {
// stores our results for uses on button clicks like product datasheets
var resData;

// used to change css on boxes during Q & A
var activeCellCSS = {
	'display'          : 'block',
	'border-color'     : '#e3d165',
	'background-color' : '#fff4b4'
};
var inactiveCellCSS = {
	'display'          : 'block',
	'border-color'     : '#dcdcdc',
	'background-color' : '#f3f3f3'
}
var hiddenCellCSS = {
	'display' : 'none'
}



//
// magic
//
function initEverything() {
	$(".cell, .grid").css( hiddenCellCSS );
	createFlexigrid();

	getNextQuestion('new');
}


//
// makes the grid, use $("#results").flexAddData() for changing contents
//
function createFlexigrid() {
	$("#results").flexigrid({
		dataType: 'json',
		colModel: [
		    { display:'System',           name:'system',           width:70,  sortable:false, align:'left' },
		    { display:'Product',          name:'products',         width:164, sortable:false, align:'left' },
		    { display:'Description',      name:'description',      width:210, sortable:false, align:'left' },
		    { display:'Max Hole Size',    name:'max_hole_size',    width:90,  sortable:false, align:'left' },
		    { display:'Pipe Size',        name:'pipe_size',        width:90,  sortable:false, align:'left' },
		    { display:'Sealant Depth',    name:'sealant_depth',    width:90,  sortable:false, align:'left' },
		    { display:'Backing Material', name:'backing_material', width:100, sortable:false, align:'left' }
		],
		sortname: "system",
		sortorder: "asc",
		singleSelect: true,
		height: 'auto',
		width: 'auto',
		rp: 1000,
		resizeable: false
	}); // end flexigrid
}



//
// gets next question and answers and makes the new box
//
function getNextQuestion(currentPath, currentCellNum) {
	$.getJSON('qa.cgi?a=nextQAInfo&curPath='+currentPath, function(json) {
		// json will have the new question, qNum and answers. qNum of 8 means we have our results
		if (json.qNum == '8') {
			showResults();
			return;
		}
		var curCell = $("#cell" + json.qNum);
		curCell.css( activeCellCSS );
		var html = new Array();
		html.push("" +
			"<strong style='position:absolute;margin-top:3px;'>" + json.question + ": &nbsp;</strong>" + 
			'<select style="float:right;" class="answer" id="' + json.qNum + '_sel">' + 
			'<option value="">Select an option</option>' +
		"");
		$(json.options).each(function(num, answer) {
			html.push('<option value="' + answer + '">' + answer + '</option>');
		});
		html.push("</select>");
		curCell.html( html.join("") ); 

		if (json.numSystems == 1) {
			$("#numSystems").html('Number of systems so far: ' + json.numSystems +'. <a href="#" id="showCurSystems">Show these systems</a>.');
		} else if (json.numSystems > 0) {
			$("#numSystems").html('Number of systems so far: ' + json.numSystems +'. <a href="#" id="showCurSystems">Show these systems</a>.');
		} else {
			$("#numSystems").html("");
		}

		hideLoader();
	}); // end json
} // end getNextQuestion()



//
//
//
$("#showCurSystems").livequery("click", function() {
	showLoader(10);
	showResults();
});



//
// handles changes to the answers, current and new ones
//
$(".answer").livequery('change', function() {
	//if ($(this).val() == "") return;
	var qNum = this.id.split('_')[0];
	showLoader(qNum);
	// blank out everything after selected
	for (var i = ++qNum; i <= 8; i++) {
		if (i < 8) $("#cell" + i).html("");
		$("#cell" + i).css( hiddenCellCSS );
	}
	$(".answer").each(function(num, selBox) {
		var c = $('#cell' + $(this).attr('id').split('_')[0]);
		c.css( inactiveCellCSS );
	});
	getNextQuestion( currentPath(), qNum );
}); // end $(".answer").live(...)



//
// displays all systems for the current path selection
//
function showResults() {
	$("#results").flexAddData({rows:[]});
	$("#numSystems").html("");
	$.getJSON('qa.cgi?a=results&curPath=' + currentPath(), function(json) {
		resData = json;
		$("#results").flexAddData(resData);
		$("#cell8").css('display', 'block');
		// add buttons and stuff
		var html = new Array;
		html.push('<span class="box">Select a system from below and click one of the following buttons to view information on the system.</span>');
		html.push('<br/><br/><br/><br/>');
		html.push('<input type="submit" class="but" name="detail" id="detail" value="System Details" style="margin-right:80px;" />');
		html.push('<select id="selbox">');
		$.each(resData.products, function(num, pro) {
			html.push('<option value="'+ pro.name +'">'+ pro.name +'</option>');
		});
		html.push('</select>');
		html.push('<input type="submit" class="but" name="ds" id="ds" value="Datasheet" style="margin-left:20px;" />');
		html.push('<input type="submit" class="but" name="msds" id="msds" value="MSDS" style="margin-left:20px;" />');
		$("#buttons").html( html.join("") );
		hideLoader();
	}); // end $.getJSON
}


$("#results").livequery("click", function() {
	var sysNum; try { sysNum = $(".trSelected").attr("id").substr(3); } catch(e) { return; }
	var proName = resData.info[sysNum].product;
	$("#selbox option[value='" + proName +"']").attr("selected", "selected");
});


//
// clicking the system details button
//
$("#detail").livequery("click", function() {
	var sysNum; try { sysNum = $(".trSelected").attr("id").substr(3); } catch(e) { return; }
	window.open( resData.info[sysNum].details_url );
});

//
// clicking datasheet button
//
$("#ds").livequery("click", function() {
	window.open( resData.products[ $("#selbox").val() ].ds_url );
});

//
// clicking msds button
// 
$("#msds").livequery("click", function() {
	window.open( resData.products[ $("#selbox").val() ].msds_url );
});



//
// moves spinny thing next to the box number given
//
function showLoader(byCellNum) {
	var cell = $("#cell" + byCellNum);
	$("#loading").offset({
		top:  cell.offset().top,
		left: cell.offset().left + cell.width() + 25
	});
	$("#loading").css('visibility', 'visible');
}
function hideLoader() {
	$("#loading").css('visibility', 'hidden');
}



//
// returns the current selected answers joined with ::
//
function currentPath(asArray) {
	var path = new Array();
	$(".answer").each(function(num, selBox) {
		path.push( $(selBox).val() );
	});

	return (asArray == true) ? path : path.join("::");
}



initEverything();

}); // end of main $()
