/*****************************
	Weather 5.0.2
	Maxthon Sidebar Plugin
	By Neo101
******************************/

var FIX_YAHOO_VISIBILITY_BUG = true


var CACHE_DIRECTORY = 'Cache/'

var isNewInstall = checkSettingsFile()

var iconSet = readSetting('ImageSet')
var iconLocation = 'images/'+iconSet+'/'
var iconExtension = readIni('images/'+iconSet+'/icons.ini', 'iconSet', 'iconExtension', '.gif')

var languageID = readSetting('Language')


var activeCity = readSetting('ActiveCity')
var numberOfCities = readSetting('NumberOfCities')

if(activeCity > numberOfCities){
	writeSetting('ActiveCity', 1)
	activeCity = 1
}

var locationId = readSetting('LocationCode' + activeCity)
var cityName = transLocation( readSetting('LocationTxt' + activeCity) )
var units = readSetting('Units')
var todayUnits
var futureUnits
var precipUnit = '%'
var humidUnit = '%'

var defaultSection = 'Main'

var showFeelsLike 	= readSetting('ShowFeelsLike')
var showPressure 	= readSetting('ShowPressure')
var showHumidity 	= readSetting('ShowHumidity')
var showUV 			= readSetting('ShowUV')
var showWind 		= readSetting('ShowWind')
var showVisibility 	= readSetting('ShowVisiblity')
var showSunSetRise 	= readSetting('ShowSunSetRise')
var showLastUpdate 	= readSetting('showLastUpdate')
var showPrecipitation = readSetting('ShowPrecipitation')
var showLowTemperature = readSetting('ShowLowTemperature')

var useAbbreviation = readSetting('useAbbreviation')

var use24Hours 	= readSetting('Use24Hours')
var compact 	= readSetting('Compact')
var small 		= readSetting('Small')

var numberOfFutureDays = readSetting('NumberOfFutureDays')
var numberOfTodayHours = readSetting('NumberOfTodayDays')

var newNowSource = readSetting('UseNewNowSource')

if(newNowSource == '1'){
	//var WEBPAGE_SUM 	= 'http://weather.msn.com/RSS.aspx?weadegreetype=C&culture=en-US&wealocations=wc:'
	var WEBPAGE_SUM 	= 'http://weather.yahooapis.com/forecastrss?u=f&p='
} else {
	var WEBPAGE_SUM 	= 'http://www.msnbc.com/m/chnk/d/weather_d_src.asp?acid='
}
var WEBPAGE_FUT 	= 'http://www.weather.com/weather/mpdwcr/tenday?locid='
var WEBPAGE_TODAY 	= 'http://www.weather.com/weather/mpdwcr/dailydetails?locid='

var useAnimation = readSetting('UseAnimation')

var weatherDay = new Array()
var weatherHour = new Array()
var weatherNow = ''
var weatherToday

var lastUpdateTime

var detailsLink = readSetting('detailsLink')
var showDetailsLink = readSetting('showDetailsLink')

var styleSheet = 'style/' + readSetting('StyleSheet')
var fontStyleSheet = 'style/' + readSetting('FontSize')

document.getElementById('stylesheet').href = styleSheet
document.getElementById('fontStylesheet').href = fontStyleSheet

if(small == '1'){
	document.getElementById('typeStylesheet').href = 'style/smallSidebar.css'
}

var dateFormat = readSetting('DateFormat')

var CACHE_TIME = 900000 //miliseconds

var VERSION = '5.0.2'
var RELEASE_DATE = '1 February 2007'

var bigTable = readFile('script/tableBig.html').replace(/\r\n/g,'EOLN')
if(small == '0'){
	bigTable = bigTable.replace(/\{\{Small.*?SmallEnd\}\}/gi,'')
}
var bigTableStart = bigTable.replace(/\{\{repeat\}\}.*/i,'')
var bigTableEnd = bigTable.replace(/.*?\{\{repeatEnd\}\}/i,'')
var bigTableRepeat = bigTable.replace(bigTableStart,'').replace(bigTableEnd,'').replace(/\{\{.*?\}\}/g,'')
	bigTableStart = bigTableStart.replace(/EOLN/g,'\r\n')
	bigTableEnd = bigTableEnd.replace(/EOLN/g,'\r\n')

