﻿ //
 // Huguenots Common
 // This file holds Bandwidth Checking and other common methods.
 // PLEASE MAKE SURE that bandwidth.jpg is in the same directory as this JS file
 //
  
 //
 // Global Var for harbouring the connection spead 
 //
 var connectionSpeed = 0;

// Global variables for Documents Archive 
var xmlDoc = null;
var xmlAnnouncementObj = null;
var xmlReportAccountsObj = null;
var xmlFactSheetsObj = null;
var dataAnnouncements = null;
var dataReportAccounts = null;
var dataFactSheets = null;

//var httpDir = "http://localhost/pctt.huguenots.co.uk.VSS/";
//var httpDir = '<%=ConfigurationManager.AppSettings["HTTPFolder"].ToString() %>';

var xmlPathAnnouncements = "Announcements.xml";
var xmlPathReportAccounts = "ReportAccounts.xml";
var xmlPathFactSheets = "FactSheets.xml";

var url1 = httpDir + xmlPathAnnouncements;
var url2 = httpDir + xmlPathReportAccounts;
var url3 = httpDir + xmlPathFactSheets

var p = {parameters:[{url:url1}, 
                    {url:url2}, 
                    {url:url3}]};
var paramIndex = 0;
var locked = false;


var nodeType_Element = 1;
 
 //
 // This function draws an image on the canvas and specifies 
 // computeConnectionSpeed as its OnLoad execution
 //
 function drawCSImageTag(fileLocation, fileSize, imgTagProperties) 
  {
    start = (new Date()).getTime();
    loc = fileLocation + '?t=' + escape(start);
    document.write('<img src="' + loc + '" ' + imgTagProperties + ' onload="connectionSpeed=computeConnectionSpeed(' + start + ',' + fileSize + ');">');
    return;
  }

  //
  // This computes the connection speed by determining how long it took to download
  // the DrawCsImageTag image
  //
  function computeConnectionSpeed( start, fileSize ) 
  {
    end = (new Date()).getTime();
    connectSpeed = (Math.floor((((fileSize * 8) / ((end - start) / 1000)) / 1024) * 10) / 10);
    return connectSpeed;
  }

  //
  // This method returns the connection type by comparing
  // the speed and assigning it to respective connection types
  //
  function connectionType() 
  {
    SLOW_MODEM = 56;
    FAST_MODEM = 500;
    ISDN_MODEM = 300;

    if (connectionSpeed != 0) 
    {
        if (connectionSpeed < SLOW_MODEM) 
        {
	        return "slow";
        } else if (connectionSpeed < ISDN_MODEM) 
        {
	        return "medium";
        } else 
        {
	        return "high";
        }
    } else 
    {
        return "high";
    }
  }
  
  //
  // A Default Error message method. This can be improved later for logging purposes
  //
  function Error(message)
  {
    alert("Usage Error: "+message);
  }
  
  function mainErrorHandler(e)
  {
      alert("An exception occurred in the script. Error name: " + e.name 
        + ". Error message: " + e.message); 
  }

  
  function ToggleDiv(target, toggleImage) 
  {
    var el = $get(target);
    var arrowImage = $get(toggleImage)
    var arrowSrc = arrowImage.src;
    var arrowCollapseSrc = "Collapse_indicator";
    var arrowExpandSrc = "Expand_Indicator";

    if ( el.style.display != "none" ) 
    {
      el.style.display = "none";
      arrowImage.src = arrowSrc.replace(arrowExpandSrc, arrowCollapseSrc);
    }
    else 
    {
      el.style.display = "";
      arrowImage.src = arrowSrc.replace(arrowCollapseSrc, arrowExpandSrc);
    }
 }
 
 function CollapseAll() 
 {
    var i;
    var objs = document.getElementsByTagName("div");
    for (i=0;i<objs.length;i++ ) 
    {
     if(objs[i].getAttribute("collapse") == "1")
     {
       var elem = objs[i];
       elem.style.display = "none";
     }
   }
 }

 function CollapseAllButOne(target, toggleImage) 
 {
    CollapseAll();
    ToggleDiv(target, toggleImage);
 }
 
 function populateButtonPDF()
 {
    var linkPDF = $get("LinkToDocument");
    var dropDownListOfDates = $get("DateList");
    var selectedIndex = dropDownListOfDates.selectedIndex;
    linkPDF.href = dropDownListOfDates.options[selectedIndex].value;
    
 }
 
 //////////////////////////////////////////////////////////////
 // The following functions are for the Document Archive
 //////////////////////////////////////////////////////////////
 function OnDocumentPageLoad()
{
    if(BrowserDetect.browser == "Safari")
    {
        paramIndex = 0;
        ProcessSafari();
    }
    else
    {
        ProcessOtherBrowsers();
    }
 }
 
 function ProcessOtherBrowsers()
 {
    xmlAnnouncementObj = LoadXML(xmlPathAnnouncements);

    if(xmlAnnouncementObj != null)
    {
        LoadAnnouncementsCombo();
        PopulateAnnouncements();
    }
    xmlReportAccountsObj = LoadXML(xmlPathReportAccounts);
    if(xmlReportAccountsObj != null)
    {
        LoadReportAccountsCombo();
        PopulateReportAccounts();
    }
    xmlFactSheetsObj = LoadXML(xmlPathFactSheets);
    if(xmlFactSheetsObj != null)
    {
        LoadFactSheetsCombo();
        PopulateFactSheets();
    }
}

