var geo = {};

geo.countrycodes = ["AF","AX","AL","DZ","AS","AD","AO","AI","AQ","AG","AR","AM","AW","AU","AT","AZ","BS","BH","BD","BB","BY","BE","BZ","BJ","BM","BT","BO","BA","BW","BV","BR","IO","VG","BN","BG","BF","BI","KH","CM","CA","CV","KY","CF","TD","CL","CN","CX","CC","CO","KM","CG","CD","CK","CR","HR","CU","CY","CZ","DK","DJ","DM","DO","TL","EC","EG","SV","GQ","ER","EE","ET","FK","FO","FJ","FI","FR","GF","PF","TF","GA","GM","GE","DE","GH","GI","GR","GL","GD","GP","GU","GT","GG","GN","GW","GY","HT","HM","HN","HK","HU","IS","IN","ID","IR","IQ","IE","IM","IL","IT","CI","JM","JP","JE","JO","KZ","KE","KI","KW","KG","LA","LV","LB","LS","LR","LY","LI","LT","LU","MO","MK","MG","MW","MY","MV","ML","MT","MH","MQ","MR","MU","YT","MX","FM","MD","MC","MN","ME","MS","MA","MZ","MM","NA","NR","NP","NL","AN","NC","NZ","NI","NE","NG","NU","NF","KP","MP","NO","OM","PK","PW","PS","PA","PG","PY","PE","PH","PN","PL","PT","PR","QA","RE","RO","RU","RW","BL","SH","KN","LC","MF","PM","VC","WS","SM","ST","SA","SN","RS","CS","SC","SL","SG","SK","SI","SB","SO","ZA","GS","KR","ES","LK","SD","SR","SJ","SZ","SE","CH","SY","TW","TJ","TZ","TH","TG","TK","TO","TT","TN","TR","TM","TC","TV","VI","UG","UA","AE","GB","US","UM","UY","UZ","VU","VA","VE","VN","WF","EH","YE","ZM","ZW"];
geo.countries = ["Afghanistan","Aland Islands","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Bouvet Island","Brazil","British Indian Ocean Territory","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Christmas Island","Cocos Islands","Colombia","Comoros","Congo - Brazzaville","Congo - Kinshasa","Cook Islands","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Guiana","French Polynesia","French Southern Territories","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guam","Guatemala","Guernsey","Guinea","Guinea-Bissau","Guyana","Haiti","Heard Island and McDonald Islands","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Ivory Coast","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macao","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique","Mauritania","Mauritius","Mayotte","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Niue","Norfolk Island","North Korea","Northern Mariana Islands","Norway","Oman","Pakistan","Palau","Palestinian Territory","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Pitcairn","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Barthˇlemy","Saint Helena","Saint Kitts and Nevis","Saint Lucia","Saint Martin","Saint Pierre and Miquelon","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Serbia and Montenegro","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Georgia and the South Sandwich Islands","South Korea","Spain","Sri Lanka","Sudan","Suriname","Svalbard and Jan Mayen","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Togo","Tokelau","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands","Tuvalu","U.S. Virgin Islands","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","United States Minor Outlying Islands","Uruguay","Uzbekistan","Vanuatu","Vatican","Venezuela","Vietnam","Wallis and Futuna","Western Sahara","Yemen","Zambia","Zimbabwe"];
geo.storedCities = [];
geo.citiescounter = 0;
geo.setCity = function(){
}
geo.addCompleteData = function(startValue, choiceObject){
    return startValue+'<span style="display:none;"><span>'+choiceObject.lng+'</span><span>'+choiceObject.lat+'</span><span>'+choiceObject.postalCode+'</span></span>';
}

geo.countStoredCheckedCities = function(){
    var quant = 0;
    geo.storedCities.each(function(item){
        if(item.selected) quant++;
    });
    return quant;
}

geo.countCheckedCities = function(){
    var quant = 0;
    $('neibourslist').getElements('input').each(function(item){
        if(item.checked) quant++;
    });
    return quant+geo.countStoredCheckedCities();
}

geo.toggleCityCheckedValue = function(cityname){
    geo.storedCities.each(function(item){
        if(item.name === cityname){
            item.selected = !item.selected;
        }
    });
}

