var pager;

function AjaxRequest(url, args) {
	url += "&_t=" + new Date()+"&rand="+(Math.random()*5);

	new Ajax.Request(url, args);
}

/**
 * This method performs the same function as document.getElementById (looking up an element by
 * its id). However, this method will also set the inner HTML of the element (if found) to a
 * spinner.
 */
function getElementAndWait(elName) {
	if (elName) {
		var el = document.getElementById(elName);
		if (el) {
			el.innerHTML = "<center><img src='imagesEx/green_rot.gif'/></center>";
			return el;
		}
	}
	return null;
}

function globalSearchClose() {
	document.getElementById("globalSearchField").value = '';
}

/**
 * Process a key stroke in the global search.
 */
var proposedCompany;
function globalSearchKeyEvent(e) {
	var keynum;

	// If IE
	if(window.event) {
		keynum = e.keyCode
	}

	// Else if Netscape/Firefox/Opera
	else if(e.which) {
		keynum = e.which
	}

	var element = document.getElementById("globalSearchField");
	var pattern = new String(element.value);

	var len = pattern.length;
	if (keynum) {
		// If the key is the delete key...
		if (8 == keynum) {
			// remove a character from the pattern.
			if (len > 0) {
				len--;
				pattern = pattern.substring(0, len);
			}
		}

		// If the key is the return key...
		else if (13 == keynum) {
		}

		// Otherwise...
		else {
			// add the character to the pattern.
			var keychar = String.fromCharCode(keynum);
			pattern += keychar;
			len++;
		}

		// Build the url for the search.
		var url = "/genotrope/browseCompanies.do?pattern=" + pattern;

		// Shouldn't wait
		var el = document.getElementById('COMPANY_MAP');
		if (el) {
			// Make the request.
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(transport) {
					if (len == pattern.length) {
						proposedCompany = pattern;

						var el = document.getElementById('COMPANY_MAP');

						if (el) {
							var html = "";

							if (pattern.length > 0) {
								if ("empty" != transport.responseText) {
									html += transport.responseText + "<br/>";
								}
							}

							el.innerHTML = html;
						}
					}
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}

		// update the element value.
		element.value = pattern;
	}

	return false;
}

function proposeNewCompany() {
	var url = "/genotrope/viewCompany.do?proposed="+unescape(proposedCompany);

	// Make the request.
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			loadCompany(null,null,false);
		},
		onFailure: function() {
			// silent failure.
		}
	});
}

/**
 * Load a company into the company panel in response to a click on the graph.
 */
function focusOn(guid) {
    window.location = './company.do?guid='+guid;
}

/**
 * Load a company into the company panel
 */
