var unit = {
	distance:'km',
	height:'m'
}


var fix_editor = {
	isNewFix:true,
	isNewTour:true,
	infoPane : new cfkit_InfoPane('infoPane'),
	fixtureTypeDropDown: new SelectBox('fixtureTypeID'),
	countryDropDown: new SelectBox('countryID'),
	tourTypeDropDown: new SelectBox('tourTypeID'),
	tourCurrencyDropDown: new SelectBox('currency'),
	tour_pager:new Grid_Pager(),
	tour_grid:new Grid(),
	search_pager:new Grid_Pager(),
	search_grid:new Grid(),
	
	init:function(){
		fix_editor.tour_grid.init('tourGrid',5);
		fix_editor.tour_pager.init('tourGridPager',fix_editor.tour_grid,'fix_editor.tour_pager');
		fix_editor.search_grid.init('searchGrid',5);
		fix_editor.search_pager.init('searchGridPager',fix_editor.search_grid,'fix_editor.search_pager');
		fix_editor.setState('step1');
		return;
	},
	
	searchExisting:function(){
		fix_editor.infoPane.busy();
		
		var startDate = dijit.byId('fix_startDateFld').getValue();
		
		dojo.byId('srch_startDate').value = cfkit_util.toDBdate(startDate);
		
		dojo.xhrPost({
			form: "frmSearch",
			url : "/server/fix_search.cfm",
			handleAs : "json",
			load : fix_editor.searchExistingOK,
			error : fix_editor.callbackError
		});

		return;
	},
	
	searchExistingOK:function(data,ioArgs){
		
		if(data.length != 0){
			cfkit_util.display('tabGrid',true);
			cfkit_util.display('tabGrid_empty',false);
			fix_editor.search_pager.updateData(data);	
		}else{
			cfkit_util.display('tabGrid',false);
			cfkit_util.display('tabGrid_empty',true);
		}
		
		fix_editor.infoPane.hide();
		return;
	},
	
	setState:function(state){
		
		if(state=='edit'){
			cfkit_util.display('fix_tours',true);
			fix_editor.showTab(0);
		}
		return;
	},
	
	showTab:function(tab){
		var aTab = new Array();
		aTab[0] = 'tabFix';
		aTab[1] = 'tabTour';
	
		if(tab == 1){
			window.scrollTo(0,0);
		}
		for (var i=0; i<aTab.length;i++){
			cfkit_util.display(aTab[i],false);
		}
		
		if(tab==1 && fix_editor.isNewTour){
			var startDate = dijit.byId('fix_startDateFld').getValue();
			var startTime = dijit.byId('fix_startTimeFld').getValue();
			var name = dojo.byId('name').value;		
			
			dijit.byId('tour_startDateFld').setValue(startDate);
			dijit.byId('tour_startTimeFld').setValue(startTime);
			dojo.byId('tour_name').value = name;	
		}
		
		cfkit_util.display(aTab[tab],true);
	
		return;
	},
	
	showSite:function(){
		var src = dojo.byId('urlHomePage').value;
		var popup = open_popup(src,'eventSite',800,600);
		
		popup.moveTo(50,50);
		
		return;
	},
	
	saveFixture:function(){
		fix_editor.infoPane.busy();
		var startDate = dijit.byId('fix_startDateFld').getValue();
		var tmp = dijit.byId('fix_startTimeFld').getValue();
		startDate.setHours(tmp.getHours());
		startDate.setMinutes(tmp.getMinutes());
		startDate.setSeconds(tmp.getSeconds());
		
		var endDate = startDate;
		
		dojo.byId('fix_startDate').value = cfkit_util.toDBdate(startDate);
		dojo.byId('fix_endDate').value = cfkit_util.toDBdate(endDate);
		dojo.byId('fix_notes').value = dojo.byId('fix_notesFld').value;
		
		dojo.xhrPost({
			form: "frmFix",
			url : "/server/fix_save.cfm",
			handleAs : "json",
			load : fix_editor.saveFixtureOK,
			error : fix_editor.callbackError
		});
		return;
	},
	
	saveFixtureOK:function(data,ioArgs){
		if(data.STATUS == 1){
			if(fix_editor.isNewFix){
				fix_editor.setState('edit');
			}
			dojo.byId('fix_fixtureID').value = data.FIXTUREID;
			dojo.byId('tour_fixtureID').value = data.FIXTUREID;
			fix_editor.isNewFix = false;
			fix_editor.infoPane.hide();
		}else{
			fix_editor.infoPane.msg(data.MSG.DISPLAYTXT);	
		}
		
		if(data.STRACTION.AWARDED){
			cfkit_award.display(data.STRACTION);
		}
		
		return;
	},
	
	loadFixture:function(fixtureID){
		fix_editor.infoPane.busy();
		dojo.xhrGet({
	      url: '/server/fix_get.cfm?fixtureID=' + fixtureID,
	      load: fix_editor.loadFixtureOk,
	      error: fix_editor.callbackError,
		  handleAs: 'json'
	   });
	},
	
	loadFixtureOk:function(data,ioArgs){	
		console.log(data);
		
		var fix_data = data.fix;
		var startDate = cfkit_util.fromDBdate(fix_data.startDate);
		var endDate = cfkit_util.fromDBdate(fix_data.endDate);
		
		if(fix_data.fixtureID != 0){
			fix_editor.isNewFix = false;
			gmap.addLocation(fix_data.lat,fix_data.lng);
		}
		fix_editor.fixtureTypeDropDown.setValue(fix_data.fixtureTypeID);
		dojo.byId('fix_fixtureID').value = fix_data.fixtureID;
		dojo.byId('tour_fixtureID').value = fix_data.fixtureID;
		dojo.byId('name').value = fix_data.name;
		dojo.byId('urlHomePage').value = fix_data.urlHomePage;
		dojo.byId('houseNr').value = fix_data.houseNr;
		dojo.byId('street').value = fix_data.street;
		dojo.byId('city').value = fix_data.city;
		fix_editor.countryDropDown.setValue(fix_data.countryID);	
		dijit.byId('fix_startDateFld').setValue(startDate);
		dijit.byId('fix_startTimeFld').setValue(startDate);
		dojo.byId('fix_notesFld').value = fix_data.notes;
		
		if(!fix_editor.isNewFix){
			fix_editor.tour_pager.updateData(data.fix.aTour);
			fix_editor.setState('edit');
		}
		
		fix_editor.infoPane.hide();
		return;
	},
	
	loadTour:function(tourID){
		fix_editor.infoPane.busy();
		dojo.xhrGet({
	      url: '/server/tour_get.cfm?tourID=' + tourID,
	      load: fix_editor.loadTourOk,
	      error: fix_editor.callbackError,
		  handleAs: 'json'
	   });
	},
	
	loadTourOk:function(data,ioArgs){
		var data = data.tour;
		var startDate = cfkit_util.fromDBdate(data.startDate);
		var plannedTime = data.plannedTime.split('|');	

		dojo.byId('tourID').value = data.tourID;
		dijit.byId('tour_startDateFld').setValue(startDate);
		dijit.byId('tour_startTimeFld').setValue(startDate);
		dijit.byId('tour_time_hh').setValue(plannedTime[0]);
		dijit.byId('tour_time_mm').setValue(plannedTime[1]);
		fix_editor.tourTypeDropDown.setValue(data.tourTypeID);
		fix_editor.tourCurrencyDropDown.setValue(data.currency);
		dojo.byId('tour_name').value = data.name;
		dojo.byId('fee').value = data.v_fee;
		if(data.competitors != 0) dojo.byId('competitors').value = data.competitors;
		if(data.competitorMax != 0) dojo.byId('competitorMax').value = data.competitorMax;
		dojo.byId('distanceFld').value = cfkit_util.fromMetersTo(unit.distance,data.distance);
		dojo.byId('ascentFld').value = cfkit_util.fromMetersTo(unit.height,data.ascent);
		dojo.byId('tour_notesFld').value = data.notes;
		
		if(data.tourID != 0){
			fix_editor.isNewTour = false;
		}else{
			fix_editor.isNewTour = true;
		}
		fix_editor.showTab(1);
		
		fix_editor.infoPane.hide();
		return;
	},
	
	
	loadTourList:function(fixtureID){
		dojo.xhrGet({
	      url: '/server/fix_get.cfm?fixtureID=' + fixtureID,
	      load: fix_editor.loadTourListOk,
	      error: fix_editor.callbackError,
		  handleAs: 'json'
	   });
	   return;
	},
	
	loadTourListOk:function(data,ioArgs){
		fix_editor.tour_pager.updateData(data.fix.aTour);
		return;
	},
	
	saveTour:function(){
		fix_editor.infoPane.busy();
		
		var startDate = dijit.byId('tour_startDateFld').getValue();
		var tmp = dijit.byId('tour_startTimeFld').getValue();		
		startDate.setHours(tmp.getHours());
		startDate.setMinutes(tmp.getMinutes());
		startDate.setSeconds(tmp.getSeconds());				
		
		var plannedTime = dijit.byId('tour_time_hh').getValue() + '|';
		plannedTime += dijit.byId('tour_time_mm').getValue() + '|';
		plannedTime += '0|0';
		
		dojo.byId('tour_startDate').value = cfkit_util.toDBdate(startDate);
		dojo.byId('plannedTime').value = plannedTime;
		dojo.byId('tour_notes').value = dojo.byId('tour_notesFld').value;
		dojo.byId('distance').value = cfkit_util.toMetersFrom(unit.distance,dojo.byId('distanceFld').value);
		dojo.byId('ascent').value = cfkit_util.toMetersFrom(unit.height,dojo.byId('ascentFld').value);
		
		dojo.xhrPost({
			form: "frmTour",
			url : "/server/tour_save.cfm",
			handleAs : "json",
			load : fix_editor.saveTourOK,
			error : fix_editor.callbackError
		});
		return;
	},
	
	saveTourOK:function(data,ioArgs){
		if(data.status == 2){
			fix_editor.setState('edit');
			fix_editor.loadTourList(dojo.byId('fix_fixtureID').value);
			fix_editor.isNewTour = false;
			fix_editor.infoPane.hide();
		}else{
			fix_editor.infoPane.msg(data.msg.displayTxt);	
		}
		return;
	},
	
	
	callbackError:function(data,ioArgs){
		console.log(data);
		fix_editor.infoPane.msg('Error when retrieving data from the server!');
		return;
	}
}