geo.showStoredCities = function(geosult){
    $('currentStoredCitiesContainer').removeClass('hidden');
    var ul = $('currentStoredCities');
    ul.empty();

    if(geo.storedCities.length>0){
        geo.storedCities.each(function(item, index){
            if(item.selected)
                var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+item.name+'" VALUE="'+item.name+'" CHECKED />&nbsp;'+item.name);
            else
                var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+item.name+'" VALUE="'+item.name+'" />&nbsp;'+item.name);
                
            ul.grab(li);
        });
    }
    ul.getElements('input').each(function(item){
        item.addEvent('click', function(ev){
            var test = ev.target.checked;
            var c = geo.countCheckedCities();
            if(ev.target.checked && geo.countCheckedCities()>=20){
                alert('No more then 20 cities can be selected, please unselect another city first.');
                return false;
            }
            else{
                geo.toggleCityCheckedValue(item.name);
            }
        });
    });

}

geo.isStoredCity = function(city){
	for(var i = 0; i< geo.storedCities.length; i++){
		if(geo.storedCities[i].name === city) return true;
	}
	return false;
}

geo.showNeighbourCities = function(geosult){
    var names = geosult.geonames;
    var ul = $('neibourslist');
    if(ul == null)
        ul = new Element('ul', {id:'neibourslist'});
    $('neighbours').empty();
    $('neighbours').grab(ul);

    if(names && names.length>0){
        var counter = 0 + geo.countStoredCheckedCities();
        names.each(function(item, index){
            if(geo.allowedtowns.indexOf(item.name)>=0){
            	//check if item.name is not in currentStoredCities
            	if(!geo.isStoredCity(item.name)){
			var name = item.name;
			if(counter<20){
			    var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+name+'" VALUE="'+name+'" CHECKED />&nbsp;'+name);
			}
			else{
			    var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+name+'" VALUE="'+name+'" />&nbsp;'+name);
			}
			ul.grab(li);
			counter++;
		}
            }
        });
    }
    ul.getElements('input').each(function(item){
        item.addEvent('click', function(ev){
            if(geo.countCheckedCities()>20){
                alert('No more then 20 cities can be selected, please unselect another city first.');
                return false;
            }
        });
    });
    $('checkAll').removeClass('hidden');
    $('addCity').removeClass('hidden');
    //alert('creating autocompleter for "extra city" field');
    geo.addedCityAutoC();

}

geo.setFirstCityParams = function(geosult){
    var test = geosult.postalCodes[0];
    if(test){
        $('lng').set('value', test.lng);
        $('lat').set('value', test.lat);
    }
}

geo.getFirstCityParams = function(isocountry){
    var geourl = 'http://ws.geonames.org/postalCodeSearchJSON';
    var requ = new Request.JSONP({
        url:geourl,
        data:{
            placename_startsWith:$('city').get('value'),
            country:isocountry,
            maxRows:1,
			isReduced:true
        },
        onFailure:function(){
            alert("FAIL FAIL FAIL");
        },
        onComplete:function(geosult){
            geo.setFirstCityParams(geosult);
        }
    });
    requ.send();
}

geo.searchNeighbours = function(){
    if($('lat').get('value')===''){
        alert('Please refine your selection by adding the region to the city');
        return;
    }
    if($('confirm').get('value')!=='' && $('confirm').get('value')!==$('city').get('value')){
        alert('You have modified a city in the text field without confirming a selection from the suggestions');
        return;
    }
    var test = geo.allowedtowns;
    var geourl = 'http://ws.geonames.org/findNearbyPlaceNameJSON';   
    var requ = new Request.JSONP({
        url:geourl,
        data:{
            lat:$('lat').get('value'),
            lng:$('lng').get('value'),
            radius:parseInt($('radiusRange').get('value'))/0.62,
            maxRows:2500,
			isReduced:true
        },
        onFailure:function(){
            alert("FAIL FAIL FAIL");
        },
        onComplete:function(geosult){
            geo.showNeighbourCities(geosult);
        }
    });
    requ.send();
}