function loadCompany(name, guid, edit) {
	if (!guid) {
		// Updated to include date in the request for IE not to cache the request
		var url = "./simpleValue.do?name=currentCompanyGuid";

		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				var guid = transport.responseText;
				if (guid) {
					// if found
					loadCompany(null, guid, edit);
				}
				else {
					// to be on safer side, clear all div
					$('WATCH_BUTTON').innerHTML = '';
					$('COMPANY_INFO').innerHTML = '';
					// clear COMPANY_MAP only if graph is shown
					// in case search list of companies is displayed,
					// don't do anything, because there may
					// be a separate request to render the list
					if($('COMPANY_MAP').innerHTML.indexOf('/genotrope/applet') > -1)
						$('COMPANY_MAP').innerHTML = '';
					$('COMPANY_LINKS').innerHTML = '';
					$('COMPANY_MAP2').innerHTML = '';
					$('DELETE_BUTTON').innerHTML = '';
				}
			},
			onFailure: function() {
				// silent failure.
			}
		});
		return;
	}

	if (!name) {
		// Updated to include date in the request for IE not to cache the request
		var url = "/genotrope/simpleValue.do?name=currentCompanyName";

		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				var name = transport.responseText;
				if (name) {
					loadCompany(name, guid, edit);
				}
			},
			onFailure: function() {
				// silent failure.
			}
		});
		return;
	}

	// Clear the global search field.
	var el = document.getElementById("globalSearchField");

	if (el) {
		el.value = '';
	}

	var el = document.getElementById('companyPanel_aux_name');
	if (el) {
		el.innerHTML = "<div class='currentCompany'>" + name + "</div>";
	}

	// Clear the content.
	var el = document.getElementById('COMPANY_INFO');

	if (el) {
		el.innerHTML = '';
	}

	currentCompanyGuid = guid;
	var url = "/genotrope/viewCompany.do?guid="+guid;

	var el = document.getElementById('COMPANIES');
	if (el) {
		el.innerHTML = name;
		// display span from linked in
		var el = document.getElementById('li');
		if(el) {
			if(edit){
				el.innerHTML = '';
			}
			else if(el.innerHTML == ''){
				// make span visible
				el.style.visibility = 'visible';
				el.style.display = 'block';
				var unescapedName = unescape(name).replace(/(\+)+/g, " ");
				if(unescapedName.indexOf('(') > -1){
					unescapedName = trim(unescapedName.substr(0, unescapedName.indexOf('(')));
				}
				try {
					// call to create popup
					new LinkedIn.CompanyInsiderPopup("li",unescapedName);
				}
				catch (err) {
					// may be the site is not up
					// hide the linked in span
					el.style.visibility = 'hidden';
					el.style.display = 'none';
				}
			}
		}
	}

	// render the company logo
	renderCompanyLogo(guid, name, true);

	var el = document.getElementById('WATCH_BUTTON');
	if (el && !isManager()) {
		// Render Watch Button
		watchUrl = "/genotrope/watch.do?isWatched=" + guid;

		// Make the request
		new AjaxRequest(watchUrl, {
			method:'get',
			onSuccess: function(transport) {
				// check for response to render buttons
				if(transport.responseText.indexOf('n/a') > -1) {
					// nothing to be rendered
				}
				else {
					if(transport.responseText.indexOf('true') > -1) {
						// already watched. render unwatch link
						renderWatchButton(guid, true);
					}
					else {
						// Not being watched. render watch link
						renderWatchButton(guid, false);
					}
					try {
						// render delete button
						// call to a method from 'javascriptEx\render.js'
						renderDeleteButton(guid);
					}
					catch (err) {
						// it seems that this method is not found
						// eat up exception
					}
				}
			},
			onFailure: function() {
				// silent failure
			}
		});
	}

	if (edit) {
		url += "&edit=true";
	}

	// check for licensed company url
	var licensedCompanyURL = false;
	if(window.location.pathname.indexOf('CompanyProfile.html') != -1) {
		licensedCompanyURL = true;
	}

	var el = getElementAndWait('COMPANY_INFO');
	if (el) {
		// confirm the visibility of the div
		el.style.visibility = 'visible';
		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				var el = document.getElementById('COMPANY_INFO');
				if (el) {
					// Set the contents of the company panel.
					el.innerHTML = transport.responseText;
					if(!edit) {
						// render some portion of comment with option of 'more...'
						if(licensedCompanyURL)
							renderCompanyComments(135, 500);
						else if(transport.responseText.indexOf('license') != -1)
							renderCompanyComments(165, 620);
						else
							renderCompanyComments(185, 650);
					}
					else {
						var addressControl = document.getElementById(guid + "_address");
						if (addressControl != null) {
							addressControl.style.display = "none";
						}
						var proformahints = getElementsByClass('proforma-hint', null, 'td');
						if(proformahints != null && proformahints.length > 0) {
							for(var h=0;h<proformahints.length;h++) {
								if(proformahints[h].getAttribute('colspan') != null && proformahints[h].getAttribute('colspan') == 2) {
									if(proformahints[h].innerHTML.indexOf('ZipCode') != -1) {
										var addressObj = eval(addressControl.value);
										var address = null;
										if(addressObj != null)
											address = addressObj[0];
										var inputsize = (licensedCompanyURL?40:37);
										// parameters : element to update, values to be updated, company id, size
										renderAddressWidget(proformahints[h], address, guid, inputsize);
										break;
									}
								}
							}
						}
					}
					renderOfficialURL();
				}
				// change proforma buttons to image buttons
				var buttons = document.getElementsByTagName('button');
				for(var i=0;i<buttons.length;i++){
					if(buttons[i].innerHTML.indexOf('Edit') != -1) {
						// Edit button
						buttons[i].innerHTML = "<img src='./chameleon/icons/edit.gif' />";
						buttons[i].title = "Edit Company";
						buttons[i].className = 'proforma-image-button';
					}
					else if(buttons[i].innerHTML.indexOf('Update') != -1) {
						// Update button
						buttons[i].innerHTML = "<img src='./chameleon/icons/check.gif' />";
						buttons[i].title = "Update Company";
						buttons[i].className = 'proforma-image-button';
					}
					else if(buttons[i].innerHTML.indexOf('Cancel') != -1) {
						// Cancel button
						buttons[i].innerHTML = "<img src='./chameleon/icons/close.gif' />";
						buttons[i].title = "Cancel";
						buttons[i].className = 'proforma-image-button';
					}
				}
			},
			onFailure: function() {
				// silent failure.
			}
		});
	}

	if (!edit) {
		var el = document.getElementById('COMPANY_MAP');
		if (el) {
			// Load Flash based graph for all users
			if(true) {
				// load SWF graph
				//loadSWFGraph(guid, true, 15);
			}
			else {
				//el = getElementAndWait('COMPANY_MAP');
				var url = "/genotrope/prefuseSingleGeneration.do?guid="+guid;

				// Make the request.
				new AjaxRequest(url, {
					method: 'get',
					onSuccess: function(transport) {
						var el = document.getElementById('COMPANY_MAP');
						if (el) {
							var xml =
								"<div id='#appletwrap'>" +
								"<APPLET " +
								"ARCHIVE='genotropes.jar,prefuse.jar' "+
								"CODEBASE='/genotrope/applet' " +
								"CODE='com/genotrope/graph/applets/GenotropeView.class' " +
								"NAME='GenotropeView' " +
								"HEIGHT='325' " +
								"WIDTH='425' " +
								"HSPACE='0' " +
								"VSPACE='0' " +
								"ALIGN='middle' " +
								"MAYSCRIPT>" +
								"  If you can read this text, the applet is not working. Perhaps you don't " +
								"  have the Java 1.4.2 (or later) web plug-in installed?<br>" +
								"  <h3><a href='http://java.com'>Get Java here.</a></h3>" +
								"  <PARAM NAME='companyInfo' value=\"" + transport.responseText + "\"/>" +
								" </APPLET>" +
								"</div>";

							// Set the contents of the company panel.
							el.innerHTML = xml;
							// hack for #115 : set the focus to search field after some time.
							setTimeout("focus('about');focus('searchField');", 250);
						}
					},
					onFailure: function() {
						// silent failure.
						// irrespective of whether the request ends in failure, the statement should execute
						// hack for #115 : set the focus to search field after some time.
						setTimeout("focus('about');focus('searchField');", 250);
					}
				});
			}
		}

		var el = document.getElementById('COMPANY_MAP2');
		// confirm the visibility of the div
		el.style.visibility = 'visible';
		if (el) {
			loadCompanyMap2(el);
		}

		var el = getElementAndWait('companyPanel_aux_children');
		if (el) {
			var url = "/genotrope/getCompanyChildren.do?guid="+guid;

			// Make the request.
			new AjaxRequest(url, {
				method: 'get',
				onSuccess: function(transport) {
					// Set the contents of the company aux child panel.
					var el = document.getElementById('companyPanel_aux_children');
					el.innerHTML = transport.responseText;
					// calculate & set the height of inner div
					if(document.getElementById('COMPANY_MAP2').clientHeight != null)
						document.getElementById('company_children').style.height = document.getElementById('COMPANY_MAP2').clientHeight - 21;
					// render some links with an option of 'more...'
					if(document.getElementById('company_children').clientHeight != null)
						renderConnectionLinks('childlinks', 'morechildlinks', false, parseInt(document.getElementById('company_children').clientHeight/18));
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}

		var el = getElementAndWait('companyPanel_aux_parents');
		if (el) {
			var url = "/genotrope/getCompanyParents.do?guid="+guid;

			// Make the request.
			new AjaxRequest(url, {
				method: 'get',
				onSuccess: function(transport) {
					// Set the contents of the company aux paents panel.
					var el = document.getElementById('companyPanel_aux_parents');
					el.innerHTML = transport.responseText;
					// calculate & set the height of inner div
					if(document.getElementById('COMPANY_MAP2').clientHeight != null)
						document.getElementById('company_parents').style.height = document.getElementById('COMPANY_MAP2').clientHeight - 21;
					// render some links with an option of 'more...'
					if(document.getElementById('company_parents').clientHeight != null)
						renderConnectionLinks('parentlinks', 'moreparentlinks', false, parseInt(document.getElementById('company_parents').clientHeight/18));
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}

		var url = "/genotrope/companyLinks.do?guid="+guid;

		var el = getElementAndWait('COMPANY_LINKS');
		// confirm the visibility of the div
		el.style.visibility = 'visible';
		if (el) {
			// Make the request.
			new AjaxRequest(url, {
				method: 'get',
				onSuccess: function(transport) {
					var el = document.getElementById('COMPANY_LINKS');
					el.innerHTML = transport.responseText;
					// calculate & set the height of inner div
					if(document.getElementById('COMPANY_LINKS').clientHeight != null)
						document.getElementById('company_news').style.height = document.getElementById('COMPANY_LINKS').clientHeight - 21;
					// render some links with an option of 'more...'
					if(document.getElementById('company_news').clientHeight != null)
						renderCompanyLinks(false, parseInt(document.getElementById('company_news').clientHeight/18));
					// render some links with an option of 'more...'
					renderCompanyLinkMessage();
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}

		var url = "/genotrope/getCompanyLocations.do?guid="+guid;

		var el = getElementAndWait('COMPANY_LOCATIONS');
		if (el) {
			// Make the request.
			new AjaxRequest(url, {
				method: 'get',
				onSuccess: function(transport) {
					var el = document.getElementById('COMPANY_LOCATIONS');
					el.innerHTML = transport.responseText;
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}
	}

	return false;
}

/**
 * Renders company logo
 */
function renderCompanyLogo(guid, name, edit) {
	// render the company logo
	var el = document.getElementById('LOGO_THUMB_NAIL');
	if (el) {
		if(edit) {
			el.innerHTML = "<img style='position:relative;top:30px;left:290px' src="+"./resize.do?guid="+guid+" alt='"+name+"' onclick='javascript:void(0);' title='Click to add/update company logo' />";
		}
		else {
			el.innerHTML = "<img style='cursor:default;position:relative;top:30px;left:290px' src="+"./resize.do?guid="+guid+" alt='"+name+"' title='Login to add/update company logo' />";
		}
	}
}

/**
 * Render company comments with an option of 'more...'
 */
function renderCompanyComments(divHeight, numberOfCharacters) {
	var proformalabels = getElementsByClass('proforma-form', null, 'td');
	if(proformalabels != null && proformalabels.length > 0) {
		for(var h=0;h<proformalabels.length;h++) {
			if(proformalabels[h].getAttribute('colspan') != null && proformalabels[h].getAttribute('colspan') == 2
				&& proformalabels[h].getAttribute('comment') != null && proformalabels[h].getAttribute('comment') == 'true'){
				var comments = proformalabels[h].innerHTML;
				var updatedComments = "<div id='visiblecomments' style='height:"+divHeight+"px;overflow:hidden'>";
				if(comments != null && trim(comments) != '' && comments.length > numberOfCharacters) {
					updatedComments += comments.substring(0,numberOfCharacters);
					updatedComments += "<a class='orangelink' onclick=";
					updatedComments += "'document.getElementById(\"leftoverComments\").style.visibility=\"visible\";";
					updatedComments += "document.getElementById(\"leftoverComments\").style.display=\"inline\";";
					updatedComments += "document.getElementById(\"visiblecomments\").style.overflow=\"auto\";";
					updatedComments += "this.style.visibility=\"hidden\";this.style.display=\"none\"' ";
					updatedComments += "style='text-decoration:underline;'> more...</a>";
					updatedComments += "<span id='leftoverComments' style='visibility:hidden;display:none'>";
					updatedComments += comments.substring(numberOfCharacters);
					updatedComments += "</span>";
				}
				else {
					updatedComments += comments;
				}
				updatedComments += "</div>";
				proformalabels[h].innerHTML = updatedComments;
			}
		}
	}
}

/**
 * Render company url, so it is not wrapped
 */
function renderOfficialURL() {
	var proformalabels = getElementsByClass('proforma-label', null, 'td');
	if(proformalabels != null && proformalabels.length > 0) {
		for(var h=0;h<proformalabels.length;h++) {
			if(proformalabels[h].innerHTML.indexOf('Website:') > -1){
				if(trim(proformalabels[h].nextSibling.innerHTML) != ''){
					var anchor = proformalabels[h].nextSibling.childNodes[0];
					if(anchor.innerHTML.length > 35) {
						anchor.setAttribute('title', anchor.innerHTML);
						anchor.innerHTML = anchor.innerHTML.substr(0, 33) + '...';
					}
				}
				break;
			}
		}
	}
}

/**
 * Render company links as per the
 * space available and an option of 'more...'
 */
function renderCompanyLinks(showAll, numberToShow) {
	var el = document.getElementById('companylinks');
	if(el){
		if(showAll){
			if(el.childNodes[0] && el.childNodes[0].childNodes) {
				// make all rows visible
				for(var s=0;s<el.childNodes[0].childNodes.length;s++){
					el.childNodes[0].childNodes[s].style.visibility = 'visible';
					el.childNodes[0].childNodes[s].style.display = 'block';
				}
				// hide row with 'more...'
				var moreCompanyLinks = document.getElementById('moreCompanyLinks');
				if(moreCompanyLinks){
					moreCompanyLinks.style.visibility = 'hidden';
					moreCompanyLinks.style.display = 'none';
				}
			}
		}
		else{
			if(el.childNodes[0] && el.childNodes[0].childNodes && el.childNodes[0].childNodes.length > numberToShow){
				// hide all rows more than specified
				for(var s=numberToShow-1;s<el.childNodes[0].childNodes.length;s++){
					el.childNodes[0].childNodes[s].style.visibility = 'hidden';
					el.childNodes[0].childNodes[s].style.display = 'none';
				}
				// render row with 'more...'
				el.parentNode.innerHTML += '<span id="moreCompanyLinks" style="margin:0;float:right;visibility:visible;"><a class="orangelink" style="text-decoration:underline" onclick="renderCompanyLinks(true);">more...</a></span>';
			}
		}
	}
}

/**
 * Render connections (parent and children) as per the
 * space available and an option of 'more...'
 */
function renderConnectionLinks(tableName, morelinks, showAll, numberToShow){
	var el = document.getElementById(tableName);
	if(el){
		if(showAll){
			if(el.childNodes[0] && el.childNodes[0].childNodes) {
				// make all rows visible
				for(var s=0;s<el.childNodes[0].childNodes.length;s++){
					el.childNodes[0].childNodes[s].style.visibility = 'visible';
					el.childNodes[0].childNodes[s].style.display = 'block';
				}
				// hide row with 'more...'
				var morelinks = document.getElementById(morelinks);
				if(morelinks){
					morelinks.style.visibility = 'hidden';
					morelinks.style.display = 'none';
				}
			}
		}
		else{
			if(el.childNodes[0] && el.childNodes[0].childNodes && el.childNodes[0].childNodes.length > numberToShow){
				// hide all rows more than specified
				for(var s=numberToShow-1;s<el.childNodes[0].childNodes.length;s++){
					el.childNodes[0].childNodes[s].style.visibility = 'hidden';
					el.childNodes[0].childNodes[s].style.display = 'none';
				}
				// render row with 'more...'
				el.parentNode.innerHTML += '<span id="'+morelinks+'" style="margin:0;float:right;visibility:visible;"><a class="orangelink" style="text-decoration:underline" onclick="renderConnectionLinks(\''+tableName+'\', \''+morelinks+'\', true);">more...</a></span>';
			}
		}
	}
}

/**
 * Render link on click of which company address
 * could be rendered on map
 */
function renderMapLink() {
	var proformaLabels = getElementsByClass('proforma-label', null, 'td');
	if(proformaLabels != null && proformaLabels.length > 0) {
		for(var g=0;g<proformaLabels.length;g++) {
			if(proformaLabels[g].innerHTML.indexOf('Address:') != -1){
				var addressCell = proformaLabels[g].parentNode.childNodes[1];
				if(addressCell != null && trim(addressCell.innerHTML) != '' && trim(addressCell.childNodes[0].title) != '') {
					addressCell.innerHTML = "<span style='position:absolute;' onclick='showMapPanel(\""+addressCell.childNodes[0].title+"\")'><img src='imagesEx/globe-big.png' width='24px' height='24px' style='cursor:pointer;position:relative;top:-5px;left:-9px;' title='Click to see address on map' /></span>" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + addressCell.innerHTML;
					correctPNG();
				}
			}
		}
	}
}

/**
 * Render Watch Button text
 */
function renderWatchButton(guid, watched) {
	var el = document.getElementById('WATCH_BUTTON');
	if(el) {
		if(watched) {
			el.innerHTML = '<a class="orangelink" style="text-decoration:underline;" onClick="dropWatchingCompany(\''+guid+'\');return false;" title="Drop Watch">Unwatch</a>&nbsp;&nbsp;&nbsp;';
		}
		else {
			el.innerHTML = '&nbsp;&nbsp;&nbsp;<a class="orangelink" style="text-decoration:underline;" onClick="watchCompany(\''+guid+'\');return false;" title="Add Watch">Watch</a>&nbsp;&nbsp;&nbsp;';
		}
	}
}

/**
 * Render address widget in edit mode
 */
function renderAddressWidget(element, address, correlationIdentifier, size) {
	if (size == 0 || size == null)
		size = 35;
	var locationguid = "";
	var street1 = "";
	var street2 = "";
	var city = "";
	var state = "";
	var zipcode = "";
	// update variables for edit mode
	if(address != null) {
		locationguid = address.guid;
		street1 = address.street1;
		street2 = address.street2;
		city = address.city;
		state = address.state;
		zipcode = address.zipcode;
	}
	if(element != null) {
		var hint = element.innerHTML;
		element.innerHTML =
			"<input type=\"hidden\" id=\"locationguid\" name=\"locationguid\" value=\""+locationguid+"\" /><table class='smallnormaltext' cellspacing='0' cellpadding='1' border='0' height='100%' width='100%'>"
			+ "<tr><td valign='top' class='proforma-label' width='84px'>Street 1:</td><td><input type=\"text\" size=\""+size+"\" name=\"street1\" id=\"street1\" value=\""+street1+"\" /></td></tr>"
			+ "<tr><td valign='top' class='proforma-label'>Street 2:</td><td><input type=\"text\" size=\""+size+"\" name=\"street2\" id=\"street2\" value=\""+street2+"\" /></td></tr>"
			+ "<tr><td valign='top' class='proforma-label'>Zip Code:</td>"
			+ "<td><input type=\"text\" size=\"7\" title=\"ZipCode\" name=\"zipcode\" id=\"zipcode\" value=\""+zipcode+"\" onblur='sendRequestForPostalCode();'/> <img src='./chameleon/icons/search_right.gif' style='position:relative;top:3px;cursor:pointer' title='Verify ZipCode' onClick='sendRequestForPostalCode();'>"
			+ " <input id=\"city\" size=\"18\" title=\"City\" name=\"city\" value=\""+city+"\" /> <input id=\"state\" title=\"State\" size=\"2\" name=\"state\" value=\""+state+"\" maxlength=\"2\" /></td></tr><tr><td valign='top' colspan='2'><span>"+hint+"</span><img src='./imagesEx/spacer.gif' width='5px'/><span id='postalCodeError' style='color:red;visibility:hidden'>Incorrect zipcode.</span></td></tr></table>";
		// resize input controls
		var text = document.getElementById(correlationIdentifier+ "_name");
		if(text != null)
			text.size = size;
		text = document.getElementById(correlationIdentifier+ "_primaryUrl");
		if(text != null)
			text.size = size;
		text = document.getElementById(correlationIdentifier+ "_comment");
		if(text != null) {
			text.cols = size-3;
			text.rows = 3;
		}
	}
}

// reference to latest script tag,
// used to remove the tag in case of any failure
var scriptRequest;
var postalCodeRequestId;

/**
 * Send request for the zip code entered by user.
 * Method 'getLocation' will be called back, once
 * response arrives
 */
function sendRequestForPostalCode() {
	var postalcode = document.getElementById('zipcode');
	if(postalcode != null && trim(postalcode.value)) {
		var url = 'http://ws.geonames.org/postalCodeLookupJSON?postalcode=' + trim(postalcode.value) + '&country='+defaultCountryCode+'&callback=getLocation';
		// var url = "http://www.geonames.org/postalCodeLookupJSON?postalcode="+trim(zipcode.value)+"&country=US&style=SHORT";
		// Create a new script object
		scriptRequest = new JSONscriptRequest(url);
		// Build the script tag
		scriptRequest.buildScriptTag();
		// Execute (add) the script tag
		scriptRequest.addScriptTag();
		// loading city and state code
		var el = document.getElementById('postalCodeError');
		if(el) {
			el.innerHTML = "Loading city and state...";
			el.style.visibility = 'visible';
			el.style.display = 'block';
		}
		// start timer of 30 seconds to cover long requests
		postalCodeRequestId = setTimeout("postalCodeRequestFailed()", 30000);
		//var place = document.getElementById('city');
		//var stateCode = document.getElementById('state');
		//if(place != null) {
		//	place.disabled = true;
		//}
		//if(stateCode != null) {
		//	stateCode.disabled = true;
		//}
	}
}

/**
 * Call back method for the postal code send request
 */
function getLocation(jData) {
	// cancel timer to check for long requests
	clearTimeout(postalCodeRequestId);
	// remove script tag
	scriptRequest.removeScriptTag();
	// check for no records
	if(jData == null)
		return;
	var postalcodes = jData.postalcodes;
	if(postalcodes.length >= 1) {
		// populate city and state controls
		var place = document.getElementById('city');
		var stateCode = document.getElementById('state');
		if(place != null) {
			place.value = postalcodes[0].placeName;
			//place.disabled = false;
		}
		if(stateCode != null) {
			stateCode.value = postalcodes[0].adminCode1;
			//stateCode.disabled = false;
		}
		var el = document.getElementById('postalCodeError');
		if(el) {
			el.innerHTML = "Incorrect zipcode.";
			el.style.visibility = 'hidden';
		}
	}
	else {
		var el = document.getElementById('postalCodeError');
		if(el) {
			el.innerHTML = "Incorrect zipcode.";
			el.style.visibility = 'visible';
		}
	}
}

/**
 * Display message for postal code search request
 */
function postalCodeRequestFailed() {
	var el = document.getElementById('postalCodeError');
	if(el) {
		el.innerHTML = "Postal code request failed, please try after some time.";
		el.style.visibility = 'visible';
	}
}

/**
 * Send request for the near by zip code of the user.
 * Method 'getNearByPostalCodes' will be called back, once
 * response arrives
 */
function checkForPostalCodesAndResetHitList() {
	// get the zip code of the user
	var postalcode = document.getElementById('userzipcode');
	// check if the zip code to get the near by zip codes is available
	// give user proper error, if it is not a valid postal code
	if(postalcode != null && trim(postalcode.value) != '' && isNumber(trim(postalcode.value))) {
		// get the location radius selected
		var radius = -1;
		var locationRadius = document.getElementsByName('location');
		if(locationRadius != null) {
			for(j=0;j<locationRadius.length;j++){
				if(locationRadius[j].checked){
					radius = locationRadius[j].value;
					break;
				}
			}
		}
		// send web service request, only if user has selected a radius
		if(radius != -1) {
			var url = "http://ws.geonames.org/findNearbyPostalCodesJSON?postalcode=" + trim(postalcode.value) + "&country="+defaultCountryCode+"&radius=" + radius + "&maxRows=500&style=SHORT&callback=getNearByPostalCodes";
			// Create a new script object
			scriptRequest = new JSONscriptRequest(url);
			// Build the script tag
			scriptRequest.buildScriptTag();
			// Execute (add) the script tag
			scriptRequest.addScriptTag();
		}
		else {
			var postalCodes = document.getElementById('postalCodes');
			if (postalCodes != null && trim(postalCodes.value) != '') {
				// reset postal codes selected
				postalCodes.value = "";
			}
			// a direct call to hit list
			resetHitList();
		}
	}
	else {
		var postalCodes = document.getElementById('postalCodes');
		if (postalCodes != null && trim(postalCodes.value) != '') {
			// reset postal codes selected
			postalCodes.value = "";
		}
		// for any characters not allowed as zip
		if(postalcode != null)
			postalcode.value = '';
		// a direct call to hit list
		resetHitList();
	}
}

/**
 * Call back method for the near by postal code request
 */
function getNearByPostalCodes(jData) {
	// remove script tag
	scriptRequest.removeScriptTag();
	var postalCodes = document.getElementById('postalCodes');
	if(postalCodes != null) {
		// check for no records
		if(jData != null) {
			var nearByPostalCodes = jData.postalCodes;
			// check for any result
			if(nearByPostalCodes.length >= 1) {
				var postalCodeString = "";
				for(var t=0;t<nearByPostalCodes.length;t++) {
					postalCodeString += ","+nearByPostalCodes[t].postalCode;
				}
				postalCodeString = postalCodeString.substr(1); // trim leading comma
				// set in the variable
				postalCodes.value = postalCodeString;
			}
		}
	}
	// call hit list
	resetHitList();
}

/**
 * Reset hit list to include all locations
 */
function resetHitListForLocation() {
	// set postal codes to empty
	var postalCodes = document.getElementById('postalCodes');
	if(postalCodes != null) {
		postalCodes.value = "";
	}
	// select all locations
	var locationRadius = document.getElementsByName('location');
	if(locationRadius != null) {
		for(j=0;j<locationRadius.length;j++){
			if(locationRadius[j].value == "-1") {
				locationRadius[j].checked = true;
				break;
			}
		}
	}
	// call hit list
	resetHitList();
}

/**
 * Send request to fetch credit points
 */
function loadCreditPoints() {
	var el = getElementAndWait('CREDIT_POINTS');

	if (el) {
		var url = "/genotrope/simpleValue.do?name=creditPoints";

		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				var el = document.getElementById('CREDIT_POINTS');
				if (el) {
					el.innerHTML = transport.responseText;
				}
			},
			onFailure: function() {
				// silent failure.
			}
		});
	}
}

/*
 * Update the login banner.
 */
function updateLoginBanner() {
	var el = document.getElementById('LOGIN');

	if (el) {
		// Setup the URL
		var url = '/genotrope/loginBanner.do?_d=d';

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				if (el) {
					el.innerHTML = transport.responseText;
				}
			},
			onFailure: function() {
			alert('Unable to update login banner... please refresh');
			}
		});
	}
}

function loadFeatureCompany() {
	document.getElementById('FEATURE').innerHTML =
		"<i>Unable to load today's feature company at this time.";
}

function loadTrackerList(el) {
	// Setup the URL
	var url = '/genotrope/resume.do?view=trackerList';

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById("TRACKER_LIST");
			if (el) {
				el.innerHTML = transport.responseText;
			}
		},
		onFailure: function() {
		}
	});
}

function loadResumeForm(el) {
	// Setup the URL
	var url = '/genotrope/resume.do?view=resumeForm';

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById("RESUME_FORM");
			if (el) {
				el.innerHTML = transport.responseText;
			}
		},
		onFailure: function() {
		}
	});
}

