/**
 * fsairlines.grid.utils.js
 *
 * Everything concerning the new JQGrid tables for displaying data.
 *
 * @author Claudio Gusmini
 * @version 0.1
 */
var lookup = false;
var gridProps = new Object();

/**
 * Display a grid on a normal page.
 * @param which  The XML file which should be loaded.
 * @param lnk_str  Additional variables which should be attached to the http request.
 * @param options  Additional options for the grid.
 */
function loadTable(which, lnk_str, options){
    if (typeof(lnk_str) == 'undefined') {
        var lnk_str = "";
    }
	if (typeof(options) == 'undefined') {
        gridProps = new Object();
    } else gridProps = options;
    lookup = false;

	createBase(which, which);
    loadGrid(which, '', lnk_str);
}

/**
 * Display a grid in a dialog box.
 * @param which  The XML file which should be loaded.
 * @param takeover  The ID of the element into which the selection should be parsed.
 * @param lnk_str  Additional variables which should be attached to the http request.
 */
function loadLookup(which, takeover, lnk_str, options, dialogOptions){
    if (typeof(lnk_str) == 'undefined') {
        var lnk_str = "";
    }
	if (typeof(options) == 'undefined') {
        gridProps = new Object();
    } else gridProps = options;
	
	if (typeof(dialogOptions) == 'undefined') {
		dialogOptions = new Object();
    }
	
	$.extend(dialogOptions, {
	        width: 'auto',
	        height: 'auto',
	        margin: '0px',
	        position: 'center',
	        modal: true,
	        bgiframe: false,
	        resizable: false
	    });
	
    lookup = true;
    
    
	
	lnk_str += "&takeover="+takeover;

    $('#dialog').dialog(dialogOptions);
    $('#dialog').dialog('open');
    
    $.get("lookups/lookup.php5?which=" + which + "&takeover=" + takeover + " " + lnk_str, function(data){
        $('#dialog').html(data);
		createBase("grid", which);
        loadGrid(which, takeover, lnk_str);
    });
}

function loadDialog(which, lnk_str, options) {
	if (typeof(lnk_str) == 'undefined') {
        var lnk_str = "";
    }
	
	if (typeof(options) == 'undefined') {
        gridProps = new Object();
    }
	
	$.get('dialogs/'+which+'.php5?'+lnk_str, function(data){
        $('#dialog').html(data);
        $('#dialog').dialog(options);
        $('#dialog').dialog('open');
	})
}

/**
 * Creates the table and pager element needed for the grid
 * @param {Object} id  The id of the div in which the grid should be created.
 */
function createBase(id, which) {
	var html = "<table id=\"grid_"+which+"\" class=\"scroll\" cellpadding=\"0\" cellspacing=\"0\"></table>";
	html += "<div id=\"pager_"+which+"\" class=\"scroll\" style=\"text-align:center;\"></div>";

	$("#" + id).html(html);
}

/**
 * Load the grid properties from the XML file.
 * @param which  The XML file which should be loaded.
 * @param takeover  The ID of the element into which the selection should be parsed.
 * @param lnk_str  Additional variables which should be attached to the http request.
 */
function loadGrid(which, takeover, lnk_str){
    $.get('lookups/' + which + '_xml.php?what=grid' + lnk_str, function(data){
        initGrid(which, data, takeover, lnk_str);
    });
}

/**
 * Read all properties from the XML file and create the JQuery Grid.
 * @param which  The XML file which should be loaded.
 * @param data  The response of the HTTP-request, containing all properties in an XML format.
 * @param takeover  The ID of the element into which the selection should be parsed.
 * @param lnk_str  Additional variables which should be attached to the http request.
 */
