/////////////////////////////////////////////////////////////////////////////////////////

function csvWrapQuotes(ptext)
{
	if(typeof ptext === 'undefined' || ptext == "" || ptext == null)
		return "\"\"";
	else {
		ptext = ptext.trim();
		if(ptext.indexOf("\"") > -1) {
			while (ptext.indexOf("\"") > -1)
				ptext = ptext.replace("\"", "{{^&}}")
			while (ptext.indexOf("{{^&}}") > -1)
				ptext = ptext.replace("{{^&}}", "\"\"")
			return '"' + ptext + '"';
		}
		if (ptext.indexOf(",") > -1 || ptext.indexOf("'") > -1)
		   return '"' + ptext + '"';
		 return ptext;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
// Download local data from a grid. The server is used only for getting back the
// data as a download.

function downloadDomainGrid(gridid, rowtype, colmode, filename)
{
	var rowText = "";
	var tablecolumns = [];
	var columns = jQuery("#"+gridid).getGridParam("colModel");
	var colnum = columns.length;
	
	var rowkey = null;
	if(rowtype == SELECTED_GRID_ROWS)
		rowkey = jQuery("#"+gridid).getGridParam("selarrrow");
	else
		rowkey  = jQuery("#"+gridid).getDataIDs(); 
	
	// Get the heading Row
	if(colmode == "grid") {
		for(i = 0; i < colnum; i++) {
			if(columns[i].name != "rn" && columns[i].name != "cb" && columns[i].name != "r_h_disp" && columns[i].name != "subgrid") {
				tablecolumns.push(columns[i].name);
				var label = columns[i].label;
				rowText += csvWrapQuotes(label);
				if(i !== (colnum-1))
					rowText += ",";
				else
					rowText += "\n";
			}
		}
	}
	
	var clen = tablecolumns.length;
	var rl = rowkey.length;
	for(i = 0; i < rl; i++) {
		var rowData = jQuery("#"+gridid).jqGrid ('getRowData', rowkey[i]);
		if(colmode == "grid") {
			for(j = 0; j < clen; j++) {
				if (typeof tablecolumns[j] != 'undefined') {
					var entry = rowData[tablecolumns[j]];
					rowText += csvWrapQuotes(entry);
				}
				else
					rowText += "-";
				if(j != (clen-1))
					rowText += ",";
				else
					rowText += "\n";
			}
		}
		else if(typeof rowData[colmode] != "undefined" && colmode != "all")
			rowText += rowData[colmode] + "\n";
	}
	
	var posturl = app_root_url + api_url_path;
	posturl += "?c=download&t=post";
	if(colmode != "all" && colmode != "grid") {
		posturl += "&mode=txt";
		if(filename == "")
			filename = "domain-data.txt";
	}
	if(filename == "")
		filename = "domain-data.csv";
	posturl += "&filename=" + encodeURIComponent(filename);
	$("#csvdownload").append('<form id="exportform" action="' + posturl + '" method="post"><input type="hidden" id="export" name="export"></form>');
    $("#export").val(rowText);
    $("#exportform").submit().remove();
    return true; 
}