function cancelConfirm(el) {
	document.location = '/genotrope/HitList.html';
}

/*
 * Show users profile.
 */
function loadProfile(edit) {
	// Setup the URL
	var url = '/genotrope/profile.do?_d=d';

	if (edit) {
		url += "&edit=true&skin=purple";
	}

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			document.getElementById('PROFILE').innerHTML = transport.responseText;
			/*
			// change proforma buttons to image buttons
			var buttons = document.getElementsByTagName('button');
			for(var i=0;i<buttons.length;i++){
				if(buttons[i].innerHTML.indexOf('Edit') != -1) {
					// Edit button
					buttons[i].innerHTML = "<img src='./chameleon/icons/edit.gif' />";
					buttons[i].title = "Edit Profile";
					buttons[i].className = 'proforma-image-button';
				}
				else if(buttons[i].innerHTML.indexOf('Update') != -1) {
					// Update button
					buttons[i].innerHTML = "<img src='./chameleon/icons/check.gif' />";
					buttons[i].title = "Update Profile";
					buttons[i].className = 'proforma-image-button';
				}
				else if(buttons[i].innerHTML.indexOf('Cancel') != -1) {
					// Cancel button
					buttons[i].innerHTML = "<img src='./chameleon/icons/close.gif' />";
					buttons[i].title = "Cancel";
					buttons[i].className = 'proforma-image-button';
				}
			}

			// A check to hide 'Old Password', 'New Password', 'Confirm'
			// and the 'hint' rows

			// Get all input elements
			var inputHidden = document.getElementsByTagName('input');
			var guid = '';
			// search for the one with the name '<userdataid>_guid'
			// and get the UserData guid.
			for(var j=0;j<inputHidden.length;j++)
			{
				if(inputHidden[j].type.toLowerCase() == 'hidden'){
					if(inputHidden[j].name.indexOf('_guid') > -1){
						guid = inputHidden[j].value;
						break;
					}
				}
			}
			//alert(guid);
			if(guid!= null && guid!='') {
				// get the html element with the name '<userdataid>_username'
				// this is found in both, editable and non-editable version
				var username = document.getElementsByName(guid+'_username');
				// get the parent table reference
				var table = username[0].parentNode.parentNode.parentNode;
				// iterate through all the elements to check for
				// rows whose visibility is to be set to null
				for(var i=0;i<table.childNodes.length;i++)
				{
					if(table.childNodes[i].innerHTML.indexOf('Old&nbsp;Password:&nbsp;') > -1 ||
						table.childNodes[i].innerHTML.indexOf('New&nbsp;Password:&nbsp;') > -1 ||
						table.childNodes[i].innerHTML.indexOf('Confirm:&nbsp;') > -1 ||
						table.childNodes[i].innerHTML.indexOf('Only required when changing password or creating user.') > -1) {
						table.childNodes[i].style.display='none'
					}
				}
			}
			*/
		},
		onFailure: function() {
			document.getElementById('PROFILE').innerHTML =
				"<i>Error while fetching your profile. Please try after some time or contact <a class='orangelink' style='text-decoration:underline;' href='mailto:support@genotrope.com?subject=My Profile Error' title='mailto:support@genotrope.com?subject=My Profile Error'>administrator</a>.</i>";
		}
	});

	// load watch list
	loadWatchList();

	// load engagement list
	loadEngagementList();
}