geo.isDuplicate = function(item, list){
    var dupl = false;
    list.each(function(tmpitem){
        var test = item;
        if(item.placeName+item.adminName2 === tmpitem.placeName+tmpitem.adminName2){
            dupl = true;
        }
    });
    return dupl;
}

geo.createAutocompleter = function(isocountry){

	var inputWord = $('city');
    var getCitiesUrl ='http://ws.geonames.org/searchJSON';// 'http://ws.geonames.org/postalCodeSearchJSON';

    new Autocompleter.JsonP(inputWord, getCitiesUrl,{
        postVar:'name_startsWith',
        jsonpOptions: {
            //this data gets added to the query string using JsonP's options
            data: {
			featureClass:'P',
            country: isocountry,
			style: 'FULL',
            maxRows:100//,
			//isReduced:true
            }
        },
		maxChoices:100,
        //require at least a key stroke from the user
        minLength: 1,
        selectMode: 'type-ahead',
        //because the data returned has a unique structure, we must manage the parsing ourselves
		
        filter: function(resp) {
            //dbug.log(resp);
            try {
                //this structure is unique to the CNET API
				
                var codes = resp.geonames;
                var filtered = [];
                if(codes && codes.length>0){
                    /*var places = [];
                    codes.each(function(item, index){
                        var testEl = item;
                        places.push(item['placeName']);
                    });*/
					
                    codes.each(function(item){
						filtered.push(item);
                    });
                    return filtered;
                }
                else return [];
                //dbug.log(choices);
                //test it
                //if(!choices || choices.length == 0) return [];
                //filter it and return it
                //return choices.filter(function(choice){
                    //return (choice.Name.$.test(this.queryValue, 'i') || choice['@id'].test(this.queryValue), 'i');
                //}.bind(this));
            } catch(e){'filterResponse error: ', dbug.log(e)}
        },
        injectChoice: function(choice) {
            //again, the structure of these items is unique to the CNET API
            var test = choice;
            if(!choice.name) return;
			if(geo.allowedtowns.indexOf(choice.name)>=0){


			var el = new Element('li').set('html', geo.addCompleteData(this.markQueryValue(choice.name+'/'+choice.adminName2), choice));
            //var el = new Element('li').set('html', geo.addCompleteData(this.markQueryValue(choice.placeName+'/'+choice.adminName2), choice));
			
            //el.inputValue = choice.placeName+'/'+choice.adminName2;
			el.inputValue = choice.name+'/'+choice.adminName2;
            this.addChoiceEvents(el).inject(this.choices);
			}
        },
        onSelection: function(text,listItem){
            var selectedItemData = listItem.getChildren()[1].getChildren();
            $('lng').set('value', selectedItemData[0].get('html'));
            $('lat').set('value', selectedItemData[1].get('html'));
            $('pc').set('value', selectedItemData[2].get('html'));
            $('confirm').set('value', text.get('value'));
        }
    });
}


geo.addedCityAutoC = function(){
    var isocountry = $('isocountry').get('text');
    var getCitiesUrl = 'http://ws.geonames.org/searchJSON';//'http://ws.geonames.org/postalCodeSearchJSON';
    var test = $('addedcity');
    new Autocompleter.JsonP($('addedcity'), getCitiesUrl,{
        postVar:'name_startsWith',//'placename_startsWith',
        jsonpOptions: {
            //this data gets added to the query string using JsonP's options
            data: {
			featureClass:'P',
            country: isocountry,
			style: 'FULL',
            maxRows:100			
            //country: isocountry,
            //maxRows:10,
			//isReduced:true
            }
        },
		maxChoices:100,		
        //require at least a key stroke from the user
        minLength: 1,
        selectMode: 'type-ahead',
        //because the data returned has a unique structure, we must manage the parsing ourselves
        filter: function(resp) {
            //dbug.log(resp);
            try {
                //this structure is unique to the CNET API
                var codes = resp.postalCodes;
                var filtered = [];
                if(codes && codes.length>0){
                    codes.each(function(item){
                        if(!geo.isDuplicate(item, filtered)){
                            filtered.push(item);
                        }
                    });
                    return filtered;
                }
                else return [];
            } catch(e){'filterResponse error: ', dbug.log(e)}
        },
        injectChoice: function(choice) {
            //again, the structure of these items is unique to the CNET API
            var test = choice;
            //if(!choice.placeName) return;
			if(!choice.name) return;
			if(geo.allowedtowns.indexOf(choice.name)>=0){			
			var el = new Element('li').set('html', this.markQueryValue(choice.name+'/'+choice.adminName2));
            //var el = new Element('li').set('html', this.markQueryValue(choice.placeName+'/'+choice.adminName2));
			el.inputValue = choice.name+'/'+choice.adminName2;
            //el.inputValue = choice.placeName+'/'+choice.adminName2;
            this.addChoiceEvents(el).inject(this.choices);
			}
        }
    });

}

