/********************** Browser detection goodness ***************************/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
/**************************************************************************************/

var LC_LINK_TYPE = "LOVECHAIN";
var WIDGET_LINK_TYPE = "WIDGET";

var pagePathPrepend;
var pageSubject;
var pageDegree;
var pageTypeNumber; //1 - 4 based on "Bucket to Link Relationship" worksheet in TCS spreadsheet
var pageWidgetSubject; //probably don't need these for TCS, just for ED
var pageWidgetDegree;  //probably don't need these for TCS, just for ED
var firstResultUrl; //first result school link from widget search results
var userZip;

var schoolToggle = ""; //used to append &tog=online when applicable

var browser;

/*
 * subject and degree - Our categories
 * widgetSubject and widgetDegree - The mapped widget category form values
 */
function populateClients(pathPrepend, subject, degree, widgetSubject, widgetDegree) 
{
	browser = BrowserDetect.browser;
	
	var fullURL = window.location.href;
	
	//Determine which ip2Loc frame to reference
	var urlHasDubs = (fullURL.indexOf("www.thecollegesearch") > 0);
	
	//Figure out page type number
	pageTypeNumber = 1; //default
	
	if (fullURL.indexOf("_1.html") > 0)
	{
		pageTypeNumber = 1;
	}
	else if (fullURL.indexOf("_2.html") > 0)
	{
		pageTypeNumber = 2;
	}
	else if (fullURL.indexOf("_3.html") > 0)
	{
		pageTypeNumber = 3;
	}
	else if (fullURL.indexOf("_4.html") > 0)
	{
		pageTypeNumber = 4;
	}
	
		
	//Set global var's
	pagePathPrepend = pathPrepend;
	pageSubject = subject;
	pageDegree = degree;
	pageWidgetSubject = widgetSubject;
	pageWidgetDegree = widgetDegree;
	
	//Check param string for zip; if not there, get it from the ip2loc frame
	var parameterString = window.location.href.replace(/.*\?(.*)/, "$1");
	var parameterTokens = parameterString.split("&");
	var parameterList = new Array();
	
	//If the url path contains "Online" then set the online selection and fill school toggle with online 
	if (window.location.href.indexOf("Online") != -1 
		|| window.location.href.indexOf("Distance-Learning") != -1
		|| window.location.href.indexOf("Correspondence") != -1) 
	{
		schoolToggle = "&tog=online";
	}
	
	for (i = 0; i < parameterTokens.length; i++)
	{
		var parameterName = parameterTokens[i].replace(/(.*)=.*/, "$1");
		var parameterValue = parameterTokens[i].replace(/.*=(.*)/, "$1");
		
		parameterList[parameterName] = parameterValue;
	}
	
	var ctValue = parameterList["ct"];
	var zip = parameterList["zip"];
	
	var frameContents = "";
	
	if (!zip) 
	{
		if (browser == "Explorer") 
		{
			if (urlHasDubs) 
			{
				frameContents = document.frames["ip2locFrame"].document.getElementById("zipDiv").innerText;
			}
			else
			{
				frameContents = document.frames["ip2locFrameNoDubs"].document.getElementById("zipDiv").innerText;
			}
		}
		else if (browser == "Firefox")
		{
			if (urlHasDubs) 
			{
				frameContents = window.frames["ip2locFrame"].document.getElementById("zipDiv").textContent;
			}
			else
			{
				frameContents = window.frames["ip2locFrameNoDubs"].document.getElementById("zipDiv").textContent;
			}
		}
		
		if (frameContents.indexOf("zip=") >= 0)
		{
			zip = frameContents.substring(frameContents.indexOf("zip=") + 4, frameContents.indexOf("zip=") + 9);
			
			userZip = zip; //may not need this
			
			var campusSecTitleHTML = document.getElementById("campussectiontitle").innerHTML;
			campusSecTitleHTML = campusSecTitleHTML.substring(0, campusSecTitleHTML.length - 5) + " " + zip + "</h1>";

			document.getElementById("campussectiontitle").innerHTML = campusSecTitleHTML;
		}
	} 
	
	//Perform search
	doAJAXSearch(pathPrepend, subject, degree, widgetSubject, widgetDegree);
}