function submitProfile(id, correlationIdentifier) {
	var zipcode = document.getElementById('zipcode');
	if(zipcode == null || trim(zipcode.value) == '') {
		var errormessage = document.getElementById('errormessage');
		errormessage.innerHTML = "Please enter a valid zip code.";
		focus('zipcode');
		return false;
	}
	// Setup the URL
	var url = "profile.do?_d=d" + "&" + Form.serialize($(id));
	//var url = "/genotrope/profile.do?correlationIdentifier=" + correlationIdentifier + "&" + Form.serialize($(id));

	// Make the request.
	new AjaxRequest(url, {
		method: 'get',
		onSuccess: function(transport) {
			if ("close" == transport.responseText) {
				loadProfile(false);
			}
			else {
				document.getElementById('PROFILE').innerHTML = transport.responseText;
			}
		},
		onFailure: function() {
			alert('Unable to update record, try again later.');
		}
	});
}

function editProfile(id) {
	loadProfile(true);
}

/*
 * Cancel a proforma form.
 */
function cancelProfile(id) {
	loadProfile(false);
}

function submitResume(form) {
	var url = "/genotrope/resume.do?" + Form.serialize($(form));

	// Make the request.
	new AjaxRequest(url, {
		method: 'get',
		onSuccess: function(transport) {
			window.location = '/genotrope/ResumeConfirm.html';
		},
		onFailure: function() {
			alert('Unable to update record, try again later.')
		}
	});
}

/*
 * Cancel a proforma form.
 */
function cancelCompany(id) {
	loadProfile();
}

function loadMessages() {
	document.getElementById('MESSAGES').innerHTML =
		"<i>You must <a href='#' onClick='showLogin(); return false;'>login</a> to view your messages.</i>";
}

function cancelTracker(guid) {
	commonHitList(guid);
}

function loadHitList() {
	commonHitList(null);
}

function toggleSelection(target) {
	// Setup the URL
	var url = 'hitList.do?checkbox=' + target + '&requestpage=HIT_LIST';
	var viewLink = document.getElementById('viewLink');
	url+='&viewLink='+viewLink.value;
	var checkBoxElem = document.getElementById(target);
	if (checkBoxElem) {

		if(checkBoxElem.checked)
		{
			url+='&checked=true';
		}
		else
		{
			url+='&checked=false';
		}
		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
			},
			onFailure: function() {
			}
		});
	}
}

/**
 * @deprecated
 * Sort hit list
 */
function sortHitList(column) {
	// Setup the URL
	var url = '/genotrope/hitList.do?column=' + column;

	updateTooltip(false);
	var el = getElementAndWait('HIT_LIST');
	if (el) {
		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById('HIT_LIST');
				if (el) {
					el.innerHTML = transport.responseText;
					// check if the list is empty, or user logged out
					if(transport.responseText.indexOf('Update profile') > -1
						|| transport.responseText.indexOf('No matches found.') > -1
						|| transport.responseText.indexOf('must login') > -1) {
						// hide submit button
						var btnSubmitResume = document.getElementById('btnSubmitResume');
						if(btnSubmitResume) {
							btnSubmitResume.style.visibility = "hidden";
						}
						// hide pager
						var divPager = document.getElementById('divPager');
						if(divPager) {
							divPager.style.visibility = "hidden";
						}
					}
				}
			},
			onFailure: function() {
				document.getElementById('HIT_LIST').innerHTML =
				"<i>Error while fetching your hit list. Please try after some time or contact <a class='orangelink' style='text-decoration:underline;' href='mailto:support@genotrope.com?subject=Hit List Error' title='mailto:support@genotrope.com?subject=Hit List Error'>administrator</a>.</i>";
			}
		});
	}
}

/**
 * Sort hit list
 */
function sortHitList2(column) {
	// update sorting column
	document.getElementById('column').value = column;
	// render page 1
	resetHitList();
}

/**
 * Update flag to reset page number in session
 * and render list
 */
function resetHitList() {
	var el = document.getElementById('resetPage');
	if(el) {
		el.value = "true";  // set flag
	}
	loadHitList();
}