var map;
var geocoder;
var gmap = {
	locationMarker:'',
	init:function(){
		return;
	},
	
	getLocalCenter:function(){
		switch(cfkit_ctx.getLocaleID()){
			case '1': /* 1=International English */
			return new GLatLng(47.81315451752765, 10.37109375);
			break;
			
			case '2': /* 2=Germany */
			return new GLatLng(50.40151532278236, 9.4921875);
			break;
			
			case '3': /* 3= USA */
			return new GLatLng(39.842286020743394, -100.37109375);
			break;
		}
		
		return new GLatLng(47.81315451752765, 10.37109375);
	},
	
	refresh:function(){
		map.checkResize();
		if(gmap.locationMarker != '')
		
		map.setCenter(gmap.locationMarker.getLatLng(), 12);
		return;
	},
	
	addLocation:function(lat,lng){
		var latlng = new GLatLng(lat,lng);
		gmap._addLocation(latlng);
		return;
	},
	
	_addLocation:function(latlng){
		if(gmap.locationMarker == ''){
			var icon = new GIcon();
		    icon.image = '/gfx/global/gmap/bike.png';
		    icon.iconSize = new GSize(20, 34);
		    icon.shadow = '/gfx/global/gmap/shadow.png';
		    icon.shadowSize = new GSize(36, 34);
		    icon.iconAnchor = new GPoint(5, 34);
			
			gmap.locationMarker = new GMarker(latlng,{icon:icon,draggable:true});
			map.addOverlay(gmap.locationMarker);
			gmap.locationMarker.enableDragging();
																				
			GEvent.addListener(gmap.locationMarker, "drag", function(){
				dojo.byId('lat').value = gmap.locationMarker.getLatLng().lat();
				dojo.byId('lng').value = gmap.locationMarker.getLatLng().lng();
				return;
			});	
		}else{
			gmap.locationMarker.setLatLng(latlng);
		}
		
		map.setCenter(latlng, 12);
		
		dojo.byId('lat').value = gmap.locationMarker.getLatLng().lat();
		dojo.byId('lng').value = gmap.locationMarker.getLatLng().lng();
	
		return;
	},
	
	findAddress:function(){
		var country = dojo.byId('countryID');
		
		cfkit_util.display('tabMap',true);
		cfkit_util.display('tabGrid',false);
		
		gmap.refresh();
		
		if(country.options[country.selectedIndex].value == 0){
			fix_editor.infoPane.msg('Please choose a country');
			return;
		}
		
		country = country.options[country.selectedIndex].text;
		
		var address = dojo.byId('street').value + ' ' + dojo.byId('houseNr').value + ' ' + dojo.byId('city').value + ' , ' + country;

		geocoder.getLatLng(address, function(latlng) {
	    								if (!latlng) {
	      									fix_editor.infoPane.msg('The location you entered could not be found!');
	    								} else {
	      									gmap._addLocation(latlng);
	      									cfkit_util.display('mapHint',true);	
	    								}		
										return;
	    							});
	   return;
	},

	
	load:function () {
		if (GBrowserIsCompatible()) {
			geocoder = new GClientGeocoder();
			map = new GMap2(document.getElementById('map'));
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(gmap.getLocalCenter(), 4);
		}
    	return;
    }
}