geo.manAddedCityAutoC = function(isocountry){
    var getCitiesUrl = 'http://ws.geonames.org/searchJSON'; //'http://ws.geonames.org/postalCodeSearchJSON';
    new Autocompleter.JsonP($('manAddedcity'), getCitiesUrl,{
        //postVar:'placename_startsWith',
		postVar:'name_startsWith',
        jsonpOptions: {
            //this data gets added to the query string using JsonP's options
            data: {
			featureClass:'P',
            country: isocountry,
			style: 'FULL',
            maxRows:100			
			
			
            //country: isocountry,
            //maxRows:10,
			//isReduced:true
            }
        },
		maxChoices:100,		
        //require at least a key stroke from the user
        minLength: 1,
        selectMode: 'type-ahead',
        //because the data returned has a unique structure, we must manage the parsing ourselves
        filter: function(resp) {
            //dbug.log(resp);
            try {
                //this structure is unique to the CNET API
                var codes = resp.postalCodes;
                var filtered = [];
                if(codes && codes.length>0){
                    codes.each(function(item){
                        if(!geo.isDuplicate(item, filtered)){
                            filtered.push(item);
                        }
                    });
                    return filtered;
                }
                else return [];
            } catch(e){'filterResponse error: ', dbug.log(e)}
        },
        injectChoice: function(choice) {
            //again, the structure of these items is unique to the CNET API
            var test = choice;
            //if(!choice.placeName) return;
			if(!choice.name) return;
			if(geo.allowedtowns.indexOf(choice.name)>=0){			
            var el = new Element('li').set('html', this.markQueryValue(choice.name+'/'+choice.adminName2));
            el.inputValue = choice.name+'/'+choice.adminName2;
			
            //var el = new Element('li').set('html', this.markQueryValue(choice.placeName+'/'+choice.adminName2));
            //el.inputValue = choice.placeName+'/'+choice.adminName2;
            this.addChoiceEvents(el).inject(this.choices);
			}
        }
    });
}

geo.doManAddCity = function(man){
    var ul = $('neibourslist');
    if(ul == null){
        ul = new Element('ul', {id:'neibourslist'});
        $('neighbours').empty();
        $('neighbours').grab(ul);
    }
    var t = $('manAddedcity').get('value');
    if(geo.countCheckedCities()<20)
        var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+t+'" VALUE="'+t+'" CHECKED />&nbsp;'+t);
    else
        var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+t+'" VALUE="'+t+'" />&nbsp;'+t);
    li.addEvent('click', function(ev){
        if(geo.countCheckedCities()>20){
            alert('No more then 20 cities can be selected, please unselect another city first.');
            return false;
        }
    });
    li.inject($('neibourslist'), 'top');

}

geo.doAddCity = function(man){
    var ul = $('neibourslist');
    if(ul == null){
        ul = new Element('ul', {id:'neibourslist'});
        $('neighbours').empty();
        $('neighbours').grab(ul);
    }
    var t = $('addedcity').get('value');
    if(geo.countCheckedCities()<20)
        var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+t+'" VALUE="'+t+'" CHECKED />&nbsp;'+t);
    else
        var li = new Element('li').set('html', '<INPUT TYPE="CHECKBOX" NAME="'+t+'" VALUE="'+t+'" />&nbsp;'+t);

    li.addEvent('click', function(ev){
        if(geo.countCheckedCities()>20){
            alert('No more then 20 cities can be selected, please unselect another city first.');
            return false;
        }
    });
    li.inject($('neibourslist'), 'top');

}