function commonHitList(guid) {
	// Setup the URL
	var url = '/genotrope/hitList.do';
	var viewLink = document.getElementById('viewLink');
	var industryFilter = document.getElementById('industryFilter');
	var statusFilter = document.getElementById('statusFilter');
	var locationFilter = document.getElementById('locationFilter');
	var postalCodes = document.getElementById('postalCodes');
	var userzipcode = document.getElementById('userzipcode');
	var companyNameFilter = document.getElementById('companyNameFilter');
	var titleFilter = document.getElementById('titleFilter');
	var categoryFilter = document.getElementById('categoryFilter');
	var sortColumn = document.getElementById('column');
	var resetPage = document.getElementById('resetPage');

	url += '?_d=d';
	// reset page number if required
	if(resetPage && resetPage.value=='true'){
		url += '&page=1&reset=true';
	}
	if(viewLink != null)
		url += '&viewLink='+viewLink.value;
	// set industry filter in url
	if(industryFilter != null){
		var industries = document.getElementsByName('industry');
		var industryNames = "";
		for(i=0;i<industries.length;i++){
			if(industries[i].checked){
				industryNames = industryNames + "," + industries[i].value;
			}
		}
		if(trim(industryNames) != "")
			industryNames = industryNames.substr(1); // trim leading comma
		url += '&industry='+industryNames;
	}
	// set status filter in url
	if(statusFilter != null) {
		var statues = document.getElementsByName('status');
		var statusNames = "";
		for(j=0;j<statues.length;j++){
			if(statues[j].checked){
				statusNames = statusNames + "," + statues[j].value;
			}
		}
		if(trim(statusNames) != "")
			statusNames = statusNames.substr(1); // trim leading comma
		url += '&status='+statusNames;
	}
	// user zip code
	if(userzipcode != null && isNumber(trim(userzipcode.value))) {
		url += '&userzipcode='+trim(userzipcode.value);
		// set area filter in url
		if(locationFilter != null) {
			var locationRadius = document.getElementsByName('location');
			for(j=0;j<locationRadius.length;j++){
				if(locationRadius[j].checked){
					url += '&location='+locationRadius[j].value;
					break;
				}
			}
		}
	}
	else {
		// null user zip code and 'all' locations
		url += '&userzipcode=';
		url += '&location=-1';
	}
	if(postalCodes != null) {
		url += '&postalCodes='+postalCodes.value;
	}
	if(companyNameFilter != null && trim(companyNameFilter.value) != 'Enter company')
		url += '&companyName='+trim(companyNameFilter.value);
	if(titleFilter != null && trim(titleFilter.value) != 'Enter title')
		url += '&jobTitle='+trim(titleFilter.value);
	if(categoryFilter != null && trim(categoryFilter.value) != 'Select category')
		url += '&jobCategory='+trim(categoryFilter.value);
	if(sortColumn != null && trim(sortColumn.value) != '')
		url += '&column='+sortColumn.value;

	// check if this is cancel request
	if (guid) {
		url += "&cancel=" + guid;
	}

	var el = null;
	// if found, show loading image only for bottom div
	if(document.getElementById('LOADING_HIT_LIST') != null) {
		getElementAndWait('LOADING_HIT_LIST');
		el = document.getElementById('HIT_LIST');
	}
	else {
		el = getElementAndWait('HIT_LIST');
	}

	updateTooltip(false);
	if (el) {
		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById('HIT_LIST');
				if (el) {
					el.innerHTML = transport.responseText;
					// check if the list is empty, or user logged out
					if(transport.responseText.indexOf('Update profile') > -1
						|| transport.responseText.indexOf('No matches found.') > -1
						|| transport.responseText.indexOf('must login') > -1) {
						// hide submit button
						var btnSubmitResume = document.getElementById('btnSubmitResume');
						if(btnSubmitResume) {
							btnSubmitResume.style.visibility = "hidden";
						}
						// hide pager
						var divPager = document.getElementById('divPager');
						if(divPager) {
							divPager.style.visibility = "hidden";
						}
					}
					var pagecount = document.getElementById('pageCount').value;
					var pageNumber = document.getElementById('pageNumber').value;
					pager = new PagerControl({
						startPage:pageNumber,
						pageCount: pagecount,
						pagesToShow: 7,
						unselectedCssClass: "spanPagerControlUnselected",
						selectedCssClass: "spanPagerControlSelected",
						hellipCssClass: "hellip",
						previousPageLabel: "Previous",
						nextPageLabel: "Next",
						alwaysShowFirst: true,
						alwaysShowLast: true,
						varName: "pager",
						targetDiv: "divPager",
						pagedCallback: renderPageData
					});
					renderContactManager();
					correctPNG();
					// set rss link
					var rsslink = document.getElementById('rsslink');
					if(rsslink){
						var rssImageId = document.getElementById('rssImageId');
						if(rssImageId) {
							rsslink.onclick = rssImageId.childNodes[0].onclick;
						}
					}
					var viewLink = document.getElementById('viewLink');
					var hitlisttext = document.getElementById('hitlisttext');
					if(viewLink == null || viewLink.value == '' ||
						viewLink.value == 'FILTERED_LIST' || viewLink.value == 'CONNECTIONS_LIST') {
						if (hitlisttext) {
							hitlisttext.innerHTML = "A lot of jobs never get listed publicly. You don't need to wait for a posting, submit your resume to a company you like.<br/><br/>";
						}
					}
					else {
						if (hitlisttext) {
							hitlisttext.innerHTML = "Now Listing these current Jobs. The Postings with the <img src='./imagesEx/favicon.png' style='height:15px;width:16px' /> Icon are at Companies where you have a professional affinity and therefore a higher probability of a good fit.";
						}
					}
					// set type ahead for job title filter, if available
					var titleFilter = document.getElementById('titleFilter');
					if(titleFilter) {
						InitQueryCode('titleFilter', '/genotrope/title.do?_d=d&titlePattern=', 'titleQueryDiv');
						document.getElementById('titleFilter').onblur=function(){
							// method from autocomplete.js
							// @TODO should think of another solution
							showDiv(false);
							// display message if required.
							toggleHintMessage(document.getElementById('titleFilter'), true);
						}
						titleFilter.select();
					}
				}
			},
			onFailure: function() {
				document.getElementById('HIT_LIST').innerHTML =
				"<i>Error while fetching your hit list. Please try after some time or contact <a class='orangelink' style='text-decoration:underline;' href='mailto:support@genotrope.com?subject=Hit List Error' title='mailto:support@genotrope.com?subject=Hit List Error'>administrator</a>.</i>";
			}
		});
	}
}

/**
 * Reset filters in the hit list page
 */
function resetHitListFilters() {
	// reset company
	var companyNameFilter = document.getElementById('companyNameFilter');
	if(companyNameFilter) {
		companyNameFilter.value = '';
		if(companyNameFilter.type != 'hidden')
			focus('companyNameFilter');
	}
	// reset job category title
	var categoryFilter = document.getElementById('categoryFilter');
	if(categoryFilter) {
		categoryFilter.value = '';
		focus('categoryFilter');
	}
	// reset title
	var titleFilter = document.getElementById('titleFilter');
	if(titleFilter) {
		titleFilter.value = '';
		focus('titleFilter');
	}
	// reset industry
	var industryFilter = document.getElementById('industryFilter');
	if(industryFilter != null){
		var industries = document.getElementsByName('industry');
		var industryNames = "";
		for(i=0;i<industries.length;i++){
			industries[i].checked = false;
		}
		industryFilter.value = '';
	}
	// reset status
	var statusFilter = document.getElementById('statusFilter');
	if(statusFilter != null) {
		var statues = document.getElementsByName('status');
		var statusNames = "";
		for(j=0;j<statues.length;j++){
			statues[j].checked = false;
		}
		statusFilter.value = '';
	}
	// reset location
	var locationFilter = document.getElementById('locationFilter');
	var postalCodes = document.getElementById('postalCodes');
	var userzipcode = document.getElementById('userzipcode');
	if(userzipcode != null) {
		userzipcode.value = 'Enter Zipcode';
	}
	if(locationFilter != null) {
		var locationRadius = document.getElementsByName('location');
		for(j=0;j<locationRadius.length;j++){
			if(locationRadius[j].value == -1){
				locationRadius[j].checked = true;
				break;
			}
		}
		locationFilter.value = '';
	}
	if(postalCodes != null) {
		postalCodes.value = '';
	}
	setAdditionalQueryString("");
}

/**
 * key handler for posting list
 */
function postingListKeyHandler(e) {
	evt = e || window.event;
	var keyPressed = evt.which || evt.keyCode;
	if(keyPressed==13)
	{
		resetHitList();
	}
}

/**
 * Makes a request to set hit list
 * link and navigate the page there after
 */
function navigateHitListLink(linkName, companyGuid) {
	// request to update view link
	var url = '/genotrope/hitList.do?linkName=' + linkName;
	if(companyGuid && trim(companyGuid) != '')
		url += '&companyGuid=' + companyGuid
	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			window.location='./HitLists.html';
		},
		onFailure: function() {
			// silent failure
			// anyhow navigate to page
			window.location='./HitLists.html';
		}
	});
}

function loadCompanyMap2(el) {
	el.innerHTML =
	"<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr>" +
	"<td style='text-align: left; vertical-align: top' width='50%'><div id='companyPanel_aux_parents'/></td>" +
	"<td width='1px'>&nbsp;</td>" +
	"<td style='text-align: left; vertical-align: top' width='50%'><div id='companyPanel_aux_children'/></td>" +
	"</tr></table>";
}

function loadPage(elName, page) {
	// Setup the URL
	var url = '/genotrope/simpleValue.do?page=' + page;

	var el = getElementAndWait(elName);

	if (el) {
		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById(elName);

				if (el) {
					el.innerHTML = transport.responseText;
				}
			},
			onFailure: function() {
				alert('Unable to load page... please try again later.')
			}
		});
	}
}

/*
 * Logout
 */
function logout() {
	// Setup the URL
	var url = '/genotrope/logout.do?_d=d';

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			onLoad();
		},
		onFailure: function(transport) {
			// IE does not handle the NO Content response
			// properly, NO response of an ajax request is taken
			// as a failure with status set to 1223, instead of 204
			// & readyStateChange set to 4
			if(transport.status == 1223) {
				onLoad();
			}
			else {
				alert('Unable to logout... please try again later.')
			}
		}
	});
}

function hideGraph() {
	var el = document.getElementById("COMPANY_MAP");
	if (el) {
		el.style.visibility = 'hidden';
	}
	el = document.getElementById("takeTourVideo");
	if(el) {
		el.style.visibility = 'hidden';
	}
}

function showGraph() {
	var el = document.getElementById("COMPANY_MAP");
	if (el) {
		el.style.visibility = 'visible';
	}
	el = document.getElementById("takeTourVideo");
	if(el) {
		el.style.visibility = 'visible';
	}
}

/*
 * Show the Invite prompt.
 */
