/* used for weather-data.shtml and /climate/data/index.shtml */
//generic bom functions
var bom = {
	//methods: addEvent, show, hide
	
	addEvent: function (obj,evt,fn){
		if(obj.addEventListener){
			obj.addEventListener(evt, fn, false);
		}
		else if(obj.attachEvent){
			obj.attachEvent('on' + evt,fn);
		}
	},
	show: function (id){
		for(var i=0; i< arguments.length; i++){
			var el = arguments[i];
			if(document.getElementById(el)){
				document.getElementById(el).style.display = 'block';
			}
		}
	},
	hide: function (id){
	   for(var i=0; i< arguments.length; i++){
			var el = arguments[i];
			if(document.getElementById(el)){
				document.getElementById(el).style.display = 'none';
			}
		}
	},
	pad: function(val, len) {
        val = String(val);
	    len = len || 2;
	    while (val.length < len) {val = "0" + val;}
	    return val;
    },
	
	hasClass: function(ele,cls) {
    	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
    },
    addClass: function(ele,cls) {
    	if (!bom.hasClass(ele,cls)) ele.className += " "+cls;
    },
    removeClass: function(ele,cls) {
    	if (bom.hasClass(ele,cls)) {
    		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
    		ele.className=ele.className.replace(reg,' ');
    	}
   }
	
};

var xmlHttp, returnElements, dwoId; 
var CdoCookieObj ='';
//currentIndex=0 //currentIndex = unused

function formInit(){
	document.getElementById('ncc_obs_code_group').selectedIndex = 0;
	dataType.doElementGroup();
	bom.hide('elementSubSelectLine');
	document.climatedata.p_display_type.value = 'dailyDataFile';
	dataType.nccObsCode(136);
	dwoId = '';
	////check below against cookie option
	dataType.searchForSiteNum = false;
	
	//pos and loc links
	dataType.initLinks();
	//location and position search + station num
	resetSearchDisplay();
	
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp === null)  {
		alert ("Your browser does not support this page. You may need to update your browser");
		return;
	}
	//checks cookie enabled, checks for cookie CDO, if yes, gets and stores values
	//CdoCookieObj = new CookieManager('CDO',30 ); //ie
	dataType.checkForCookie();
}
if(CdoCookieObj === ''){ 
    CdoCookieObj = new CookieManager('CDO',30, '/climate/' );
}

function resetSearchDisplay(){
	//hide form elements until relevant, reset site num
	bom.hide('p_name_step1','matchingForm','tab2', 'nearestStations','holdings','holdingsMessage', 'daily_year');
	document.getElementById('p_stn_num').value= '';
}

