﻿function getRateTableHtml(json){
	var html;
	var jsonObj;
	var jsonIsValid = true;
				
	try{
		jsonObj = jQuery.parseJSON(json);
	}
	catch(err){
		jsonIsValid = false;
	}

	if(jsonIsValid){
		if(jsonObj != null){
			var htmlTableStr = convertJSONToHTMLTable(jsonObj);

			if(htmlTableStr != null){
				html = htmlTableStr;
			}
			else{
				html = '<table><tr><td><strong>No rate data is available at this time.</strong></td></tr></table>';
			}
		}
		else{
			html = '<table><tr><td><strong>No rate data is available at this time.</strong></td></tr></table>';
		}
	}
	else{
		html = '<table><tr><td><strong>No rate data is available at this time.</strong></td></tr></table>';
	}
				
	return html;
}
			
function convertJSONToHTMLTable(data) {
	var html = '<table>';
				
	var rowsProcessed = 0;
	$.each(data, function(rowPosition, columns) {
			html += '<tr>';

			columnPosition = 0;						
			$.each(columns, function(columnName, value) {							
				if(rowPosition == 0 && columnPosition == 0){
				  value = '&nbsp;';
				}
							
				if(rowPosition == 0){
					html += '<th>' + value + '</th>';
				}
				else{
					if(columnPosition == 0){
						html += '<td class="first">' + value + '</td>';
					}
					else{
						html += '<td class="data">' + value + '</td>';
					}
				}			
							
				columnPosition++;
			});
        
			html += '</tr>';
			rowsProcessed++;
	});

	html += '</table>';
				
	if(rowsProcessed == 0){
		html = null;
	}
				
	return html;

}

function insertParam(key, value) {
  key = escape(key); value = escape(value);
  var kvp = document.location.search.substr(1).split('&');
  var i = kvp.length; var x; while (i--) {
    x = kvp[i].split('=');
    if (x[0] == key) {
      x[1] = value;
      kvp[i] = x.join('=');
      break;
    }
  }
  if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
  //this will reload the page, it's likely better to store this until finished
  document.location.search = kvp.join('&');
}
