// This is a list of XMLHttpRequest-creation factory functions to try
var HTTP_factories = [
	function() { return new XMLHttpRequest();},
	function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
	function() { return new ActiveXObject("Microsoft.XMLHTTP");}
];
	
// When we find a factory that works, store it here.
var HTTP_factory = null;
//HTTP_factory_working_index;
// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions until
// we find one that returns a non-null value and does not throw an 
// exception.  Once we find a working facotry, remember it for later use.
//
HTTPnewRequest = function() 
{
	if(HTTP_factory !== null) {return HTTP_factory();}

	for(var i = 0; i < HTTP_factories.length; i++) 
	{
		try 
		{
			var test = "something";
			var factory = HTTP_factories[i];
			var request = factory();
			if( request !== null) 
			{
				HTTP_factory = factory;
				return request;
			}
		}
		catch(e) 
		{
			continue;
		}
	}
	// If we get here, none of the factory candidates succeeded,
	// so throw an exception now and for all future calls.
	HTTP_factory = function() 
	{
		throw new Error("XMLHttpRequest not supported");
	};
	HTTP_factory(); // Throw an error
};
function ChangeImage( imageid, sometext) 
{
	var txt = document.getElementById("AddToWatchListImage");
	txt.src = "/Main/images/WatchAdded.bmp";
}
function ChangeText( imageid, txt) 
{
	//remove image icon.
	//some more text.
	var image = document.getElementById(imageid);
	image.parentNode.removeChild(image);
	// replace the old text with the new. Javascript and DHTML cookbook, pg 446.
	var elem = document.getElementById("WatchText");
	var newtext = document.createTextNode(decodeURI(txt));
	var oldtext = elem.replaceChild(newtext, elem.firstChild);
}
function ChangeElements( imageid, result) 
{
	var image = document.getElementById(imageid);
	image.parentNode.removeChild(image);
	
	var elem = document.getElementById("WatchText");
	if( result == "0" ) 
	{
		var newtext = document.createTextNode("done");
		var oldtext = elem.replaceChild(newtext, elem.firstChild);
	}
	else 
	{
		elem.replaceChild( document.createTextNode(""),elem.firstChild);
		
		elem.appendChild( document.createTextNode("please "));
		var loginlink = document.createElement("a");
		loginlink.href = "/User/LoginMain.aspx?target=" + escape(document.location);
		loginlink.innerHTML = "login";
		elem.appendChild( loginlink);
		elem.appendChild( document.createTextNode( " to add to your watchlist"));
	}
}
function replaceBlock(blockid, html) 
{
	var div = document.getElementById(blockid);
	if(div !== null) 
	{
		div.innerHTML = html;
	}
}
function FillWatchTable( blockid, objecttype, contenttype, page)
{
	//alert( blockid + "-" + objecttype + "-" + contenttype + "-" + page);
	var request = HTTPnewRequest();
	var random = Math.random();
	//ReplaceBlock(blockid, "<span class=\"loadingtext\">Loading ...</span>");
	request.onreadystatechange = function() 
	{
		if( request.readyState == 4 && request.status == 200)
		{
			var response = request.responseText;
			//alert(response);
			replaceBlock(blockid, response);
		}
	};
	var url = "/Main/GetWatchListTable.aspx?ot=" + objecttype + "&t=" + contenttype + "&p=" + page + "&random=" + random;
	request.open("GET", url, true); // Asynchronous
	request.send(null);
}
function FillTable( blockid, type, page, itemsperpage, field, ascendingorder, daysago)
{
	var request = HTTPnewRequest();
	
	request.onreadystatechange = function()
	{
		if( request.readyState == 4 && request.status == 200)
		{
			var response = request.responseText;
			//alert( response);
			replaceBlock(blockid, response);
		}
	}
	var url = "/Main/GetInsiderTrades.aspx?block=" + blockid + "&t=" + type + "&p=" + page + "&ipp=" + itemsperpage + "&ao=" + ascendingorder + "&f=" + field + "&d=" + daysago;
	//alert(url);
	request.open("GET", url, true);
	request.send(null);
}
function LoadTables()
{
	var args = getArgs();
	var element;
	switch(args.type )
	{
		default :
		case "0" : element = document.getElementById("Companies");
			FillTable( "tradeTable",0 , 1, 100, "Total", true, 90);
			break;
		case "1" : element = document.getElementById("Insiders");
			FillTable( "tradeTable", 1, 1, 100, "Total", true, 90);
			break;
		case "2" : element = document.getElementById("Connected");
			FillTable( "tradeTable", 2, 1, 100, "Total", true, 90);
			break;
	}
	element.id = "selected";
	/*	FillTable( "insiderTable", 1, 1, 20, "Total", true, 30);*/
}
function changeParentId( child, id)
{
	var root = child.parentNode.parentNode;
	for( var index = 0; index < root.children.length; index++)
	{
		 root.children[index].id = "";
	}
	child.parentNode.id = "selected";	
}
function ManageWatchList( objecttype, contenttype) 
{
	var url = "/User/Profile/ManageWatchList.aspx?ot=" + objecttype + "&t=" + contenttype;
	location.href = url;
}
function LoadWatchContentTables() 
{
	FillWatchTable("CompanyContent", "2", "c", "1");
	FillWatchTable("UserContent", "4", "c", "1");
	FillWatchTable("GroupContent", "5", "c", "1");
}
function LoadWatchTradeTables() 
{
	FillWatchTable("CompanyTrades", "2", "t", "1");
	FillWatchTable("IndividualTrades", "3", "t", "1");
}
function LoadWatchTables() 
{
	LoadWatchContentTables();
	LoadWatchTradeTables();
}
function WatchObject(imageid) 
{
	var request = HTTPnewRequest();
	var random = Math.random();
	var querystring = location.search.substring(1);
	request.onreadystatechange = function() 
	{
		if( request.readyState == 4 && request.status == 200) 
		{
			var response = request.responseText;

			ChangeElements(imageid,response);
		}
			
	};
	//random number is a cache busting method
	var url = "/User/AddWatch.aspx?" + querystring + "&r=" + random;
	//alert( url);
	request.open("GET", url,true); //Asynchronous
	request.send(null);
}