function LoadAnnouncementsCombo()
{
    var comboAnnouncements = document.forms[0].ddlAnnouncements;
    dataAnnouncements = xmlAnnouncementObj.getElementsByTagName("yeargroup");
    for(var i=0; i < dataAnnouncements.length; i++)
    {
        var y = new Option(dataAnnouncements[i].getAttribute("year"), i);
        if(i == 0)
            y.setAttribute("selected", 1);
        try
        {
            comboAnnouncements.add(y, null);
        }
        catch(ex)
        {
            comboAnnouncements.add(y);
        }
    }
}
function PopulateAnnouncements()
{
    var comboAnnouncements = document.forms[0].ddlAnnouncements;
    var tblAnnouncements = document.getElementById("tblAnnouncements");
    ClearChildControls(tblAnnouncements);
    var selectedIndex = comboAnnouncements.selectedIndex;
    var newData = dataAnnouncements[selectedIndex];
    var j = -1;
    for(var i=0; i < newData.childNodes.length; i++)
    {
        if( newData.childNodes[i].nodeType == nodeType_Element )
        {
            j++;
            OutputTable(newData.childNodes[i], j, tblAnnouncements);
        }
    }
}

function LoadReportAccountsCombo()
{
    var comboReports = document.forms[0].ddlReports;
    dataReportAccounts = xmlReportAccountsObj.getElementsByTagName("yeargroup");
    for(var i=0; i < dataReportAccounts.length; i++)
    {
        var y = new Option(dataReportAccounts[i].getAttribute("year"), i);
        if(i == 0)
            y.setAttribute("selected", 1);
        try
        {
            comboReports.add(y, null);
        }
        catch(ex)
        {
            comboReports.add(y);
        }
    }
}
function PopulateReportAccounts()
{
    var comboReports = document.forms[0].ddlReports;
    var tblReportAccounts = document.getElementById("tblReportAccounts");
    ClearChildControls(tblReportAccounts);
    var selectedIndex = comboReports.selectedIndex;
    var newData = dataReportAccounts[selectedIndex];
    var j = -1;
    for(var i=0; i < newData.childNodes.length; i++)
    {
        if( newData.childNodes[i].nodeType == nodeType_Element )
        {
            j++;
            OutputTable(newData.childNodes[i], j, tblReportAccounts);
        }
    }
}

