/* global constants */
var STN_STATUS_UPDATE_SCRIPT = ROOT_URL + 'ajax/updateStation.php';
var USR_CHECK_USRNAME_AVAIL = ROOT_URL + 'ajax/checker.php';
var USR_CHECK_STNID_AVAIL = ROOT_URL + 'ajax/checker.php'
var GKEY = 'ABQIAAAAMaHR2A6vFlEv9UyvI67vSRQtOv1z2FVva5LiRoPKQpou2oQ1mxRjhyKFS-dPbc4E6NDsslOscIngtg';

var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};

/* prototypes */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

document.getElementsByClassName = function (clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

/* general functions */
var rules = new Array();
function removeYavRule (field) {
	if (rules) {
		for (var i=0; i < rules.length; i++) {
			var r = rules[i];
			if (r.indexOf(field) >= 0) {
				rules.splice(i, 1);
			}
		}
	}
}

function checkCountry (country, statesel) {
	country = country.toUpperCase();
	if (country == 'US' || country == 'CA') {
		rules.push(statesel + '|required|State is required');
		if ($(statesel + '_req')) $(statesel + '_req').style.display = 'inline';
	}
	else {
		removeYavRule(statesel);
		if ($(statesel + '_req')) $(statesel + '_req').style.display = 'none';
		if ($(statesel)) $(statesel).className = '';
		if ($('errorsDiv_' + statesel)) $('errorsDiv_' + statesel).innerHTML = '';
	}
}

function swapStationGraph (timg, stnid, date, plot, type, detailed) {
	if ($(timg) && stnid) {
		type2 = (detailed) ? type + 'full' : type;
		$(timg).src = ROOT_URL + 'scripts/wxgraph.php?id=' + stnid + '&plot=' + plot + '&s=' + date + '&do=' + type2;
		$(timg + '-linker').innerHTML = '<a href="#" onclick="swapStationGraph(\'' + timg + '\', \'' + stnid + '\', \'' + date + '\', \'' + plot + '\', \'' + type + '\', ' + ((detailed) ? 0 : 1) + '); return false;">Click here for the ' + ((detailed) ? 'summary' : 'detailed') + ' graph</a>.';
	}
}

function showStatusEditor (station, close) {
	if ($('status-' + station) && $('statedit-' + station)) {
		if (close) {
			$('status-' + station).show();
			$('statedit-' + station).hide();
		}
		else {
			$('status-' + station).hide();
			$('statedit-' + station).show();
		}
	}
}

function updateStationStatus (station, status, adm) {
	if (station) {
		$('detail-' + station).innerHTML = '<img src="' + ROOT_URL + 'images/ajaxloader.gif" width="16" height="16" />';

		// update station status
		new Ajax.Request(STN_STATUS_UPDATE_SCRIPT,
		{
			method:'get',
			parameters: 'do=setstatus&status=' + status + '&id=' + station,
		    onSuccess: function(transport) {
				var response = transport.responseText || '';
				if (response == 1) {
					$('staticn-' + station).className = 'staticn-active';
					$('stattext-' + station).innerHTML = 'Active';
					$('detail-' + station).innerHTML = '(<a href="javascript:updateStationStatus(\'' + station + '\',0);">deactivate</a>)';
				}
				else if (response == 0) {
					$('staticn-' + station).className = 'staticn-inactive';
					$('stattext-' + station).innerHTML = 'Inactive';
					$('detail-' + station).innerHTML = '(<a href="javascript:updateStationStatus(\'' + station + '\',1);">activate</a>)';
				}
				else if (response == -1) {
					$('staticn-' + station).className = 'staticn-noapprv';
					$('stattext-' + station).innerHTML = 'Unapproved';
				}
				else if (response == 2) {
					$('staticn-' + station).className = 'staticn-nodata';
					$('stattext-' + station).innerHTML = 'Old/No Data';
				}

				if (adm == true) {
					$('detail-' + station).innerHTML = '(<a href="#" onclick="showStatusEditor(\'' + station + '\')">change</a>)';
					showStatusEditor(station, true);
				}
		    },
		    onFailure: function() {
				$('detail-' + station).innerHTML = 'Failed!';
			}
		});
	}
}

function checkUsernameAvail (name, tmsg) {
	if (name) {
		$(tmsg).innerHTML = '<img src="' + ROOT_URL + 'images/ajaxloader.gif" width="16" height="16" />checking...';

		// update station status
		new Ajax.Request(USR_CHECK_USRNAME_AVAIL,
		{
			method:'get',
			parameters: 'do=unameavail&un=' + name,
		    onSuccess: function(transport) {
				var response = transport.responseText || '';
				if (response == 1) {
					$(tmsg).className = '';
					$(tmsg).innerHTML = 'Username available!';
				}
				else if (response == 0) {
					$(tmsg).className = 'innerError';
					$(tmsg).innerHTML = 'Username taken!';
				}
		    },
		    onFailure: function() {
				$(tmsg).innerHTML = 'Check failed';
			}
		});
	}
}

function checkStationIdAvail (id, tmsg) {
	if (id) {
		$(tmsg).innerHTML = '<img src="' + ROOT_URL + 'images/ajaxloader.gif" width="16" height="16" />checking...';

		new Ajax.Request(USR_CHECK_STNID_AVAIL,
		{
			method:'get',
			parameters: 'do=stnidavail&id=' + id,
		    onSuccess: function(transport) {
				var response = transport.responseText || '';
				if (response == 1) {
					$(tmsg).className = '';
					$(tmsg).innerHTML = 'Station ID available!';
				}
				else if (response == 0) {
					$(tmsg).className = 'innerError';
					$(tmsg).innerHTML = 'Station ID taken!';
				}
		    },
		    onFailure: function() {
				$(tmsg).innerHTML = 'Check failed';
			}
		});
	}
}

function isValidPhone (str, USonly) {
	var stripped = str.replace(/[\(\)\.\-\ ]/g, '');
	var maxlen = (USonly) ? 10 : 15;
	if (str == '') {
		return;
	}
	if (isNaN(parseInt(stripped))) {
	   return "Phone number contains illegal characters";
	}
	if (!(stripped.length == maxlen)) {
		return "Phone number is the wrong length";
	}
	return;
}

function getURL (url, target) {
	document.location = url;
}

function switchToDateArchive (id, year, mon, date) {
	if (year != null && mon != null && date != null && id) {
		if (date.length == 1) date = '0' + date;
		if (mon.length == 1) mon = '0' + mon;
		document.location = ROOT_URL + 'archivewx.php?id=' + id + '&d=' + year + mon + date;
		Control.Modal.close();
	}
}

var win_topomap = null;
var win_topoinfo = null;
function showElevLookup (lat, lon) {
	if (!lat || !lon || lat == '' || lon == '') {
		alert("Please enter your station's latitude and longitude position above before searching for it's elevation.");
	}
	else {
		Control.Modal.open($('modal-elevselector').innerHTML);
		win_topomap = window.open('http://www.topozone.com/map.asp?lat=' + lat + '&lon=' + lon + '&datum=nad27&u=4&layer=DRG&size=l&s=25','TopoZone','width=1100,height=800,scrollbars=yes,resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no');
	}
}

function showElevMapInfo (lat, lon) {
	if (!lat || !lon || lat == '' || lon == '') {
		alert("Please enter your station's latitude and longitude position above before searching for it's elevation.");
	}
	else {
		win_topointo = window.open('http://www.topozone.com/quadinfo.asp?lat=' + lat + '&lon=' + lon + '&datum=nad83','TopoZoneInfo','width=800,height=600,scrollbars=yes,resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no');
	}
}

function closeElevLookup () {
	$('stn_elev').value = $('stn_lookup_elev').value;
	Control.Modal.close();
	if (win_topomap) win_topomap.close();
	if (win_topoinfo) win_topoinfo.close();
	win_topomap = null;
	win_topoinfo = null;
}

function setLocModalFields (tval) {
	tlat = (tval.lat) ? tval.lat : [];
	tlon = (tval.lon) ? tval.lon : [];
	for (i=0; i < tlat.length; i++) {
		$(tlat[i]).value = point.lat();
	}
	for (i=0; i < tlon.length; i++) {
		$(tlon[i]).value = point.lng();
	}

}

function setLocFields (tval) {
	tlat = (tval.lat) ? tval.lat : [];
	tlon = (tval.lon) ? tval.lon : [];
	taddr = (tval.addr) ? tval.addr : [];
	tcity = (tval.city) ? tval.city : [];
	tstate = (tval.state) ? tval.state : [];
	tzip = (tval.zip) ? tval.zip : [];
	tcountry = (tval.country) ? tval.country : [];
	tmaps = (tval.maps) ? tval.maps : [];

	for (i=0; i < tlat.length; i++) {
		$(tlat[i]).value = point.lat();
	}
	for (i=0; i < tlon.length; i++) {
		$(tlon[i]).value = point.lng();
	}
	for (i=0; i < taddr.length; i++) {
		$(taddr[i]).value = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
	}
	for (i=0; i < tcity.length; i++) {
		$(tcity[i]).value = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
	}
	for (i=0; i < tstate.length; i++) {
		if ($(tstate[i]).tagName.toUpperCase() == 'INPUT') {
			$(tstate[i]).value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
		}
		else if ($(tstate[i]).tagName.toUpperCase() == 'SELECT') {
			setSelectBoxVal($(tstate[i]), place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
		}
	}
	for (i=0; i < tzip.length; i++) {
		$(tzip[i]).value = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
	}
	for (i=0; i < tcountry.length; i++) {
		if ($(tcountry[i]).tagName.toUpperCase() == 'INPUT') {
			$(tcountry[i]).value = place.AddressDetails.Country.CountryNameCode;
		}
		else if ($(tcountry[i]).tagName.toUpperCase() == 'SELECT') {
			setSelectBoxVal($(tcountry[i]), place.AddressDetails.Country.CountryNameCode);
		}
	}

	// center all referenced maps to udpated lat/lon
	if (tmaps.length) {
		for (i=0; i < tmaps.length; i++) {
			map = new GMap2($(tmaps[i]));
			map.clearOverlays();
			map.setCenter(point, 11);
			marker = new GMarker(point);
			map.addOverlay(marker);
		}
	}
}

function closeLatLonLookup () {
	if ($('stn_lookup_address').value == '') {
		alert('You must enter and geocode your address before saving, or Cancel this function.');
	}
	else {
		setLocFields(loctval);
		Control.Modal.close();
	}
}

function setSelectBoxVal (obj, val) {
	for (var j=0; j < obj.length; j++) {
		if (obj[j].value == val) {
			obj.selectedIndex = j;
			break;
		}
	}
}

function showUnits (type) {
	if (!type) {
		if (UNITS ==  'eng') type = 'met';
		else type = 'eng';
	}

	//var holders = $('genwrapper').getElementsByTagName('SPAN');
	if (type == 'met') {
		eng_spans = document.getElementsByClassName('u-eng');
		met_spans = document.getElementsByClassName('u-met-hide');
		for (var i=0; i < eng_spans.length; i++) {
			eng_spans[i].className = 'u-eng-hide';
		}
		for (var i=0; i < met_spans.length; i++) {
			met_spans[i].className = 'u-met';
		}
		$('units-switchtxt').innerHTML = $('units-switchtxt2').innerHTML = 'View data in english units';
	}
	else {
		eng_spans = document.getElementsByClassName('u-eng-hide');
		met_spans = document.getElementsByClassName('u-met');
		for (var i=0; i < eng_spans.length; i++) {
			eng_spans[i].className = 'u-eng';
		}
		for (var i=0; i < met_spans.length; i++) {
			met_spans[i].className = 'u-met-hide';
		}
		$('units-switchtxt').innerHTML = $('units-switchtxt2').innerHTML = 'View data in metric units';
	}

/*
	if (type == 'met') {
		$('units-set').innerHTML = '<style type="text\/css">div.u-eng { display: none; } div.u-met { display: inline; }<\/style>';
		$('units-switchtxt').innerHTML = $('units-switchtxt2').innerHTML = 'View data in english units';
	}
	else {
		$('units-set').innerHTML = '<style type="text\/css">div.u-eng { display: inline; } div.u-met { display: none; }<\/style>';
		$('units-switchtxt').innerHTML = $('units-switchtxt2').innerHTML = 'View data in metric units';
	}
*/
	UNITS = type;
	Cookie.set('PWSunits', type, 30);
}

function getUserUnits () {
	units = Cookie.get('PWSunits');
	if (!units) units = '';

	return units;
}
var UNITS = getUserUnits();