function createHttpRequestObject() 
{
	var xmlHttp;
	
	try
    {   
		// Firefox, Opera 8.0+, Safari    
		xmlHttp=new XMLHttpRequest();    
	}
  	catch (e)
    {    
		// Internet Explorer    
		try
    	{      
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
		}
    	catch (e)
      	{
			try
        	{        
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");        
			}
      		catch (e)
        	{        
				alert("Your browser does not support AJAX!");        
				return false;        
			}      
		}    
	}
	
	return xmlHttp;
}

var navigatingCurrentResults = false;
var paginationParams = "";

function navigateResults(params) 
{
	//Set pagination params
	paginationParams = params;
	navigatingCurrentResults = true;
	
	//Do new AJAX search
	//doAJAXSearch();
	doAJAXSearch(pagePathPrepend, pageSubject, pageDegree, pageWidgetSubject, pageWidgetDegree);
	
	//Clear params
	paginationParams = "";
	navigatingCurrentResults = false;
}


function doAJAXSearch(pathPrepend, subject, degree, widgetSubject, widgetDegree)
{  
	var searchingHTML = '<table cellpadding="10" cellspacing="0" width="70%" height="100%" align="center" border="0"><tr><td class="text" align="center"><b>Searching...</b><br><img src="' + pathPrepend + 'img/searching.gif" width="100" height="10"></td></tr></table>';
	
	//First set "Searching" message/image
	document.getElementById("resultsDiv").innerHTML = searchingHTML;
	
	var xmlHttp = createHttpRequestObject();
	
	if (xmlHttp != null) {
    
		xmlHttp.onreadystatechange=function()
    	{
      		if(xmlHttp.readyState == 4)
        	{
        		var fullPage = xmlHttp.responseText;
				var bodyStartIndex = fullPage.lastIndexOf("<body>");
				var bodyEndIndex = fullPage.indexOf("</body>");
				
				var justTheBody = xmlHttp.responseText.substring(bodyStartIndex + 6, bodyEndIndex);

				/* Old way
				document.getElementById("resultsDiv").innerHTML = justTheBody; //for just search results
				
				reformatResults(pathPrepend);
				
				setTimeout('checkForMissingImages()', 5000);
				*/
				
				//New way - Get first result and automatically open that form
				var firstResultIndex = justTheBody.indexOf("<h3><a href");
				var endOfFirstResultIndex = justTheBody.indexOf("target=", firstResultIndex);
				
				firstResultUrl = justTheBody.substring(firstResultIndex + 13, endOfFirstResultIndex - 2);

				//doAJAXFirstResultRetrieval();
				
				if (browser == "Explorer") 
				{
					//document.getElementById("resultsDiv").innerHTML = "<object id=\"formPanel\" name=\"formPanel\" type=\"text/html\" classid=\"clsid:25336920-03F9-11CF-8FD0-00AA00686F13\" data=\"" + formURL + "\" width=\"652\" height=\"400\"></object>";
			
					document.getElementById("resultsDiv").innerHTML = "<iframe id=\"widgetformframe\" name=\"widgetformframe\" type=\"text/html\" src=\"" + firstResultUrl + "\" width=\"820\" height=\"600\" frameborder=\"0\"></iframe>";

				}
				else if (browser == "Firefox") 
				{
					document.getElementById("resultsDiv").innerHTML = "<object id=\"widgetformframe\" name=\"widgetformframe\" type=\"text/html\" data=\"" + firstResultUrl + "\" width=\"820\" height=\"600\" frameborder=\"0\"></object>";
					
					//The iframe src in FF is too big for some reason so readjust it here
					//document.getElementById("formframe").height = document.getElementById("formframe").height - 50;
				}
        	}
      	}
		
		var hostName = (window.location.href.indexOf("http://www.thecollegesearch") != -1) ? "http://www.thecollegesearch.org" : "http://thecollegesearch.org";
    
		var widgetLink = document.getElementById("campuslink").href;
		
		var requestUrl = hostName + "/search.aspx?url=" + widgetLink + "&pc=" + userZip;
		
		xmlHttp.open("GET", requestUrl, true);
		xmlHttp.send(null);
	
	}
	else 
	{
		alert("Unable to create AJAX connection; Search");
	}
}

