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


window.onerror=showError

readIni = dialogArguments.readIni
writeIni = dialogArguments.writeIni
readFile = dialogArguments.readFile
writeFile = dialogArguments.writeFile
VERSION = dialogArguments.VERSION
RELEASE_DATE = dialogArguments.RELEASE_DATE

var TRUE = '1'
var FALSE = '0'
var languageID = readSetting('Language')

var defaultSection = 'Configuration'

var activeCity = readSetting('ActiveCity')
var cityName = transLocation( readSetting('LocationTxt' + activeCity) )
var WEBPAGE_LOCATION_SEARCH = 'http://xml.weather.com/search/search?where='
var imageAvailable = true

var changedSettings = false

var newNowSource

var title = '<title> ' +  translate('Configuration', null, 'Main')
for(var i=0; i<100; i++){
	title += '&nbsp;'
}
title += '</title>'
document.write(title)



try{
	var xmlObject = dialogArguments.external.max_activex(SECURITY_ID,"Microsoft.XMLDOM")
}
catch(err) {
	var xmlObject = new ActiveXObject("Microsoft.XMLDOM")
}

window.onload = function(){
	writeHTML()
	loadSettings()
	
	if(languageID=='0002' || languageID=='0016') {
		document.body.style.direction='RTL'//set the text alignment for the Arabic and Hebrew languagefiles to right to left
	}
}

window.onunload = function(){
	dialogArguments.configClose(changedSettings)
}

function getIconSets(){
	var text = ''
	var MAX_NUMBER_OF_ICONS = 15
	
	for(var i=1; i<MAX_NUMBER_OF_ICONS; i++){
		checkIconSet(i)
		if(imageAvailable){
			var iconName = readIni('images/'+i+'/icons.ini', 'iconSet', 'iconName', i+'')
			text += '<option value="'+i+'">'+iconName.replace(/Type/g,translate('type'))+'</option>'
		}
	}
	
	return text
}

function checkIconSet(i){
	var image = new Image()
	var iconExtension = readIni('images/'+i+'/icons.ini', 'IconSet', 'iconExtension', '.gif')
	var iconLocation = 'images/'+i+'/'
	imageAvailable = true
	image.onerror = function(){ 
						imageAvailable = false
					}
	image.src = iconLocation+'1'+iconExtension
}

function loadSettings() {
	
	var styleSheet = 'style/' + readSetting('StyleSheet')
	document.getElementById('styleSheet').href = styleSheet


	var allInputTags = document.getElementsByTagName('input')
	for(var i=0; i<allInputTags.length; i++) {
		if(allInputTags[i].type=='checkbox') {
			if(readSetting(allInputTags[i].id+'') == TRUE) 
				allInputTags[i].checked = true
			else allInputTags[i].checked = false
		}
		if(allInputTags[i].type == 'text') 
			allInputTags[i].value = readSetting(allInputTags[i].id+'')
	}
	
	var selectTags = document.getElementsByTagName('select');
	for(var i=0; i<selectTags.length; i++) {
		var iniValue = readSetting(selectTags[i].id)
		for(var d=0; d<selectTags[i].options.length; d++) {
			if(iniValue == selectTags[i].options[d].value) {
				selectTags[i].selectedIndex = d
				break
			}
		}
	}
	
	setLocation(cityName)
	document.getElementById('cityLink'+activeCity).style.fontWeight = 'bold'
	if(readSetting('showDetailsLink') != '1'){
		document.getElementById('detailsLink').disabled = true
	}
	
	newNowSource = readSetting('UseNewNowSource')
}