function initGrid(which, data, takeover, lnk_str){
    // title
    var title = getString(data, "title");
    
    // multiselect
    var selection = getString(data, "selection");
    if (selection == "multiple") var multipleSelect = true;
    else var multipleSelect = false;
    
    
    var pdf = getBoolean(data, "pdf");
    
    // number of columns
    var cols = getInt(data, "cols");
    
    // number of rows
    var rowNum = getInt(data, "rowNum");
    if (rowNum == null) rowNum = 20;
    
    // sort
    var sortname = getString(data, "sortname");
    var sortorder = getString(data, "sortorder");
    if (sortname == null) sortname = "id";
    if (sortorder == null) sortorder = "desc";
    
    // column data
    var columns = data.getElementsByTagName("col");
    
    // the colModel data for jqGrid
    var initColModel = new Array();
    
    // collect data from all columns
    for (currColumn=0; currColumn < cols; currColumn++) {
        // colModel data for this columns
        var colLine = new Array();
        
        colLine['name'] = getString(columns[currColumn], "label");
        
        colLine['index'] = getString(columns[currColumn], "index");
        
        colLine['width'] = getInt(columns[currColumn], "width");
		if (!colLine['width']) colLine['width'] = 100;
		
        colLine['search'] = getBoolean(columns[currColumn], "searchable");
		if (colLine['search'] == null) colLine['search'] = true;
		
		colLine['sortable'] = getBoolean(columns[currColumn], "sortable");
		if (colLine['sortable'] == null) colLine['sortable'] = true;
        
        // write data for this column in colModel
        initColModel.push(colLine);
    }
    if (lookup) 
        $("#dialog").dialog({
            title: title
        });
    
    // TAKEOVER
    // if there is no specific function for double-click, use default takeover
	if (gridProps['ondblClickRow'] == null) {
			gridProps['ondblClickRow'] = function(rowid){
				if (!multipleSelect) 
					takeOver(rowid, takeover);
			};
	}


    
    // Scrollbar width is different in IE (adapt)
    var scrollWidth = 18;
    if (isIE()) 
        scrollWidth = 18;
    
    var options = {
            url: 'lookups/' + which + '_xml.php?what=data' + lnk_str,
            datatype: 'xml',
            mtype: 'GET',
            colModel: initColModel,
            pager: $('#pager_'+which),
            rowNum: rowNum,
            rowList: [10, 20, 30, 40, 50],
            width: 'auto',
            height: 'auto',
            multiselect: multipleSelect,
            sortname: sortname,
            sortorder: sortorder,
            scroll: false,
            imgpath: 'styles/jquery/images',
            viewrecords: true,
            gridview: true,
            altRows: true,
    		altclass: "altrow",
            scrollOffset: scrollWidth,
            ondblClickRow: gridProps['ondblClickRow'],
            gridComplete: function(id) {$('#dialog').dialog('option', 'position', 'center');}
        };
    $.extend(options, gridProps);
    
    // init jqGrid
    var mygrid = $("#grid_"+which).jqGrid(options).navGrid('#pager_'+which, {
        edit: false,
        add: false,
        del: false,
        search: false,
        refresh: false
    });
    
    
	if (multipleSelect) {
		mygrid.navButtonAdd("#pager_"+which, {
            caption: "Take Over",
            title: "Take Over",
            buttonicon: 'ui-icon-check',
            onClickButton: function() { multipleTakeOver(which, takeover); }
        });
	}

	if (pdf) {
		mygrid.navButtonAdd("#pager_"+which, {
	        caption: "PDF",
	        title: "PDF",
	        buttonicon: 'ui-icon-document',
	        onClickButton: function() { window.open('lookups/' + which + '_xml.php?what=pdf' + lnk_str + buildGET(which), title); }
	    });
	}
	
    mygrid.filterToolbar();
}

/**
 * The takeover function for single selection.
 * @param rowid  The ID of the selected row.
 * @param takeover  The ID of the element into which the selection should be parsed.
 */
function takeOver(id, rowid, takeover){
    var cellContent = jQuery("#grid_"+id).getCell(rowid, 0);
    jQuery("#" + takeover).val(cellContent);
    jQuery("#dialog").dialog('close');
}

/**
 * The takeover function for multiple selection.
 * @param takeover  The ID of the element into which the selection should be parsed.
 */
function multipleTakeOver(id, takeover) {
	var takeoverMode;
	var additive = true;
	if(typeof(takeover) == "string") takeoverMode="simple";
	else takeoverMode="complex";
	
	
	var selectedRows = jQuery("#grid_"+id).getGridParam('selarrrow');
    
	var result = "";
	
	// only take over one column
	if (takeoverMode=="simple") {
		result = buildTakeOverFromColumn(id, selectedRows, 1);
		$("#" + takeover).val(result);
	}
	
	// take over multiple columns
	if (takeoverMode=="complex") {
		for (var i=0; i < takeover.length; i+=2) {
			var takeoverCol= takeover[i];
			var takeoverID = takeover[i+1];
			result = buildTakeOverFromColumn(id, selectedRows, takeoverCol);
			
			if (!additive) $("#" + takeoverID).val(result);
			else {
				var val = $("#" + takeoverID).val();
				if (val != "") val += ",";
				$("#" + takeoverID).val(val + result);
			}
		}
	}
	
    $("#dialog").dialog('close');
}


function buildTakeOverFromColumn(id, selectedRows, col) {
	var result = "";
    for (var j=0; j < selectedRows.length; j++) {
        result += $("#grid_"+id).getCell(selectedRows[j], col);
          if (j < selectedRows.length-1) 
            result += ",";
    }
    return result;
}




/**
 * Convert all tables on the current page into JQuery Grids.
 * @param options  A property list with additional JQuery Grid properties.
 */
function convertAllTables(options){
    var scrollWidth = 18;
    if (isIE()) 
        scrollWidth = -18;
    
    var stdOptions = {
        scrollOffset: scrollWidth,
		height: "auto",
		altRows: true,
		altclass: "altrow"
    }
    if (options != null) {
        $.extend(options, stdOptions);
    }
    else 
        var options = stdOptions;
    
    $(document).ready(function(){
        tableToGrid("div#MainText table", options);       
    });
}

/**
 * Convert one table into a JQuery Grid.
 * @param id  The ID of the table element.
 * @param options  A property list with additional JQuery Grid properties.
 */
function convertTable(id, options){
    var scrollWidth = 18;
    if (isIE()) 
        scrollWidth = -12;

    var stdOptions = {
        scrollOffset: scrollWidth,
		height: "auto",
		altRows: true,
		altclass: "altrow"
    };
    
    if (options != null) {
        $.extend(options, stdOptions);
    }
    else 
        var options = stdOptions;
    
    $(document).ready(function(){
		$("#" + id).removeClass();
        tableToGrid("#" + id, options);
    });
}


function buildGET(id) {
	var sidx = $("#grid_"+id).getGridParam('sortname');
	var sord = $("#grid_"+id).getGridParam('sortorder');
	var page = $("#grid_"+id).getGridParam('page');
	var rows = $("#grid_"+id).getGridParam('rowNum');
	var url = $("#grid_"+id).jqGrid('getGridParam','url');
	return "&sidx="+sidx+"&sord="+sord+"&rows="+rows+"&page="+page;
}