/*
 * #########################################################################
 * ##       Copyright � Meta Integration Technology, Inc. 2007            ##
 * ##                        All Rights Reserved.                         ##
 * #########################################################################
 * ##                  http://www.metaintegration.com                     ##
 * #########################################################################
 */
var mbDataMapping = new function () {

	var _iData = {};
	var _eData = {};
	
	
	/**
	 * Show the filtered list of bridges.
	 */
    this.checkForToolReturn = function(event, dir, val) {
        if (event && event.keyCode==13){
			mbBridgeList.requestBridgeList(dir, val);
        }
    };
	/**
	 * Respond to the bridge selection.
	 */
    this.selectTool = function(dir, id) {
    	this.dialog.close();
		this.comboToFill.setValue(id);
		this.comboToFill.fireEvent('select', this.comboToFill);
    };

	 /**
	 * Open lineage for a config when clicked from an icon.
	 */
	 this.selectToolFromIcon = function(dir, id) {
	 	return function() {
	 		mbBridgeList.selectTool(dir, id);
	 	};
	 };

	/**
	 * Get mappings json.
	 */
	this.getMappingForWebsite = function(vvalue) {
		
		// get the mapping from the JSon file...
		var xmlhttp=false;
	    /*@cc_on @*/
	    /*@if (@_jscript_version >= 5)
	    // for old IE...
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	    @end @*/
	    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	    	try {
	    		xmlhttp = new XMLHttpRequest();
	    	} catch (e) {
	    		xmlhttp=false;
	    	}
	    }
	    if (!xmlhttp && window.createRequest) {
	    	try {
	    		xmlhttp = window.createRequest();
	    	} catch (e) {
	    		alert("Cannot create XHR! Please upgrade your browser :-)");
	    	}
	    }
	    xmlhttp.open("GET", "../../Home/MIRDataTypeMapping.json", true);
	    xmlhttp.onreadystatechange=function() {
		    if (xmlhttp.readyState==4) {
		        var json = eval("("+xmlhttp.responseText+")");	
		        processData(json);		        
	    	    fillupDataStoreList();
		    }
	    };
	    xmlhttp.send(null);
	};
	
	/**
	 * Callback to populate the datastore dropdown.
	 */
	var fillupDataStoreList = function() {
		// populate the dropdown
		var cboImport = document.getElementById("importDs");
		var cboExport = document.getElementById("exportDs");
		
		for (var name in _iData) {
		  var ds = document.createElement('option');
		  ds.text = name;
		  ds.value = name;
		  try {
		  	cboImport.add(ds, null);  // standards compliant; doesn't work in IE
		  } catch(ex) {
		  	cboImport.add(ds); //IE only
		  }
		}
		for (name in _eData) {
		  var ds = document.createElement('option');
		  ds.text = name;
		  ds.value = name;
		  try {
		  	cboExport.add(ds, null);  // standards compliant; doesn't work in IE
		  } catch(ex) {
		  	cboExport.add(ds); //IE only
		  }
		}
		
		
		mbDataMapping.fillupVersionList(cboImport.value, 'import');
		mbDataMapping.fillupVersionList(cboExport.value, 'export');
		mbDataMapping.populateTableWithJSON();

	};
	
	/**
	 * Callback to populate the version dropdown
	 * @param datastore
	 * @param direction
	 */
	this.fillupVersionList = function(ds, dir) {
		var data = null;
		if (dir == 'import') {
			data = _iData[ds];
			//remove existing version			
			// populate the dropdown
			var cboImport = document.getElementById("importVs");	
			while (cboImport.length > 0) {
				cboImport.remove(cboImport.length - 1);
			}
			for (var version in data) {
			  var ds = document.createElement('option');
			  ds.text = version;
			  ds.value = version;
			  try {
			  	cboImport.add(ds, null);  // standards compliant; doesn't work in IE
			  } catch(ex) {
			  	cboImport.add(ds); //IE only
			  }
			}
		} else {
			data = _eData[ds];
			var cboExport = document.getElementById("exportVs");
			while (cboExport.length > 0) {
				cboExport.remove(cboExport.length - 1);
			}
			for (version in data) {
			  var ds = document.createElement('option');
			  ds.text = version;
			  ds.value = version;
			  try {
			  	cboExport.add(ds, null);  // standards compliant; doesn't work in IE
			  } catch(ex) {
			  	cboExport.add(ds); //IE only
			  }
			}
		}		
		
	};

	/**
	 * Pre-process mapping json for future use
	 * json in format of {'name': name, 
	 * 					'ver': version, 
	 * 					'dir': direction, 
	 * 					'map': [{'from': srcDataType, 'to': dstDataType}, {}]}
	 */
	var processData = function(json) {
		if (json.length === 0) {
			alert("Cannot connect to the MIMB Web Service. <br/> Please start the service and try again.");
			return;
		}
		for (var i = 0; i < json.length; i++) {
			if (json[i].dir == 'import') {
				if (_iData[json[i].name]) {
					_iData[json[i].name][json[i].ver] = json[i].map;
				} else {
					_iData[json[i].name] = {};
					_iData[json[i].name][json[i].ver] = json[i].map;
				}
			} else if (json[i].dir == 'export') {
				if (_eData[json[i].name]) {
					_eData[json[i].name][json[i].ver] = json[i].map;
				} else {
					_eData[json[i].name] = {};
					_eData[json[i].name][json[i].ver] = json[i].map;
				}
			}
		}
		
	};
	
	
	/**
	 * Populates the table with the given datastore and version
	 */
	this.populateTableWithJSON = function() {
		var iDataStore = document.getElementById("importDs").value;
		var iVersion = document.getElementById("importVs").value;
		var eDataStore = document.getElementById("exportDs").value;
		var eVersion = document.getElementById("exportVs").value;
		
		if (!iDataStore || !iVersion || !eDataStore || !eVersion) {
			return
		}
		
		var mytable = document.getElementById("mappingTable");
        
  		// Here we need to remove all the content so it may be added again below.
		var body = mytable.tBodies[0];
		if (body) {
			while(body.childNodes.length>0){
				body.removeChild(body.childNodes[0]);
			}
			body.parentNode.removeChild(body);
		}

		mytablebody = document.createElement("tbody");
		
		// add header
		var row, cell, text, title;
		row = document.createElement("tr");
        cell = document.createElement("td");	 
        cell.setAttribute("class", "FrontHeader");   //  Gecko
        cell.setAttribute("className", "FrontHeader");  // IE
        cell.setAttribute("width", "50%");
        title = document.createElement("strong");
    	text = document.createTextNode("Import Data Type");   
    	title.appendChild(text);
    	cell.appendChild(title);
        row.appendChild(cell);
        cell = document.createElement("td");
        cell.setAttribute("class", "FrontHeader");  //  Gecko
        cell.setAttribute("className", "FrontHeader");  // IE
        cell.setAttribute("width", "50%");
        title = document.createElement("strong");
        text = document.createTextNode("Export Data Type");	       
        title.appendChild(text);
    	cell.appendChild(title);
        row.appendChild(cell);
		mytablebody.appendChild(row); 		

		var iMaps = _iData[iDataStore][iVersion];
		var eMaps = _eData[eDataStore][eVersion];
		if (!iMaps || !eMaps) {
			alert ('Unknow database or version selected. Please contect the administrator.');
			// hide loading div
			var loadingdiv = document.getElementById("loadingDiv");
			if (loadingdiv) {
				loadingdiv.style.display = 'none';
			}
			return;
		}
		
		var odd = true;
		for (var i = 0; i < iMaps.length; i++) {
			row = document.createElement("tr");			
            cell = document.createElement("td");
            if (odd) {
            	row.setAttribute("bgColor","#fdf9ff");
            } else {
            	row.setAttribute("bgColor","#f0f0f0");
            }
            odd = !odd;
        	text = document.createTextNode(iMaps[i].from === 'undefined' ? '<undefined>' : iMaps[i].from);
        	cell.appendChild(text);
	        row.appendChild(cell);
	        cell = document.createElement("td");
	        var dst = 'unknow';
	        for (var j = 0; j < eMaps.length; j++) {	        	
	        	if (eMaps[j].from === iMaps[i].to) {
	        		dst = eMaps[j].to;	        		 
	        		 break;
	        	}
	        }
	        text = document.createTextNode(dst === 'undefined' ? '<undefined>' : dst);	       
	        cell.appendChild(text);
	        row.appendChild(cell);
			mytablebody.appendChild(row);   
		}

		// hide loading div
		var loadingdiv = document.getElementById("loadingDiv");
		if (loadingdiv) {
			loadingdiv.style.display = 'none';
		}
		mytable.appendChild(mytablebody);
    };	



};