function OutputTable(node, index, table)
{
    if(BrowserDetect.browser == "Safari")
    {
        table.setAttribute("width", "100%");
    }
        
    var imgPDF = document.createElement("img");
    imgPDF.setAttribute("src", "images/pdficon_small.gif");
    
    var tr = table.insertRow(index);
    
    var tdLeft = tr.insertCell(0);
    tdLeft.setAttribute("width", "2%");
    tdLeft.appendChild(imgPDF);
    
    var tdCentre = tr.insertCell(1);
    tdCentre.setAttribute("width", "14%");
    tdCentre.setAttribute("align","right");
    var date = null;
    try
    {
        date = node.getAttributeNode("date").nodeValue;
    }
    catch (ex)
    {
        date = node.getAttribute("date"); 
    }
    tdCentre.appendChild(document.createTextNode(date));
    var tdCentreGap = tr.insertCell(2);
    tdCentreGap.setAttribute("width", "1%");

    var tdRight = tr.insertCell(3);
    var linkPDF = document.createElement("a");
    linkPDF.className = "ResourceLinks";
    var path = null;
    try
    {
        path = node.getAttributeNode("path").nodeValue;
    }
    catch (ex)
    {
        //path = node.path.value;
        path = node.getAttribute("path");
    }
    var text = null;
    try
    {
        text = node.getAttributeNode("text").nodeValue;
    }
    catch (ex)
    {
        //path = node.text.value;
        text = node.getAttribute("text");
    }

    linkPDF.setAttribute("href", path);
    linkPDF.setAttribute("target", "_blank");
    linkPDF.appendChild(document.createTextNode(text));
    tdRight.appendChild(linkPDF);
    text = null;
}

function LoadFactSheetsCombo()
{
    var comboFactSheets = document.forms[0].ddlFactSheets;
    dataFactSheets = xmlFactSheetsObj.getElementsByTagName("yeargroup");
    for(var i=0; i < dataFactSheets.length; i++)
    {
        var y = new Option(dataFactSheets[i].getAttribute("year"), i);
        if(i == 0)
            y.setAttribute("selected", 1);
        try 
        {
            comboFactSheets.add(y, null);   // standards compliant; doesn't work in IE
        }
        catch(ex)
        {
            comboFactSheets.add(y);         // IE only
        }
    }
}
function PopulateFactSheets()
{
    var comboFactSheets = document.forms[0].ddlFactSheets;
    var tblFactSheets = document.getElementById("tblFactSheets");
    tblFactSheets.setAttribute("width", "100%");
    ClearChildControls(tblFactSheets);
    var selectedIndex = comboFactSheets.selectedIndex;
    var newData = dataFactSheets[selectedIndex];
    var j = -1;
    for(var i=0; i < newData.childNodes.length; i++)
    {
        if( newData.childNodes[i].nodeType == nodeType_Element )
        {
            j++;
            OutputFactSheetTable(newData.childNodes[i], j, tblFactSheets);
        }
    }
}

function OutputFactSheetTable(node, index, table)
{
    var imgPDF = document.createElement("img");
    imgPDF.setAttribute("src", "images/pdficon_small.gif");
    
    var tr = table.insertRow(index);
    var tdLeft = tr.insertCell(0);
    tdLeft.setAttribute("width", "2%");
    tdLeft.appendChild(imgPDF);
    
    var tdCentre = tr.insertCell(1);
    tdCentre.setAttribute("width", "11%");
    tdCentre.setAttribute("align","right");
    var path = null;
    var date = null;
    try
    {
        path = node.getAttributeNode("path").nodeValue;
        date = node.getAttributeNode("date").nodeValue;
    }
    catch (ex)
    {
        //path = node.path.value;
        path = node.getAttribute("path");
        date = node.getAttribute("date");
    }

    var linkPDF = document.createElement("a");
    linkPDF.className = "ResourceLinks";
    linkPDF.setAttribute("href", path);
    linkPDF.setAttribute("target", "_blank");
    linkPDF.appendChild(document.createTextNode(date));
    tdCentre.appendChild(linkPDF);
    var tdRight = tr.insertCell(2);
    tdRight.setAttribute("width", "87%");

}