function showInvite() {
	hideGraph();

	// Setup the URL
	var url = '/genotrope/invite.do?_d=d';

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('popupPanelBody');
			if (el) {
				el.innerHTML = transport.responseText;

				var el = document.getElementById('popupPanelTitle');
				if (el) {
					el.innerHTML = "Invitations";
				}

				show('popupPanel');
				focus('email');
			}
		},
		onFailure: function() {
			alert('Something went wrong...')
		}
	});
}

/*
 * Submit an Invite request.
 */
function submitInvite(form) {
	var url = "/genotrope/invite.do?submit=submit";
	url += "&email=" + document.getElementById("email").value;
	url += "&notes=" + document.getElementById("notes").value;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			if ("close" == transport.responseText) {
				hide("popupPanel");
				onLoad();
			}
			else {
				var el = document.getElementById('popupPanelBody');

				if (el) {
					el.innerHTML = transport.responseText;
					focus('email');
				}
			}
		},
		onFailure: function() {
			alert("Can't Invite... try again later");
		}
	});

	return false;
}

/*
 * Show the login prompt.
 */
function showLogin() {
	hideGraph();

	// Setup the URL
	var url = '/genotrope/login.do?_d=d';

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('popupPanelBody');
			if (el) {
				el.innerHTML = transport.responseText;

				var el = document.getElementById('popupPanelTitle');
				if (el) {
					el.innerHTML = "Login";
				}

				show('popupPanel');
				focus('username');
			}
		},
		onFailure: function() {
			alert('Something went wrong...')
		}
	});
}

/*
 * Submit a login request.
 */
function submitLogin(form) {
	var url = "/genotrope/login.do?submit=submit";
	url += "&username=" + document.getElementById("username").value;
	url += "&password=" + document.getElementById("password").value;
	url += "&rememberMe=" + document.getElementById("rememberMe").checked;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			if ("close" == transport.responseText) {
				hide("popupPanel");
				onLoad();
			}
			else {
				var el = document.getElementById('popupPanelBody');

				if (el) {
					el.innerHTML = transport.responseText;
					focus('username');
				}
			}
		},
		onFailure: function() {
			alert("Can't login... try again later");
		}
	});

	return false;
}

function focus(elName) {
	var el = document.getElementById(elName);

	if (el) {
		el.focus();
	}
}

function show(elName) {
	var el = document.getElementById(elName);

	if (el) {
		el.style.visibility = 'visible';
	}
}

function hide(elName) {
	var el = document.getElementById(elName);

	if (el) {
		el.style.visibility = 'hidden';
	}
}

/*
 * Show the registration prompt.
 */
function showRegistration() {
	var url = '/genotrope/register.do?_d=d';

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			hide('popupPanel');

			var el = document.getElementById('popupPanelBody');

			if (el) {
				el.innerHTML = transport.responseText;

				var el = document.getElementById('popupPanelTitle');
				if (el) {
					el.innerHTML = "Registration";
				}
			}

			show('popupPanel');
			focus('email');
		},
		onFailure: function() {
			alert('Something went wrong...')
		}
	});

	return false;
}

/*
 * Submit a registration request.
 */
function submitRegistration(form) {
	var url = "/genotrope/register.do?submit=submit";
	url += "&email=" + document.getElementById("email").value;
	url += "&confirm=" + document.getElementById("confirm").value;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			hide('popupPanel');

			var el = document.getElementById('popupPanelBody');

			if (el) {
				el.innerHTML = transport.responseText;

				var el = document.getElementById('popupPanelTitle');

				if (el) {
					el.innerHTML = "Registration";
				}

				show('popupPanel');
				focus('email');
			}
		},
		onFailure: function() {
			alert('Something went wrong...')
		}
	});

	return false;
}

// ACTIVATION PROCESSING

function showActivation() {
	var el = document.getElementById('popupPanel');

	if (el) {
		var url = '/genotrope/activation.do?_d=d';

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				hide('popupPanel');

				var el = document.getElementById('popupPanelBody');

				if (el) {
					el.innerHTML = transport.responseText;

					var el = document.getElementById('popupPanelTitle');

					if (el) {
						el.innerHTML = "Activation";
					}

					show('popupPanel');
					focus('code');
				}
			},
			onFailure: function() {
				alert('Something went wrong...')
			}
		});
	}

	return false;
}

function submitActivation(form) {
	workingPanel = "popupPanel";
	workingTitleId = "popupPanelTitle";
	workingTitle = "Activation";
	workingBodyId = "popupPanelBody";

	var url = "/genotrope/activation.do?submit=submit";
	url += "&email=" + document.getElementById("email").value;
	url += "&code=" + document.getElementById("code").value;
	url += "&password=" + document.getElementById("password").value;
	url += "&confirm=" + document.getElementById("confirm").value;

	// Make the request.
	new AjaxRequest(url, {
		method: 'get',
		onSuccess: function(transport) {
			if ("close" == transport.responseText) {
				hide("popupPanel");
				onLoad();
			}
			else {
				var el = document.getElementById('popupPanelBody');

				if (el) {
					el.innerHTML = transport.responseText;
				}
			}
		},
		onFailure: function() {
			alert('Unable to activate at this time, try again later.')
		}
	});
}

// global flag to check if credits
// are to be updated
var updateCredits = false;

/**
 * Submit a proforma form.
 */
function submitCompany(id, correlationIdentifier) {
	// Setup the URL
	var url = "/genotrope/proformaCrud.do?correlationIdentifier=" + correlationIdentifier + "&" + Form.serialize($(id));

	// Make the request.
	new AjaxRequest(url, {
		method: 'get',
		onSuccess: function(transport) {
			loadCompany(null,null,false);
			updateCredits = true;
		},
		onFailure: function(transport) {
			// IE does not handle the NO Content response
			// properly, NO response of an ajax request is taken
			// as a failure with status set to 1223, instead of 204
			// & readyStateChange set to 4
			if(transport.status == 1223) {
				loadCompany(null,null,false);
				updateCredits = true;
			}
			else
			{
				alert('Unable to update record, try again later.')
			}

		}
	});
}

function editCompany(id) {
	loadCompany(null,null,true);
}

/*
 * Cancel a proforma form.
 */
function cancelCompany(id) {
	loadCompany(null,null,false);
}

var selectFor = null;

function proposeChild() {
	selectFor = 'CHILD';

	var el = document.getElementById('COMPANY_MAP');
	if (el) {
		el.style.visibility = 'hidden';
	}

	// Make sure that the company picker panel is visible.
	var el = document.getElementById('companyPickerPanel');
	if (el) {
		el.style.visibility = 'visible';
	}

	var el = document.getElementById('companyPickerPanelTitle');
	if (el) {
		el.innerHTML = '<b>Propose Child</b>';
	}

	// set focus to 'companyPickerField'
	focus('companyPickerField');
}

function dropChild(guid) {
	var url = "/genotrope/childCompany.do?remove=" + guid;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('companyPanel_aux_children');

			if (el) {
				el.innerHTML = transport.responseText;
				// calculate & set the height of inner div
				if(document.getElementById('COMPANY_MAP2').clientHeight != null)
					document.getElementById('company_children').style.height = document.getElementById('COMPANY_MAP2').clientHeight - 21;
				// render some links with an option of 'more...'
				if(document.getElementById('company_children').clientHeight != null)
					renderConnectionLinks('childlinks', 'morechildlinks', false, parseInt(document.getElementById('company_children').clientHeight/18));
		}
		},
		onFailure: function() {
		}
	});
}

function proposeParent() {
	selectFor = 'PARENT';

	var el = document.getElementById('COMPANY_MAP');
	if (el) {
		el.style.visibility = 'hidden';
	}

	// Make sure that the company picker panel is visible.
	var el = document.getElementById('companyPickerPanel');
	if (el) {
		el.style.visibility = 'visible';
	}

	var el = document.getElementById('companyPickerPanelTitle');
	if (el) {
		el.innerHTML = '<b>Propose Parent</b>';
	}

	// set focus to 'companyPickerField'
	focus('companyPickerField');
}

function dropParent(guid) {
	var url = "/genotrope/parentCompany.do?remove=" + guid;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('companyPanel_aux_parents');

			if (el) {
				el.innerHTML = transport.responseText;
				if(document.getElementById('COMPANY_MAP2').clientHeight != null)
					document.getElementById('company_parents').style.height = document.getElementById('COMPANY_MAP2').clientHeight - 21;
				// render some links with an option of 'more...'
				if(document.getElementById('company_parents').clientHeight != null)
					renderConnectionLinks('parentlinks', 'moreparentlinks', false, parseInt(document.getElementById('company_parents').clientHeight/18));
			}
		},
		onFailure: function() {
		}
	});
}


function selectWatchingCompany() {
	selectFor = 'WATCHING';

	// Make sure that the company picker panel is visible.
	document.getElementById('companyPickerPanel').style.visibility = "visible";

	var el = document.getElementById('companyPickerPanelTitle');
	if (el) {
		el.innerHTML = '<b>Select Company</b>';
	}

	// set focus to 'companyPickerField'
	focus('companyPickerField');
}

/**
 * Suggest an associate and redisplay the parent list.
 */