var smallTable = readFile('script/table.html')
if(small == '0'){
	smallTable = smallTable.replace(/\r\n/g,'EOLN').replace(/\{\{Small.*?SmallEnd\}\}/gi,'').replace(/EOLN/g,'\r\n')
} else {
	smallTable = smallTable.replace(/\{\{.*?\}\}/g,'')
}


	
var objXMLHTTP = new Array()
for(var i=0; i<3; i++){
	try{
		objXMLHTTP[i] = external.max_activex(SECURITY_ID, "Microsoft.XMLHTTP")
	} catch(err) {
		objXMLHTTP[i] = new ActiveXObject("Microsoft.XMLHTTP");
	}
}


window.onload = function(){ //Called when document is fully loaded
	if(isNewInstall){
		writeNewUserMessage()
	}
	
	if(!summaryDone){
		showNow(1)
	}
	if(!futureDone){
		showFuture(1)
	}
	if(!todayDone){
		showToday(1)
	}
	
	if(languageID=='0002' || languageID=='0016') {
		document.body.style.direction='RTL' //set the text alignment for the Arabic and Hebrew languagefiles to right to left
	}
	
	setStates()
	blurLinks()
	setAutoUpdate()
	document.getElementById('cityLink'+activeCity).style.fontWeight = 'bold'
	
	if(errorMessages != ''){
		document.getElementById('error').innerHTML = errorMessages
	}
	if(numberOfTodayHours == '0'){
		document.getElementById('dataTodayDetailedDiv').style.display = 'none'
	}
	if(numberOfFutureDays == '0'){
		document.getElementById('dataFutureDiv').style.display = 'none'
	}
	
	document.getElementById('reloadImage').alt = translate('reload')
	document.getElementById('configImage').alt = translate('configuration')
}


loadWeatherData()
checkIcons()

function loadWeatherData(){
	futureDone 	= false
	todayDone 	= false
	summaryDone = false
	showErrorMessage = false
	
	weatherDay 	= new Array()
	weatherHour = new Array()
	weatherNow 	= ''
	weatherToday = ''
	
	var timeNow = new Date().getTime()
	var lastUpdateTime = readSetting('LastUpdate'+activeCity)
	var lastUpdateLocationId = readSetting('LastUpdateLocation'+activeCity)
	if( timeNow - lastUpdateTime > CACHE_TIME || lastUpdateLocationId != locationId){
		openConnection(WEBPAGE_FUT, 1)
		openConnection(WEBPAGE_SUM, 0)
		openConnection(WEBPAGE_TODAY, 2)
		writeSetting('LastUpdate'+activeCity, timeNow)
		writeSetting('LastUpdateLocation'+activeCity,locationId)
	}
	else {
		var futureData = readFile(CACHE_DIRECTORY+'Future'+locationId+'.txt')
		var summaryData = readFile(CACHE_DIRECTORY+'Summary'+locationId+'.txt')
		var todayData = readFile(CACHE_DIRECTORY+'Today'+locationId+'.txt')
		if(futureData != undefined && futureData != ''){
			evaluate( futureData , 1)
		}
		else{
			openConnection(WEBPAGE_FUT, 1)
		}
		if(summaryData != undefined && summaryData != ''){
			evaluate( summaryData , 0)
		}
		else{
			openConnection(WEBPAGE_SUM, 0)
		}
		if(todayData != undefined && todayData != ''){
			evaluate( todayData , 2)
		}
		else{
			openConnection(WEBPAGE_TODAY, 2)
		}
	}
}



function openConnection(url, i) {
	var url = url + locationId
	try{
		objXMLHTTP[i].open("GET", url, true);
		objXMLHTTP[i].onreadystatechange = function(){getHTML(i)}
		objXMLHTTP[i].send();
	} catch(err){
		evaluate(0, null, err.description) 
	}
}


function getHTML(i){
	var xmlObject = objXMLHTTP[i]
	if(xmlObject && xmlObject.readyState == 4) {
		if(xmlObject.status == 200) {
			evaluate(xmlObject.responseText, i)
		}
		else {
			evaluate(0, null, xmlObject.status + ': ' + xmlObject.statusText)
		}
	}
}


function evaluate(data, i, errorMessage){
	if(data == 0){
		showError( '220 ' + translate('ErrorLoading') + '<br>' + errorMessage )
		return
	}
	switch(i){
		case 0:	evaluateSummary(data);	break;
		case 1: evaluateFuture(data);	break;
		case 2: evaluateToday(data);	break;
	} 
}