// End of functions for Document Archives

// Functions to read xml files
function LoadXML(xmlFile)
{
    if (window.ActiveXObject)
    {// code for IE
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    }
    else if (document.implementation.createDocument)
    {// code for Mozilla, Firefox, Opera, etc.
        xmlDoc=document.implementation.createDocument("","",null);
    }
    xmlDoc.async=false;
    xmlDoc.onreadystatechange=Verify; 
    try
    {
        xmlDoc.load(xmlFile); 
    }
    catch(e)
    {
        alert("Error: " + e.message);
    }
    return xmlDoc.documentElement; 
}
 
 
function Verify() 
{ 
 // 0 Object is not initialized 
 // 1 Loading object is loading data 
 // 2 Loaded object has loaded data 
 // 3 Data from object can be worked with 
 // 4 Object completely initialized 
 if (xmlDoc.readyState != 4) 
 { 
   return false; 
 }
}
// End of functions to read xml files
///////////////////////////////////////////////////////////////////////////////////////////
//////////// Safari code //////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
function ProcessSafari()
{
    // Discovered that it is not possible to read the XML file synchronously
    // as you can with the other browsers, so Safari has to be processed differently.
    
    if(paramIndex < p.parameters.length)
    {
        SafariLoadXML(p.parameters[paramIndex]);
    }    
}

function SafariLoadXML(parameter)
{
    if (window.XMLHttpRequest) 
    { 
        safariXmlDoc = new XMLHttpRequest();
        if (safariXmlDoc.overrideMimeType) 
        {
	        safariXmlDoc.overrideMimeType('text/xml');
	    }
        safariXmlDoc.onreadystatechange=VerifySafari; 
        
        // Put in a random querystring to avoid caching the xml file
        var randomValue = "?RandomKey=" + Math.random() * Date.parse(new Date());
        var thisFile = parameter.url + randomValue;
        try
        {
            safariXmlDoc.open("GET", thisFile, true);                
            safariXmlDoc.send(null); 
        }
        catch(e)
        {
            alert("Error trying to read the XML document: " + thisFile + ". Error name: " + e.name + ". Error message: " + e.message);
        }
    }
}

function VerifySafari()
{ 
     if(safariXmlDoc.readyState == 4)
     {
        if(safariXmlDoc.status == 200)
        {
            LoadControl(safariXmlDoc);
            paramIndex++;
            ProcessSafari();
        }
        else
        { 
              alert("Error: returned status code " + 
                   safariXmlDoc.status + " " + safariXmlDoc.statusText); 
       } 
    } 
}

function LoadControl(safariXmlDoc)
{
    var obj = safariXmlDoc.responseXML;
    var root = obj.childNodes(0).tagName;
    switch(root)
    {
        case "Announcements": xmlAnnouncementObj = obj;
                                LoadAnnouncementsCombo();
                                PopulateAnnouncements();
                                break;    
                                  
        case "ReportAccounts": xmlReportAccountsObj = obj;
                                LoadReportAccountsCombo();
                                PopulateReportAccounts();
                                break;    
                                  
        case "FactSheets": xmlFactSheetsObj = obj;
                            LoadFactSheetsCombo();
                            PopulateFactSheets();  
                            break;          
    }
}

// Clear all child controls from a control
//
function ClearChildControls(control)
{
    if(control.hasChildNodes())
    {
        while(control.childNodes.length > 0)
        {
            control.removeChild(control.firstChild);
        }
    }     
}

/////////////////////////////////////////////////////////////////////////////////////
// Browser Detect code

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();
// End of Browser Detect code
///////////////////////////////////////////////////////////////////////////////////