function associateCompanies(name,guid) {
	companyPickerClose();

	if (selectFor == "CHILD") {
		var el = document.getElementById('companyPanel_aux_children');
		if (el) {
			url = "/genotrope/childCompany.do?childGuid=" + guid;
			url += "&parentGuid=" + currentCompanyGuid;

			// Make the request.
			new AjaxRequest(url, {
				method: 'get',
				onSuccess: function(transport) {
					var el = document.getElementById('companyPanel_aux_children');
					el.innerHTML = transport.responseText;
					if(document.getElementById('COMPANY_MAP2').clientHeight != null)
						document.getElementById('company_children').style.height = document.getElementById('COMPANY_MAP2').clientHeight - 21;
					// render some links with an option of 'more...'
					if(document.getElementById('company_children').clientHeight != null)
						renderConnectionLinks('childlinks', 'morechildlinks', false, parseInt(document.getElementById('company_children').clientHeight/18));
					updateCredits = true;
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}
	}
	else if (selectFor == "PARENT") {
		var el = document.getElementById('companyPanel_aux_parents');
		if (el) {
			url = "/genotrope/parentCompany.do?childGuid=" + currentCompanyGuid;
			url += "&parentGuid=" + guid;

			// Make the request.
			new AjaxRequest(url, {
				method: 'get',
				onSuccess: function(transport) {
					var el = document.getElementById('companyPanel_aux_parents');
					el.innerHTML = transport.responseText;
					if(document.getElementById('COMPANY_MAP2').clientHeight != null)
						document.getElementById('company_parents').style.height = document.getElementById('COMPANY_MAP2').clientHeight - 21;
					// render some links with an option of 'more...'
					if(document.getElementById('company_parents').clientHeight != null)
						renderConnectionLinks('parentlinks', 'moreparentlinks', false, parseInt(document.getElementById('company_parents').clientHeight/18));
					updateCredits = true;
				},
				onFailure: function() {
					// silent failure.
				}
			});
		}
	}
	else if (selectFor == "WATCHING") {
		watchCompany(guid);
	}
	else if (selectFor == "ENGAGEMENT") {
		engageCompany(guid);
	}
}

function setCurrentCompany(guid) {
	var url = "/genotrope/simpleValue.do?name=currentCompanyGuid&value=" + guid;

	// Make the request.
	new AjaxRequest(url, {
		method: 'get',
		onSuccess: function(transport) {
			window.location='Companies.html';
		},
		onFailure: function() {
			// silent failure.
		}
	});
}

/**
 * Method to render watch list
 */
function loadWatchList() {
	var el = document.getElementById('WATCH_LIST');
	if(el) {
		// Setup the URL
		var url = '/genotrope/watch.do?_d=d';

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				el.innerHTML = transport.responseText;
				if(document.getElementById('WATCH_LIST').clientHeight != null)
					document.getElementById('watches_list').style.height = document.getElementById('WATCH_LIST').clientHeight - 21;
				renderWatchMessage();
			},
			onFailure: function() {
			}
		});
	}
}

function watchCompany(guid) {
	if (!guid) {
		var url = "/genotrope/simpleValue.do?name=currentCompanyGuid";

		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				var guid = transport.responseText;
				if (guid) {
					watchCompany(guid);
				}
			},
			onFailure: function() {
				// silent failure.
			}
		});
		return;
	}

	url = "/genotrope/watch.do?add=" + guid;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('WATCH_LIST');

			if (el) {
				el.innerHTML = transport.responseText;
				if(document.getElementById('WATCH_LIST').clientHeight != null)
					document.getElementById('watches_list').style.height = document.getElementById('WATCH_LIST').clientHeight - 21;
			}
			// Add successfully. render unwatch link
			renderWatchButton(guid, true);
		},
		onFailure: function() {
		}
	});
}

function dropWatchingCompany(guid) {
	var url = "/genotrope/watch.do?remove=" + guid;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('WATCH_LIST');

			if (el) {
				el.innerHTML = transport.responseText;
				if(document.getElementById('WATCH_LIST').clientHeight != null)
					document.getElementById('watches_list').style.height = document.getElementById('WATCH_LIST').clientHeight - 21;
				renderWatchMessage();
			}
			// Removed successfully. render watch link
			renderWatchButton(guid, false);
		},
		onFailure: function() {
		}
	});
}

/**
 * Render message for watch/hiring target
 * if the list returned are empty
 */
function renderWatchMessage() {
	var watchList = document.getElementById('WATCH_LIST');
	if(watchList && watchList.innerHTML.indexOf('emptywatchlist') != -1) {
		watchList = document.getElementById('emptywatchlist');
		if(watchList) {
			if(isManager()) {
				watchList.innerHTML = '<br/><br/><br/><i>Companies entered here will deliver your company&rsquo;s updates of News and Job Openings to users from these Target companies. Your company will also be included on their Find Job Page listing.</i>';
			}
			else {
				watchList.innerHTML = '<br/><br/><br/><br/><br/><br/><br/><br/><i>Companies entered here will show up in your professional graph and your update feed.</i>';
			}
		}
	}
}

/**
 * Method to render engagements/hiring targets
 */
function loadEngagementList() {
	var engagements = document.getElementById('ENGAGEMENT_LIST');
	if (engagements) {
		// Setup the URL
		var url = '/genotrope/engage.do?_d=d';

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				engagements.innerHTML = transport.responseText;
				renderEngagementMessage();
			},
			onFailure: function() {
			}
		});
	}
}

/**
 * Render message for engagements/hiring
 * target list if the list returned are empty
 */
function renderEngagementMessage() {
	var engagementList = document.getElementById('ENGAGEMENT_LIST');
	if(engagementList && engagementList.innerHTML.indexOf('emptylist') != -1) {
		engagementList = document.getElementById('emptylist');
		if(engagementList) {
			if(isManager()) {
				// any message for hiring managers users??
			}
			else {
				engagementList.innerHTML = '<br/><br/><br/><br/><br/><br/><br/><i>You haven\'t entered any employers yet, so we can\'t create your professional graph or match you to your next great company. When you do enter a company, make sure that you add connections so there are robust links to the past companies of the founders, executives and VCs</i>';
			}
		}
	}
}

function engageCompany(guid) {
	if (!guid) {
		var url = "/genotrope/simpleValue.do?name=currentCompanyGuid";

		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				var guid = transport.responseText;
				if (guid) {
					watchCompany(guid);
				}
			},
			onFailure: function() {
				// silent failure.
			}
		});
		return;
	}

	url = "/genotrope/engage.do?add=" + guid;

	// Make the request
	new AjaxRequest(url, {
		method:'get',
		onSuccess: function(transport) {
			var el = document.getElementById('ENGAGEMENT_LIST');

			if (el) {
				el.innerHTML = transport.responseText;
			}
		},
		onFailure: function() {
		}
	});
}

function dropEngagement(guid) {
	var el = document.getElementById('ENGAGEMENT_LIST');

	if (el) {
		var url = "engage.do?remove=" + guid;

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById('ENGAGEMENT_LIST');

				if (el) {
					el.innerHTML = transport.responseText;
					renderEngagementMessage();
				}
			},
			onFailure: function() {
			}
		});
	}
}

function companyPickerClose() {
	// Make sure that the company picker panel is visible.
	document.getElementById('companyPickerPanel').style.visibility = "hidden";

	// Make sure that the company picker field is blank.
	document.getElementById("companyPickerField").value="";

	var el = document.getElementById('COMPANY_MAP');
	if (el) {
		el.style.visibility = 'visible';
	}
}

function selectEngagementCompany() {
	selectFor = 'ENGAGEMENT';

	// Make sure that the company picker panel is visible.
	document.getElementById('companyPickerPanel').style.visibility = "visible";

	var el = document.getElementById('companyPickerPanelTitle');
	if (el) {
		el.innerHTML = '<b>Select Company</b>';
	}
	// set focus to 'companyPickerField'
	focus('companyPickerField');
}

/**
 * Process a key stroke in the global search.
 */
function companyPickerKeyEvent(e) {
	var keynum;

	// If IE
	if(window.event) {
		keynum = e.keyCode
	}

	// Else if Netscape/Firefox/Opera
	else if(e.which) {
		keynum = e.which
	}

	if (keynum) {

		var element = document.getElementById("companyPickerField");
		var pattern = new String(element.value);

		len = pattern.length;
		if (8 == keynum) {
			if (len > 0) {
				len--;
				pattern = pattern.substring(0, len);
			}
		}
		else {
			var keychar = String.fromCharCode(keynum);
			pattern += keychar;
		}

		var url = "companyPicker.do?pattern=" + pattern;

		// Make the request.
		new AjaxRequest(url, {
			method: 'get',
			onSuccess: function(transport) {
				// Set the contents of the search panel.
				document.getElementById('companyPickerPanelContent').innerHTML = transport.responseText;
			},
			onFailure: function() {
				// silent failure.
			}
		});

		// update the element value.
		element.value = pattern;
	}

	return false;
}

function dropCompanyLink(guid) {
	var el = document.getElementById('COMPANY_LINKS');

	if (el) {
		var url = "/genotrope/companyLinks.do?remove=" + guid;

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById('COMPANY_LINKS');

				if (el) {
					el.innerHTML = transport.responseText;
					// calculate & set the height of inner div
					if(document.getElementById('COMPANY_LINKS').clientHeight != null)
						document.getElementById('company_news').style.height = document.getElementById('COMPANY_LINKS').clientHeight - 21;
					// render some links with an option of 'more...'
					if(document.getElementById('company_news').clientHeight != null)
						renderCompanyLinks(false, parseInt(document.getElementById('company_news').clientHeight/18));
					renderCompanyLinkMessage();
				}
			},
			onFailure: function() {
			}
		});
	}
}

// Moved to ajaxEx.js
//function addCompanyLink() {
//	addUpdationCitationPanel();
//	var el = document.getElementById('ADD_LINK');
//
//	if (el) {
//		el.innerHTML =
//			"<form class='proforma-form' action='#' method='post' onSubmit='return false;' style='margin:0px'>"+
//			"	<input id='NEW_LINK_VALUE' class='proforma-form' type='text' size='40'/>" +
//			"	<a style='cursor:pointer;' onClick='submitNewLink(this.form); return false;'>" +
//			"		<img src='/genotrope/chameleon/icons/check.gif' height='16px' width='16px'/>" +
//			"	</a>" +
//			"	<a style='cursor:pointer;' onClick='cancelNewLink(this.form); return false;'>" +
//			"		<img src='/genotrope/chameleon/icons/close.gif' height='16px' width='16px'/>" +
//			"	</a>" +
//			"</form>";
//	}
//}

function submitNewLink(form) {
	var value;

	var el = document.getElementById('NEW_LINK_VALUE');
	if (el) {
		value = el.value;
	}

	var el = document.getElementById('COMPANY_LINKS');
	if (el) {
		var url = "/genotrope/companyLinks.do?url=" + value.replace(/&/g, "%26").replace(/ /g, "%20");

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById('COMPANY_LINKS');

				if (el) {
					el.innerHTML = transport.responseText;
				}
			},
			onFailure: function() {
			}
		});
	}
}

