


//initialize dynamic iframe variable
var oIFrame = null;

//Creating IFrame dynamically

function createIFrame(name){
		//create the iframe
		var oIFrameElement = document.createElement("iframe");
		//attributes
		oIFrameElement.width=0;
		oIFrameElement.height=0;
		oIFrameElement.frameBorder=0;
		oIFrameElement.name = name;
		oIFrameElement.id = name;
		//add the iframe to the document structure
		document.body.appendChild(oIFrameElement);
		oIFrame = frames[name];
}


//use to show and hide any dropdown menu
function showmenu(elmnt)
{
	if (document.getElementById(elmnt).style.display == "block"){
		hidemenu(elmnt)
	}
	else{
	document.getElementById(elmnt).style.display="block"
	}
}
function hidemenu(elmnt)
{
     document.getElementById(elmnt).style.display="none"
}



//Used when the main page is load
//call all the necessary functions 
function firstLoad(){
	//call aToZ function to display A To Z for the left column
	aToZ();
}//end of firstload function

//function to load Health NewsInfo
function HealthNewsInfo(){
	
		//if frame hiddenHealth is not defined equal to true
		if (!frames["hiddenHealth"] == true){
			createIFrame("hiddenHealth");						
			//setTimeout use to wait for 5 seconds for it to process
			//setTimeout ("CurrNewsInfo()", 5000);
			//setInterval rerun for every 60 seconds
			//setInterval ("HealthNewsInfo()", 60000);				
		}	
				
		top.frames["hiddenHealth"].location = "/phcommon/public/media/media_p.cfm?option=2";
		CurrNewsInfo('1');
}	
function displayHealthNews(sHealth){
	var OutHealthNews = document.getElementById("OutHealthNews");
	OutHealthNews.innerHTML = sHealth;
}


//function to load Current News and Alert news

function CurrNewsInfo(a){
	//if frame hidden current is not defined equal to true
	if (!frames["hiddenCurrent"] == true){
		//alert("current");
		createIFrame("hiddenCurrent");	
	}	
	top.frames["hiddenCurrent"].location = "/phcommon/public/media/media_p.cfm?option="+a;			
}	
function displayCurrNews(sText){
	var OutCurNews = document.getElementById("OutCurNews");
	OutCurNews.innerHTML = sText;
}

//use to dynamically set the global navigation level to on State 
function chgOnState(a){
	//the a paramter is the object that the color will be change to emphasis it is currently on the page
	var obj= document.getElementById(a);
	obj.style.color = "#c97962";
	obj.style.fontSize = "12px";	
}
//use to load the A - Z buttons 
function aToZ(){
	//6 alpha per line for it to looks good in IE and FireFox
	var cont = "";
	cont = cont + "<table align='center' class='atoz'><tr>";
	for (i=65;i<=90; i++){
		cont = cont + "<td class='atoz' align='center'>" + 
			"<input type='Submit' class='aTozButton' name='ALPHA' value='" + String.fromCharCode(i) +  "'></td>"
		if (i == 70 || i==76 || i ==82 || i == 88 ){
		cont = cont + "</tr><tr>";
		
		}
	}
	cont = cont + "<td colspan=4 class='atoz' align='center'><input type='Submit' class='aTozButton' name='ALPHA' value='ALL'></td>"
	cont = cont + "</tr></table>";	
	var divAtoZ = document.getElementById("divAtoZ");
		divAtoZ.innerHTML = cont;	
		
}//end of aToZ function

//use to open portlet content - open and close
function portletOpenClose(a){
	indText= a + "1";;
	indView = document.getElementById(indText);
	indopen=document.getElementById(a);	
	if (indopen.style.display == "block"){
		indopen.style.display = "none"		
		indView.innerHTML = "Open"	
	}
	else{
		indopen.style.display = "block"	
		indView.innerHTML = "Close"	
	
	}
}//end of portletOpenClose function