/*
function doAJAXFirstResultRetrieval()
{  
	var xmlHttp = createHttpRequestObject();
	
	if (xmlHttp != null) {
    
		xmlHttp.onreadystatechange=function()
    	{
      		if(xmlHttp.readyState == 4)
        	{
        		var fullPage = xmlHttp.responseText;
				var bodyStartIndex = fullPage.lastIndexOf("<body>");
				var bodyEndIndex = fullPage.indexOf("</body>");
				
				var justTheBody = xmlHttp.responseText.substring(bodyStartIndex + 6, bodyEndIndex);

				document.getElementById("resultsDiv").innerHTML = fullPage;
        	}
      	}

		var hostName = (window.location.href.indexOf("http://www.thecollegesearch") != -1) ? "http://www.thecollegesearch.org" : "http://thecollegesearch.org";
    
		var requestUrl = hostName + "/search.aspx?url=" + firstResultUrl;
		
		xmlHttp.open("GET", requestUrl, true);
		xmlHttp.send(null);
	
	}
	else 
	{
		alert("Unable to create AJAX connection; Retrieving first school result");
	}
}
*/

function reformatResults(pathPrepend) 
{
	var browser = BrowserDetect.browser;
	
	//Hide "Refine Your Search" search fields included in results
	document.getElementById("search").style.display = "none";
	
	//Hide title arrow bar included from SSN
	if (document.getElementById("learnmore2")) 
	{
		document.getElementById("learnmore2").style.display = "none";
	}
	
	//Reformat links
	for (var i = 0; i < document.links.length; i++) 
	{
		var linkHref = document.links[i].href;
		
		if (linkHref.indexOf("results.jsp") != -1 && linkHref.indexOf("&aff=results.jsp") == -1)
		{
			var paramStartIndex = linkHref.indexOf("?");
			var params = linkHref.substring(paramStartIndex + 1); //don't include the '?'
			var newLink = "javascript:navigateResults('&" + params + "');"; //prepend a '&' to params
			
			document.links[i].href = newLink;
		}
	}
	
	//Reformat logo image paths
	for (var i = 0; i < document.images.length; i++) 
	{
		var imgSrc = document.images[i].src;
		
		if (imgSrc.indexOf("logos/") != -1) 
		{
			var logoPathIndex = imgSrc.indexOf("logos/");
			var newPath = imgSrc.substring(logoPathIndex);
			document.images[i].src = pathPrepend + newPath;
			
			//Remove image border
			document.images[i].border = 0;
		}
	}
	
	
	//Remove leading comma in intro (if there)
	if (browser == "Explorer") 
	{
		if (document.getElementById("intro").innerHTML.indexOf("<H1>,") == 0) 
		{
			document.getElementById("intro").innerHTML = "<H1>" + document.getElementById("intro").innerHTML.substring(5, document.getElementById("intro").innerHTML.length);
		}
	}
	else if (browser == "Firefox")
	{
		if (document.getElementById("intro").innerHTML.indexOf("<h1>,") == 3) 
		{
			document.getElementById("intro").innerHTML = "<H1>" + document.getElementById("intro").innerHTML.substring(8, document.getElementById("intro").innerHTML.length);
		}
	}
	
	do_onload();
	
	viewall('show');
}


function checkForMissingImages() 
{
	for (var i = 0; i < document.images.length; i++) 
	{
		var broken = false;
		
		if (browser == "Explorer") 
		{
			if (!document.images[i].complete)
			{
				broken = true;
			}
		}
		else if (browser == "Firefox")
		{
			if ((document.images[i].width == 24 && document.images[i].height == 24) 
				|| (document.images[i].width == 0 && document.images[i].height == 0))
			{
				broken = true;
			}
		}
		
		if (broken) 
		{
			doAJAXMissingImageAlert(document.images[i].src);
		}
	}
}


function doAJAXMissingImageAlert(imageName)
{
	var xmlHttp = createHttpRequestObject();
	
	if (xmlHttp != null) {
    
		xmlHttp.onreadystatechange=function()
    	{
      		//do nothing
      	}
		
		var hostName = (window.location.href.indexOf("http://www.education") != -1) ? "http://www.education-destination.org" : "http://education-destination.org";
    
		var requestUrl = hostName + "/MissingImageAlert.aspx?method=db&domain=www.education-destination.org&img=" + imageName;
	
		xmlHttp.open("GET", requestUrl, true);
		xmlHttp.send(null);
	
	}
	else 
	{
		alert("Unable to create AJAX connection; Missing Image");
	}
}