function GetXmlHttpObject(){
	xmlHttp=null;
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e){
		// Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
    	catch (e){
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

//mini-map
function displayMap(state){
	if(document.getElementById("mapimage")){document.getElementById("mapimage").className=state; } 
}

//check site number
function checkSiteNum(val){
	val = val.replace(/^\s*/, "").replace(/\s*$/, "");    // remove leading & trailing whitespace
	if(val === ''){
		alert("Please search for or enter a weather station number.");
	    return false;
	}

	if ( val.match(/\D/) ) {                                   // any non-digit characters?
		alert("The station number must consist only of numbers,\n so '" + val + "' cannot be used.");
		return false;
	} 
	if (val < 1000 || val >= 400000) {             // in range?
		alert("The station number must be between 001000 and 399999");
		return false;
	} 
	else {
        return bom.pad(val,6);
	}
}

//check site number then submit
function validateSiteNum(dataType) {
	var path, nccObsCode, theInput, newWindow;
    nccObsCode = document.getElementById("p_nccObsCode").value;
	theInput = document.getElementById("p_stn_num").value;
	if(!checkSiteNum(theInput)){ return;
	} 
	else { 
	   theInput = checkSiteNum(theInput);
	}
        
	if (dataType=="pdfmetadata"){
		document.pdfmetadata.stationid.value = theInput;// save the modified version
		document.pdfmetadata.submit();                  // go get it
	}
	else if (dataType=="climatedata"){

		if(nccObsCode === "200"){
			path = "/climate/averages/tables/cw_" + theInput + ".shtml";   
			//window.location = path;
			newWindow = window.open(path,dataType);
			if (newWindow.focus){newWindow.focus();}
			return; 
		 }
		
		else if(nccObsCode === "201"){
			//if has been searched for
			if(dwoId !== ''){
				path = "/climate/dwo/IDCJDW" + dwoId + ".latest.shtml";   
			   //window.location = path;
				newWindow = window.open(path,dataType);
				if (newWindow.focus){newWindow.focus();}
				return; 
			}
			//for direct entry
			else { 
			    document.getElementById('p_display_type').value= 'dwo';
			}
		}
		document.climatedata.p_nccObsCode.value = nccObsCode;
		document.climatedata.submit();	
	}
}

function getMatching(arg1, arg2){
	var url, searchLoc, state;
	
	url="/jsp/ncc/cdio/weatherData/av";
	searchLoc = arg1;
	state = arg2;
	returnElements = '';
	if (searchLoc.length<1){
		alert("Please enter at least one letter in your location box first");
		return;
	}
	//p_nccObsCode is not used for gazetteer search thus hardcoded to 139
	url=url+"?p_stn_num=86071&p_display_type=gazetteer&p_nccObsCode=139&p_locSearch="+searchLoc+"&p_state="+state;
	url=url+"&sid="+Math.random();

	xmlHttp=GetXmlHttpObject();
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=populateMatchList;
	xmlHttp.send(null);
}
//id matchlist has name p_match
function populateMatchList(arg1){
	var responseStr, returnMatchElements;
	bom.show('matchingForm');
    document.getElementById('matchingForm').focus();
	document.getElementById("matchList").options.length=0;
	document.getElementById("matchList").options[0]=new Option("Loading matching towns...", "0");
	document.getElementById("nearest10").options.length=0;
	
	getImage('holdings-img',"/climate/cdo/images/about/no-site.png");
		
	if (xmlHttp.readyState==4){
		responseStr = xmlHttp.responseText;
		returnMatchElements = responseStr.split("||");
		
		if (returnMatchElements.length > 100){
			document.getElementById("matchList").options[0]=new Option("Too many locations matched your search criteria", "criteria");
		}
		else if (responseStr.indexOf("Empty resultset") >= 0){
			document.getElementById("matchList").options[0]=new Option("No town name matches your search criteria", "criteria");
		}
		else if (responseStr.indexOf("HTTP Status 503") > 0){
			document.getElementById("matchList").options[0]=new Option("Data download and searching tool is currently not available", "notAvailable");
		}
		else {
			for (var i=0; i<returnMatchElements.length-1; i++){				
				    document.getElementById("matchList").options[i]= new Option(returnMatchElements[i],returnMatchElements[i]);
			}
		}
	}
}

//searchType = name or loc
//for loc ar1 = radius + site num + lat + lon //site num OR (lat + lon) should be ''
function getNearest10(arg1, searchType){
	var url, arg1Temp, matchString, nccObsCode;
	
	xmlHttp=GetXmlHttpObject();
	if (arg1.length === 0){
		alert("Please search for matching towns first. If you already know a station number, enter it in the the 'Station number' field, then  click the 'Get Data' button");
		return;
	}
	url="/jsp/ncc/cdio/weatherData/av";
	arg1Temp = arg1.replace('\u00B0S',''); //remove \u00B0S
	matchString = arg1Temp.replace('\u00B0E','');
	nccObsCode = document.getElementById("p_nccObsCode").value;

	if ( (matchString.indexOf("criteria") < 0)&&(matchString.indexOf("notAvailable") < 0)&&(matchString.length > 0) ){
		if (searchType === "name"){
			matchString = matchString+",,LATLON,"+nccObsCode;	
			url=url+"?p_stn_num=86071&p_display_type=nearest10_tab1&p_nccObsCode="+nccObsCode+"&p_match="+matchString;
		}
		
		else if (searchType === "loc"){
            matchString = matchString+",";
			var locForm = document.getElementById("radiusForm");
			
			//station number and distance?
			if (locForm.distOption[0].checked === true){
				matchString = matchString+',S_NUM';
				
				if(locForm.radius.value ===""  || locForm.refStation.value ===""){
					alert("Please fill in Station number and search distance");
					return;
				}
				else if(locForm.refStation.value !== ""){
				   if(!checkSiteNum(locForm.refStation.value)){return;}
			    }
				else if(document.getElementById("radiusForm").radius.value>500 ){
					alert("Search distance must be less than 500 km");
					return;
				}
			}
			
			else if (locForm.distOption[1].checked === true){
				matchString = matchString+',LATLON';
				if(locForm.radius.value ==="" || document.getElementById("radiusForm").refLat.value ==="" || document.getElementById("radiusForm").refLon.value ===""){
					alert("Please fill in the Coordinates and search distance");
					return;
				}
				else if(locForm.radius.value>500 || locForm.refLat.value>90 || locForm.refLon.value>180 ){
					alert("Must be less than 90 for degrees South and less than 180 for degrees East and search distance must be less than 500 km");
					return;
				}
			}
			
		    matchString = matchString+","+ nccObsCode;
			url=url+"?p_stn_num=86071&p_display_type=nearest10_tab2&p_nccObsCode=139&p_match="+matchString;		
		}
		
		url = url + "&sid=" + Math.random();
		xmlHttp.open("GET",url,true);
		
		document.getElementById("nearest10").options.length=0;
		document.getElementById("nearest10").options[0]=new Option("Loading nearest stations...", "0");

        getImage('holdings-img',"/climate/cdo/images/about/no-site.png");
		xmlHttp.onreadystatechange=populateNearest10;
		
		xmlHttp.send(null);
	}
}
//dwoId is global...
function dwoText(str){
	var siteNum, text;
	//remove dwo id refs
	str = str.substring(5);
    //extract siteNum and pad
	siteNum = str.match(/\d{4,}/);
	if(siteNum.length === 0){ return;}
	
	text = str.replace(siteNum, "");
	
	siteNum = bom.pad(siteNum,6);
	str = siteNum + " " + text;
	return str;
}

function refreshStationList(){
	var j=0; var i, optionText ;
	if (returnElements.length === 1){ return;}
	document.getElementById("nearest10").options.length=0;
	
//needs a check, re: exceptions	
	if(document.nearestForm.openStation.checked === true){
		if(document.getElementById('p_nccObsCode').value === "201"){
			for (i=0; i<returnElements.length; i++){
				if(returnElements[i].match(/[\s]{4}/)){				
					optionText = dwoText(returnElements[i]);
					
					document.getElementById("nearest10").options[j] = new Option(optionText,returnElements[i]);
					j++;
				}
			}
		 }     
        else{
			for (i=0; i<returnElements.length; i++){
				if(returnElements[i].match(/[\s]{4}/)){
					document.getElementById("nearest10").options[j] = new Option(returnElements[i],returnElements[i]);
					j++;
				}
			}
         }
	}

	else{
		if(document.getElementById('p_nccObsCode').value === "201"){	
			for (i=0; i<returnElements.length; i++){
				optionText = dwoText(returnElements[i]);
				document.getElementById("nearest10").options[i]=new Option(optionText,returnElements[i]);
			}
		} 
		else{
			for (i=0; i<returnElements.length; i++){
				document.getElementById("nearest10").options[i]=new Option(returnElements[i],returnElements[i]);
			}
		}
	}
	getImage('holdings-img',"/climate/cdo/images/about/no-site.png");	
}

function checkEnter(e, searchStr, state){ //e is event object passed from function invocation
	var keynum;
	if(window.event){ // IE
		keynum = e.keyCode;
	}
	else if(e.which){ // Netscape/Firefox/Opera
		keynum = e.which;
	}	
	if (keynum == "13"){
		getMatching(searchStr,state);
	}
	else{
		return true; 
	}
}

//get distance/location val or they can set a variable - if selected and no return then error message
function populateNearest10(){
	var nccObsCode, msg, responseStr;
	document.getElementById('p_stn_num').value= '';
	bom.show('nearestStations');
     document.getElementById('nearestStations').focus();
	nccObsCode = document.getElementById("p_nccObsCode").value;
	
	msg = 'There are no search matches for your search values';
	//searchType === 'loc'? msg ="No station within 300km to the selected town" : msg="No station matched the specified search criteria";
	if (xmlHttp.readyState === 4){
		responseStr = xmlHttp.responseText;
		document.getElementById("nearest10").options.length=0;
		
		if (responseStr.indexOf("Empty resultset") >= 0) {
			document.getElementById("nearest10").options[0]=new Option(msg, "0");
		}
		else if (responseStr.indexOf("HTTP Status 503") > 0){
			document.getElementById("nearest10").options[0]=new Option(msg, "notAvailable");
		}
		else {
		    returnElements = responseStr.split("||");
			refreshStationList();
		}
	}
}

function populateStationBox(arg1, searchType){
	var stn_num, url, matchString, nccObsCode, siteNum, a;
	stn_num = arg1.substr(0,6); 
    dataType.checkSaved();
	
	xmlHttp = GetXmlHttpObject();
	url="/jsp/ncc/cdio/weatherData/av";
	matchString = arg1;	
	nccObsCode = document.getElementById('p_nccObsCode').value;
 
	if(nccObsCode === "201"){
		siteNum = document.nearestForm.nearest10.value;
		dwoId = arg1.substr(0,4);	
	    siteNum = siteNum.replace(/\d{4}_(\d{4,6}).*/, "$1");
        siteNum = bom.pad(siteNum,6);
		document.getElementById("p_stn_num").value = siteNum;
		bom.show('holdings');

		holdingsMessage("Daily weather data is available for the previous 13 months for most stations.");
		return;
	}
	if(nccObsCode === "200"){
		bom.show('holdings');
		holdingsMessage("No information is available for this type of data.");
	}
		
	if ((matchString.indexOf("criteria") < 0)&&(matchString.indexOf("notAvailable") < 0)&&(matchString.length > 1)){       //there should be more, but enough to test just > 1
        getImage('holdings-img',"/climate/cdo/images/about/loading-graph.png");
		
		url=url+"?p_stn_num="+stn_num+"&p_display_type=holdingGraph&p_nccObsCode="+nccObsCode;
		url=url+"&sid="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=function(){ fillStationNumber();};
		xmlHttp.send(null);
		
		if(nccObsCode !== "200"){
            a=setTimeout('getImage(\'holdings-img\',\'/tmp/cdio/'+stn_num+'_'+nccObsCode+'.gif\') ',2000);
		    bom.show('holdings');
		}

	}
}

function fillStationNumber(){
	var nccObsCode, responseStr, stn_num;
	nccObsCode = document.getElementById('p_nccObsCode').value;
	
	if (xmlHttp.readyState === 4){
  		responseStr = xmlHttp.responseText;
  		if (responseStr.indexOf("Success") !== -1) {

			if(nccObsCode === "136"){
                doYears(responseStr);
				document.climatedata.p_display_type.value = 'dailyDataFile';
			}

			stn_num = responseStr.substr(0,6);
			document.climatedata.p_stn_num.value=stn_num;
			////
            dataType.searchForSiteNum = true;
			
			document.getElementById('saveMe').focus();
  		}
	}
}

function getImage(pExistingImageID, pImageURL){
	var img;
	img = document.createElement('img');
	img.onload = function (evt) {
		document.getElementById(pExistingImageID).src=this.src;
	};
	img.src = pImageURL;
	return true;
}

function doYears(xhrResponse){
	var ystring, years;
	ystring = xhrResponse.substr(16);
	////some daily stations have no years
	if(ystring.length===0){
		document.getElementById("p_startYear").value ='1970';
		bom.hide('daily_year');
		return;
	}
	years = ystring.split(',');
	years.reverse();
	//make option list
	for(var i = 0; i < years.length; i++){
		document.getElementById('year_select').options[i] = new Option(years[i], years[i]);
	}
	document.climatedata.p_startYear.value = document.getElementById('year_select').options[0].value;
	
	bom.show('daily_year');
    document.getElementById('daily_year').focus();
}

function doYear(year){
	if(year) {document.climatedata.p_startYear.value = year;}
}

function clearAll(){
	//changed data type so reset 
	clearOptions(document.getElementById('nearest10'));
	document.getElementById('matchList').selectedIndex = -1;
    getImage('holdings-img','/climate/cdo/images/about/no-site.png');
	document.climatedata.p_stn_num.value='';
	bom.hide('daily_year', 'holdingsMessage');
	bom.show('holdings-img', 'timescale');
	if(document.getElementById('p_nccObsCode').value === '200'){
		holdingsMessage('No information is available for this type of data.');
	}
	if(document.getElementById('p_nccObsCode').value === '201'){
		holdingsMessage('Daily weather data is available for the previous 13 months for most stations.');
	}
////make cookie link active
document.getElementById('saveSelection').className = 'link';
}

function clearOptions(selectbox){
    var i;
	for(i=selectbox.options.length-1; i>=0;i--){
	selectbox.remove(i);
	}
}

function holdingsMessage(msg){
	if(msg){
		document.getElementById('holdingsMessage').innerHTML = msg;
	}
	bom.hide('holdings-img','timescale' );
	bom.show('holdingsMessage');
}

function siteMap(arg1){
	var siteNum, url, newWindow;
    if(arg1 ===''){alert("Please select a weather station first");return;}
	
	siteNum = arg1.substr(0,6);
	url="/jsp/ncc/cdio/cvg/av";
	
	//for dwo get site number via select val
	if(document.getElementById('p_nccObsCode').value === "201"){
	
	    siteNum = document.nearestForm.nearest10.value;
	    siteNum = siteNum.replace(/\d{4}_(\d{4,6}\b).*/, "$1");
	}
	
	siteNum = checkSiteNum(siteNum);
	url=url+"?p_stn_num="+siteNum+"&p_prim_element_index=0&p_display_type=enlarged_map&period_of_avg=&normals_years=&p_comp_element_index=0&redraw=null";
	
	//check whether to use pop-ups
	newWindow=window.open(url,"topomap");
		if (newWindow.focus){
			newWindow.focus();
		}
}

//init = redundant?
function checkdwo(){
	if(document.getElementById('p_nccObsCode').value === '201'){
		dwoId = '';
	    document.getElementById("p_stn_num").value = '';
	}
}

//add
function doKey(e){
	var key;
	if(window.event){ // IE
		key = e.keyCode;
	}
	else if(e.which){ // Netscape/Firefox/Opera
		key = e.which;
	}	
	return key;
}

//replace below with above
function numberOnly(e){
	var key, keychar, numcheck;
	key  = doKey(e);
	keychar = String.fromCharCode(key);
	numcheck = /\d|[.]|[\b]/;
	return numcheck.test(keychar);
}

//called by station number field
function numberAndSubmit(e){
	var keynum;
	keynum = doKey(e);
	if (keynum == "13"){
		validateSiteNum('climatedata');
	}
//requires onKeyUp for x-browser below, onkeypress for alphanums
	else if (keynum == "9"){
		if(document.climatedata.p_stn_num.value !==''){
		   document.climatedata.getData.focus();
		}
		else {return false;}
	}
	else{
		return numberOnly(e);
	}
}


//arg1 = radius, site num, lat, lon
function numberAndGetNearest10(e, arg1, searchType){
	var keynum;
	keynum= doKey(e);
	if (keynum == "13"){
		getNearest10(arg1, searchType );
	}
	else if (keynum == "9"){
		//trapping
		return false;
	}
	else{
		return numberOnly(e);
	}
}

/* data type selection and config */
var dataType = {
	//config constants
	bgroup: ['dt1','dt2','dt3'],	
	//ncc obs code, element group,  element type, element order, description
	dataTypes:[[136, 'rainfall',    1, 'daily',      'Daily rainfall data and graphs for a selected year.' ],
			   [139, 'rainfall',    1, 'monthly',    'Monthly rainfall data and graphs for all available years.' ],
			   [36,  'temperature', 2, 'monthly',    'Mean maximum temperature data and graphs for all available years.'],
			   [38,  'temperature', 2, 'monthly',    'Mean minimum temperature data and graphs for all available years.'],  
			   [40,  'temperature', 2, 'monthly',    'Highest temperature data and graphs for all available years.'],
			   [41,  'temperature', 2, 'monthly',    'Lowest maximum temperature data and graphs for all available years.'],
			   [42,  'temperature', 2, 'monthly',    'Highest minimum temperature data and graphs for all available years.'], 
			   [43,  'temperature', 2, 'monthly',    'Lowest temperature data and graphs for all available years.'],
			   [201, 'weather',     3, 'daily',      'Daily weather observations data for the last month. Links to data for the previous year. Data may be from a number of stations.'],
			   [200, 'weather',     3, 'statistics', 'Monthly weather statistics and graphs for all available years.']
			   ],
	
	daily: {
		rainfall: [136, 'Rainfall'],
		weather: [[201, 'Weather']]
	},
	
	monthly: {
		temperature: [[36,'Mean maximum temperature'],[38 ,'Mean minimum temperature'],  [40,'Highest temperature'],[ 41, 'Lowest maximum temperature'],[42,'Highest minimum temperature'], [43, 'Lowest temperature']],
		rainfall: [[139,'Monthly rainfall']]
	},
	
	statistics: {
		weather: [[200, 'Statistics']]
	},
	
	rainfall:{daily:{},monthly:{},statistics:{}},
	temperature:{
		monthly:[[36,'Mean maximum temperature'],[38 ,'Mean minimum temperature'],  [40,'Highest temperature'],[ 41, 'Lowest maximum temperature'],[42,'Highest minimum temperature'], [43, 'Lowest temperature']]
	},
	
	//build subselect
	typeSubSelect: function(el){
		var element,selectEl,val;
		//get type && getbutton vals ==>
		element = dataType[el].monthly;
		
		selectEl = document.getElementById("elementSubSelect");
		selectEl.options.length=0;
		for(var i=0;i< element.length;i++){
		     selectEl.options[i]=new Option(element[i][1], element[i][0]);
		}
		val = selectEl.options[0].value;
		dataType.nccObsCode(val);
	}, 
	
	//bgroup = array of button ids
	disable: function(){
		var bgroup; 
		//make all active
		bgroup = this.bgroup;
		for(var j=0; j < bgroup.length; j++){
			document.getElementById(bgroup[j]).disabled=false;
			document.getElementById(bgroup[j]+ '_t').className = 'active';
			bom.hide('elementSubSelectLine');
		}
		//some inactive
		for(var i=0;i<arguments.length;i++){
			document.getElementById(arguments[i]).disabled=true;
			document.getElementById(arguments[i]+ '_t').className = 'disabled';
		}
	},
	//val: integer as string
	nccObsCode: function (val){
		document.getElementById('p_nccObsCode').value = val;
		dataType.checkSaved();
		dataType.description(val);
		//// review temperature checked status, ie. explicitly uncheck default
		if((document.data_type.data[0].checked === true) && (document.getElementById('ncc_obs_code_group').value != 2)){
			document.climatedata.p_display_type.value = 'dailyDataFile';
			}
		else{document.climatedata.p_display_type.value = 'dataFile';}
    },
	description: function(val){
		var description;
		if(!document.getElementById('descriptionDisplay')){return;}
			
		for(var i = 0; i< dataType.dataTypes.length;i++){
			if(dataType.dataTypes[i][0] == val){
				description = dataType.dataTypes[i][4];
				document.getElementById('descriptionDisplay').innerHTML = description;
			}
		}
	},

	//disabled from initial values - use for cookie call
	disabledButtons: function(){
		var elGroup = document.getElementById('ncc_obs_code_group');
		//rainfall
		if(elGroup.value === '1'){
			//disable stats button
			dataType.disable('dt3');
			//checkbuttons
		}
		//temperature
		else if(elGroup.value === '2'){
			//disable daily and stats button
			dataType.disable('dt1','dt3');
			dataType.typeSubSelect('temperature');
			bom.show('elementSubSelectLine');
			}
		//weather
		else if(elGroup.value === '3'){
			//disable monthly button
			dataType.disable('dt2');
			}
	},
	
	initSetButtons: function(){
		var elGroup = document.getElementById('ncc_obs_code_group');
		//rainfall
		if(elGroup.value === '1'){
			if(document.data_type.data[0].checked===true){
				dataType.nccObsCode(136);
				}
			else if(document.data_type.data[1].checked===true){
				dataType.nccObsCode(139);
				}
			else{document.data_type.data[0].checked=true;
			    dataType.nccObsCode(136);
			}
		}
		//temperature
		else if(elGroup.value === '2'){
			document.getElementById('dt2').checked=true;
		}
		//weather
		else if(elGroup.value === '3'){
			document.getElementById('dt1').checked=true;
			dataType.nccObsCode(201);
		}
	},
	
	//primary element group select - init values and disabled
	//ncc_obs_code_group - sets default values
	doElementGroup: function (){
		var elGroup;
		elGroup = document.getElementById('ncc_obs_code_group');
		//rainfall
		if(elGroup.value === '1'){
			//disable stats button
			dataType.disable('dt3');
			
			//checkbuttons
			if(document.data_type.data[0].checked===true){
				dataType.nccObsCode(136);
				}
			else if(document.data_type.data[1].checked===true){
				dataType.nccObsCode(139);
				}
			else{document.data_type.data[0].checked=true;
			    dataType.nccObsCode(136);
			}
			
		}
		//temperature
		else if(elGroup.value === '2'){
			//disable daily and stats button
			dataType.disable('dt1','dt3');
			document.getElementById('dt2').checked=true;
			dataType.typeSubSelect('temperature');
			bom.show('elementSubSelectLine');
			}
		//weather
		else if(elGroup.value === '3'){
			//disable monthly button
			dataType.disable('dt2');
			document.getElementById('dt1').checked=true;
			dataType.nccObsCode(201);
			}
	},

	//for radio buttons
	dodata: function (val){
		var element;
		element = document.getElementById('ncc_obs_code_group').value;
		if(val ==='monthly'){
			if(element ==="1"){dataType.nccObsCode(139); clearAll();}
			else if(element ==="2"){
				alert("Please select a temperature option below");
				return; 
			}
		}
		else if(val ==='daily'){
			if(element ==="1"){dataType.nccObsCode(136); 
			clearAll();
			}
			else if(element ==="3"){dataType.nccObsCode(201);
			clearAll();
			}
		}
		else if(val === 'statistics'){
			////
			if(element ==="3"){dataType.nccObsCode(200); clearAll();}
		}
		else {
			return;
		}
	 },
	initLinks: function (){
		document.getElementById('searchByLocation').onclick = function(){
			resetSearchDisplay();
			bom.hide('tab2');
			bom.show('p_name_step1');
            document.getElementById('p_name_step1').focus();
			document.getElementById('saveSelection').className = 'link';
		};
		document.getElementById('searchByPosition').onclick = function(){
			resetSearchDisplay();
			bom.show('tab2');
            document.getElementById('tab2').focus();
			bom.hide('p_name_step1');
			document.getElementById('saveSelection').className = 'link';
		};
		document.getElementById('saveSelection').onclick = function(){
            dataType.saveSelection();
			
            ////stage 2: dataType.saveSet();
            document.getElementById('getData').focus();
		};
		    document.getElementById('clearSelection').onclick = function(){
			CdoCookieObj.removeKey('p_nccObsCode', 'p_display_type','p_stn_num', 'p_startYear');
			formInit();
			document.getElementById('saveSelection').className = 'link';
			document.getElementById('clearSelection').className = 'innactive';
		};
		    document.getElementById('aboutSaving').onfocus = document.getElementById('aboutSaving').onmouseover = function(){
			bom.show('cookieMessage');
            document.getElementById('cookieMessage').focus();
		};
		    document.getElementById('aboutSaving').onmouseout = document.getElementById('aboutSaving').onblur = function(){
			bom.hide('cookieMessage');
		};
		    //station information link
		if(document.getElementById('station-info')){
			document.getElementById('station-info').onclick  = function(){
			siteMap(document.climatedata.p_stn_num.value);
		    }
		}
	},
	/*
	* set of values for constructing saved value sets
	*/
    saveSet: function(){
		var val='', key;
		if(CdoCookieObj.p_nccObsCode){
		    key = 'id_' + CdoCookieObj.p_stn_num;
		}
		else{return;}
		//get set
	    val = CdoCookieObj.keySet('p_stn_num', 'p_nccObsCode' , 'p_display_type','p_startYear'); 
		CdoCookieObj.setCookie(key,val);
	},
	/*
	* read of values from specified set, then load into page
	*/
	displaySet: function(){
		
	},
	/*
	* construct a custom menu from all sets
	*/
	menuForSets: function(){
		//get all sets, match labels, order by site number, construct menu

	},
    checkForCookie: function (){
		if(!CdoCookieObj.$exists){return;}
		//else get values and write to form
		//clear any location /station selections 
	    clearAll();
	    resetSearchDisplay();
		var thisForm = document.getElementById('climatedata');
		if(CdoCookieObj.p_nccObsCode  && CdoCookieObj.p_stn_num && CdoCookieObj.p_nccObsCode){
			thisForm.p_nccObsCode.value =  CdoCookieObj.p_nccObsCode;
			thisForm.p_stn_num.value = CdoCookieObj.p_stn_num;
			thisForm.p_display_type.value = CdoCookieObj.p_display_type;
		} 
		//
		dataType.showDataType(CdoCookieObj.p_nccObsCode);
   },
   //set data type selectors to match cookie val
   showDataType: function(type){
		for (var i = 0;i< dataType.dataTypes.length ; i++){
		   if(type == dataType.dataTypes[i][0]){
			   //set form
				document.getElementById('ncc_obs_code_group').selectedIndex = dataType.dataTypes[i][2] -1;
                //disable irrelevant buttons + reinits values
				dataType.disabledButtons();
                //reset init value to cookie val       
				//set active button
				dataType.buttonGroup(i);
				if(dataType.dataTypes[i][1] === 'temperature'){
					dataType.subElGroup(i);
				}
				document.getElementById('descriptionDisplay').innerHTML =dataType.dataTypes[i][4];
		   }
		}
	   //dim Save link
	   document.getElementById('saveSelection').className = 'innactive';
	   document.getElementById('clearSelection').className = 'link';
   },
   buttonGroup: function(i){
	   var typeOf, formEl;
	   typeOf = dataType.dataTypes[i][3]; 
	   formEl = document.data_type.data;
	   
	   for(var j = 0; j<formEl.length;j++){
		   if(formEl[j].value == typeOf ){
			   formEl[j].checked = true;
		   }
	   }
   },

   subElGroup: function(i){
	   var type = dataType.dataTypes[i][0];
	   //to make generic - glean or generate  subselects
	   var formEl = document.getElementById('elementSubSelect');
	   for(var j=0; j<formEl.length; j++){
		   if(formEl.options[j].value == type){
			   formEl.selectedIndex = j;
			   //reset the nccobs code
			   document.getElementById('p_nccObsCode').value =type;
		   }
	   }
   },
	
	saveSelection: function(){
		//link visible after submitting or station search, hidden with clearAll()
		var formel, code, display, station;
		formel = document.getElementById('climatedata');
        code = formel.p_nccObsCode.value;
		display = formel.p_display_type.value;
		station = formel.p_stn_num.value;
        
		if(!checkSiteNum(station)){return;}
		if(CdoCookieObj){
		   CdoCookieObj.setCookie({'p_nccObsCode': code,'p_display_type': display, 'p_stn_num': station});
		   alert('This station number and the type of data you selected will be saved if your web settings permit.\n They will be loaded next time you visit on this computer.');
		   document.getElementById('saveSelection').className = 'innactive';
		   document.getElementById('clearSelection').className = 'link';
		}
	},
	checkSaved: function(){
		if(CdoCookieObj && CdoCookieObj.p_nccObsCode){
		    //check the current nccobs code against stored cookie val
		    if(document.getElementById('p_nccObsCode').value == CdoCookieObj.p_nccObsCode){
				document.getElementById('saveSelection').className = 'innactive';
				document.getElementById('clearSelection').className = 'link'; 
		    }
		    else {
				document.getElementById('saveSelection').className = 'link';
				document.getElementById('clearSelection').className = 'innactive'; 
			}
		}
	}
};

window.onLoad = bom.addEvent( window, 'load', formInit );