//function use to render content for the center column
function getCenterContent(indpath) {

	var oXmlHttp = createXMLHttp();
	//true = asynochronous
	oXmlHttp.open("get", indpath, true);
	oXmlHttp.onreadystatechange = function (){
		//alert(oXmlHttp.readyState);
		if (oXmlHttp.readyState == 4){
			if (oXmlHttp.status == 200){
				//alert("Data returned is :" + oXmlHttp.responseText);
				//alert(oXmlHttp.getAllResponseHeaders());
				var sData = oXmlHttp.responseText;
				var disContent = document.getElementById("disContent");
					disContent.innerHTML = sData;				
				//document.write(sData);
				//alert(sData);
			}
			else{
				var disContent = document.getElementById("disContent");
					disContent.innerHTML = 	"An error occured: " + 	oXmlHttp.statusText;	
				//alert("An error occurred:" + oXmlHttp.statusText);
				//document.write(oXmlHttp.responseText);
			}
			//alert(oXmlHttp.responseText);
			//alert ("Got response : all data has been received and the connection has been closed");
		}
	}
	
	/*
	if (oXmlHttp.status == 200){
		alert("Data return is : " + oXmlHttp.responseText);
	}
	else {
		alert("An error occurred: " + oXmlHttp.statusText);
	
	}*/
	oXmlHttp.send(null);
	
}	
	
	//alert(sData);
	
function createXMLHttp(){
	if (typeof XMLHttpRequest != "undefined"){
		//alert ("other browser XMLHTTP OBJECT");		
		return new XMLHttpRequest();
		
	}
	else if (window.ActiveXObject){
		//var oXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		var aVersions = ["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHttp.5.0",
				"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
				"MSXML2.XMLHttp", "Microsoft.XMLHTTP"
				];
		for (var i=0; i < aVersions.length; i++){
			try {
				//alert("Microsoft XMLHttp object");
				var oXmlHttp = new ActiveXObject(aVersions[i]);
				return oXmlHttp;
			} catch (oError){
				//Do Nothing
				document.write ("Your browser doesn't support XMLHTTP.");
				}
		}
	}
	throw new Error ("XMLHttp object could not be created.");
	//document.write ("Hello");

}

//google radio button get check

function lasite(){
	document.gosearch.cx[0].checked = true
}

function trsite(){	
	document.gosearch.cx[1].checked = true
}


//use to open and close sub section in the side navigation
function sideAction(a){
	indAction=document.getElementById(a);	
	if (indAction.style.display == "block"){
		indAction.style.display = "none"
	}
	else{
		indAction.style.display = "block"
	}
}//end of sideAction function

function sideOnState(b){
	indState = document.getElementById(b);
	if (indState.style.textDecoration == "underline"){
		indState.style.textDecoration = "none";
	}
	else
		{
		indState.style.textDecoration = "underline";
		}
}



/******************************************************************************
    Query Handling Methods 
    
    these work with dataset specific javascript methods that are dynamically added
    to the query page to allow delegation at specific page lifecycle events    
    
******************************************************************************/

//see note in code behind file for details on how this event dispatch code functions

$(document).ready(function() {
    var mode = $('#queryMode');

    switch (mode.val()) {
        case 'load':
            QueryFormLoad();
            break;
        case 'reload':
            QueryFormReload();
            break;
        case 'parse':
            QueryResultsLoad();
            break;
        case 'wizard':            
            QueryWizardLoad();
            break;
    }
});

function QueryFormLoad() {
    if (typeof OnQueryFormLoad == 'function') {
        //call query specific method if it exists
        OnQueryFormLoad();
    }
}
function QueryFormReload() {
    if (typeof OnQueryFormReload == 'function') {
        //call query specific method if it exists
        OnQueryFormReload($('#queryString').val());
    }
    else {
        //the query doesn't handle reloading. let's try to reset the users last settings ourselves
        //if the query scripts have change handlers, the users settings may be out of date but we'll at least try to restore...
        repopulateForm();
    }
}
function QueryResultsLoad() {
    parseResults();
}

function QueryWizardLoad() {
    //parseResults(); //clean up the temporary form
}