function saveSettings()  {
	var allInputTags = document.getElementsByTagName('input');
	for(var i=0; i<allInputTags.length; i++) {
		if(allInputTags[i].type == 'checkbox') {
			if(allInputTags[i].checked == true)
				writeSetting(allInputTags[i].id+'', TRUE)
			else writeSetting(allInputTags[i].id+'', FALSE)
		}
		if(allInputTags[i].type == 'text' && allInputTags[i].id != 'citySearch') 
			writeSetting(allInputTags[i].id+'', allInputTags[i].value)
	}
	
	var selectTags = document.getElementsByTagName('select');
	for(var i=0; i<selectTags.length; i++) {
		writeSetting(selectTags[i].id, selectTags[i].options[selectTags[i].selectedIndex].value)
	}
	
	
	var newNowSourceAfterSave = readSetting('UseNewNowSource')
	if( newNowSource != newNowSourceAfterSave){
		for(var i=0; i<=5; i++){
			writeSetting('LastUpdate'+i, '')
		}
	}
	
	changedSettings = true
	closeWindow()
}


function closeWindow() {
	window.opener = ''
	window.close()
}


function clickTab(activeTab, element){
	//var obj		= document.getElementById("navmenu");
	var objs	= navmenu.getElementsByTagName("DIV");
	
	for(var i=0; i<objs.length; i++){
		if(objs[i].id.indexOf("tab") != -1){
			objs[i].className = "unselected-tab";
		}
	}
	
	var objs = document.getElementsByTagName('div')
	
	for(var i=0; i<objs.length; i++){
		if(objs[i].id.indexOf("data") != -1){
			objs[i].style.display = "none";
		}
	}
	
	var obj 		= document.getElementById("tab"+activeTab);
	obj.className 	= "selected-tab";
	var obj 		= document.getElementById("data"+activeTab);
	obj.style.display 	= "block";
}


function showError(msg, url, line){
	alert('Message: '+msg+'\nURL: '+url+'\nLine: '+line)
	return true
}



function setLocation( location ){
	document.getElementById('location').innerHTML = location
}

function getConfigHtml(){
	var data = readFile('configurationMain.html').replace(/\r\n/g,'NEWLINE').split('<<split>>')
	var result = ''

	for(var i=0; i<data.length; i++){
		var j=0
		while(data[i].match(/\{\(.*?\)\}/) != null){
			try{
				var word = translate( data[i].match(/\{\(.*?\)\}/).toString().replace(/\{\(|\)\}/g,'') , null, 'Configuration')
				data[i] = data[i].replace(/\{\((.+?)\)\}/, word)
			}
			catch(err){
				break
			}
			j++
			if(j>200) break
		}
		result += data[i].replace(/NEWLINE/g,'\r\n')
	}
	
	result = result.replace(/<<version\(\)>>/g,VERSION).replace(/<<releaseDate\(\)>>/g,RELEASE_DATE)
	
	writeFile('Script/Configuration-Translated.html',result)
	writeSetting('configLanguage', languageID)

	return configurationFunctions(result)
}

function configurationFunctions(result){
	return result.replace(/<<getIconSets\(\)>>/,getIconSets()).replace(/<<writeCities\(\)>>/,writeCities())
}


function writeHTML(){
	var configLanguage = readSetting('configLanguage')
	
	if(configLanguage == languageID) {
		var configHTML = null//readFile('script/Configuration-Translated.html')
		if(configHTML == null || configHTML == ''){
			var configHTML = getConfigHtml()
		} else {
			configHTML = configurationFunctions(configHTML)
		}
	}
	else {
		var configHTML = getConfigHtml()
	}
	document.body.innerHTML = configHTML
}


function writeCities(numberOfCities){
	var result = '<table class=navigation><tr>'
	if(numberOfCities == null)
		var numberOfCities = readSetting('NumberOfCities')
	for(var i=1; i<=numberOfCities; i++){
		var location = transLocation( readSetting('LocationTxt' + i) )
		result += '<td><span title="'+location+'" id="cityLink'+i+'" onclick="changeCity('+i+')">'+i+'</span></td>'
	}
	result += '</tr></table>'
	return result
}


function changeCity(number){
	document.getElementById('cityLink'+activeCity).style.fontWeight = 'normal'
	document.getElementById('cityLink'+number).style.fontWeight = 'bold'
	
	locationId = readSetting('LocationCode' + number)
	cityName = transLocation( readSetting('LocationTxt' + number) )
	activeCity = number
	
	setLocation(cityName)
}