function cancelNewLink(form) {
	var el = document.getElementById('COMPANY_LINKS');

	if (el) {
		var url = '/genotrope/companyLinks.do?_d=d';

		// Make the request
		new AjaxRequest(url, {
			method:'get',
			onSuccess: function(transport) {
				var el = document.getElementById('COMPANY_LINKS');

				if (el) {
					el.innerHTML = transport.responseText;
				}
			},
			onFailure: function() {
			}
		});
	}
}

/**
 * Render message for company links
 * if the list returned are empty
 */
function renderCompanyLinkMessage() {
	var el = document.getElementById('COMPANY_LINKS');
	if(el && el.innerHTML.indexOf('emptylist') != -1) {
		el = document.getElementById('emptylist');
		if(el) {
			if(window.location.pathname.indexOf('CompanyProfile.html') != -1) {
				el.style.textAlign = 'center';
				el.innerHTML = '<br/><br/><i>Frequently posting Jobs and positive news or PR in this section will keep targeted users informed about career opportunities and the progress of your company. The result is long term communications with your targeted passive talent pool.</i>';
			}
			else {
				// any message for regular users??
			}
		}
	}
}

function onLoad() {
	// Paint the login banner.
	updateLoginBanner();

	var el = document.getElementById('MENUBAR');
	if (el) {
		el.innerHTML =
			"<a class='menubarItem' href='HireArchives.html'>HireArchives</a>" +
			"&nbsp;&middot;&nbsp;" +
			"<a class='menubarItem' href='Companies.html'>Companies</a>" +
			"&nbsp;&middot;&nbsp;" +
			"<a class='menubarItem' href='MyProfile.html'>MyProfile</a>" +
			"&nbsp;&middot;&nbsp;" +
			"<a class='menubarItem' href='HitList.html'>Find Companies / Jobs</a>" +
			"&nbsp;&middot;&nbsp;" +
			"<a class='menubarItem' href='http://buzzboston.wordpress.com/'>Buzz</a>" +
			"&nbsp;&middot;&nbsp;" +
			"<a class='menubarItem' href='Help.html'>FAQ / Help</a>" +
			"&nbsp;&middot;&nbsp;" +
			"<a class='menubarItem' href='About.html'>About</a>";
	}

	var el = document.getElementById('SEARCH')
	if (el) {
		el.innerHTML = "Search:&nbsp;<input id='globalSearchField' type='text' onkeypress='return globalSearchKeyEvent(event);'/>";
	}

	if (onPageLoad) {
		onPageLoad();
	}

	var el = document.getElementById('FEATURE');
	if (el) {
		loadFeatureCompany();
	}

	var el = document.getElementById('COMPANIES');
	if (el) {
		loadCompany(null,null,false);
	}

	var el = document.getElementById('PROFILE');
	if (el) {
		loadProfile();
	}

	var el = document.getElementById('CREDIT_POINTS');
	if (el) {
		loadCreditPoints();
	}

	var el = document.getElementById('MESSAGES');
	if (el) {
		loadMessages();
	}

	var el = document.getElementById('HIT_LIST');
	if (el) {
		loadHitList();
	}

	var el = document.getElementById('STARTUPLINK');
	if (el) {
		el.innerHTML = "<a href='Companies.html' onClick='loadCompany(\"Tabblo\",\"8CD2A8CB-3768-5730-AE3D-B615C22E9474\",false);>more info...</a>";
	}

	var el = document.getElementById('TRACKER_LIST');
	if (el) {
		loadTrackerList(el);
	}

	var el = document.getElementById('RESUME_FORM');
	if (el) {
		loadResumeForm(el);
	}

	var el = document.getElementById('RESEARCH_COMPANIES');
	if (el) {
		el.innerHTML =
			"<a href='Companies.html'>Research Companies</a> to understand about the investors and the prior companies of the founders and executive team. " +
			"Our Editors are continually adding information. Users are encouraged to contribute company and link information as well. " +
			"Together we are creating a valuable and powerful resource.";
	}

	var el = document.getElementById('REGISTER');
	if (el) {
		el.innerHTML = "<a href='#' onClick='showLogin(); return false;'>Login</a> to  Find Employment Opportunities. " +
			"Not Looking but Curious? Give our Find Company Tool a test run to discover start-ups of interest.";
	}

	loadPage("HELP", "faqHelp");
	loadPage("PAST_COMPANY", "pastCompany");
	loadPage("SPOTLIGHT_COMPANY", "spotlightCompany");

	// Load the google analytic, cray egg etc, if required for this page
	loadTracker('siteTrackerPanel');
}

/**
 * Method places the Site tracker agents like Google Analytic, Crazy Egg etc in pages which has the appropriate
 * place holder in place.
 * @see Ticket 52 for more information
 */
function loadTracker(elName)
{
	var el = document.getElementById(elName);
	if(el){
		el.innerHTML = '<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript">     _uacct="UA-2461239-1";     urchinTracker(); </script><script type="text/javascript" src="http://cetrk.com/pages/scripts/0006/3039.js"> </script>';
	}
}

// Utility functions

/**
 * This function is used to validate email id.
 */
function checkEmail(emailid)
{
	if (/^[a-zA-Z0-9_\+-]+(\.[a-zA-Z0-9_\+-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/.test(emailid))
	{
		return (true)
	}
	return false;
}

/**
 * Returns true if the input is a number, else false
 */
function isNumber(input) {
	if(input == null || trim(input) == '') {
		return false;
	}
	else if(isNaN(parseInt(trim(input)))) {
		return false;
	}
	else {
		return true;
	}
}

/**
 * Function to return true, if the user agent is IE.
 * else false.
 */
function isIE() {
	return (navigator.userAgent.toLowerCase().indexOf("msie") >= 0);
}

/**
 * Function to trim a string
 */
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/**
 * Method to create a cookie, takes the name & the value of the cookie
 * the expiry date of the cookie
 */
function createCookie(name,value,days) {
	if (days && days > 0) {
		var date = new Date();
		date.setTime(date.getTime()+(10*365*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
		var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/**
 * reads the content of the cookie if a valid name is provided
 */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/**
 * erase the content of the cookie
 */
function eraseCookie(name) {
	createCookie(name,"",-1);
}

/**
 * Function to return all elements with the class name
 */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/**
 * Method to create a blinking effect
 * for the name of the object passed
 * using Rico library
 */
function fade(objectName, fadeObject) {
	if(fadeObject) {
		new Rico.Effect.FadeTo(objectName, 1, 1000, 20, {complete : function() {
			fade(objectName, false);}}
		);
	}
	else {
		new Rico.Effect.FadeTo(objectName, 0, 1000, 20, {complete : function() {
			fade(objectName, true);}}
		);
	}
}

/**
 * Starts a timer to fade in an
 * object by calling 'setOpacity', till
 * the object is fully visible
 */
function fadeIn(objId, opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 5;
			window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
		}
	}
}

/**
 * Starts a timer to fade out an
 * object by calling 'setOpacity', till
 * the object is fully invisible
 */
function fadeOut(objId, opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity > -1) {
			setOpacity(obj, opacity);
			opacity -= 10;
			window.setTimeout("fadeOut('"+objId+"',"+opacity+")", 100);
		}
	}
}

/**
 * Sets the opacity of the specified
 * object, irrespective of browser
 */
function setOpacity(obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

/**
 * Javascript page object
 */
function PagerControl(parameters) {

	var PagerControl = new Object();

	// Public

	PagerControl.page = function(pageNumber) {
		parameters.pagedCallback(pageNumber);
		this.currentPage = pageNumber;
		this.draw();
	};

	// Private

	PagerControl.currentPage = parameters.startPage;
	PagerControl.pageCount = parameters.pageCount;

	PagerControl.hasPreviousPage = function() {
		return (this.currentPage > 1);
	};

	PagerControl.hasNextPage = function() {
		return (this.currentPage < this.pageCount);
	};

	PagerControl.draw = function() {

		var createElement = function(page, selected, text) {

			var elementNode = document.createElement(selected ? "span" : "a");

			if (!selected)
				elementNode.setAttribute("href", "javascript:" + parameters.varName + ".page(" + page + ")");

			elementNode.setAttribute("class", selected ? parameters.selectedCssClass : parameters.unselectedCssClass);
			elementNode.appendChild(document.createTextNode(text ? text : page));

			targetDiv.appendChild(elementNode);
		}

		var currentPage = this.currentPage;
		var pageCount = this.pageCount;
		var pagesToShow = parameters.pagesToShow;
		var hellipHTML = "<span class=\"" + parameters.hellipCssClass + "\">&hellip;</span>";

		// Reset the pager element; then paint it progressively
		var targetDiv = document.getElementById(parameters.targetDiv);
		targetDiv.innerHTML = "";

		var radius = Math.floor(parameters.pagesToShow/2);
		var start = parseInt(currentPage) - parseInt(radius);
		var stop = parseInt(currentPage) + parseInt(radius);

		if (start < 1) {
			start = 1;
			stop = (pagesToShow > pageCount)? pageCount : pagesToShow;
		}

		if (stop > pageCount) {
			stop = pageCount;
			var potentialStart = parseInt(stop) - parseInt(pagesToShow);
			start = (potentialStart < 1)? 1 : potentialStart;
		}

		if (this.hasPreviousPage())
			createElement(parseInt(currentPage-1), false, parameters.previousPageLabel);

		if (parameters.alwaysShowFirst && start > 1) {
			createElement(1, false);
			if (start > 2)
				targetDiv.innerHTML += hellipHTML;
		}

		for (var i = start; i <= stop; i++)
			createElement(i, (i == currentPage));

		if (parameters.alwaysShowLast && stop < pageCount) {
			if (stop < pageCount - 1)
				targetDiv.innerHTML += hellipHTML;
			createElement(parseInt(pageCount), false);
		}

		if (this.hasNextPage())
			createElement(parseInt(currentPage)+1, false, parameters.nextPageLabel);

		// IE won't display class styles until this:
		targetDiv.innerHTML += "";
	};

	PagerControl.draw();

	return PagerControl;
}

