/*
 * #########################################################################
 * ##       Copyright © Meta Integration Technology, Inc. 2007            ##
 * ##                        All Rights Reserved.                         ##
 * #########################################################################
 * ##                  http://www.metaintegration.com                     ##
 * #########################################################################
 */
var mbBridgeList = new function () {

	this.remoteURL = "localhost:19980";
	this.imagePath = "/MIMBWeb/images/";
	this.vendorPath = "/MIMBWeb/images/vendor/";
	
	this.filterText = "";
	this.filterField = "All";
	this.filterWhole = false;
	this.filterVendor = null;
	this.fromMIMB = false;
	this.filterDir = "BOTH";
	this.dialog = null;
	this.comboToFill = null;
	
	var imgMIMBImport = "MIMBLogoImport.gif";
	var imgMIMBExport = "MIMBLogoExport.gif";
	var imgImport = "MIMBLogoImportFromRepository.gif";
	var imgExport = "MIMBLogoExportToRepository.gif";
	var imgMultiModel = "MIMBLogoMultiModel.gif";
	var imgWindows = "MIMBLogoWindowsOnly.gif";
	var imgToolRequired = "MIMBLogoToolRequired.gif";
	var imgBrowseRepo = "MIMBLogoBrowsableRepository.gif";
	var imgIncreHarv = "MIMBLogoIncrementalHarvest.png";
	
	/**
	 * Get the initial list of bridges flattened with all data.
	 */
    this.requestBridgeList = function(direction, vvalue) {
		this.filterDir = direction;
		// call to get the bridges parameters
		var callUrl = mbConstants.URL_GET_BRIDGE_LIST_DATA; 
		var params = { type: direction , url: this.remoteURL  };
		var kw = {
			url: callUrl,
			content: params,
			mimetype: "text/javascript",
			load: function(type, js, http) {
		        if (vvalue) {
					document.getElementById("searchText").value = vvalue;
		        }
				mbBridgeList.fromMIMB = true;
				fillupBridgeList(js);
			},
			error: function(type, errorObject) {
				mbHelper.showErrorMessage(mbConstants.ERR_CANNOT_CONNECT_MIMBAGENT);	
			}						
		};
		dojo.io.bind(kw);		
	};
	
	/**
	 * Callback to populate the bridge list.
	 */
	function fillupBridgeList(jsonData) {
		if (!jsonData) {
			mbHelper.showErrorMessage(mbConstants.ERR_CANNOT_CONNECT_MIMBAGENT);
			return;
		}
		// populate the table...
		mbBridgeList.populateTableWithJSON(jsonData);

		mbHelper.hideLoadingMessage();
	}

	/**
	 * 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 the initial list of bridges flattened with all data.
	 */
	this.getBridgeListForWebsite = function(vvalue) {
		this.imagePath = "../../Images/";
		this.vendorPath = this.imagePath;
		// get the bridges specs 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/SupportedTools.json", true);
	    xmlhttp.onreadystatechange=function() {
		    if (xmlhttp.readyState==4) {
		        var myjs = eval("("+xmlhttp.responseText+")");
		        if (vvalue) {
					document.getElementById("searchText").value = vvalue;
		        }
	    	    fillupBridgeListForWebsite(myjs);
		    }
	    };
	    xmlhttp.send(null);
	};
	
	/**
	 * Callback to populate the bridge list.
	 */
	function fillupBridgeListForWebsite(jsonData) {
		if (!jsonData) {
			alert("Cannot connect to the MIMB Web Service. <br/> Please start the service and try again.");
			return;
		}
		// populate the table...
		mbBridgeList.populateTableWithJSON(jsonData);
	}

	/**
	 * Get the Vendor list of bridges flattened with all Vendor data.
	 */
	this.getBridgeListForVendor = function(vendor) {
		this.imagePath = "../Images/";
		this.vendorPath = this.imagePath;
		// get the bridges specs 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/SupportedTools.json", true);
	    xmlhttp.onreadystatechange=function() {
		    if (xmlhttp.readyState==4) {
		        var myjs = eval("("+xmlhttp.responseText+")");
		        mbBridgeList.filterVendor = vendor;
	    	    fillupBridgeListForWebsite(myjs);
		    }
	    };
	    xmlhttp.send(null);
	};
	
	/**
	 * Check to see if this bridge should be in the list.
	 */
	function filterBridge(jsonVal) {
		if (!jsonVal) {
			return true;
		}
		if (jsonVal.able!="True") {
 			return true;
 		}
		if (mbBridgeList.filterDir!="BOTH" && mbBridgeList.filterDir.toLowerCase()!=jsonVal.dir.toLowerCase()) {
 			return true;
 		}

		var venid = jsonVal.vid? jsonVal.vid.toLowerCase(): "";
    	if (mbBridgeList.filterVendor!==null && mbBridgeList.filterVendor.length>0 &&
    			mbBridgeList.filterVendor.toLowerCase()!=venid) {
    		return true;
    	}

    	var str = mbBridgeList.filterText? mbBridgeList.filterText.toLowerCase(): "";
    	if (str.length===0) {
    		return false;
    	}
		var vname = jsonVal.vnam? jsonVal.vnam.toLowerCase(): "";
		var tname = jsonVal.tnam? jsonVal.tnam.toLowerCase(): "";
		var tprev = jsonVal.tpre? jsonVal.tpre.toLowerCase(): "";
		var tvers = jsonVal.tver? jsonVal.tver.toLowerCase(): "";
		var tmeth = jsonVal.meth? jsonVal.meth.toLowerCase(): "";
		var name = jsonVal.meth? jsonVal.name.toLowerCase(): "";
    	if (mbBridgeList.filterWhole) {
   			str = " " + str + " ";
   			vname = " " + vname + " ";
   			venid = " " + venid + " ";
   			tname = " " + tname + " ";
   			tprev = " " + tprev + " ";
   			tvers = " " + tvers + " ";
   			tmeth = " " + tmeth + " ";
   			name = " " + name + " ";
   		}
	    if (((vname.indexOf(str)>=0 || venid.indexOf(str)>=0) &&
           		(mbBridgeList.filterField=="All" || mbBridgeList.filterField=="Vendor Name")) ||
           	((tname.indexOf(str)>=0 || tprev.indexOf(str)>=0 || tvers.indexOf(str)>=0) &&
           		(mbBridgeList.filterField=="All" || mbBridgeList.filterField=="Tool Name")) ||
           	(name.indexOf(str)>=0 &&
           		(mbBridgeList.filterField=="All" || mbBridgeList.filterField=="Bridge Name"))) {
	 		return false;
        }
 		return true;
	}

	/**
	 * Populates the table with the given JSON
	 * json should be in { name:<name>, id:<id>} format
	 */
	this.populateTableWithJSON = function(jsonData) {
		var mytable = document.getElementById("bridgeListTable");
        mytable.setAttribute("width", "100%");
        
  		// 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);
		}
        
      	if (!mbBridgeList.filterVendor) {
			this.filterText = document.getElementById("searchText").value;
			this.filterField = document.getElementById("searchField").value;
			this.filterWhole = document.getElementById("searchWhole").checked;
		}

		mytablebody = document.createElement("tbody");

		var lastvendid = "";
		var lasttoolname = "";
		var lasttoolversion = "";
		var jsonVal;
		var isOneFound = false;
		var image;
		var href;
		
		for (var index = 0; index < jsonData.length; index++) {
			jsonVal = jsonData[index];
 			if (filterBridge(jsonVal)) {
 				continue;
 			}
			isOneFound = true;
			//var bridgeid = jsonVal.id;
			// TODO:  we dont show the name,  but we need to use it 
			//  to synchronize with the combobox selection, since the ids are not unique...
			//var bridgename = bridge.getAttribute("name");
            
            if (jsonVal.vid!=lastvendid) {
				current_row = document.createElement("tr");
	            current_cell = document.createElement("td");	            
            	// after an extra empty line,...
            	currenttext = document.createTextNode("\u00a0");
            	current_cell.appendChild(currenttext);
		        current_row.appendChild(current_cell);
				mytablebody.appendChild(current_row);    	
    	        current_row = document.createElement("tr");
	            current_cell = document.createElement("td");
	            current_cell.setAttribute("align", "center");
				current_cell.setAttribute("id", "tool-logo-cell");
				
		        innertable = document.createElement("table");
		        innertablebody = document.createElement("tbody");
	    	    innertable.appendChild(innertablebody);
	           	inner_row = document.createElement("tr");
    	        inner_cell = document.createElement("td");
            	// wrap the image in an anchor to open in a new window...
            	if (jsonVal.vweb && jsonVal.vweb.length>0) {
	            	anchor = document.createElement("a");
		            anchor.setAttribute("href", jsonVal.vweb);
		            anchor.setAttribute("target", "_blank");
        	    	image = document.createElement("img");
	        	    image.setAttribute("src", this.vendorPath+jsonVal.vid+"Logo.gif");
    	        	image.setAttribute("title", jsonVal.vnam);
		            image.setAttribute("alt", jsonVal.vnam);
        		    anchor.appendChild(image);
        		    inner_cell.appendChild(anchor);
            	} else {
           			image = document.createElement("img");
	    	        image.setAttribute("src", this.vendorPath+jsonVal.vid+"Logo.gif");
    		        image.setAttribute("title", jsonVal.vnam);
		            image.setAttribute("alt", jsonVal.vnam);
		            inner_cell.appendChild(image);
            	}
    	        inner_row.appendChild(inner_cell);
        	    innertablebody.appendChild(inner_row);
        	    // Do not show the partner link on the partner's page...
		      	if (!mbBridgeList.filterVendor &&
   	        			(jsonVal.lev=="OEM" || jsonVal.lev=="Established")) {
		           	inner_row = document.createElement("tr");
	    	        inner_cell = document.createElement("td");
	    	        inner_cell.setAttribute("id", "tool-partner");
		            inner_cell.setAttribute("align", "center");
	            	anchor = document.createElement("a");
	            	// Point to the vendor's partner page on our website...
		            anchor.setAttribute("href", "http://metaintegration.net/Partners/"+jsonVal.vid+".html");
		            anchor.setAttribute("target", "_blank");
		            if (jsonVal.lev=="OEM") {
		            	currenttext = document.createTextNode("OEM Partner");
		            } else {
		            	currenttext = document.createTextNode("Partner");
		            }
        		    anchor.appendChild(currenttext);
	    	        inner_cell.appendChild(anchor);
	    	        inner_row.appendChild(inner_cell);
	        	    innertablebody.appendChild(inner_row);
	            }
	            current_cell.appendChild(innertable);
	            lastvendid = jsonVal.vid;
        	    lasttoolname = "";
				current_row.appendChild(current_cell);
				
				current_cell = document.createElement("td");
				current_cell.setAttribute("id", "tool-inner-cell");
            }            
	
            

	        innertable = document.createElement("table");
            innertable.setAttribute("id", "tool-table");
	        innertablebody = document.createElement("tbody");
	        innertable.appendChild(innertablebody);

            if (jsonVal.tnam!=lasttoolname) {
            	if (lasttoolname != ""){
            		currenttext = document.createTextNode("\u00a0");
            		current_cell.appendChild(currenttext);
            	}
            	inner_row = document.createElement("tr");
	            inner_cell = document.createElement("td");
	            inner_cell.setAttribute("colspan", "6");
            	if (jsonVal.tweb && jsonVal.tweb.length>0) {
	            	anchor = document.createElement("a");
		            anchor.setAttribute("href", jsonVal.tweb);
		            anchor.setAttribute("target", "_blank");
	            	currenttext = document.createTextNode(jsonVal.tnam);
        		    anchor.appendChild(currenttext);
        		    inner_cell.appendChild(anchor);
            	} else {
	            	currenttext = document.createTextNode(jsonVal.tnam);
		            inner_cell.appendChild(currenttext);
            	}
	            inner_cell.setAttribute("id", "tool-title");
    	        inner_row.appendChild(inner_cell);
        	    innertablebody.appendChild(inner_row);
        	    lasttoolname = jsonVal.tnam;
				lasttoolversion = "";
            }

            if (jsonVal.tver!=lasttoolversion) {
            	inner_row = document.createElement("tr");
	            inner_cell = document.createElement("td");
	            if (this.fromMIMB) {
	               // set class if table in mimbweb
	               inner_cell.setAttribute("id", "tool-mimb-version");
	            }
	            inner_cell.setAttribute("colspan", "6");
				if (jsonVal.tver) {
				   	span = document.createElement("span");
				    span.setAttribute("id", "tool-version");
				   	currenttext = document.createTextNode("v "+jsonVal.tver);
    			    span.appendChild(currenttext);
    			    inner_cell.appendChild(span);
				}
				if (jsonVal.tpre) {
					currenttext = document.createTextNode("\u00a0\u00a0\u00a0");
				    inner_cell.appendChild(currenttext);
					currenttext = document.createTextNode("(previously "+jsonVal.tpre+")");
				    inner_cell.appendChild(currenttext);
				}
    	        inner_row.appendChild(inner_cell);
        	    innertablebody.appendChild(inner_row);
        	    lasttoolversion = jsonVal.tver;
            }

           	inner_row = document.createElement("tr");
            inner_cell = document.createElement("td");
            inner_cell.setAttribute("colspan", "6");
		   	div = document.createElement("div");
		   	var imgdiv = document.createElement("div");
		   	
		   	if (this.fromMIMB) {
		   	    div.setAttribute("id", "tool-mimb-meth");
		   	    imgdiv.setAttribute("id", "tool-mimb-meth-img");
		   	} else {
		      div.setAttribute("id", "tool-meth");
		      imgdiv.setAttribute("id", "tool-meth-img");
		   	}
            
            
           	image = document.createElement("img");
           	if (this.fromMIMB) {
           	    image.setAttribute("src", jsonVal.dir == "IMPORT" ? 
           	                            this.imagePath+imgMIMBImport : this.imagePath+imgMIMBExport);
			
			    inner_cell.setAttribute("id", "tool-mimb-cell");
	            // show the popout select link...
				var linkdiv = document.createElement("div");
				linkdiv.setAttribute("id", "select-link");
				linkdiv.style.display = "none";
				var popimage = document.createElement("img");
	            popimage.setAttribute("src", this.imagePath+"_SELECT.gif");
				popimage.onclick = mbBridgeList.selectToolFromIcon(jsonVal.dir, jsonVal.id);
        	    text = "Select this Bridge";
            	popimage.setAttribute("title", text);
	            popimage.setAttribute("alt", text);
	            popimage.style.cursor = 'pointer';
				linkdiv.appendChild(popimage);
	            inner_cell.appendChild(linkdiv);
	            inner_cell.onmouseover = mbBridgeList.hoverShowFromSpan(linkdiv, inner_cell);
	            inner_cell.onmouseout = mbBridgeList.hoverHideFromSpan(linkdiv, inner_cell);
	            // also, add the image selection...
	            image.onclick = mbBridgeList.selectToolFromIcon(jsonVal.dir, jsonVal.id);
            	image.setAttribute("title", text);
	            image.setAttribute("alt", text);
	            image.style.cursor = 'pointer';
			} else {
			    image.setAttribute("src", jsonVal.dir == "IMPORT" ? 
           	                            this.imagePath+imgImport : this.imagePath+imgExport);
			    
        	    text = jsonVal.dir=="IMPORT"? "MIMB Import Bridge": "MIMB Export Bridge";
            	image.setAttribute("title", text);
	            image.setAttribute("alt", text);
		    }
			
		    imgdiv.appendChild(image);
		    div.appendChild(imgdiv);

          	
            var methdiv = document.createElement("div");
            methdiv.setAttribute("id", "tool-meth-meth");
            
            //currenttext = document.createTextNode("\u00a0\u00a0\u00a0");
            //methdiv.appendChild(currenttext);            
   	       	
   	       	//currenttext = document.createTextNode("\u00a0");
            //methdiv.appendChild(currenttext);
			anchor = document.createElement("a");
            text = jsonVal.dir=="IMPORT"? "Import": "Export";
            if (this.fromMIMB) {
            	href = "http://metaintegration.net" + "/Products/MIMB/Specifications/MIR"+jsonVal.id+text+".html"
            } else {
            	href = "/Products/MIMB/Specifications/MIR"+jsonVal.id+text+".html"
            }
		    anchor.setAttribute("href", href);
            anchor.setAttribute("target", "_blank");
            anchor.setAttribute("id", "tool-more");
            var prefix = jsonVal.dir=="IMPORT"? "Import from ": "Export to ";
           	currenttext = document.createTextNode(prefix + jsonVal.name);
   		    anchor.appendChild(currenttext);

		    methdiv.appendChild(anchor);
		    
		    div.appendChild(methdiv);
            
              
            currenttext = document.createTextNode("\u00a0\u00a0\u00a0");
            methdiv.appendChild(currenttext);            
            
           	/*
           	currenttext = document.createTextNode(jsonVal.meth);
            methdiv.appendChild(currenttext);

   	       	currenttext = document.createTextNode("\u00a0\u00a0\u00a0");
            methdiv.appendChild(currenttext);
            
            */
			if (jsonVal.req=="True") {
	           	image = document.createElement("img");
	            image.setAttribute("src", this.imagePath+imgToolRequired);
	            image.setAttribute("title", "Requires the tool to be installed to access its SDK");
	            image.setAttribute("alt", "Requires external tool");
	            methdiv.appendChild(image);
           		currenttext = document.createTextNode("\u00a0\u00a0");
        	    methdiv.appendChild(currenttext);
			}
 			if (jsonVal.win=="True") {
 	           	image = document.createElement("img");
	            image.setAttribute("src", this.imagePath+imgWindows);
	            image.setAttribute("title", "Runs on Microsoft Windows only");
	            image.setAttribute("alt", "Requires Microsoft Windows");
	            methdiv.appendChild(image);
    	       	currenttext = document.createTextNode("\u00a0\u00a0");
	            methdiv.appendChild(currenttext);
			}
			if (jsonVal.mult=="True") {
	           	image = document.createElement("img");
	            image.setAttribute("src", this.imagePath+imgMultiModel);
	            image.setAttribute("title", "Supports a repository with multiple models");
	            image.setAttribute("alt", "Supports repository browsing multi-select");
	            methdiv.appendChild(image);
    	       	currenttext = document.createTextNode("\u00a0\u00a0");
	            methdiv.appendChild(currenttext);
			}
			if (jsonVal.brow=="True") {
	           	image = document.createElement("img");
	            image.setAttribute("src", this.imagePath+imgBrowseRepo);
	            image.setAttribute("title", "Offers remote repository browsing for model selection");
	            image.setAttribute("alt", "Supports repository browsing");
	            methdiv.appendChild(image);
    	       	currenttext = document.createTextNode("\u00a0\u00a0");
	            methdiv.appendChild(currenttext);
			}
			if (jsonVal.inchar=="True") {
	           	image = document.createElement("img");
	            image.setAttribute("src", this.imagePath+imgIncreHarv);
	            image.setAttribute("title", "Supports incremental harvesting since last harvested date");
	            image.setAttribute("alt", "Supports incremental harvesting");
	            methdiv.appendChild(image);
    	       	currenttext = document.createTextNode("\u00a0\u00a0");
	            methdiv.appendChild(currenttext);
			}
						
		    inner_cell.appendChild(div);
            
   	        inner_row.appendChild(inner_cell);
       	    innertablebody.appendChild(inner_row);

            current_cell.appendChild(innertable);
            current_row.appendChild(current_cell);

            mytablebody.appendChild(current_row);
        }


		if (!isOneFound) {
			current_row = document.createElement("tr");
		    current_cell = document.createElement("td");
		   	span = document.createElement("span");
		    span.setAttribute("id", "tool-bold");
	       	currenttext = document.createTextNode("No match found:");
		    span.appendChild(currenttext);
			current_cell.appendChild(span);
	       	currenttext = document.createTextNode("  Searching for " + 
				(this.filterDir=="BOTH"? "": this.filterDir+" ") + "tools containing '");
			current_cell.appendChild(currenttext);
		   	span = document.createElement("span");
		    span.setAttribute("id", "tool-bold");
	       	currenttext = document.createTextNode(this.filterText);
		    span.appendChild(currenttext);
			current_cell.appendChild(span);
	       	currenttext = document.createTextNode("' " +
				(this.filterField=="All"? "": "in "+this.filterField) + " " + 
				(this.filterWhole? "(Whole Word) ": "") +
				(this.filterVendor? "for vendor '"+this.filterVendor+"'": ""));
			current_cell.appendChild(currenttext);
		    current_row.appendChild(current_cell);
	        mytablebody.appendChild(current_row);
		}

		// add a final blank line
        current_row = document.createElement("tr");
        current_cell = document.createElement("td");
       	currenttext = document.createTextNode("\u00a0");
        current_cell.appendChild(currenttext);
	    current_row.appendChild(current_cell);
        mytablebody.appendChild(current_row);

	// hide loading div
	var loadingdiv = document.getElementById("loadingDiv");
	if (loadingdiv) {
		loadingdiv.style.display = 'none';
	}
        mytable.appendChild(mytablebody);
    };	

	 /**
	 *  Show the popout select link.
	 */
	 this.hoverShowFromSpan = function(linkdiv, outercell) {
	 	return function() {
	 		mbBridgeList.hoverShow(linkdiv, outercell);
	 	};
	 };
	 this.hoverShow = function(linkdiv, outercell) {
		linkdiv.style.display = "inline";
		outercell.setAttribute("id", "tool-mimb-cell-selected");
	 };
	 /**
	 *  Hide the popout select link.
	 */
	 this.hoverHideFromSpan = function(linkdiv, outercell) {
	 	return function() {
	 		mbBridgeList.hoverHide(linkdiv, outercell);
	 		outercell.setAttribute("id", "tool-mimb-cell");
	 	};
	 };
	 this.hoverHide = function(linkdiv) {
		linkdiv.style.display = "none";
	 };

};