function changeNumberOfCities(select){
	var newNumberOfCities = select.options[select.selectedIndex].value
	document.getElementById('citiesHTML').innerHTML = writeCities( newNumberOfCities )
	activeCity = 1
	changeCity(1)
}

function enterKeyPress() {
	if (window.event.keyCode == 13){
		findlocationId()
	}
}


function clearRows() {
	var rowsLength = resultcontent.rows.length
	for(var i=0; i<rowsLength; i++) 
		resultcontent.deleteRow()
		
	confirmButton.style.display = 'none'
	cityInfo.innerHTML = ''
}

function addRow(rowHTML) {
	var newRow = resultcontent.insertRow()
	var newCell= resultcontent.rows(newRow.rowIndex).insertCell()
	newCell.innerHTML = rowHTML
}

/* Search for Cities */

function findlocationId() {
	var name = citySearch.value
	if(name.search(/[a-zA-Z]{4}[0-9]{4}/)!=-1) {
		writeSetting("LocationCode" + activeCity, name)
		writeSetting("LocationTxt" + activeCity, 'unknown')
		return
	} else if(name=='') {
		clearRows()
		addRow( translate('NoKeywords') )
		return
	}
	name = transCity( name.toLowerCase() )
	var scriptURL = WEBPAGE_LOCATION_SEARCH + name
	retrieveHTML(scriptURL)
}

function retrieveHTML(url) {
	try{
		xmlObject.onreadystatechange = readyStateChange
		xmlObject.load(url);
	} catch(err){
		evaluate(0) 
	}
}


function readyStateChange() {
	if(xmlObject && xmlObject.readyState==4) {
		if(xmlObject.xml)
			evaluate(xmlObject.xml)
		else
			evaluate(0)
	}
}


function evaluate(dataall,x){
	if(dataall == 0) {
		clearRows()
		addRow( translate('ConnectionError') )	
		return
	}
	citiesArray = xmlParse(dataall)
	if(citiesArray.length == 0 || citiesArray[0][0].search(/location provided|unknown error/i) != -1) {
		clearRows()
		addRow( translate('NoResult') )		
	} else {
		clearRows()
		cityInfo.innerHTML = '<b>'+translate('Found')+' '+citiesArray.length+' '+translate('Cities')+'</b>'
		for(var i=0; i<citiesArray.length; i++) {
			rowHTML = '<input type=radio '+((citiesArray.length==1)?'checked':'')+
						' id=list'+i+' name=listcities value='+citiesArray[i][1]+'>'+
					'<label for=list'+i+'>&nbsp;'+transLocation( citiesArray[i][0] )+'</label>'
			addRow(rowHTML)			
		}
		confirmButton.style.display = 'block'
	}
}


/* Parse the XML file with search results */

function xmlParse(xmlText) {
	var nodes = new Array()
	var elements = xmlObject.documentElement.childNodes
	for(var i=0; i<elements.length; i++){
		nodes[i] 	= new Array()
		nodes[i][0] = elements.item(i).text
		nodes[i][1] = elements.item(i).getAttribute("id") 
	}
	return nodes
}


function confirmcity() {
	var set = false
	if(citiesArray.length == 1 && listcities.checked) {
		saveLocation(0)
		set = true
	} else if(citiesArray.length>1){
		for(var i=0; i<citiesArray.length; i++) {
			if(listcities[i].checked) {
				saveLocation(i)
				set = true
				break
			}
		}
	}
	if(set == 1) {
		document.all['location'].innerHTML = transLocation( locationTxt )
		document.all['citySearch'].value = ''
		clearRows()
		addRow( '<b>'+translate('Saved')+'</b>' )
	}
}


function saveLocation(i){
	locationId = citiesArray[i][1]
	locationTxt = citiesArray[i][0]
	writeSetting('LocationCode'+activeCity, locationId)
	writeSetting('LocationTxt'+activeCity, locationTxt)
}


function changeStyle(select){
	var selectedStyle = select.options[select.selectedIndex].value
	document.getElementById('styleSheet').href = 'style/'+selectedStyle
}


function openWindow(url){
	dialogArguments.window.open(url)
}