function getCookie( name ) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while( i < clen) 
	{
		var j = i + alen;
		if( document.cookie.substring(i, j) == arg )
		{
			return getCookieVal(j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if( i === 0) {break;}
	}
	return "";
}
function getCookieVal( offset) 
{
	var endstr = document.cookie.indexOf( ";", offset);
	if( endstr == 1) 
	{
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
}

function setCookie(name, value, expires, path, domain, secure)
{
	document.cookie = name + "=" + escape(value) + 
		((expires) ? "; expires=" + expires : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") + 
		((secure) ? "; secure" : "");
}
function deleteCookie(name, path, domain)
{
	if( getCookie(name))
	{
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") + 
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";		
	}
}
function getExpDate( days, hours, minutes)
{
	var expDate = new Date();
	if( typeof days == "number" && typeof hours == "number" && typeof minutes == "number")
	{
		expDate.setDate( expDate.getDate() + parseInt(days));
		expDate.setHours(expDate.getHours() + parseInt(hours));
		expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
		return expDate.toUTCString();
	}
}
var compareCookieName = "Compare";
var compareQueryString = "";
function CompareAdd( securityId, ToCookie)
{
	var args = getArgs();
	var securityIds = "";
	if( ToCookie)
	{
		securityIds = getCookie( compareCookieName);
	}
	else
	{
		securityIds = args.s === "" ? getCookie( compareCookieName) : args.s;
	}
	var securityList = securityIds.split(',');
	var found = false;
	for( var i = 0; i < securityList.length; i++)
	{
		if(securityId == securityList[i] )
		{
			found = true;
			break;
		}
	}
	securityIds += found ? "" : "," + securityId; 
	if( ToCookie || args.s === "")
	{
		setCookie( compareCookieName,securityIds);
	}
	else
	{
		var thisQuery = location.search;
		var start = thisQuery.search(/s\=[^&]*/i);
		//alert( start);
		if( start >= 0)
		{
			thisQuery = thisQuery.replace( /s\=[^&]*/i,"s="+securityIds);
		}
		//location.href = location.pathname + thisQuery;
		alert( location.pathname + thisQuery);
	}
}
function CompareRemove( securityId, ToCookie)
{
	var args = getArgs();
	var securityIds = "";
	if( ToCookie)
	{
		securityIds = getCookie( compareCookieName);
	}
	else
	{
		securityIds = args.s === "" ? getCookie( compareCookieName) : args.s;
	}
	var securityList = securityIds.split(',');
	var newSecurityIds = "";
	var found = false;
	for( var i = 0; i < securityList.length; i++)
	{
		newSecurityIds += securityId == securityList[i] ? "" : securityList[i] + ",";
	}
	newSecurityIds = newSecurityIds.slice( 0, -1);
	if( ToCookie || args.s === "")
	{
		setCookie( compareCookieName,newSecurityIds);
	}
	else
	{
		var thisQuery = location.search;
		var start = thisQuery.search(/s\=[^&]*/i);
		//alert( start);
		if( start >= 0)
		{
			thisQuery = thisQuery.replace( /s\=[^&]*/i,"s="+newSecurityIds);
		}
		location.href = location.pathname + thisQuery;
		//alert( location.pathname + thisQuery);
	}
}