geo.createStoredCitiesList = function(){//hidden div containing a set of textfields with stored cities data
    $('storedvalues').getElements('input').each(function(item){
        geo.storedCities.push({name:item.get('value'),selected:true});
    });
}

geo.createStoredCitiesList2 = function(){//hidden textfields containing one csv string of stored cities data
    var sc = $('storedvalues2').get('value');
    var myArr = sc.split(',');
    myArr.each(function(item){
        geo.storedCities.push({name:item.trim(),selected:true});
    });
}

geo.clean = function(){
    $(document.body).getElements('input[class=clean]').each(function(item){
        item.set('value', '');
    });

}

document.addEvent('domready', function() {
    var test = $('country').get('value'); 
    var index = geo.countries.indexOf($('country').get('value'));
    if(index>0) $('isocountry').set('text', geo.countrycodes[index]);
    geo.clean();
    if(!$('app')) geo.createAutocompleter($('isocountry').get('text'));
    geo.getFirstCityParams($('isocountry').get('text'));
    $('searchNeighboursBtn').addEvent('click', function(ev){
        geo.searchNeighbours();
        ev.target.getParent().getNext().addClass('hidden');
    });
    $('selectAll').addEvent('click', function(ev){
        var counter = geo.countStoredCheckedCities();;
        if(ev.target.get('checked'))
            $('neibourslist').getElements('input').each(function(item){if(counter<20){item.set('checked', true); counter++}});
        else
            $('neibourslist').getElements('input').each(function(item){item.set('checked', false)});
    });
    /*$('manSearchNeighboursBtn').addEvent('click', function(ev){
        ev.target.getParent().getParent().addClass('hidden');
        //ev.target.getParent().addClass('hidden');
        $('manAddCity').removeClass('hidden');
        $('saveArea').removeClass('hidden');
        geo.manAddedCityAutoC($('isocountry').get('text'));
    });*/
    $('manSel').addEvent('click', function(ev){
        //geo.searchNeighbours();
        $('neighbours').empty();
        $('checkAll').addClass('hidden');
        $('addCity').addClass('hidden');
        $('resultArea').addClass('hidden');
        $('autosearch').addClass('hidden');
        $('mansearch').removeClass('hidden');
        geo.manAddedCityAutoC($('isocountry').get('text'));
        $('resultArea').addClass('hidden');
    });
    $('autoSel').addEvent('click', function(ev){
        //geo.searchNeighbours();
        $('neighbours').empty();
        $('mansearch').addClass('hidden');
        $('autosearch').removeClass('hidden');
    });
    //$('setCityButton').addEvent('click', geo.setCity);
    $('doAddCityBtn').addEvent('click', geo.doAddCity);
    $('doManAddCityBtn').addEvent('click', geo.doManAddCity);
    $('saveBtn').addEvent('click', function(){
        var resultString = '';
        $('neibourslist').getElements('input').each(function(item){
            if(item.checked){
                var city = item.get('value');
                if(city.indexOf('/')>0)
                    resultString += city.substring(0, city.indexOf('/'));
                else
                    resultString += city;
                resultString += ', ';
            }
        });
        if($('currentStoredCities')){
		$('currentStoredCities').getElements('input').each(function(item){
		    if(item.checked){
			var city = item.get('value');
			if(city.indexOf('/')>0)
			    resultString += city.substring(0, city.indexOf('/'));
			else
			    resultString += city;
			resultString += ', ';
		    }
		});
        }
        $('result').set('value', resultString.substr(0, resultString.length-2));
        var test = resultString.substr(0, resultString.length-2);
    });
    geo.createStoredCitiesList2();
    var test = geo.storedCities;
    geo.showStoredCities();
    var testt = 'wait';
    $('startBtn').addEvent('click', function(){
        $('app').removeClass('hidden');
        $('start').addClass('hidden');
        geo.createAutocompleter($('isocountry').get('text'));

    })
    $('stopBtn').addEvent('click', function(){
        $('start').removeClass('hidden');
        $('app').addClass('hidden');
    })

});