// The submit buttons first call this client click handler before doing postback to server.
// Give the local script a chance to validate the form before submitting. return true to have 
// it postback
function QuerySubmitted(debug) {
    var passed = true;
    if (typeof OnQuerySubmitted == 'function') {
        if (OnQuerySubmitted() == 'false') {
            passed = false;
        }
    }
    if (passed == true) {
        //serialize form and return true to have server handle postback
        SerializeForm(debug);
        StartThrobber();
    }
    else {
        //what do we do here? show messagebox? report to form and have it display an alertbox on page?
        alert("The current query is invalid. Please correct and submit again.");
        return false;
    }
}

function StartThrobber() {
    // engage throbber
    $('#loadingIndicator').show();
    $("#queryData").html("<div style=\"width:99%;text-align:center;\"<h4>Please wait while we process your query.</h4>");
    // hide submit buttons
    $('.submitButton').hide();
    return true;
}

function SerializeForm(debug) {
    // serialize form...
    var query = $('#queryData input').serialize();
    query += "&" + $('#queryData select').serialize();
    //query += $('#queryData textarea').serialize();
    // DEBUG : _DEBUG = 138?
    if (debug) {
        query += "&_DEBUG=131";
    }
    $('#queryString').val(query);
}

function parseResults() {
    // remove styling
    $('#queryData style').remove();
    // remove scripting
    $('#queryData script').remove();
    $('#queryData noscript').remove();
}

function repopulateForm() {
    //the delegate already had a chance to do this and didn't let's try to restore the users form selections ourselves...
    //$("#queryData select option[selected]").removeAttr("selected"); //remove any selected items
    $("#queryData select option:selected").removeAttr("selected"); //remove any selected items
    var params = $('#queryString').val().split('&');
    var x = 0;
    var cleaned = [];
    for (var i = 0; i < params.length; i++) {
        var f = params[i].split('=');
        // do some quick checks
        if (f[0].charAt(0) != '_'
                && f[1] != ""
                ) {

            // first clean up value
            // replace + for spaces....
            var val = f[1].replace(/\+/g, " ");

            var multiple = -1;
            // now check if its a multiple...
            for (var j = 0; j < cleaned.length; j++) {
                if (cleaned[j][0] == f[0]) {
                    multiple = j;
                    break;
                }
            }

            if (multiple == -1) {
                // add new
                cleaned[x] = [];
                cleaned[x][0] = f[0];
                cleaned[x][1] = val;
                x++;
            } else {
                // add existing 
                cleaned[multiple][1] += ',' + val;
            }
        }
    }

    for (var i = 0; i < cleaned.length; i++) {
        populateFormElement(document.forms[0], cleaned[i][0], cleaned[i][1]);
    }    
}

function populateFormElement(form, name, value) {

    var element = form[name];
    var elements = element.type == undefined && element.item ? element : [element];

    // populate the element correctly
    for (var e = 0; e < elements.length; e++) {
        var element = elements[e];

        switch (element.type || element.tagName) {

            case 'radio':
                // use the single value to check the radio button
                element.checked = (element.value != '' && value.toString().toLowerCase() == element.value.toLowerCase());
                break;

            case 'checkbox':
                // depends on the value.
                // if it's an array, perform a sub loop
                // if it's a value, just do the check

                value = value.split(',');

                var values = value.constructor == Array ? value : [value];
                for (var j = 0; j < values.length; j++) {
                    element.checked |= element.value == values[j];
                }

                //element.checked = (element.value != '' && value.toString().toLowerCase() == element.value.toLowerCase());
                break;

            case 'select-multiple':
                //debugger;
                value = value.split(',');

                var values = value.constructor == Array ? value : [value];
                for (var i = 0; i < element.options.length; i++) {
                    for (var j = 0; j < values.length; j++) {
                        element.options[i].selected |= element.options[i].value == values[j];
                    }
                }
                break;

            case 'select':
            case 'select-one':
                element.value = value.toString().toLowerCase() || value;
                break;

            case 'text':
            case 'button':
            case 'textarea':
            case 'submit':
            default:
                value = value == null ? '' : value
                element.value = value;
        }
    }
}

