var GpsBabelBase=Class.create({CONST:{line_color:{'route':'#00FF00','track':'#0000FF'}},routes:[],tracks:[],initialize:function(init,cnf){this.cnf=cnf;this.place_id='way_file_upload_place';this.progress_id='way_import_progress_container';this.format_id='way_import_format';if(init){this.first_time_init();}},first_time_init:function(){document.body.ui.fetch('/gps/babel/formats/read',this.fill_format.bind(this,this.format_id,true));this._swf=new SWFUpload({upload_url:'/gps/babel/upload',preserve_relative_urls:false,flash_url:'/static/scripts/swfupload/Flash/swfupload.swf',button_placeholder_id:this.place_id,button_width:200,button_height:18,button_text:'<span class="button">'+I18N.select_file+'</span>',button_text_style:'.button { font-family: Verdana; font-size: 12pt; text-decoration:underline; font-weight: bold; }',button_window_mode:SWFUpload.WINDOW_MODE.TRANSPARENT,button_cursor:SWFUpload.CURSOR.HAND,file_queue_error_handler:this.fileQueueError.bind(this),file_dialog_complete_handler:this.fileDialogComplete.bind(this),upload_progress_handler:this.uploadProgress.bind(this),upload_error_handler:this.uploadError.bind(this),upload_success_handler:this.uploadSuccess.bind(this),upload_complete_handler:this.uploadComplete.bind(this),upload_start_handler:this.upload_start.bind(this)});this.init_map();$('import_routes').observe('change',function(){this.show_route_on_map($('import_routes').getValue());}.bind(this));$('import_tracks').observe('change',function(){this.show_track_on_map($('import_tracks').getValue());}.bind(this));$('way_import').down('.edit').observe('click',this.edit_selected_track.bind(this));$('way_import').down('.reset').observe('click',this.reset_changes.bind(this));},fill_format:function(id,has_autodetect,json){if('formats' in json){this._formats=json.formats;this.add_common_formats(id,json.formats,has_autodetect);$(id).appendChild(Builder.node('optgroup',{'label':I18N.other},[$H(json.formats).keys().sort(function(a,b){return this[a].name.localeCompare(this[b].name);}.bind(json.formats)).map(function(formats,id,key){var value=formats[key];if(!value.name.match(/output/i)){option=new Option('',key,false,false);option.appendChild(document.createTextNode(value.name));return option;}
return null;}.bind(this,json.formats,id)).compact()]));$(id).options.selectedIndex=has_autodetect?1:0;}},add_common_formats:function(id,formats,has_autodetect){$(id).appendChild(Builder.node('optgroup',{'label':I18N.common},(has_autodetect?[(function(){var option=new Option('','autodetect',true,true);option.appendChild(document.createTextNode(I18N.autodetect));return option;})()]:[]).concat(['kml','gpx','gdb'].map(function(n){if(n=='kml'&&has_autodetect){this[n].name+=' (*.KML, *.KMZ)';}
var option=new Option('',n,false,false);option.appendChild(document.createTextNode(this[n].name));return option;}.bind(formats)))));},init_map:function(){if(GBrowserIsCompatible()){this.map=new GMap2($('import_map'));this.map.setUIToDefault();this.overview=new GOverviewMapControl();this.map.addControl(this.overview);this.map.setCenter(google.loader.ClientLocation?new GLatLng(google.loader.ClientLocation.latitude,google.loader.ClientLocation.longitude):new GLatLng(40,70),10);}},upload_start:function(file){var format=$('way_import_format').getValue();if(format==='autodetect'){var extension=file.name.split('.').last().toLowerCase();if(extension=='kmz'){extension='kml';}
if(extension in this._formats){format=extension;}else if((format=this.get_format_by_extension(extension))!==null){extension=format;}else{alert(I18N.specify_format);return false;}}
this._swf.setPostParams({'format':format,'max_points':$('way_import_max_points').getValue()});this.progress=new ProgressBar(this.progress_id,{start_color:[0,0,255],end_color:[0,255,0]});$('way_import_progress_container').show();return true;},get_format_by_extension:function(extension){var option=$('way_import_format').options.find(function(o){return o.text.match(this);}.bind(new RegExp('\\*\\.'+extension,"i")));return option?option.value:null;},fileDialogComplete:function(files){if(files>1){alert(I18N.one_file);return false;}
this._swf.startUpload();return true;},fileQueueError:function(file,errorCode,message){if(errorCode===SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED){return alert(I18N.to_many_files);}
switch(errorCode){case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:return alert(I18N.empty_file);case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:return alert(I18N.empty_file);default:return alert(errorCode+': '+message);}
return true;},uploadProgress:function(file,bytesLoaded){this.progress.set(bytesLoaded/file.size);if((bytesLoaded/file.size)==1){this.progress.process();}},uploadSuccess:function(file,data){if(data.isJSON()){return this.builder(data.evalJSON().result);}else{alert(I18N.nothing_found);}
return true;},uploadComplete:function(file){this.progress.set(1);this.progress.stop().set(1);},uploadError:function(file,errorCode,message){switch(errorCode){case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:return alert(I18N.limit_exceeded);case-270:this._swf.cancelUpload(null,false);return true;default:return alert(errorCode+':'+message);}
return true;},builder:function(json){var routes=this.routes.size();var tracks=this.tracks.size();if(json instanceof Object){if('routes' in json&&json.routes){json.routes.each(function(item){if('points' in item){this.register_route(item);}}.bind(this));}
if('tracks' in json&&json.tracks instanceof Array){json.tracks.each(function(item){if('segments' in item){this.register_track(item);}}.bind(this));}}
if(this.routes.size()==routes&&this.tracks.size()==tracks){alert(I18N.nothing_found+($('way_import_format').getValue()=='autodetect'?('. '+I18N.specify_format):''));}
return true;},register_route:function(item){if(item.points.length>=2){this.routes.push(item);$('routes_found').update(this.routes.size());$('import_routes').options[$('import_routes').options.length]=new Option((item.name||(I18N.route+' '+this.routes.size()))+' ('+item.points.length+' '+I18N.points+')',this.routes.size()-1,false,false);}},register_track:function(item){var points=item.segments.inject(0,function(val,segment){val+=segment.points.length;return val;});if(points>=2){this.tracks.push(item);$('tracks_found').update(this.tracks.size());$('import_tracks').options[$('import_tracks').options.length]=new Option((item.name||(I18N.track+' '+this.tracks.size()))+' ('+points+' '+I18N.points+')',this.tracks.size()-1,false,false);}},show_route_on_map:function(index){if(index){var points=this.routes[index].points.collect(function(i){return new GLatLng(i.lat,i.lon);});this.show_line_on_map('route',points);}else{this.remove_line_from_map('route');}},show_track_on_map:function(index){if(index){var points=this.tracks[index].segments.inject([],function(arr,segment){arr.push(segment.points.collect(function(i){return new GLatLng(i.lat,i.lon);}));return arr;}).flatten();this.show_line_on_map('track',points);}else{this.remove_line_from_map('track');}},show_line_on_map:function(type,points){this.remove_line_from_map(type);if(points.size()>2){this[type+'_overlay']=new GPolyline(points,this.CONST.line_color[type]);this.map.addOverlay(this[type+'_overlay']);var bounds=this[type+'_overlay'].getBounds();this.map.setCenter(bounds.getCenter(),this.map.getBoundsZoomLevel(bounds));this[type+'_markers']=[new GMarker(this[type+'_overlay'].getVertex(this[type+'_overlay'].getVertexCount()-1),this.icon('stop')),new GMarker(this[type+'_overlay'].getVertex(0),this.icon('start'))];this.map.addOverlay(this[type+'_markers'][0]);this.map.addOverlay(this[type+'_markers'][1]);}else{alert(I18N.nothing_found);}},edit_selected_track:function(){if('track_overlay' in this){this.track_overlay.enableEditing();GEvent.addListener(this.track_overlay,'click',function(o){$R(0,(this.getVertexCount()-1)).each(function(o,n){if(o.equals(this.getVertex(n))){this.deleteVertex(n);}}.bind(this,o));}.bind(this.track_overlay));}},remove_line_from_map:function(type){if(this[type+'_overlay']){GEvent.clearListeners(this[type+'_overlay']);this.map.removeOverlay(this[type+'_overlay']);delete this[type+'_overlay'];this.map.removeOverlay(this[type+'_markers'][0]);this.map.removeOverlay(this[type+'_markers'][1]);delete this[type+'_markers'];}},reset_changes:function(){this.show_track_on_map($('import_tracks').getValue());},icon:function(type,options){var icon;switch(type){case'start':icon=new GIcon(G_DEFAULT_ICON,'http://www.google.com/mapfiles/dd-start.png');break;case'stop':icon=new GIcon(G_DEFAULT_ICON,'http://www.google.com/mapfiles/dd-end.png');break;default:icon=new GIcon(G_DEFAULT_ICON);break;}
return{icon:icon,'draggable':false};}});var GpsBabel=Class.create(GpsBabelBase,{first_time_init:function($super){$super();document.body.ui.fetch('/gps/babel/formats/write',this.fill_format.bind(this,'way_import_output_format',false));$('way_import').down('.clear_tracks').observe('click',this.clear_list.bind(this,'track'));$('way_import').down('.clear_routes').observe('click',this.clear_list.bind(this,'route'));$('way_import_do').observe('click',this.convert.bind(this,'convert'));$('way_get_url').observe('click',this.convert.bind(this,'url'));if($('clear_saved_result')){$('clear_saved_result').observe('click',this.clear_saved_results.bind(this));}
this.load_state=new LoadState();$('way_import').down('.resize').observe('click',this.enable_map_resize.bind(this));$('way_import').down('.static').observe('click',this.get_static_image_url.bind(this));},convert_result:function(action,json){this.load_state.stop();if('id' in json){$('process_result').show().down('td').update(Builder.node('span',[new Element('span').update(I18N.url_to_share+': '),new Element('a',{'href':window.location.href+'/'+json.id,'target':'_blank'}).update(window.location.href+'/'+json.id)]));if(action==='convert'){window.location=window.location.href+'/'+json.id+'/'+$('way_import_output_format').getValue();}}else{alert(I18N.error);}},convert:function(action){this.load_state.start();var routes=[];var tracks=[];var route_quantity=Utils.get_radio_value(document.forms.way_import.route_quantity);var track_quantity=Utils.get_radio_value(document.forms.way_import.track_quantity);if(route_quantity==1&&$('import_routes').options.selectedIndex>0){if(this.route_overlay.getVertexCount()>1){routes.push(this.current_route_data());}}else if(route_quantity=='all'){routes=this.routes;if($('import_routes').options.selectedIndex>0){routes[$('import_routes').getValue()]=this.current_route_data();}}
if(track_quantity==1&&$('import_tracks').options.selectedIndex>0){if(this.track_overlay.getVertexCount()>1){tracks.push(this.current_track_data());}}else if(track_quantity=='all'){tracks=this.tracks.map(function(track){return{'name':track.name||'','line':track.segments.inject([],function(arr,segment){arr=arr.concat(segment.points.collect(function(i){return[i.lat,i.lon];}));return arr;})}}.bind(this));if($('import_tracks').options.selectedIndex>0){tracks[$('import_tracks').getValue()]=this.current_track_data();}}
if(tracks.size()>0||routes.size()>0){document.body.ui.fetch('/gps/babel/store',this.convert_result.bind(this,action),new Hash({'action':action,'data':new Hash({'tracks':tracks,'routes':routes}).toJSON(),'format':$('way_import_output_format').getValue()}),function(){alert(I18N.error);this.load_state.stop();}.bind(this));}else{alert(I18N.nothing_import);this.load_state.stop();}},current_track_data:function(){return{'name':this.tracks[$('import_tracks').getValue()].name||'','line':$R(0,this.track_overlay.getVertexCount()-1).collect(function(index){var pos=this.getVertex(index);return[pos.lat(),pos.lng()];}.bind(this.track_overlay))}},current_route_data:function(){return{'name':this.routes[$('import_routes').getValue()].name,'points':$R(0,this.route_overlay.getVertexCount()-1).map(function(index){var pos=this.route_overlay.getVertex(index);return{'name':this.routes[$('import_routes').getValue()].points[index].name||'','lat':pos.lat(),'lon':pos.lng()}}.bind(this))};},clear_list:function(what){this.remove_line_from_map(what);$('import_'+what+'s').options.length=1;$('import_'+what+'s').options.selectedIndex=0;this[what+'s']=[];$(what+'s_found').update(0);},clear_saved_results:function(){document.body.ui.fetch('/gps/clear_list',function(json){if('result' in json){$('saved_results').hide();}else{alert(I18N.error);}}.bind(this))},enable_map_resize:function(){$('import_map').addClassName('import_map_resizable');this.map.removeControl(this.overview);new Resizable($('import_map'),{minWidth:375,minHeight:261,only_rb:true,onEnd:function(){this.checkResize();}.bind(this.map),maxWidth:$('import_map').getWidth()-4});},get_static_image_url:function(){var polylines=['route','track'].map(function(encoder,s){if(s+'_overlay' in this){return encoder.dpEncode($R(0,this[s+'_overlay'].getVertexCount()-1).map(function(s){return this.getVertex(s);}.bind(this[s+'_overlay'])));}
return null;}.bind(this,new PolylineEncoder())).compact();var markers=['route','track'].map(function(s){if(s+'_overlay' in this){return[this[s+'_overlay'].getVertex(0),this[s+'_overlay'].getVertex(this[s+'_overlay'].getVertexCount()-1)];}
return null;}.bind(this)).flatten().compact().partition(function(n,i){return 0==i%2;});var size=$('import_map').getDimensions();var center=this.map.getCenter();var map_types={'h':'hybrid','k':'satellite','m':'roadmap','p':'terrain'};var settings=new Hash({'key':this.cnf.api_key,'sensor':'false','size':size.width+'x'+size.height,'zoom':this.map.getZoom(),'center':center.lat()+','+center.lng(),'maptype':map_types[this.map.getCurrentMapType().getUrlArg()],'language':language,'path':polylines.map(function(s){return'enc:'+s.encodedPoints}).join('|'),'markers':[(['size:mid','color:red'].concat(markers[1].map(function(s){return[s.lat(),s.lng()].join(',')}))).join('|'),(['size:mid','color:green'].concat(markers[0].map(function(s){return[s.lat(),s.lng()].join(',')}))).join('|')]});var url=settings.toQueryString();if(('http://maps.google.com/maps/api/staticmap?'+url).length<2048){$('static_image_url').update('...').show();document.body.ui.fetch('/gps/make_static',function(json){if('shorten' in json){$('static_image_url').update('<a href="'+json.shorten+'" target="_blank">'+I18N.click_to_open_static+'</a>: '+json.shorten);}else{alert(I18N.error);}},new Hash({'url':url}));$('way_import').down('.static').update(I18N.refresh_static_url);}else{alert(I18N.too_much_data);}}});