function evaluateFuture(data){
	writeFile(CACHE_DIRECTORY+'Future'+locationId+'.txt', data)

	data = data.split('\n')
	var a = 0
	
	var match
	
	for(var i=0; i<data.length; i++){
		var line = data[i]
		if( /new mpdFDObj\(new Date\(/.test(line) ) {
			eval( line.replace(/mpdData\['dayf'\].day\[([0-9])\]/i,'weatherDay[$1]') )
			a++
			if(a==10){
				break;
			} else {
				continue
			}
		}
		match = line.match(/new mpdLocObj\((.*)/i)
		if(match) {
			var loc = match[1]
			var split = loc.split(',')
			var location = (split[3]+', '+split[4]).replace(/'/g,'')
			continue
		}
		match = line.match(/new mpdHeadObj\('(.)'/i)
		if(match){
			futureUnits = match[1].replace(/C/i,'Celcius').replace(/F/i,'Fahrenheit')
		}
	}
	if(document.getElementById('dataFuture') && !futureDone){
		showFuture()
	}
}

function evaluateToday(data){
	writeFile(CACHE_DIRECTORY+'Today'+locationId+'.txt', data)
	
	data = data.split('\n')
	var a = 0
	var sunUp, sunDown
	
	var match
	
	for(var i=0; i<data.length; i++){
		var line = data[i]
		if( /new mpdHMHrObj\(new Date\(/.test(line) ) {
			eval(line.replace(/mpdData\['HMhour'\].hour\['([0-9])'\]/i,'weatherHour[$1]'))
			a++
		}
		if( /new mpdFObj/.test(line) ) {
			lastUpdateTime = line.replace(/.*?new mpdFObj\((.*)/i,'$1').replace(/.*?(\d\d?:\d\d (P|A)M).*/i,'$1')
			continue
		}
		match = line.match(/new mpdHeadObj\('(.)'/i)
		if(match){
			todayUnits = match[1].replace(/C/i,'Celcius').replace(/F/i,'Fahrenheit')
			continue
		}
		match = line.match(/mpdClimoSunRiseSetObj\((.*)\)/i)
		if(match){
			var q = match[1].replace(/PM/gi, translate('PM') ).replace(/AM/gi, translate('AM') )
			sunUp = setClockSun( q.split(',')[0].replace(/'/g,'') )
			sunDown = setClockSun( q.split(',')[1].replace(/'/g,'') )
			continue
		}
		if( /mpdFDPObj/.test(line) ){
			eval( line.replace(/mpdData\['dayPartFcst'\].day\[0\]/i,'weatherToday') )
			weatherToday.sunUp = quantity('SunUp') + sunUp
			weatherToday.sunDown = quantity('SunDown') + sunDown
		}
	}
	if(document.body && !todayDone){
		showToday()
	}
}


function getNode(xml, xpath){
	var node = xml.selectSingleNode(xpath)
	if(node){
		return node.text
	}
	return ''
}


function convertWindDirection(degrees){ //convert from degrees to these wind names below
	try{
		var names = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'ES', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
		var stepSize = 360 / names.length
		var index = parseInt( (degrees / stepSize) + 0.5 )
		var result = names[index % 16]
		return result
	} catch(e){
		return ''
	}
}


function evaluateSummary(data){
	writeFile(CACHE_DIRECTORY+'Summary'+locationId+'.txt', data)
	
	if(newNowSource == '1'){
		var objXMLDOM = new ActiveXObject("Microsoft.XMLDOM")
		objXMLDOM.async = false 
		objXMLDOM.loadXML(data) 
		var responseXML = objXMLDOM.documentElement
		
		var temperature = getNode(responseXML, 'channel/item/yweather:condition/@temp')
		var icon = getNode(responseXML, 'channel/item/yweather:condition/@code')
		var text = getNode(responseXML, 'channel/item/yweather:condition/@text')
		var humidity = getNode(responseXML, 'channel/yweather:atmosphere/@humidity')
		var windSpeed = getNode(responseXML, 'channel/yweather:wind/@speed')
		var windDirection = getNode(responseXML, 'channel/yweather:wind/@direction')
		var feelsLikeTemp = getNode(responseXML, 'channel/yweather:wind/@chill')
		try{
			var visibility = getNode(responseXML, 'channel/yweather:atmosphere/@visibility') / 100
		} catch(e){
			var visibility = ''
		}
		var pressure = getNode(responseXML, 'channel/yweather:atmosphere/@pressure')
		var pressureRising = getNode(responseXML, 'channel/yweather:atmosphere/@rising')
		if(pressureRising == 0){
			pressureRising = '&rarr;' //right arrow
		} else if(pressureRising == 1){
			pressureRising = '&uarr;' //up arrow
		} else if(pressureRising == 2){
			pressureRising = '&darr;' //down arrow
		}
		
		windDirection = convertWindDirection( windDirection)
		
		/*var match
		
		match = data.match(/(-?\d+)&#176;C \(Feels like/i)
		if(match){
			temperature = match[1]
		}
		match = data.match(/<br \/><img src=.*?\/(\d+)\.gif/i)
		if(match){
			icon = match[1]
		}
		match = data.match(/<br \/>([^<]*?)\. \d/i)
		if(match){
			text = match[1].replace(/\n/g,'')
		}
		match = data.match(/Humidity: (.*?)%/i)
		if(match){
			humidity = match[1]
		}
		match = data.match(/Winds: (\d+) km\/hr/i)
		if(match){
			windSpeed = match[1]
		}
		match = data.match(/Winds: \d+ km\/hr (\w+)\./i)
		if(match){
			windDirection = match[1]
		}
		match = data.match(/\(Feels like (\d+)\)/i)
		if(match){
			feelsLikeTemp = match[1]
		}*/
		
		if(document.body && !todayDone){
			showToday()
		}
		
		weatherNow = new WeatherObject(temperature, icon, text, 'Summary')
		if(feelsLikeTemp != null){
			weatherNow.feelTemp = quantity('FeelsLike') + convertTemp(feelsLikeTemp,'Summary')
		}
		else{
			weatherNow.feelTemp = ''
		}
		weatherNow.humid = quantity('Humid') + humidity + humidUnit
		weatherNow.wind = quantity('Wind') + convertWind(windSpeed, 'Summary') + ' ' + translateWind(windDirection)
		weatherNow.visibility = quantity('Visibility') + convertVisibility(visibility, 'Summary')
		weatherNow.pressure = quantity('Pressure') + convertPress(pressure, 'Summary') + ' ' + pressureRising
	
	} else {
	
		try{
			eval(data)
		}
		catch(err){
			showError( '305 ' + translate('NotParseSummaryData') + err.description )
			showErrorMessage = true
			if(document.body && !summaryDone){
				showNow()
			}
			return
		}
		try{
			var summaryData = new makeWeatherObj()
		}
		catch(err){
			showError( '312 ' + translate('NotReadSummaryData') )
			showErrorMessage = true
			if(document.body && !summaryDone){
				showNow()
			}
			return
		}
		if(summaryData.swAcid == '' || (summaryData.swTemp == '0' && summaryData.swHumid == '') || 
			(summaryData.swReal == '' && summaryData.swCIcon == '')){
			showError( '317 ' + translate('BadSummaryData') )
			showErrorMessage = true
			if(document.body && !summaryDone){
				showNow()
			}
			return
		}
		weatherNow = new WeatherObject( summaryData.swTemp, summaryData.swCIcon, summaryData.swConText, 'Summary')
		if(summaryData.swReal != '')
			weatherNow.feelTemp = quantity('FeelsLike') + convertTemp(summaryData.swReal,'Summary')
		else
			weatherNow.feelTemp = ''
		weatherNow.pressure = quantity('Pressure') + convertPress(summaryData.swBaro, 'Summary')
		weatherNow.humid = quantity('Humid') + summaryData.swHumid + humidUnit
		weatherNow.uv = quantity('UV') + summaryData.swUV
		weatherNow.wind = quantity('Wind') + convertWind(summaryData.swWindS, 'Summary') + ' ' + translateWind(summaryData.swWindD)
		weatherNow.visibility = quantity('Visibility') + convertVisibility(summaryData.swVis, 'Summary')
	
	}
	
	if(document.body && !summaryDone){
		showNow()
	}
}



/* Data from the future forecast */

function mpdFDObj(date, day, temp, lowTemp, uv, icon, text, windSpeed, windDirection, windDirShort, precip, humidity) {
	var object = new WeatherObject( temp, icon, text, 'Future', 2 )
	object.lowTemp = quantity('TempLow', 'notAlways') + convertTemp(lowTemp, 'Future')
	object.precip = quantity('Precip', 'notAlways') + precip + precipUnit
	
	var dayArray = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
	object.day = translate( dayArray[ date.getDay() ] , true)
	object.date = dateFormat.replace(/%DAY/g, date.getDate() ).replace(/%MONTH/g, date.getMonth()+1 )
	
	object.uv = uv
	object.wind = quantity('Wind', 'notAlways') + convertWind(windSpeed, 'Future') + ' ' + translateWind(windDirShort, true)
	object.humid = quantity('Humid') + humidity + humidUnit
	return object
}

/* Data from today's forecast */

function mpdHMHrObj(date, icon, text, temp, feelTemp, precip, dew, humid, windDirSpeed) {
	var split = windDirSpeed.replace(/From /i,'').split(' ')
	var windDirShort = split[0]
	var windSpeed = split[1]
	var object = new WeatherObject( temp, icon, text, 'Today', 2 )
	object.feelTemp = quantity('FeelsLike') + convertTemp(feelTemp, 'Today')
	object.precip = quantity('Precip', 'notAlways') + precip + precipUnit
	var hours = date.getHours()
	var time
	if(use24Hours != 1){
		if(hours > 12){
			hours -= 12
			time = hours + ' '+translate('PM')
		} else {
			time = hours + ' '+translate('AM')
		}
	}
	else time = hours + ':00'
	object.date = time
	object.humid = quantity('Humid') + humid + humidUnit
	object.wind = quantity('Wind', 'notAlways') + convertWind(windSpeed, 'Today') + ' ' + translateWind(windDirShort, true)
	return object
}

/* for today/tonight weather */

function mpdFDPObj(date, day, temp, tempNight, uv, icon, text, windSpeed, windDirection, windDirShort, precip, humid, 
	iconNight, textNight, windSpeedNight, windDirNight, windDirShortNight, precipNight, humidNight) {
	
	var object = new WeatherObject( temp, icon, text, 'Today')
	object.precip = quantity('Precip') + precip + precipUnit
	object.date = date
	object.iconNight = iconLocation + iconNight + iconExtension
	object.textNight = translate(textNight, null, 'WeatherTypes')
	object.tempNight = convertTemp(tempNight, 'Today')
	object.precipNight = quantity('Precip') + precipNight + precipUnit
	object.wind = quantity('Wind') + convertWind(windSpeed, 'Today') + ' ' + translateWind(windDirShort)
	object.windNight = quantity('Wind') + convertWind(windSpeedNight, 'Today') + ' ' + translateWind(windDirShortNight)
	object.humidNight = quantity('Humid') + humidNight + humidUnit
	object.humid = quantity('Humid') + humid + humidUnit
	
	return object
}


function WeatherObject( temp, icon, text, type, showQuantity ){
	if(showQuantity && showQuantity == 2 && compact == '1')
		showQuantity = null
	this.temp = (( showQuantity != null) ? quantity('Temp') : '' ) + convertTemp(temp, type)
	this.icon = iconLocation + icon + iconExtension
	this.text = translate(text, null, 'WeatherTypes')
}


function createTable(name){
	var table = smallTable
	var element
	if(name == 'now'){
		element = weatherNow
		if(element == undefined || element.length == 0){
			return translate('loading')
		}
	} 
	else if(name == 'today'){
		element = weatherToday
		if(element == undefined || element.length == 0)
			return translate('loading')
		if(weatherToday && weatherToday.text.search('N/A') != -1) {
			dataToday.parentElement.style.display = 'none'
		} else {
			dataToday.parentElement.style.display = 'block'  //debug?
		}
	}
	else if(name == 'tonight'){
		element = weatherToday
		if(element == undefined || element.length == 0) 
			return translate('loading')
	}
	eval( name+'Done = true' )
	
	if(name != 'tonight'){
		for( i in element ) {
			if(i != 'icon' && i != 'iconNight')
				element[i] = element[i] + '<br>'
		}
	}
	if(name == 'now'){
		var icon = element.icon
		var important = element.temp + element.text
		var mainData = ''
		if(showFeelsLike == '1')
			mainData += element.feelTemp 
		if(showHumidity == '1')
			mainData += element.humid
		if(showWind == '1')
			mainData += element.wind
		if(showVisibility == '1')
			mainData += element.visibility
		if(showPressure == '1')
			mainData += element.pressure
		
		if(newNowSource != '1'){
			if(showUV == '1')
				mainData += element.uv
		}
	}
	if(name == 'today'){
		var icon = element.icon
		var important = element.temp + element.text
		var mainData = ''
		if(showPrecipitation == '1')
			mainData += element.precip
		if(showWind == '1')
			mainData += element.wind
		if(showHumidity == '1')
			mainData += element.humid
		if(showSunSetRise == '1')
			mainData += element.sunUp + element.sunDown
	}
	else if(name == 'tonight'){
		var icon = element.iconNight
		var important = element.tempNight + element.textNight
		var mainData = ''
		if(showPrecipitation == '1')
			mainData += element.precipNight
		if(showWind == '1')
			mainData += element.windNight
		if(showHumidity == '1')
			mainData += element.humidNight 
	}
	table = table.replace(/\[\[icon\]\]/, icon)
	table = table.replace(/\[\[important\]\]/, important)
	table = table.replace(/\[\[mainData\]\]/, mainData)
	
	return table
}


function createBigTable(name){
	var result = bigTableStart
	var element, length, elementArray, start
	
	if(name == 'future'){
		elementArray = weatherDay
		start = 1
		length = numberOfFutureDays
	} else if(name == 'todayDetailed'){
		elementArray = weatherHour
		start = 0
		length = numberOfTodayHours
	}
	if(elementArray == undefined || elementArray.length == 0){
		return translate('loading')
	}
	eval( name+'Done = true' )
	
	for(var i=start; i<length; i++){
		try{
			var element = elementArray[i]
			for( j in element ) {
				if(j != 'date' && j != 'icon' && j != 'text' && ( ( compact == '1' && j != 'temp' && j != 'lowTemp') || compact != '1') )
					element[j] = element[j] + '<br>'
				else if(j=='temp' || j=='lowTemp')
					element[j] = element[j] + '&nbsp;&nbsp;'
			}
			if(name == 'future'){
				var date = '<span title="'+element.date+'">'+element.day+'</span>'
			} else {
				var date = element.date
			}
			var icon = element.icon
			var important = element.temp
			var mainData = '' 
			if(name == 'future' && showLowTemperature == '1'){
				mainData += element.lowTemp
			}
			if(showPrecipitation == '1')
				mainData += element.precip
			if(showWind == '1')
				mainData += element.wind
			var iconAlt = element.text
			
			tablePart = bigTableRepeat.replace(/EOLN/g,'\r\n')
			tablePart = tablePart.replace(/\[\[icon\]\]/, icon)
			tablePart = tablePart.replace(/\[\[important\]\]/, important)
			tablePart = tablePart.replace(/\[\[iconAlt\]\]/, iconAlt)
			tablePart = tablePart.replace(/\[\[date\]\]/, date)
			tablePart = tablePart.replace(/\[\[mainData\]\]/, mainData)
			result += tablePart
		}
		catch(err){
			alert(err.description)
		}
	}
	result += bigTableEnd
	return result
}


function quantity(word, notAlways){
	if(compact == '1' && notAlways != null) return ' '
	
	var abbreviation
	if(useAbbreviation == '1')
		abbreviation = true
	else abbreviation = null
	
	var text = translate(word, abbreviation) + ': '
	return text
}


function convertTemp(value, type){
	var newValue
	
	if( toMetricSystem(type) ){ //Fahrenheit -> Celcius
		newValue = (5/9) * (value-32)
	}
	else if( fromMetricSystem(type) ){ //Celcius -> Fahrenheit
		newValue = (value*1.8) + 32
	} else { //Do not convert anything!
		newValue = value
	}

	return Math.round(newValue) + '&deg;' + ( (units == 'Celcius') ? 'C' : 'F' )
}


function convertPress(value, type){
	return convert(value, type, 33.86389, 'hPa', 'inches', true)
}


function convertWind(value, type){
	return convert(value, type, 1.609334, 'km/h', 'mph')
}


function convertVisibility(value, type){
	if(value == 999) return translate('infinite')
	//start yahoo fix
	if(FIX_YAHOO_VISIBILITY_BUG && type == 'Summary' && newNowSource == '1'){
		if(units == 'Fahrenheit'){
			return (value / 1.609334).toFixed(2) + ' ' + translate('miles')
		} else {
			return value + ' ' + translate('km')
		}
	}
	//end yahoo fix
	return convert(value, type, 1.609334, 'km', 'miles')
}



function convert(value, type, convertValue, unitCel, unitFahr, notRound){
	var newValue
	if( toMetricSystem(type) ){
		newValue = value * convertValue
	} else if( fromMetricSystem(type) ){
		newValue = value / convertValue
	} else {
		newValue = value
	}
	
	if(notRound == null || units == 'Celcius')
		newValue = Math.round(newValue)
		
	return newValue + ' ' + translate( (units == 'Celcius') ? unitCel : unitFahr )
}


function toMetricSystem(type){
	return ( units == 'Celcius' && 
				(
					(type == 'Summary') ||
					(type == 'Today' && todayUnits == 'Fahrenheit') || 
					(type == 'Future' && futureUnits == 'Fahrenheit')
				) 
			)
}


function fromMetricSystem(type){
	return ( units == 'Fahrenheit' && 
				(
					(type == 'Today' && todayUnits == 'Celcius') || 
					(type == 'Future' && futureUnits == 'Celcius')
				)
			)
}


function setUpdateTime(time){
	if(time == null) time = lastUpdateTime
	var split = time.split(' ')
	if(split.length != 2) showError( '622 ' + translate('NoUpdateTime') )
	var hours = eval(split[0].split(':')[0])
	var minutes = eval(split[0].split(':')[1])
	if(minutes < 10){
		minutes = '0' + minutes
	}
	var text = ''
	if(split[1].search(/PM/)!=-1){
		if(use24Hours == 1)
			hours += 12
		else text = ' PM'
	}
	if(hours < 10){
		hours = '0' + hours
	}
	if(document.body){
		updateTime.innerHTML = translate('UpdatedAt') + ' '+ hours+':'+minutes 
								+ text + ' '+translate('LocalTime')
	}
}


/* Convert Sun UP/Down to 12h/24h */

function setClockSun(time){
	if(use24Hours == 0) {
		return time
	}
	if(time.search(/PM/) != -1){
		var y = time.split(':')
		time = ( eval( y[0] ) + 12 ) + ':' + y[1].replace(/ PM/,'')
	} else if(time.search(/AM/) != -1) time = time.replace(/ AM/,'')
	return time
}


function setAutoUpdate(){
	var auotUpdateTime = readSetting('AutoUpdateTime')
	if(auotUpdateTime != '' && auotUpdateTime != '999')
		window.setInterval("loadWeatherData()", 1000 * 60 * auotUpdateTime);
}


function showNow(onBodyLoad){
	//summaryDone = true
	var element = document.getElementById('dataNow')
	if(showErrorMessage || (onBodyLoad == null && weatherNow == '')){
		element.innerHTML = translate('ErrorLoading')
	} else {
		element.innerHTML = createTable('now')
		if(useAnimation == '1'){
			element.style.height = '1px'
			increaseHeight('dataNow')
		}
	}
}


function showFuture(onBodyLoad){
	//futureDone = true
	var element = document.getElementById('dataFuture')
	if(onBodyLoad == null && weatherDay.length == 0){
		element.innerHTML = translate('ErrorLoading')
	}
	else {
		element.innerHTML = createBigTable('future')
		if(useAnimation == '1'){
			element.style.height = '1px'
			increaseHeight('dataFuture')
		}
	}
}


function showToday(onBodyLoad){
	//todayDone = true
	//if(onBodyLoad == null && weatherHour.length == 0){
		// dataTodayDetailed.innerHTML = translate('loadError')
		// dataToday.innerHTML = translate('loadError')
		// dataTonight.innerHTML = translate('loadError')
	//} else {
	var elementToday = document.getElementById('dataToday')
	var elementTonight = document.getElementById('dataTonight')
	var elementDetailed = document.getElementById('dataTodayDetailed')
	elementToday.innerHTML = createTable('today')
	elementTonight.innerHTML = createTable('tonight')
	elementDetailed.innerHTML = createBigTable('todayDetailed')
	if(useAnimation == '1'){
		elementToday.style.height = '1px'
		elementTonight.style.height = '1px'
		elementDetailed.style.height = '1px'
		increaseHeight('dataToday')
		increaseHeight('dataTonight')
		increaseHeight('dataTodayDetailed')
	}
	if(lastUpdateTime != null && showLastUpdate != '0'){
		setUpdateTime(lastUpdateTime)
	}
	//}
}





function checkIcons(){ //Tests if icon set exists
	var image = new Image()
	image.onerror = function(){
						showError( '712 ' + translate('NoIconSet') )
						iconSet = '1'
						iconLocation = 'images/'+iconSet+'/' 
					}
	image.src = iconLocation+'1'+iconExtension
}
