// js/elabel.js

function ELabel(point,html,classname,pixelOffset,percentOpacity,overlap){this.point=point;this.html=html;this.classname=classname||"";this.pixelOffset=pixelOffset||new GSize(0,0);if(percentOpacity){if(percentOpacity<0){percentOpacity=0;}
if(percentOpacity>100){percentOpacity=100;}}
this.percentOpacity=percentOpacity;this.overlap=overlap||false;this.hidden=false;}
ELabel.prototype=new GOverlay();ELabel.prototype.initialize=function(map){var div=document.createElement("div");div.style.position="absolute";div.innerHTML='<div class="'+this.classname+'">'+this.html+'</div>';map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div);this.map_=map;this.div_=div;if(this.percentOpacity){if(typeof(div.style.filter)=='string'){div.style.filter='alpha(opacity:'+this.percentOpacity+')';}
if(typeof(div.style.KHTMLOpacity)=='string'){div.style.KHTMLOpacity=this.percentOpacity/100;}
if(typeof(div.style.MozOpacity)=='string'){div.style.MozOpacity=this.percentOpacity/100;}
if(typeof(div.style.opacity)=='string'){div.style.opacity=this.percentOpacity/100;}}
if(this.overlap){var z=GOverlay.getZIndex(this.point.lat());this.div_.style.zIndex=z;}
if(this.hidden){this.hide();}}
ELabel.prototype.remove=function(){this.div_.parentNode.removeChild(this.div_);}
ELabel.prototype.copy=function(){return new ELabel(this.point,this.html,this.classname,this.pixelOffset,this.percentOpacity,this.overlap);}
ELabel.prototype.redraw=function(force){var p=this.map_.fromLatLngToDivPixel(this.point);var h=parseInt(this.div_.clientHeight);var w=parseInt(this.div_.clientWidth);if(this.pixelOffset.width==0||this.pixelOffset.width>=1){this.div_.style.left=(p.x+this.pixelOffset.width)+"px";}else if(this.pixelOffset.width<0){this.div_.style.left=(p.x+this.pixelOffset.width-w)+"px";}else{var offset=w*this.pixelOffset.width;this.div_.style.left=(p.x+offset-w)+"px";}
if(this.pixelOffset.height>=1){this.div_.style.top=(p.y+this.pixelOffset.height)+"px";}else if(this.pixelOffset.height<=0){this.div_.style.top=(p.y+this.pixelOffset.height-h)+"px";}else{var offset=h*this.pixelOffset.height;this.div_.style.top=(p.y+offset-h)+"px";}}
ELabel.prototype.show=function(){if(this.div_){this.div_.style.display="";this.redraw();}
this.hidden=false;}
ELabel.prototype.hide=function(){if(this.div_){this.div_.style.display="none";}
this.hidden=true;}
ELabel.prototype.isHidden=function(){return this.hidden;}
ELabel.prototype.supportsHide=function(){return true;}
ELabel.prototype.setContents=function(html){this.html=html;this.div_.innerHTML='<div class="'+this.classname+'">'+this.html+'</div>';this.redraw(true);}
ELabel.prototype.setPoint=function(point){this.point=point;if(this.overlap){var z=GOverlay.getZIndex(this.point.lat());this.div_.style.zIndex=z;}
this.redraw(true);}
ELabel.prototype.setOpacity=function(percentOpacity){if(percentOpacity){if(percentOpacity<0){percentOpacity=0;}
if(percentOpacity>100){percentOpacity=100;}}
this.percentOpacity=percentOpacity;if(this.percentOpacity){if(typeof(this.div_.style.filter)=='string'){this.div_.style.filter='alpha(opacity:'+this.percentOpacity+')';}
if(typeof(this.div_.style.KHTMLOpacity)=='string'){this.div_.style.KHTMLOpacity=this.percentOpacity/100;}
if(typeof(this.div_.style.MozOpacity)=='string'){this.div_.style.MozOpacity=this.percentOpacity/100;}
if(typeof(this.div_.style.opacity)=='string'){this.div_.style.opacity=this.percentOpacity/100;}}}
ELabel.prototype.getPoint=function(){return this.point;}
ELabel.prototype.U=function(){return this.point;}
ELabel.prototype.V=function(){return this.point;}
ELabel.prototype.W=function(){return this.point;}
ELabel.prototype.X=function(){return this.point;}
ELabel.prototype.Y=function(){return this.point;}
ELabel.prototype.Z=function(){return this.point;}
// js/globals.js

Ext.BLANK_IMAGE_URL='ext/resources/images/default/s.gif';Ext.namespace('CivilWar');var DefaultLat=54.5;var DefaultLng=-3;var DefaultZoom=6;var MinLat=48.0;var MaxLat=59.0;var MinLng=-11.250;var MaxLng=5.625;var MainMap;var MonthSelector;var YearSelector;var TaskBar;var SearchBox;function current_year_month()
{var year;var month=parseInt(MonthSelector.getActiveItem().id.substring(6),10);if(YearSelector.getActiveItem().text==='1642-1651'){year=9999;}else{year=parseInt(YearSelector.getActiveItem().text,10);}
return{year:year,month:month};}
// js/detail_map_control.js

function DetailControl(stages)
{this.stages=stages;this.overlays=[];this.labels=[];this.points=[];this.titles=[];}
DetailControl.prototype=new GControl(true,false);DetailControl.prototype.stages=0;DetailControl.prototype.current_stage=0;DetailControl.prototype.overlays=null;DetailControl.prototype.labels=null;DetailControl.prototype.points=null;DetailControl.prototype.map=null;DetailControl.prototype.title='';DetailControl.prototype.titles=null;DetailControl.prototype.label_toggle=null;DetailControl.prototype.label_check=null;DetailControl.prototype.has_labels=0;DetailControl.prototype.initialize=function(map)
{var that=this;this.map=map;var container=document.createElement("div");if(this.stages>1){var mapsize=map.getSize();var titlebar_container=document.createElement("div");container.appendChild(titlebar_container);titlebar_container.style.width=mapsize.width+"px";titlebar_container.style.height="28px";titlebar_container.style.background="#000000 url( images/buttons/taskbuttons-panel-bg.gif)";titlebar_container.style.paddingTop="0";titlebar_container.style.position="relative";var prev_button=document.createElement("div");titlebar_container.appendChild(prev_button);prev_button.className="ux-taskbuttons-scroller-left";prev_button.style.height="28px";Ext.get(prev_button).addClass('ux-taskbuttons-scroller-left-disabled');GEvent.addDomListener(prev_button,"click",function(){if(that.current_stage>0){that.current_stage--;that.display();}
if(that.current_stage===0){Ext.get(prev_button).addClass('ux-taskbuttons-scroller-left-disabled');}else{Ext.get(prev_button).removeClass('ux-taskbuttons-scroller-left-disabled');}
Ext.get(next_button).removeClass('ux-taskbuttons-scroller-right-disabled');});var next_button=document.createElement("div");titlebar_container.appendChild(next_button);next_button.className="ux-taskbuttons-scroller-right";next_button.style.height="28px";GEvent.addDomListener(next_button,"click",function(){if(that.current_stage<that.stages-1){that.current_stage++;that.display();}
Ext.get(prev_button).removeClass('ux-taskbuttons-scroller-left-disabled');if(that.current_stage===(that.stages-1)){Ext.get(next_button).addClass('ux-taskbuttons-scroller-right-disabled');}else{Ext.get(next_button).removeClass('ux-taskbuttons-scroller-right-disabled');}});var title=document.createElement("div");titlebar_container.appendChild(title);title.style.position="absolute";title.style.width=(mapsize.width-36)+"px";title.style.height="28px";title.style.left="32px";title.style.top="5px";title.style.color="#fff";title.style.font="bold 10px Verdana, Arial, Helvetica";title.innerHTML="";this.title=title;}
var label_toggle=document.createElement("div");container.appendChild(label_toggle);label_toggle.style.position="absolute";label_toggle.style.right="18px";label_toggle.style.top="30px";label_toggle.style.color="#000";label_toggle.style.backgroundColor="#ffffff";label_toggle.style.font="normal 10px Verdana, Arial, Helvetica";label_toggle.style.border="1px solid black";label_toggle.style.padding="1px";label_toggle.style.cursor="pointer";var label_check=document.createElement("input");label_check.type="checkbox";label_check.defaultChecked=true;label_toggle.appendChild(label_check);this.label_check=label_check;this.label_toggle=label_toggle;label_toggle.appendChild(document.createTextNode("Labels"));GEvent.addDomListener(label_toggle,"click",function()
{that.label_check.checked=!that.label_check.checked;that.display();});GEvent.addDomListener(label_check,"click",function()
{that.label_check.checked=!that.label_check.checked;that.display();});map.getContainer().appendChild(container);return(container);};DetailControl.prototype.getDefaultPosition=function()
{return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(0,0));};DetailControl.prototype.display=function()
{if(this.overlays[this.current_stage]===undefined||this.labels[this.current_stage]===undefined||this.points[this.current_stage]===undefined){return;}
if(this.has_labels){Ext.get(this.label_toggle).show();}else{Ext.get(this.label_toggle).hide();}
var i,j;for(i=0;i<this.overlays.length;i++){if(this.overlays[i]){for(j=0;j<this.overlays[i].length;j++){if(this.overlays[i][j]){this.overlays[i][j].hide();}}}}
for(i=0;i<this.labels.length;i++){if(this.labels[i]){for(j=0;j<this.labels[i].length;j++){if(this.labels[i][j]){this.labels[i][j].hide();}}}}
this.title.innerHTML=this.titles[this.current_stage];var bounds=new GLatLngBounds();if(this.points[this.current_stage]){for(i=0;i<this.points[this.current_stage].length;i++){if(this.points[this.current_stage][i]){bounds.extend(this.points[this.current_stage][i]);}}}
this.map.setZoom(this.map.getBoundsZoomLevel(bounds));this.map.panTo(bounds.getCenter());if(this.overlays[this.current_stage]){for(i=0;i<this.overlays[this.current_stage].length;i++){if(this.overlays[this.current_stage][i]){this.overlays[this.current_stage][i].show();}}}
if(this.label_check.checked){if(this.labels[this.current_stage]){for(i=0;i<this.labels[this.current_stage].length;i++){if(this.labels[this.current_stage][i]){this.labels[this.current_stage][i].show();}}}}};DetailControl.prototype.addStage=function(stage,title)
{this.overlays[stage]=[];this.labels[stage]=[];this.points[stage]=[];this.titles[stage]=title;};DetailControl.prototype.addOverlay=function(stages,overlay)
{for(var i=0;i<stages.length;i++){var stage=parseInt(stages[i],10);if(this.overlays[stage]===undefined){return;}
this.overlays[stage].push(overlay);this.map.addOverlay(overlay);overlay.hide();}};DetailControl.prototype.addLabel=function(stages,label)
{for(var i=0;i<stages.length;i++){var stage=parseInt(stages[i],10);if(this.labels[stage]===undefined){return;}
this.labels[stage].push(label);this.map.addOverlay(label);label.hide();this.has_labels=1;}};DetailControl.prototype.addPoint=function(stages,latlng)
{for(var i=0;i<stages.length;i++){var stage=parseInt(stages[i],10);if(this.points[stage]===undefined){return;}
this.points[stage].push(latlng);}};
// js/detail_window.js

var Copyright="Copyright &#169; 2007-2010 Richard Porter";var degreesPerRadian=180.0/Math.PI;function bearing(from,to)
{var lat1=from.latRadians();var lon1=from.lngRadians();var lat2=to.latRadians();var lon2=to.lngRadians();var angle=-Math.atan2(Math.sin(lon1-lon2)*Math.cos(lat2),Math.cos(lat1)*Math.sin(lat2)-
Math.sin(lat1)*Math.cos(lat2)*Math.cos(lon1-lon2));if(angle<0.0){angle+=Math.PI*2.0;}
angle=angle*degreesPerRadian;angle=angle.toFixed(1);return angle;}
function arrow_head(points,colour,tooltip)
{var p1=points[points.length-1];var p2=points[points.length-2];var dir=bearing(p2,p1);dir=Math.round(dir/3)*3;while(dir>=120){dir-=120;}
var arrowIcon=new GIcon();arrowIcon.iconSize=new GSize(24,24);arrowIcon.shadowSize=new GSize(1,1);arrowIcon.iconAnchor=new GPoint(12,12);arrowIcon.infoWindowAnchor=new GPoint(0,0);arrowIcon.image="http://www.ecgtheow.com/~dick/arrow/"+encodeURIComponent(colour.toLowerCase())+"/dir_"+dir+".png";return new GMarker(p1,{icon:arrowIcon,title:tooltip});}
function parse_stages(stage_str)
{return stage_str.split(",");}
function create_detail_map(div,xml)
{var detail_map=new GMap2(document.getElementById(div),{mapTypes:[detailmaptype]});detail_map.disableDragging();detail_map.disableInfoWindow();detail_map.addControl(new GScaleControl());detail_map.setCenter(new GLatLng(0.0,0.0),0);var stage_info=xml.documentElement.getElementsByTagName("stage");var xmllines=xml.documentElement.getElementsByTagName("line");var i;var j;var detail_control=new DetailControl(stage_info.length);detail_map.addControl(detail_control);for(i=0;i<stage_info.length;i++){var stage=parseInt(stage_info[i].getAttribute("stage"),10);var title=stage_info[i].getAttribute("title");detail_control.addStage(stage,title);}
for(i=0;i<xmllines.length;i++){var colour=xmllines[i].getAttribute("colour");var width=5;var points=xmllines[i].getElementsByTagName("point");var pts=[];var noarrow=false;var stages=parse_stages(xmllines[i].getAttribute("stages"));var bounds=parse_stages(xmllines[i].getAttribute("bounds"));for(j=0;j<points.length;j++){pts[j]=new GLatLng(parseFloat(points[j].getAttribute("lat")),parseFloat(points[j].getAttribute("lng")));detail_control.addPoint(stages,pts[j]);detail_control.addPoint(bounds,pts[j]);if(points[j].getAttribute("noarrow")!==null){noarrow=true;}
if(points[j].getAttribute("text")!==null){var xoff=parseFloat(points[j].getAttribute("xoff"));var yoff=parseFloat(points[j].getAttribute("yoff"));var labelwidth=parseInt(points[j].getAttribute("labelwidth"),10);var label=new ELabel(pts[j],'<div style=\"width: '+labelwidth+'px;\">'+points[j].getAttribute("text")+'</div>',"detail_label",new GSize(xoff,yoff));detail_control.addOverlay(stages,label);}}
if(pts.length>1){detail_control.addOverlay(stages,new GPolyline(pts,colour,width,0.9));if(noarrow===false){detail_control.addOverlay(stages,arrow_head(pts,colour));}}}
var xmlpolys=xml.documentElement.getElementsByTagName("polygon");for(i=0;i<xmlpolys.length;i++){var polycolour=xmlpolys[i].getAttribute("colour");var polytype=xmlpolys[i].getAttribute("type");var polywidth=2;var polypts=[];var corner1=new GLatLng(parseFloat(xmlpolys[i].getAttribute("corner1_lat")),parseFloat(xmlpolys[i].getAttribute("corner1_lng")));var corner2=new GLatLng(parseFloat(xmlpolys[i].getAttribute("corner2_lat")),parseFloat(xmlpolys[i].getAttribute("corner2_lng")));var corner3=new GLatLng(parseFloat(xmlpolys[i].getAttribute("corner3_lat")),parseFloat(xmlpolys[i].getAttribute("corner3_lng")));var corner4=new GLatLng(parseFloat(xmlpolys[i].getAttribute("corner4_lat")),parseFloat(xmlpolys[i].getAttribute("corner4_lng")));var polystages=parse_stages(xmlpolys[i].getAttribute("stages"));var polybounds=parse_stages(xmlpolys[i].getAttribute("bounds"));polypts.push(corner1);polypts.push(corner2);polypts.push(corner3);polypts.push(corner4);polypts.push(corner1);var polyalpha;switch(polytype){case"Foot":polyalpha=1;break;case"Cavalry":polyalpha=0.2;polypts.push(corner3);break;case"Dragoon":polyalpha=0;polypts.push(corner3);polypts.push(corner2);polypts.push(corner4);break;default:polyalpha=0;}
detail_control.addPoint(polystages,corner1);detail_control.addPoint(polystages,corner2);detail_control.addPoint(polystages,corner3);detail_control.addPoint(polystages,corner4);detail_control.addPoint(polybounds,corner1);detail_control.addPoint(polybounds,corner2);detail_control.addPoint(polybounds,corner3);detail_control.addPoint(polybounds,corner4);if(xmlpolys[i].getAttribute("text")!==null){var polyxoff=parseFloat(xmlpolys[i].getAttribute("xoff"));var polyyoff=parseFloat(xmlpolys[i].getAttribute("yoff"));var polylabelwidth=parseInt(xmlpolys[i].getAttribute("labelwidth"),10);var labelcorner=parseInt(xmlpolys[i].getAttribute("labelcorner"),10);var labelstyle;if(polylabelwidth!==60){labelstyle='style=\"width: '+polylabelwidth+'px;\"';}else{labelstyle="";}
var corner;switch(labelcorner){case 2:corner=corner2;break;case 3:corner=corner3;break;case 4:corner=corner4;break;default:corner=corner1;break;}
var polylabel=new ELabel(corner,'<div '+labelstyle+'>'+xmlpolys[i].getAttribute("text")+'</div>',"detail_label",new GSize(polyxoff,polyyoff));detail_control.addLabel(polystages,polylabel);}
detail_control.addOverlay(polystages,new GPolygon(polypts,polycolour,polywidth,0.9,polycolour,polyalpha,{clickable:false}));}
detail_control.display();}
function format_references(reference_book,reference_web)
{var winHTML='';if(reference_book.length>0||reference_web.length>0){winHTML+='<div class="reference_title">References:</div><div class="reference_content">';var i;for(i=0;i<reference_book.length;i++){winHTML+='<span class="reference_content_title">'+reference_book[i].getAttribute("title")+'</span>';if(reference_book[i].getAttribute("author")!==''){winHTML+=', '+reference_book[i].getAttribute("author");}
if(parseInt(reference_book[i].getAttribute("year"),10)!==0){winHTML+=', '+reference_book[i].getAttribute("year");}
winHTML+='<br>';}
for(i=0;i<reference_web.length;i++){winHTML+='<a target="_blank"  href="'+reference_web[i].getAttribute("url")+'">'+reference_web[i].getAttribute("title")+'</a><br>';}
winHTML+='</div>';}
return(winHTML);}
function format_detail_window_contents(xml,eventid,hasdetail,map_link,mailto,show_title)
{var xmlevents=xml.documentElement.getElementsByTagName("event");var presence=xml.documentElement.getElementsByTagName("person");var reference_book=xml.documentElement.getElementsByTagName("book");var reference_web=xml.documentElement.getElementsByTagName("site");var winHTML='<div class="event_content">';if(show_title){var title_text="<div class=\"event_title\">"+xmlevents[0].getAttribute("name")+" ("+xmlevents[0].getAttribute("dates")+")</div>";winHTML+=title_text;}
winHTML+=xmlevents[0].getAttribute("notes");winHTML+="<div style=\"clear: both\">&nbsp;</div>";if(hasdetail){if(Ext.isIE&&map_link){winHTML+="<div style=\"\"><p>[A working browser would display an interactive map here.  IE users can see it by following the 'format for printing' link below.]</p></div>";}else{winHTML+="<div style=\"margin-top: 10px; margin-left: 10px; height: 500px; width: 660px;\" id=\"event_map_"+eventid+"\"></div>";}}
if(presence.length>0){winHTML+="<div id=\"presence\">";var pres_royalist='<div class="presence_title">Royalists involved:</div><div class="presence_content">';var pres_parliament='<div class="presence_title">Parliamentarians involved:</div><div class="presence_content">';var pres_neutral='<div class="presence_title">Those involved but neutral:</div><div class="presence_content">';var pres_unknown='<div class="presence_title">Those involved with unknown affiliation:</div><div class="presence_content">';var pres_lords='<div class="presence_title">Those involved as members of the House of Lords:</div><div class="presence_content">';var pres_commons='<div class="presence_title">Those involved as members of the House of Commons:</div><div class="presence_content">';var i;var had_royalist=0;var had_parl=0;var had_neut=0;var had_unknown=0;var had_lords=0;var had_commons=0;for(i=0;i<presence.length;i++){if(presence[i].getAttribute("affiliation")==='Royalist'){if(had_royalist){pres_royalist+='; ';}
if(map_link){pres_royalist+='<a href="javascript:CivilWar.UI.open_window_by_personid('+presence[i].getAttribute("personid")+',false,null)">'+presence[i].getAttribute("name")+'</a>';}else{pres_royalist+=presence[i].getAttribute("name");}
had_royalist=1;}else if(presence[i].getAttribute("affiliation")==='Parliamentarian'){if(had_parl){pres_parliament+='; ';}
if(map_link){pres_parliament+='<a href="javascript:CivilWar.UI.open_window_by_personid('+presence[i].getAttribute("personid")+',false,null)">'+presence[i].getAttribute("name")+'</a>';}else{pres_parliament+=presence[i].getAttribute("name");}
had_parl=1;}else if(presence[i].getAttribute("affiliation")==='Neutral'){if(had_neut){pres_neutral+='; ';}
if(map_link){pres_neutral+='<a href="javascript:CivilWar.UI.open_window_by_personid('+presence[i].getAttribute("personid")+',false,null)">'+presence[i].getAttribute("name")+'</a>';}else{pres_neutral+=presence[i].getAttribute("name");}
had_neut=1;}else if(presence[i].getAttribute("affiliation")==='Unknown'){if(had_unknown){pres_unknown+='; ';}
if(map_link){pres_unknown+='<a href="javascript:CivilWar.UI.open_window_by_personid('+presence[i].getAttribute("personid")+',false,null)">'+presence[i].getAttribute("name")+'</a>';}else{pres_unknown+=presence[i].getAttribute("name");}
had_unknown=1;}else if(presence[i].getAttribute("affiliation")==='House of Lords'){if(had_lords){pres_lords+='; ';}
if(map_link){pres_lords+='<a href="javascript:CivilWar.UI.open_window_by_personid('+presence[i].getAttribute("personid")+',false,null)">'+presence[i].getAttribute("name")+'</a>';}else{pres_lords+=presence[i].getAttribute("name");}
had_lords=1;}else if(presence[i].getAttribute("affiliation")==='House of Commons'){if(had_commons){pres_commons+='; ';}
if(map_link){pres_commons+='<a href="javascript:CivilWar.UI.open_window_by_personid('+presence[i].getAttribute("personid")+',false,null)">'+presence[i].getAttribute("name")+'</a>';}else{pres_commons+=presence[i].getAttribute("name");}
had_commons=1;}}
pres_royalist+='</div>';pres_parliament+='</div>';pres_neutral+='</div>';pres_unknown+='</div>';pres_lords+='</div>';pres_commons+='</div>';if(had_royalist){winHTML+=pres_royalist;}
if(had_parl){winHTML+=pres_parliament;}
if(had_lords){winHTML+=pres_lords;}
if(had_commons){winHTML+=pres_commons;}
if(had_neut){winHTML+=pres_neutral;}
if(had_unknown){winHTML+=pres_unknown;}
winHTML+="</div>";}
winHTML+=format_references(reference_book,reference_web);winHTML+='</div>';if(map_link){winHTML+='<div class="event_window_link"><p style="float: left;"><a href="javascript:MainMap.show_event('+eventid+')">Show on map</a></p><p style="float: right;"><a target="_blank" href="single.html?'+eventid+'">Format for printing</a></p><p style="clear: both"></p></div>';}
if(mailto){winHTML+="<div><p class=\"copyright_text\"><a href=\"mailto:dick.porter+ecw@gmail.com?subject=Civil War: "+xmlevents[0].getAttribute("name")+"\">"+Copyright+"</a></p></div>";}else{winHTML+="<div><p class=\"copyright_text\">"+Copyright+"</p></div>";}
return(winHTML);}
function format_person_window_contents(xml,bio,mailto,event_links)
{var presence=xml.documentElement.getElementsByTagName("event");var movement=xml.documentElement.getElementsByTagName("arrive");var reference_book=xml.documentElement.getElementsByTagName("book");var reference_web=xml.documentElement.getElementsByTagName("site");var textlength=bio[0].getAttribute("biography").length;var winHTML='<div class="person_title"><p>'+bio[0].getAttribute("name");var i;if(bio[0].getAttribute("dates").length>0){winHTML+='<span class="person_dates">, '+bio[0].getAttribute("dates")+'</span>';}
winHTML+='</p></div>';if(textlength){winHTML+='<div class="person_bio"><p>'+bio[0].getAttribute("biography")+'</p></div>';}
winHTML+="<div style=\"clear: both\">&nbsp;</div>";if(presence.length>0){winHTML+='<div class="person_detail_title"><p>Involved with:</p></div>';winHTML+='<div class="person_presence">';winHTML+='<table>';for(i=0;i<presence.length;i++){var datefrom=presence[i].getAttribute("datefrom");var dateto=presence[i].getAttribute("dateto");winHTML+='<tr>';if(datefrom===dateto){winHTML+='<td colspan="2" style="white-space: nowrap;">'+datefrom+'</td>';}else{winHTML+='<td style="white-space: nowrap; border-right-style: none;">'+datefrom+'</td>';winHTML+='<td style="white-space: nowrap; border-left-style: none;">- '+dateto+'</td>';}
if(event_links){winHTML+='<td><a href="javascript:CivilWar.UI.open_window_by_eventid('+presence[i].getAttribute("eventid")+',false,null)">'+presence[i].getAttribute("eventname")+'</a></td>';}else{winHTML+='<td>'+presence[i].getAttribute("eventname")+'</td>';}
winHTML+='<td>'+presence[i].getAttribute("affiliation")+'</td>';winHTML+='</tr>';}
winHTML+='</table>';winHTML+='</div>';}
if(movement.length>0){winHTML+='<div class="person_detail_title"><p>Itinerary:</p></div>';winHTML+='<div class="person_movement">';winHTML+='<table>';for(i=0;i<movement.length;i++){var arrivaldate=movement[i].getAttribute("arrivaldate");var location=movement[i].getAttribute("location");winHTML+='<tr>';winHTML+='<td style="white-space: nowrap;">'+arrivaldate+'</td>';winHTML+='<td>'+location+'</td>';winHTML+='</tr>';}
winHTML+='</table>';winHTML+='</div>';}
winHTML+=format_references(reference_book,reference_web);if(mailto){winHTML+="<div><p class=\"copyright_text\"><a href=\"mailto:dick.porter+ecw@gmail.com?subject=Civil War: "+bio[0].getAttribute("name")+"\">"+Copyright+"</a></p></div>";}else{winHTML+="<div><p class=\"copyright_text\">"+Copyright+"</p></div>";}
return(winHTML);}
// js/taskbar.js

CivilWar.TaskBar=function()
{var activeWindow;this.init();};Ext.extend(CivilWar.TaskBar,Ext.util.Observable,{init:function(){this.tbPanel=new CivilWar.TaskButtonsPanel({el:'ux-taskbuttons-panel',id:'TaskBarButtons',region:'center'});var container=new CivilWar.TaskBarContainer({el:'ux-taskbar',layout:'border',items:[this.tbPanel]});return this;},addTaskButton:function(win){var btn=this.tbPanel.addButton(win,'ux-taskbuttons-panel');var tb=this;win.taskButton=btn;win.animateTarget=win.taskButton.el;win.on({activate:function(win){win.getEl().syncFx().setOpacity(1,true).frame();if(tb.activeWindow&&tb.activeWindow!==win){tb.activeWindow.setActive(false);}
tb.setActiveButton(win.taskButton);tb.activeWindow=win;Ext.fly(win.taskButton.el).addClass('active-win');win.minimized=false;},beforeshow:function(win){win.getEl().syncFx().setOpacity(1,true).frame();if(tb.activeWindow&&tb.activeWindow!==win){tb.activeWindow.setActive(false);}
tb.setActiveButton(win.taskButton);tb.activeWindow=win;Ext.fly(win.taskButton.el).addClass('active-win');win.minimized=false;},deactivate:function(win){win.getEl().setOpacity(0.25,true);if(win===tb.activeWindow){tb.activeWindow=null;Ext.fly(win.taskButton.el).removeClass('active-win');}},minimize:function(win){win.minimized=true;win.hide();},close:function(win){tb.removeTaskButton(win.taskButton);}});return btn;},removeTaskButton:function(btn){this.tbPanel.removeButton(btn);},setActiveButton:function(btn){this.tbPanel.setActiveButton(btn);},update_title:function(btn,title){this.tbPanel.update_title(btn,title);}});CivilWar.TaskBarContainer=Ext.extend(Ext.Container,{initComponent:function(){CivilWar.TaskBarContainer.superclass.initComponent.call(this);this.el=Ext.get(this.el)||Ext.getBody();this.el.setHeight=Ext.emptyFn;this.el.setWidth=Ext.emptyFn;this.el.setSize=Ext.emptyFn;this.el.setStyle({overflow:'hidden',margin:'0',border:'0 none'});this.el.dom.scroll='no';this.allowDomMove=false;this.autoWidth=true;this.autoHeight=true;Ext.EventManager.onWindowResize(this.fireResize,this);this.renderTo=this.el;},fireResize:function(w,h){this.fireEvent('resize',this,w,h,w,h);}});CivilWar.TaskButtonsPanel=Ext.extend(Ext.BoxComponent,{activeButton:null,enableScroll:true,scrollIncrement:0,scrollRepeatInterval:400,scrollDuration:0.35,animScroll:true,resizeButtons:true,buttonWidth:168,minButtonWidth:118,buttonMargin:2,buttonWidthSet:false,initComponent:function(){CivilWar.TaskButtonsPanel.superclass.initComponent.call(this);this.on('resize',this.delegateUpdates);this.items=[];this.stripWrap=Ext.get(this.el).createChild({cls:'ux-taskbuttons-strip-wrap',cn:{tag:'ul',cls:'ux-taskbuttons-strip'}});this.stripSpacer=Ext.get(this.el).createChild({cls:'ux-taskbuttons-strip-spacer'});this.strip=new Ext.Element(this.stripWrap.dom.firstChild);this.edge=this.strip.createChild({tag:'li',cls:'ux-taskbuttons-edge'});this.strip.createChild({cls:'x-clear'});},addButton:function(win){var li=this.strip.createChild({tag:'li'},this.edge);var btn=new CivilWar.TaskBar.TaskButton(win,li);this.items.push(btn);if(!this.buttonWidthSet){this.lastButtonWidth=btn.container.getWidth();}
this.setActiveButton(btn);return btn;},removeButton:function(btn){var li=document.getElementById(btn.container.id);btn.destroy();li.parentNode.removeChild(li);var s=[];for(var i=0,len=this.items.length;i<len;i++){if(this.items[i]!==btn){s.push(this.items[i]);}}
this.items=s;this.delegateUpdates();},setActiveButton:function(btn){this.activeButton=btn;this.delegateUpdates();},update_title:function(btn,title){btn.setText(title);btn.setTooltip(title);this.delegateUpdates();},delegateUpdates:function(){if(this.resizeButtons&&this.rendered){this.autoSize();}
if(this.enableScroll&&this.rendered){this.autoScroll();}},autoSize:function(){var count=this.items.length;var ow=this.el.dom.offsetWidth;var aw=this.el.dom.clientWidth;if(!this.resizeButtons||count<1||!aw){return;}
var each=Math.max(Math.min(Math.floor((aw-4)/count)-this.buttonMargin,this.buttonWidth),this.minButtonWidth);var btns=this.stripWrap.dom.getElementsByTagName('button');this.lastButtonWidth=Ext.get(btns[0].id).findParent('li').offsetWidth;for(var i=0,len=btns.length;i<len;i++){var btn=btns[i];var tw=Ext.get(btns[i].id).findParent('li').offsetWidth;var iw=btn.offsetWidth;btn.style.width=(each-(tw-iw))+'px';}},autoScroll:function(){var count=this.items.length;var ow=this.el.dom.offsetWidth;var tw=this.el.dom.clientWidth;var wrap=this.stripWrap;var cw=wrap.dom.offsetWidth;var pos=this.getScrollPos();var l=this.edge.getOffsetsTo(this.stripWrap)[0]+pos;if(!this.enableScroll||count<1||cw<20){return;}
wrap.setWidth(tw);if(l<=tw){wrap.dom.scrollLeft=0;if(this.scrolling){this.scrolling=false;this.el.removeClass('x-taskbuttons-scrolling');this.scrollLeft.hide();this.scrollRight.hide();}}else{if(!this.scrolling){this.el.addClass('x-taskbuttons-scrolling');}
tw-=wrap.getMargins('lr');wrap.setWidth(tw>20?tw:20);if(!this.scrolling){if(!this.scrollLeft){this.createScrollers();}else{this.scrollLeft.show();this.scrollRight.show();}}
this.scrolling=true;if(pos>(l-tw)){wrap.dom.scrollLeft=l-tw;}else{this.scrollToButton(this.activeButton,true);}
this.updateScrollButtons();}},createScrollers:function(){var h=this.el.dom.offsetHeight;var sl=this.el.insertFirst({cls:'ux-taskbuttons-scroller-left'});sl.setHeight(h);sl.addClassOnOver('ux-taskbuttons-scroller-left-over');this.leftRepeater=new Ext.util.ClickRepeater(sl,{interval:this.scrollRepeatInterval,handler:this.onScrollLeft,scope:this});this.scrollLeft=sl;var sr=this.el.insertFirst({cls:'ux-taskbuttons-scroller-right'});sr.setHeight(h);sr.addClassOnOver('ux-taskbuttons-scroller-right-over');this.rightRepeater=new Ext.util.ClickRepeater(sr,{interval:this.scrollRepeatInterval,handler:this.onScrollRight,scope:this});this.scrollRight=sr;},getScrollWidth:function(){return this.edge.getOffsetsTo(this.stripWrap)[0]+this.getScrollPos();},getScrollPos:function(){return parseInt(this.stripWrap.dom.scrollLeft,10)||0;},getScrollArea:function(){return parseInt(this.stripWrap.dom.clientWidth,10)||0;},getScrollAnim:function(){return{duration:this.scrollDuration,callback:this.updateScrollButtons,scope:this};},getScrollIncrement:function(){return(this.scrollIncrement||this.lastButtonWidth+2);},scrollToButton:function(item,animate){item=item.el.dom.parentNode;if(!item){return;}
var el=item;var pos=this.getScrollPos();var area=this.getScrollArea();var left=Ext.fly(el).getOffsetsTo(this.stripWrap)[0]+pos;var right=left+el.offsetWidth;if(left<pos){this.scrollTo(left,animate);}else if(right>(pos+area)){this.scrollTo(right-area,animate);}},scrollTo:function(pos,animate){this.stripWrap.scrollTo('left',pos,animate?this.getScrollAnim():false);if(!animate){this.updateScrollButtons();}},onScrollRight:function(){var sw=this.getScrollWidth()-this.getScrollArea();var pos=this.getScrollPos();var s=Math.min(sw,pos+this.getScrollIncrement());if(s!==pos){this.scrollTo(s,this.animScroll);}},onScrollLeft:function(){var pos=this.getScrollPos();var s=Math.max(0,pos-this.getScrollIncrement());if(s!==pos){this.scrollTo(s,this.animScroll);}},updateScrollButtons:function(){var pos=this.getScrollPos();this.scrollLeft[pos===0?'addClass':'removeClass']('ux-taskbuttons-scroller-left-disabled');this.scrollRight[pos>=(this.getScrollWidth()-this.getScrollArea())?'addClass':'removeClass']('ux-taskbuttons-scroller-right-disabled');}});CivilWar.TaskBar.TaskButton=function(win,el){this.win=win;CivilWar.TaskBar.TaskButton.superclass.constructor.call(this,{iconCls:win.iconCls,text:win.title,renderTo:el,handler:function(){if(win.minimized||win.hidden){win.show();}else if(win===win.manager.getActive()){win.minimize();}else{win.toFront();}},clickEvent:'mousedown'});};Ext.extend(CivilWar.TaskBar.TaskButton,Ext.Button,{onRender:function(){CivilWar.TaskBar.TaskButton.superclass.onRender.apply(this,arguments);this.cmenu=new Ext.menu.Menu({items:[{text:'Restore',handler:function(){if(!this.win.isVisible()){this.win.show();}else{this.win.restore();}},scope:this},{text:'Minimize',handler:this.win.minimize,scope:this.win},{text:'Maximize',handler:this.win.maximize,scope:this.win},'-',{text:'Close',handler:this.closeWin.createDelegate(this,this.win,true),scope:this.win}]});this.cmenu.on('beforeshow',function(){var items=this.cmenu.items.items;var w=this.win;items[0].setDisabled(w.maximized!==true&&w.hidden!==true);items[1].setDisabled(w.minimized===true);items[2].setDisabled(w.maximized===true||w.hidden===true);},this);this.el.on('contextmenu',function(e){e.stopEvent();if(!this.cmenu.el){this.cmenu.render();}
var xy=e.getXY();xy[1]-=this.cmenu.el.getHeight();this.cmenu.showAt(xy);},this);},closeWin:function(cMenu,e,win){if(!win.isVisible()){win.show();}else{win.restore();}
win.close();},setTooltip:function(text){var btnEl=this.getEl().child(this.buttonSelector);Ext.QuickTips.register({target:btnEl.id,text:text});}});
// js/map_data.js

function MarkerData(year,eventid,datefrom,dateto,html,side,tooltip,type,lat,lng)
{this.year=year;this.eventid=eventid;var fromsplit=datefrom.split('-');var tosplit=dateto.split('-');this.datefrom=new Date(fromsplit[0],fromsplit[1]-1,fromsplit[2],0,0);this.dateto=new Date(tosplit[0],tosplit[1]-1,tosplit[2],23,59,59,999);this.html=html;this.side=side;this.tooltip=tooltip;this.type=type;this.lat=lat;this.lng=lng;}
var tilelayers=[];var currentlayer;var markers=[];var allmarkers=[];var detailmaptype=new GMapType(G_NORMAL_MAP.getTileLayers(),G_NORMAL_MAP.getProjection(),G_NORMAL_MAP.getName(),{maxResolution:17,minResolution:6});var allowed_bounds=new GLatLngBounds(new GLatLng(MinLat,MinLng),new GLatLng(MaxLat,MaxLng));CivilWar.MapPanel=Ext.extend(Ext.Panel,{initComponent:function(){var defConfig={plain:true,defaultZoom:DefaultZoom,defaultLat:DefaultLat,defaultLng:DefaultLng};Ext.applyIf(this,defConfig);CivilWar.MapPanel.superclass.initComponent.call(this);},afterRender:function(){var wh=this.ownerCt.getSize();Ext.applyIf(this,wh);CivilWar.MapPanel.superclass.afterRender.call(this);this.battleIcon=new GIcon(G_DEFAULT_ICON,"images/map/bluemarker.png");this.skirmishIcon=new GIcon(G_DEFAULT_ICON,"images/map/greenmarker.png");this.otherIcon=new GIcon(G_DEFAULT_ICON,"images/map/redmarker.png");this.highlightIcons=[];var eventHighlightIcon=new GIcon();var trackHighlightIcon=new GIcon();eventHighlightIcon.image="images/map/marker_highlight.png";eventHighlightIcon.iconSize=new GSize(60,75);eventHighlightIcon.shadowSize=new GSize(1,1);eventHighlightIcon.iconAnchor=new GPoint(29,60);eventHighlightIcon.infoWindowAnchor=new GPoint(0,0);eventHighlightIcon.imageMap=[29,26,26,27,24,28,22,30,20,34,20,38,21,40,22,42,25,45,27,49,28,52,29,56,29,60,31,60,31,56,32,52,33,50,34,47,36,44,38,42,40,38,40,34,38,30,36,28,35,27,33,26];trackHighlightIcon.image="images/map/track_icon_highlight.png";trackHighlightIcon.iconSize=new GSize(48,48);trackHighlightIcon.shadowSize=new GSize(1,1);trackHighlightIcon.iconAnchor=new GPoint(24,24);trackHighlightIcon.infoWindowAnchor=new GPoint(0,0);trackHighlightIcon.imageMap=[18,18,18,30,30,30,30,18];this.highlightIcons['bluemarker.png']=eventHighlightIcon;this.highlightIcons['greenmarker.png']=eventHighlightIcon;this.highlightIcons['redmarker.png']=eventHighlightIcon;this.highlightIcons['track_icon.png']=trackHighlightIcon;var i;for(i=0;i<=120;i+=3){var dirIcon=new GIcon();dirIcon.image="images/map/dir_"+i+"_highlight.png";dirIcon.iconSize=new GSize(66,66);dirIcon.shadowSize=new GSize(1,1);dirIcon.iconAnchor=new GPoint(33,33);dirIcon.infoWindowAnchor=new GPoint(0,0);dirIcon.imageMap=[20,20,20,46,46,46,46,20];this.highlightIcons['dir_'+i+'.png']=dirIcon;}
this.map=new GMap2(this.body.dom);var max_lat=allowed_bounds.getNorthEast().lat();var max_lng=allowed_bounds.getNorthEast().lng();var min_lat=allowed_bounds.getSouthWest().lat();var min_lng=allowed_bounds.getSouthWest().lng();var copyright=new GCopyright(1,allowed_bounds,6,Copyright);var copyright_collection=new GCopyrightCollection('Simple Map:');copyright_collection.addCopyright(copyright);var simple_tilelayers=[new GTileLayer(copyright_collection,6,10)];simple_tilelayers[0].getTileUrl=function(tile,zoom){if((zoom<6)||(zoom===6&&(tile.y<18||tile.y>21||tile.x<30||tile.x>32))||(zoom===7&&(tile.y<37||tile.y>43||tile.x<60||tile.x>65))||(zoom===8&&(tile.y<75||tile.y>87||tile.x<120||tile.x>131))||(zoom===9&&(tile.y<151||tile.y>176||tile.x<240||tile.x>263))||(zoom===10&&(tile.y<302||tile.y>354||tile.x<480||tile.x>527))||(zoom>10)){return"http://www.ecgtheow.com/~dick/tile/tile_blank.png";}else{var ts=((tile.x+tile.y)%3)+1;return"http://ts"+ts+".ecgtheow.com/~dick/maptile/tile_"+tile.x+"_"+tile.y+"_"+zoom+".png";}};var simplemaptype=new GMapType(simple_tilelayers,G_NORMAL_MAP.getProjection(),"Simple",{maxResolution:10,minResolution:6});this.map.addMapType(simplemaptype);var mt=this.map.getMapTypes();for(i=0;i<mt.length;i++){mt[i].getMinimumResolution=function(){return 6;};mt[i].getMaximumResolution=function(){return 10;};}
this.map.addControl(new GLargeMapControl());this.map.addControl(new GMapTypeControl());this.map.addControl(new GScaleControl());this.daily=new DailyControl();this.map.addControl(this.daily);this.daily.reset();this.setCentre(this.defaultLat,this.defaultLng,this.defaultZoom);this.map.setMapType(simplemaptype);GEvent.bind(this.map,'load',this,function(){this.onMapReady();});GEvent.addListener(this.map,"click",function(overlay,latlng,overlatlng){SearchBox.collapse();});GEvent.addListener(this.map,"move",function(){if(allowed_bounds.contains(this.getCenter())){return;}
var map_centre=this.getCenter();var map_lat=map_centre.lat();var map_lng=map_centre.lng();if(map_lat<min_lat){map_lat=min_lat;}
if(map_lat>max_lat){map_lat=max_lat;}
if(map_lng<min_lng){map_lng=min_lng;}
if(map_lng>max_lng){map_lng=max_lng;}
this.setCenter(new GLatLng(map_lat,map_lng));});},onMapReady:function(){},onResize:function(w,h){if(typeof this.getMap()==='object'){this.map.checkResize();}
CivilWar.MapPanel.superclass.onResize.call(this,w,h);},setSize:function(width,height,animate){if(typeof this.getMap()==='object'){this.map.checkResize();}
CivilWar.MapPanel.superclass.setSize.call(this,width,height,animate);},getMap:function(){return this.map;},getDaily:function(){return this.daily;},getCentre:function(){return this.getMap().getCenter();},getCentreLatLng:function(){var latlng=this.getCentre();return{lat:latlng.lat(),lng:latlng.lng()};},getZoom:function(){return this.getMap().getZoom();},setCentre:function(lat,lng,zoom){var latlng=new GLatLng(lat,lng);if(allowed_bounds.contains(latlng)){this.getMap().setCenter(latlng,zoom);}},setBounds:function(bounds){var zoom=this.getMap().getBoundsZoomLevel(bounds);this.getMap().setCenter(bounds.getCenter(),zoom);},addOverlay:function(overlay){this.getMap().addOverlay(overlay);},removeOverlay:function(overlay){this.getMap().removeOverlay(overlay);},createMarker:function(year,datefrom,dateto,eventid,tooltip,html,side,type,lat,lng){var md=new MarkerData(year,eventid,datefrom,dateto,html,side,tooltip,type,lat,lng);if(year===9999){allmarkers[eventid]=md;return allmarkers[eventid];}else{if(markers[eventid]){if(markers[eventid].year<year){return markers[eventid];}}
markers[eventid]=md;return markers[eventid];}},createMapMarker:function(point,tooltip,html,type,oldmarker){var marker;if(type==="Highlight"){var old_image=oldmarker.getIcon().image;var old_image_filepart=old_image.substring(old_image.lastIndexOf('/')+1);marker=new GMarker(point,{icon:this.highlightIcons[old_image_filepart],title:tooltip});}else if(type==="Battle"){marker=new GMarker(point,{icon:this.battleIcon,title:tooltip});}else if(type==="Skirmish"||type==="Capture"){marker=new GMarker(point,{icon:this.skirmishIcon,title:tooltip});}else{marker=new GMarker(point,{icon:this.otherIcon,title:tooltip});}
marker.CivilWarEventID=0;marker.CivilWarEventIDRequested=false;if(type!=="Highlight"){GEvent.addListener(marker,"click",function(){marker.openInfoWindowHtml(html);});GEvent.addListener(marker,"visibilitychanged",function(isVisible){if(isVisible){if(marker.CivilWarEventIDRequested){marker.CivilWarEventIDRequested=false;MainMap.show_event(marker.CivilWarEventID);}}else{marker.closeInfoWindow();}});}
this.getMap().addOverlay(marker);marker.hide();return marker;},is_event_visible:function(eventid){var year=current_year_month().year;if(year===9999){if(allmarkers[eventid]===undefined){return false;}
return!allmarkers[eventid].marker.isHidden();}else{if(markers[eventid]===undefined){return false;}
return!markers[eventid].marker.isHidden();}
return false;},show_event:function(eventid){var year=current_year_month().year;if(year===9999){if(allmarkers[eventid]===undefined){CivilWar.Alert.msg(5,"Show Marker Error","Marker {0} is undefined",eventid);return;}
if(allmarkers[eventid].marker.isHidden()){CivilWar.Alert.msg(5,"Show Marker Error","Something went wrong, the marker is hidden!");return;}
allmarkers[eventid].marker.openInfoWindowHtml('<div class="infowindow">'+allmarkers[eventid].html+'</div>');}else{if(markers[eventid]===undefined){CivilWar.Alert.msg(5,"Show Marker Error","Marker {0} is undefined",eventid);return;}
if(markers[eventid].marker.isHidden()){markers[eventid].marker.CivilWarEventIDRequested=true;markers[eventid].marker.CivilWarEventID=eventid;CivilWar.UI.display_year(markers[eventid].year);return;}
markers[eventid].marker.openInfoWindowHtml('<div class="infowindow">'+markers[eventid].html+'</div>');}},hide_info_window:function(){this.getMap().closeInfoWindow();},is_event_in_view:function(eventid){var year=current_year_month().year;var visible_bounds=this.getMap().getBounds();if(year===9999){if(allmarkers[eventid]===undefined){return false;}
if(allmarkers[eventid].marker.isHidden()){return false;}
return visible_bounds.containsLatLng(allmarkers[eventid].marker.getLatLng());}else{if(markers[eventid]===undefined){return false;}
if(markers[eventid].marker.isHidden()){return false;}
return visible_bounds.containsLatLng(markers[eventid].marker.getLatLng());}},year_month_to_offset:function(year,month){return(((year-1642)*12)+month);},create_overlay:function(year,month){var tilelayer=new GTileLayer(new GCopyrightCollection(),6,9);tilelayer.getTileUrl=function(tile,zoom){if((zoom<6)||(zoom===6&&(tile.y<18||tile.y>21||tile.x<30||tile.x>32))||(zoom===7&&(tile.y<37||tile.y>43||tile.x<60||tile.x>65))||(zoom===8&&(tile.y<75||tile.y>87||tile.x<120||tile.x>131))||(zoom===9&&(tile.y<151||tile.y>176||tile.x<240||tile.x>263))||(zoom===10&&(tile.y<302||tile.y>354||tile.x<480||tile.x>527))||(zoom>10)){return"http://www.ecgtheow.com/~dick/tile/tile_blank.png";}else{var ts=((tile.x+tile.y)%3)+1;return"http://ts"+ts+".ecgtheow.com/~dick/tile/"+year+"/"+month+"/tile_"+tile.x+"_"+tile.y+"_"+zoom+".png";}};tilelayer.getOpacity=function(){if(Ext.isIE){return 1;}else{return 0.5;}};tilelayer.isPng=function(){return 1;};return new GTileLayerOverlay(tilelayer);},hide_layers:function(){if(currentlayer!==undefined){this.getMap().removeOverlay(currentlayer);}
currentlayer=undefined;},show_layer:function(year,month){this.hide_layers();if(year===0||month===0){return;}
var i=this.year_month_to_offset(year,month);if(tilelayers[i]===undefined){tilelayers[i]=this.create_overlay(year,month);this.getMap().addOverlay(tilelayers[i]);}else{this.getMap().addOverlay(tilelayers[i]);}
currentlayer=tilelayers[i];}});Ext.reg('mappanel',CivilWar.MapPanel);
// js/ui_data.js

CivilWar.UI=function()
{var HelpWindow;var AboutWindow;var ReferencesWindow;var UrlWindow;var EventWindows=[];var PersonWindows=[];var SmallMode=false;var BodySize;var MainPanel;var base_url;var initial_view_data;var options_menu;var layer_first_time=true;function decode_view(items)
{var cent_lat=DefaultLat;var cent_lng=DefaultLng;var map_zoom=DefaultZoom;var month=0,year='1642',infl=0,i,j,id;var tracklist=[];var eventlist=[];var eventminlist=[];var personlist=[];var personminlist=[];var onthisday=false;for(i=0;i<items.length;i++){if(items[i].indexOf("lat=")===0){cent_lat=parseFloat(items[i].substring(4));}else if(items[i].indexOf("lng=")===0){cent_lng=parseFloat(items[i].substring(4));}else if(items[i].indexOf("zoom=")===0){map_zoom=parseInt(items[i].substring(5),10);}else if(items[i].indexOf("mon=")===0){month=parseInt(items[i].substring(4),10);}else if(items[i].indexOf("yr=")===0){year=items[i].substring(3);if(year==='9999'){year='1642-1651';}}else if(items[i].indexOf("infl=")===0){if(items[i].substring(5)==='true'){infl=1;}else{infl=parseInt(items[i].substring(5),10);}}else if(items[i].indexOf("track=")===0){var tracks=items[i].substring(6).split(',');for(j=0;j<tracks.length;j++){if(tracks[j]===""){continue;}
id=parseInt(tracks[j],10);if(id>0){tracklist.push(id);}}}else if(items[i].indexOf("evwin=")===0){var events=items[i].substring(6).split(',');for(j=0;j<events.length;j++){if(events[j]===""){continue;}
id=parseInt(events[j],10);if(id>0){eventlist.push(id);}}}else if(items[i].indexOf("evwinmin=")===0){var minevents=items[i].substring(9).split(',');for(j=0;j<minevents.length;j++){if(minevents[j]===""){continue;}
id=parseInt(minevents[j],10);if(id>0){eventminlist.push(id);}}}else if(items[i].indexOf("personwin=")===0){var pers=items[i].substring(10).split(',');for(j=0;j<pers.length;j++){if(pers[j]===""){continue;}
id=parseInt(pers[j],10);if(id>0){personlist.push(id);}}}else if(items[i].indexOf("personwinmin=")===0){var minpers=items[i].substring(13).split(',');for(j=0;j<minpers.length;j++){if(minpers[j]===""){continue;}
id=parseInt(minpers[j],10);if(id>0){personminlist.push(id);}}}else if(items[i]==="onthisday"){onthisday=true;}}
return{lat:cent_lat,lng:cent_lng,zoom:map_zoom,month:month,year:year,infl:infl,tracks:tracklist,eventwin:eventlist,eventwinmin:eventminlist,personwin:personlist,personwinmin:personminlist,onthisday:onthisday};}
function encode_view()
{var data;var cent_latlng=MainMap.getCentreLatLng();var map_zoom=MainMap.getZoom();var ym=current_year_month();var infl=Ext.getCmp('infl-cb').checked;var first;data="lat="+cent_latlng.lat;data+="&lng="+cent_latlng.lng;data+="&zoom="+map_zoom;data+="&mon="+ym.month;data+="&yr="+ym.year;data+="&infl="+infl;data+="&track=";first=1;options_menu.items.each(function(item){if(item.id.indexOf('track-cb-')===0&&item.checked){var personid=item.id.substring(9);if(first){data+=personid;first=0;}else{data+=","+personid;}}});data+="&evwin=";first=1;for(var evid=0;evid<EventWindows.length;evid++){if(EventWindows[evid]){if(!EventWindows[evid].hidden){if(first){data+=evid;first=0;}else{data+=","+evid;}}}}
data+="&evwinmin=";first=1;for(var minevid=0;minevid<EventWindows.length;minevid++){if(EventWindows[minevid]){if(EventWindows[minevid].hidden){if(first){data+=minevid;first=0;}else{data+=","+minevid;}}}}
data+="&personwin=";first=1;for(var persid=0;persid<PersonWindows.length;persid++){if(PersonWindows[persid]){if(!PersonWindows[persid].hidden){if(first){data+=persid;first=0;}else{data+=","+persid;}}}}
data+="&personwinmin=";first=1;for(var minpersid=0;minpersid<PersonWindows.length;minpersid++){if(PersonWindows[minpersid]){if(PersonWindows[minpersid].hidden){if(first){data+=minpersid;first=0;}else{data+=","+minpersid;}}}}
return(data);}
function cookie_set(name,value,time,path)
{if(name===null||typeof value==='undefined'){return;}
if(path===null){path='/';}
var expires;if(time){var date=new Date();date.setTime(date.getTime()+time);expires='; expires='+date.toGMTString();}else{expires='';}
document.cookie=name+'='+value+expires+'; path='+path;}
function cookie_get(name)
{name=name+'=';var values=document.cookie.split(';');for(var i=0;i<values.length;i++){var v=values[i];while(v.charAt(0)===' '){v=v.substring(1,v.length);}
if(v.indexOf(name)===0){return v.substring(name.length,v.length);}}
return null;}
function store_bookmark()
{var data=encode_view();cookie_set('ecw_bookmark',data,30*365*24*60*60*1000);}
function restore_bookmark()
{var data=cookie_get('ecw_bookmark');if(data!==null){var items=data.split('&');var view=decode_view(items);return view;}else{return null;}}
function update_layer()
{var infl=Ext.getCmp('infl-cb').checked;var ym=current_year_month();if(layer_first_time&&infl){if(ym.month===0||ym.year===9999){CivilWar.Alert.msg(5,"Influence Zones","Zones are only visible when the month and year controls are set to show a particular month.");}
layer_first_time=false;}
if(infl){if(ym.month!==0&&ym.year>=1642&&ym.year<=1651){MainMap.show_layer(ym.year,ym.month);}else{MainMap.hide_layers();}}else{MainMap.hide_layers();}}
function update_tracks()
{var ym=current_year_month();options_menu.items.each(function(item){if(item.id.indexOf('track-cb-')===0){var personid=parseInt(item.id.substring(9),10);hide_track(personid);if(item.checked){show_track(personid,ym.year,ym.month);}}});}
function help_click(help_item)
{if(!HelpWindow){HelpWindow=new Ext.Window({title:'Help',cls:'cbox_content',width:600,height:300,autoScroll:true,html:"<h2>Menu Buttons</h2>"+"<h3>Help</h3>"+"<p>Displays this help text</p>"+"<h3>Near me</h3>"+"<p>Centres the map and zooms in on your location</p>"+"<h3>Options</h3>"+"<p>Displays a menu that allows certain options to be set.  <em>(See below)</em></p>"+"<h3>Month</h3>"+"<p>Month selector.  Click on the button to select the next month.  Clicking on the button with 'December' already selected will cause the Year to be incremented and 'January' selected.  Click on the arrow to bring up a menu allowing particular months to be chosen.  The special value 'All' selects the entire year.</p>"+"<h3>Year</h3>"+"<p>Year selector.  Values available are 1642-1651 inclusive. Click on the button to select the next year.  Click on the arrow to bring up a menu allowing particular years to be chosen.  The special value '1642-1651' selects the entire range.</p>"+"<h3>Quick Search</h3>"+"<p>Type a search string into the box, and a list of matching events and people is displayed.  Click on a returned item to open the event or person detail window.  At least four characters must be typed before a search is initiated.</p>"+"<h3>Bookmark</h3>"+"<p>Saves the current map position and zoom, and open event and person detail windows.  The page will be restored to this point when this web page is reloaded.</p>"+"<h3>URL</h3>"+"<p>Similar to the Bookmark button, but instead of saving a cookie will display a window containing a URL, which when loaded will show the page with the current map position and zoom, and open event and person detail windows.  The URL can be bookmarked in the browser or sent to another computer, eg by email.</p>"+"<h3>About</h3>"+"<p>Information about this application.</p>"+"<h2>Options</h2>"+"<h3>Show zones of influence</h3>"+"<p>Turns on or off the display of coloured regions overlayed on the map.  Red zones show royalist control, blue zones show parliamentarian.  The month and year selectors must be set to a single month, which must contain events, for any data to be displayed.</p>"+"<h3>Displayed Tracks</h3>"+"<p>Turns on or off the display of the movement of particular personalities.</p>"+"<h2>Side bar</h2>"+"<p>The side bar shows the events that occurred during the month and year specified by the month and year selector buttons.  Click on an event name to show its location on the main map, and display some basic details about the event.  Click on the link provided in the display to show a window containing detailed information.</p>"+"<h2>Taskbar</h2>"+"<p>This shows a list of currently open event and person detail windows.  Click on a button to bring the selected window to the front, or to display it if it had been minimised.</p>"+"<h2>Main map</h2>"+"<p>This shows the locations of events listed in the side bar.  Clicking on a marker has the same effect as selecting an event name in the side bar.  The map can be dragged around by the mouse, or can be positioned and zoomed with the controls in the top left hand corner.</p>"+"<p>If the month and year selectors are set to show a single month, then an additional zoom control appears.  This controls the highlighting of events on a particular day.  Optionally the map can be set to zoom and pan to show the highlighted events, and to open the event information popup windows (only one popup window can be open at a time - if there are multiple highlighted events, one will be chosen at random.)</p>"+"<h2>Windows</h2>"+"<p>Windows can be minimised, maximised or closed using the buttons in the top right hand corner of the window.  They can be moved by clicking and dragging the window title bar, or resized by clicking and dragging the window edges.</p>"+"<h2>Marker Key</h2>"+"<p>"+"  <img src=\"images/map/bluemarker.png\" alt=\"Battles\"></img>Battles"+"  <img src=\"images/map/greenmarker.png\" alt=\"Skirmishes\"></img>Skirmishes or Captures"+"  <img src=\"images/map/redmarker.png\" alt=\"Other events\"></img>Other events"+"</p>"+"<p style=\"margin-top: 20px;\"></p>",closeAction:'close',plain:true,minimizable:true,maximizable:false,constrainHeader:true,renderTo:MainPanel.body,listeners:{close:function(){HelpWindow=null;}}});TaskBar.addTaskButton(HelpWindow);}
HelpWindow.show(help_item);}
function near_me_click()
{CivilWar.Alert.msg(5,'Near Me','Updating location...');if(window.google&&google.gears){try{var geolocation=google.gears.factory.create('beta.geolocation');geolocation.getCurrentPosition(function(response){var address=response.gearsAddress.city+', '+
response.gearsAddress.region+', '+
response.gearsAddress.country;CivilWar.Alert.msg(5,'Position Updated (Gears)','{0}',address);MainMap.setCentre(response.latitude,response.longitude,10);},function(error){CivilWar.Alert.msg(5,'Position Update Failed','Error: {0}',error.message);},{enableHighAccuracy:true,gearsRequestAddress:true});return;}catch(ex){CivilWar.Alert.msg(5,'Gears Error','{0}',ex.message);}}
Ext.Ajax.request({url:'hostip_proxy.php',disableCaching:false,success:function(response){var xml=response.responseXML;var hostip=xml.documentElement.getElementsByTagName("Hostip")[0];var city=hostip.getElementsByTagNameNS("http://www.opengis.net/gml","name")[0].firstChild.nodeValue;var coords=xml.documentElement.getElementsByTagNameNS("http://www.opengis.net/gml","coordinates");var lat=DefaultLat;var lng=DefaultLng;var zoom=DefaultZoom;for(var i=0;i<coords.length;i++){if(coords[i].nodeType===1){var coord_val=coords[i].childNodes[0].nodeValue;var coord_content=coord_val.split(",");lat=parseFloat(coord_content[1]);lng=parseFloat(coord_content[0]);zoom=10;break;}}
CivilWar.Alert.msg(5,'Position Updated (HostIP)','{0}',city);MainMap.setCentre(lat,lng,zoom);},failure:function(response){CivilWar.Alert.msg(5,'Position Update Failed','Error code {0}: {1}',response.status,response.statusText);}});}
function build_options_menu()
{var menu=new Ext.menu.Menu({id:'optionsMenu',items:['<b>Map Display</b>',{id:'infl-cb',text:'Show zones of influence',checked:false,tooltip:{text:'The month and year selectors must be set to a single month, which must contain events, for any data to be displayed.',title:'Influence Zones'},listeners:{checkchange:update_layer}},'-','<b>Displayed Tracks</b>']});Ext.Ajax.request({url:'get_possible_tracks.php',disableCaching:false,success:function(response){var xml=response.responseXML;var lines=xml.documentElement.getElementsByTagName("line");var i;for(i=0;i<lines.length;i++){var id=parseInt(lines[i].getAttribute("id"),10);var colour=lines[i].getAttribute("colour");var name=lines[i].getAttribute("name");var item=new Ext.menu.CheckItem({id:'track-cb-'+id,text:name,style:'border: 3px solid; border-color: '+colour+';',listeners:{checkchange:function(item){update_tracks();MainMap.getDaily().display();}}});menu.addItem(item);}
if(initial_view_data){for(i=0;i<initial_view_data.tracks.length;i++){if(initial_view_data.tracks[i]){var trackitem=Ext.getCmp('track-cb-'+initial_view_data.tracks[i]);if(trackitem){trackitem.setChecked(true);}}}}},failure:function(response){CivilWar.Alert.msg(5,'Track Option Load Failed','Error code {0}: {1}',response.status,response.statusText);}});return menu;}
function bookmark_click()
{CivilWar.Alert.msg(3,'Bookmark','Bookmark cookie has been stored');store_bookmark();}
function url_click(url_item)
{if(!UrlWindow){UrlWindow=new Ext.Window({title:'URL to this view',cls:'cbox_content',width:200,height:75,autoScroll:true,html:'',closeAction:'close',plain:true,minimizable:true,maximizable:false,constrainHeader:true,renderTo:MainPanel.body,listeners:{beforeshow:function(win){var data=encode_view();win.body.update('<a href="'+base_url+'?'+data+'">Copy this URL</a>');},close:function(){UrlWindow=null;}}});TaskBar.addTaskButton(UrlWindow);}
UrlWindow.show(url_item);}
function about_click(about_item)
{if(!AboutWindow){var about_html="<p>All text and application code not otherwise attributed <a href=\"mailto:dick.porter+ecw@gmail.com?subject=Civil War\">"+Copyright+"</a>.</p>"+"<p>Uses the Google Maps API, see <a href=\"http://code.google.com/apis/maps/documentation/index.html\">http://code.google.com/apis/maps/documentation/index.html</a> for details.</p>"+"<p>Uses a locally-modified version of elabel.js by Mike Williams.  See <a href=\"http://econym.org.uk/gmap/elabel.htm\">http://econym.org.uk/gmap/elabel.htm</a> for details.</p>"+"<p>Uses the Ext javascript widget kit, see <a href=\"http://www.extjs.com/\">http://www.extjs.com/</a> for details.</p>"+"<p>Geolocation (the <span class=\"btn_menu_1\" style=\"width: 75px; height: 16px;\">Near me</span> button) powered by <a href=\"http://gears.google.com\">Google Gears</a> if it's installed and available, or <a href=\"http://www.hostip.info\">http://www.hostip.info</a> otherwise.  If hostip gets your location wrong, go there to tell it which is the nearest city!</p>";AboutWindow=new Ext.Window({title:'About',cls:'cbox_content',width:700,height:300,autoScroll:true,html:about_html,closeAction:'close',plain:true,minimizable:true,maximizable:false,constrainHeader:true,renderTo:MainPanel.body,listeners:{close:function(){AboutWindow=null;}}});TaskBar.addTaskButton(AboutWindow);AboutWindow.show(about_item);Ext.Ajax.request({url:'get_dbstats.php',disableCaching:false,scope:AboutWindow,success:function(response){var xml=response.responseXML;var events_count=xml.documentElement.getElementsByTagName("events")[0].firstChild.nodeValue;var garrisons_count=xml.documentElement.getElementsByTagName("garrisons")[0].firstChild.nodeValue;var locations_count=xml.documentElement.getElementsByTagName("locations")[0].firstChild.nodeValue;var movements_count=xml.documentElement.getElementsByTagName("movements")[0].firstChild.nodeValue;var persons_count=xml.documentElement.getElementsByTagName("persons")[0].firstChild.nodeValue;var presences_count=xml.documentElement.getElementsByTagName("presences")[0].firstChild.nodeValue;var refs_count=xml.documentElement.getElementsByTagName("refs")[0].firstChild.nodeValue;var content=about_html+"<p>The database currently contains "+
events_count+" events, "+
locations_count+" locations, "+
persons_count+" people, "+
garrisons_count+" garrisons, "+
movements_count+" movement records, "+
presences_count+" involvement records, "+"and "+
refs_count+" data references."+"</p>";if(this){this.body.update(content);}}});}else{AboutWindow.show(about_item);}}
function references_click(references_item)
{if(!ReferencesWindow){ReferencesWindow=new Ext.Window({title:'References',cls:'cbox_content',width:700,height:300,autoScroll:true,closeAction:'close',plain:true,minimizable:true,maximizable:false,constrainHeader:true,renderTo:MainPanel.body,listeners:{close:function(){ReferencesWindow=null;}}});TaskBar.addTaskButton(ReferencesWindow);ReferencesWindow.show(references_item);ReferencesWindow.load({url:'get_references.php',callback:function(panel,success,response){if(success){var xml=response.responseXML;var reference_book=xml.documentElement.getElementsByTagName("book");var reference_web=xml.documentElement.getElementsByTagName("site");var content=format_references(reference_book,reference_web);panel.update(content);}else{CivilWar.Alert.msg(3,'Load Failed','Error code {0}: {1}',response.status,response.statusText);ReferencesWindow.close();ReferencesWindow=null;}},text:"Loading references...",timeout:30});}else{ReferencesWindow.show(references_item);}}
function comparemarker(a,b)
{if(a.datefrom<b.datefrom){return-1;}
if(a.datefrom>b.datefrom){return 1;}
return 0;}
function between_dates(event_datefrom,event_dateto,year,month)
{if(month===0){return true;}
if(year===9999){var start=new Date(event_datefrom);var end=new Date(event_dateto);for(var i=start.getFullYear();i<=end.getFullYear();i++){if(between_dates(event_datefrom,event_dateto,i,month)){return true;}}
return false;}
var display_datefrom=new Date(year,month-1,1,0,0);var display_dateto=new Date(year,month,1,0,0)-1;if((event_datefrom>=display_datefrom&&event_datefrom<display_dateto)||(event_dateto>=display_datefrom&&event_dateto<display_dateto)||(display_datefrom>=event_datefrom&&display_datefrom<event_dateto)||(display_dateto>=event_datefrom&&display_dateto<event_dateto)){return true;}else{return false;}}
function display_panel(panel)
{update_layer();update_tracks();if(!panel.CivilWarMarkerIndex){return;}
if(panel.isVisible()){var ym=current_year_month();var i;for(i=0;i<panel.CivilWarMarkerIndex.length;i++){if(panel.CivilWarMarkerIndex[i]){panel.CivilWarMarkerIndex[i].marker.hide();}}
for(i=0;i<panel.CivilWarMarkerIndex.length;i++){if(panel.CivilWarMarkerIndex[i]){var mi=panel.CivilWarMarkerIndex[i];var sidebar_item=Ext.getCmp('sidebar-'+ym.year+'-'+mi.eventid);if(ym.month===0||between_dates(mi.datefrom,mi.dateto,ym.year,ym.month)){mi.marker.show();sidebar_item.show();}else{sidebar_item.hide();}}}}}
function hide_panel(panel)
{if(!panel.CivilWarMarkerIndex){return;}
for(var i=0;i<panel.CivilWarMarkerIndex.length;i++){if(panel.CivilWarMarkerIndex[i]){panel.CivilWarMarkerIndex[i].marker.hide();}}}
function ensure_events_loaded(panel,suppress_display)
{if(!panel.CivilWarLoaded){panel.CivilWarLoaded=true;var year;if(panel.title==='1642-1651'){year=9999;}else{year=parseInt(panel.title,10);}
CivilWar.Alert.msg(5,"Loading Year","Loading data for year {0}",panel.title);Ext.Ajax.request({url:'get_battles.php',disableCaching:false,method:'GET',params:{year:year},success:function(response){var xml=response.responseXML;var xmlmarkers=xml.documentElement.getElementsByTagName("marker");var i;var count=0;var locations=[];var eventid;panel.CivilWarMarkerIndex=[];for(i=0;i<xmlmarkers.length;i++){var datefrom=xmlmarkers[i].getAttribute("datefrom");var dateto=xmlmarkers[i].getAttribute("dateto");eventid=parseInt(xmlmarkers[i].getAttribute("eventid"),10);var tooltip=xmlmarkers[i].getAttribute("tooltip");var side=xmlmarkers[i].getAttribute("side");var lat=parseFloat(xmlmarkers[i].getAttribute("lat"));var lng=parseFloat(xmlmarkers[i].getAttribute("lng"));var type=xmlmarkers[i].getAttribute("type");var html=xmlmarkers[i].getAttribute("html");var locid=parseInt(xmlmarkers[i].getAttribute("locid"),10);if(locations[locid]===undefined){locations[locid]=[];}
var marker=MainMap.createMarker(year,datefrom,dateto,eventid,tooltip,html,side,type,lat,lng);panel.CivilWarMarkerIndex[count++]=marker;locations[locid].push(marker);}
panel.CivilWarMarkerIndex.sort(comparemarker);for(i=0;i<locations.length;i++){if(locations[i]){locations[i].sort(comparemarker);var point=new GLatLng(locations[i][0].lat,locations[i][0].lng);var infohtml='<div class="infowindow">';var j;var maptype='';for(j=0;j<locations[i].length;j++){infohtml+="<div>"+locations[i][j].html+"</div>";if(locations[i][j].type==='Battle'){maptype='Battle';}else if((locations[i][j].type==='Skirmish'||locations[i][j].type==='Capture')&&maptype!=='Battle'){maptype='Skirmish';}else if(maptype!=='Battle'&&maptype!=='Skirmish'&&maptype!=='Capture'){maptype=locations[i][j].type;}}
infohtml+="</div>";var mapmarker=MainMap.createMapMarker(point,locations[i][0].tooltip,infohtml,maptype);for(j=0;j<locations[i].length;j++){locations[i][j].marker=mapmarker;MainMap.getDaily().register_range(mapmarker,locations[i][j].side,locations[i][j].eventid,year,locations[i][j].datefrom,locations[i][j].dateto);}}}
for(i=0;i<panel.CivilWarMarkerIndex.length;i++){if(panel.CivilWarMarkerIndex[i]){var mi=panel.CivilWarMarkerIndex[i];var elem=new Ext.Panel({id:'sidebar-'+year+'-'+mi.eventid,html:'<a href="javascript:MainMap.show_event('+mi.eventid+')">'+mi.side+'</a>',cls:'cbox_content_sidebar',border:false});panel.add(elem);}}
panel.body.on('click',function(event){Ext.get(event.target).highlight();});panel.doLayout();if(!suppress_display){display_panel(panel);}},failure:function(response){panel.CivilWarLoaded=false;CivilWar.Alert.msg(5,'Year Data Load Failed','Error code {0}: {1}',response.status,response.statusText);}});}else{if(!suppress_display){display_panel(panel);}}}
function set_month_selector_by_month(month)
{MonthSelector.setActiveItem('month-'+month,true);}
function set_year_selector_by_year(year)
{YearSelector.setActiveItem('year-'+year,true);}
function load_initial_view()
{var view;var url=window.document.URL.toString();if(url.indexOf("?")>0){var split_url=url.split("?");base_url=split_url[0];view=decode_view(split_url[1].split("&"));}else{view=restore_bookmark();base_url=url;}
initial_view_data=view;}
function set_initial_view()
{CivilWar.Alert.msg(10,'Map ready!','Please note, this is very much a work in progress: data is being added all the time.  I\'ve hardly scratched the surface so far! (In particular, events after mid-1644 are not yet covered in any detail.)<br><br>Select an event on the map or in the sidebar, or click on \'Help\' in the top left-hand corner for more information.');if(!initial_view_data){Ext.getCmp('sidebar-1642').expand(true);}else{MainMap.setCentre(initial_view_data.lat,initial_view_data.lng,initial_view_data.zoom);set_month_selector_by_month(initial_view_data.month);Ext.getCmp('sidebar-'+initial_view_data.year).expand(true);MainMap.getDaily().reset();if(initial_view_data.infl){Ext.getCmp('infl-cb').setChecked(true);}
var id;for(id=0;id<initial_view_data.eventwin.length;id++){if(initial_view_data.eventwin[id]){CivilWar.UI.open_window_by_eventid(initial_view_data.eventwin[id],false,null);}}
for(id=0;id<initial_view_data.eventwinmin.length;id++){if(initial_view_data.eventwinmin[id]){CivilWar.UI.open_window_by_eventid(initial_view_data.eventwinmin[id],true,null);}}
for(id=0;id<initial_view_data.personwin.length;id++){if(initial_view_data.personwin[id]){CivilWar.UI.open_window_by_personid(initial_view_data.personwin[id],false,null);}}
for(id=0;id<initial_view_data.personwinmin.length;id++){if(initial_view_data.personwinmin[id]){CivilWar.UI.open_window_by_personid(initial_view_data.personwinmin[id],true,null);}}
if(initial_view_data.onthisday){Ext.Ajax.request({url:'get_on_this_day.php',disableCaching:false,method:'GET',success:function(response){var xml=response.responseXML;var xmlmarkers=xml.documentElement.getElementsByTagName("event");var hidden=xmlmarkers.length>2?true:false;var i;for(i=0;i<xmlmarkers.length;i++){var eventid=parseInt(xmlmarkers[i].getAttribute("eventid"),10);CivilWar.UI.open_window_by_eventid(eventid,hidden,null);}},failure:function(response){CivilWar.Alert.msg(5,'On This Day Load Failed','Error code {0}: {1}',response.status,response.statusText);}});}}}
function create_ui()
{var menu_tb;var search_result_template;var menubar_panel;var taskbar_panel;var viewport;Ext.QuickTips.init();var search_ds=new Ext.data.Store({proxy:new Ext.data.HttpProxy({url:'quick_search.php',method:'GET',disableCaching:false}),reader:new Ext.data.XmlReader({root:"search_results",totalRecords:"results_count",record:"row",id:"id"},[{name:'result_id',mapping:'id'},{name:'query_text',mapping:'query_text'},{name:'result_type',mapping:'type'},{name:'result_name',mapping:'name'},{name:'datefrom'},{name:'dateto'},{name:'excerpt'},{name:'error'}])});if(SmallMode){var main_panel=new Ext.Panel({region:'center',layout:'fit',cls:'cbox_content',autoScroll:true,html:'Using "Small Mode" due to size of browser window:<br>(height '+BodySize.height+', width '+BodySize.width+')',collapsible:false});search_result_template=new Ext.XTemplate('<tpl for="."><div class="search-item">','<tpl if="result_type == \'event\'">','<h3><span class="dates" style="width: 75px;">{datefrom}','<tpl if="datefrom != dateto">','<br />to {dateto}','</tpl>','</span>{result_name}</h3>','{excerpt}','</tpl>','<tpl if="result_type == \'person\'">','<h3>{result_name}</h3>','{excerpt}','</tpl>','<tpl if="result_type == \'error\'">','<span class="search_error">{error}</span>','</tpl>','</div></tpl>');SearchBox=new Ext.form.ComboBox({emptyText:'Quick search...',loadingText:'Searching...',store:search_ds,displayField:'result_name',typeahead:false,pageSize:10,selectOnFocus:true,tpl:search_result_template,itemSelector:'div.search-item',width:BodySize.width-10,onSelect:function(record){var result_id=record.get('result_id');var highlight=record.get('query_text');this.collapse();if(record.get('result_type')==='event'){main_panel.load({url:'get_event.php',method:'GET',params:{eventid:result_id,highlight_regex:highlight},callback:function(panel,success,response){if(success){var xml=response.responseXML;var winHTML=format_detail_window_contents(xml,result_id,0,0,0,0);panel.update(winHTML);}else{panel.update('Load Failed:<br><br>Error code '+response.status+': '+response.statusText);}},text:'Loading event information...',timeout:30});}else if(record.get('result_type')==='person'){main_panel.load({url:'get_person.php',method:'GET',params:{personid:result_id,highlight_regex:highlight},callback:function(panel,success,response){if(success){var xml=response.responseXML;var bio=xml.documentElement.getElementsByTagName("bio");var wincontent=format_person_window_contents(xml,bio,0,0);panel.update(wincontent);}else{panel.update('Load Failed:<br><br>Error code '+response.status+': '+response.statusText);}},text:'Loading person information...',timeout:30});}else if(record.get('result_type')==='error'){}else{main_panel.update('Bad Data: <br><br>Don\'t know how to display search result type '+record.get('result_type'));}}});menu_tb=new Ext.Toolbar({items:[SearchBox]});menubar_panel=new Ext.Panel({region:'north',collapsible:false,height:0,tbar:menu_tb});taskbar_panel=new Ext.Panel({region:'south',layout:'fit',height:0,collapsible:false,items:[{contentEl:'ux-taskbar'}]});viewport=new Ext.Viewport({layout:'border',items:[menubar_panel,taskbar_panel,main_panel],renderTo:Ext.getBody()});}else{MonthSelector=new Ext.CycleButton({showText:true,prependText:'Month: ',items:[{id:'month-0',text:'All',iconCls:'view-text',checked:true},{id:'month-1',text:'January',iconCls:'view-text'},{id:'month-2',text:'February',iconCls:'view-text'},{id:'month-3',text:'March',iconCls:'view-text'},{id:'month-4',text:'April',iconCls:'view-text'},{id:'month-5',text:'May',iconCls:'view-text'},{id:'month-6',text:'June',iconCls:'view-text'},{id:'month-7',text:'July',iconCls:'view-text'},{id:'month-8',text:'August',iconCls:'view-text'},{id:'month-9',text:'September',iconCls:'view-text'},{id:'month-10',text:'October',iconCls:'view-text'},{id:'month-11',text:'November',iconCls:'view-text'},{id:'month-12',text:'December',iconCls:'view-text'}],changeHandler:function(btn,item){var year=YearSelector.getActiveItem().text;var sidebar_panel=Ext.getCmp('sidebar-'+year);display_panel(sidebar_panel);MainMap.getDaily().reset();},listeners:{click:function(btn,ev){var item=btn.getActiveItem();if(item.id==='month-12'){btn.toggleSelected();YearSelector.toggleSelected();}}}});YearSelector=new Ext.CycleButton({showText:true,prependText:'Year: ',items:[{id:'year-1642',text:'1642',iconCls:'view-text',checked:true},{id:'year-1643',text:'1643',iconCls:'view-text'},{id:'year-1644',text:'1644',iconCls:'view-text'},{id:'year-1645',text:'1645',iconCls:'view-text'},{id:'year-1646',text:'1646',iconCls:'view-text'},{id:'year-1647',text:'1647',iconCls:'view-text'},{id:'year-1648',text:'1648',iconCls:'view-text'},{id:'year-1649',text:'1649',iconCls:'view-text'},{id:'year-1650',text:'1650',iconCls:'view-text'},{id:'year-1651',text:'1651',iconCls:'view-text'},{id:'year-1642-1651',text:'1642-1651',iconCls:'view-text'}],changeHandler:function(btn,item){Ext.getCmp('sidebar-'+item.text).expand(true);MainMap.getDaily().reset();}});options_menu=build_options_menu();search_result_template=new Ext.XTemplate('<tpl for="."><div class="search-item">','<tpl if="result_type == \'event\'">','<h3><span class="dates">{datefrom}','<tpl if="datefrom != dateto">','<br />to {dateto}','</tpl>','</span>{result_name}</h3>','{excerpt}','</tpl>','<tpl if="result_type == \'person\'">','<h3>{result_name}</h3>','{excerpt}','</tpl>','<tpl if="result_type == \'error\'">','<span class="search_error">{error}</span>','</tpl>','</div></tpl>');SearchBox=new Ext.form.ComboBox({emptyText:'Quick search...',loadingText:'Searching...',store:search_ds,displayField:'result_name',typeahead:false,pageSize:20,selectOnFocus:true,tpl:search_result_template,itemSelector:'div.search-item',listAlign:'t-b',listWidth:500,onSelect:function(record){var result_id=record.get('result_id');var highlight=record.get('query_text');this.collapse();if(record.get('result_type')==='event'){if(MainMap.is_event_visible(result_id)){MainMap.show_event(result_id);}
CivilWar.UI.open_window_by_eventid(result_id,false,highlight);}else if(record.get('result_type')==='person'){CivilWar.UI.open_window_by_personid(result_id,false,highlight);}else if(record.get('result_type')==='error'){}else{CivilWar.Alert.msg(5,'Bad Data','Don\'t know how to display search result type {0}',record.get('result_type'));}}});menu_tb=new Ext.Toolbar({items:[{text:'Help',handler:help_click,tooltip:{text:'Get help',title:'Help'}},{text:'Near Me',handler:near_me_click,tooltip:{text:'Show events near my location',title:'Near Me'}},{text:'Options',iconCls:'bmenu',menu:options_menu,tooltip:{text:'Select options',title:'Options'}},MonthSelector,YearSelector,SearchBox,{text:'Bookmark',handler:bookmark_click,tooltip:{text:'Remember this view',title:'Bookmark'}},{text:'URL',handler:url_click,tooltip:{text:'Obtain URL to this view',title:'URL'}},{text:'About',handler:about_click,tooltip:{text:'Information about this application',title:'About'}},{text:'References',handler:references_click,tooltip:{text:'Further reading',title:'References'}}]});menubar_panel=new Ext.Panel({region:'north',collapsible:false,height:0,tbar:menu_tb});var sidebar_panel=new Ext.Panel({region:'east',width:200,collapsible:false,layout:'accordion',defaults:{autoScroll:true,collapsed:true,layout:'anchor',listeners:{expand:function(p){set_year_selector_by_year(p.title);ensure_events_loaded(p,false);MainMap.getDaily().reset();},beforecollapse:function(p){hide_panel(p);}}},layoutConfig:{animate:true,activeOnTop:false},items:[{id:'sidebar-1642',title:'1642'},{id:'sidebar-1643',title:'1643'},{id:'sidebar-1644',title:'1644'},{id:'sidebar-1645',title:'1645'},{id:'sidebar-1646',title:'1646'},{id:'sidebar-1647',title:'1647'},{id:'sidebar-1648',title:'1648'},{id:'sidebar-1649',title:'1649'},{id:'sidebar-1650',title:'1650'},{id:'sidebar-1651',title:'1651'},{id:'sidebar-1642-1651',title:'1642-1651'}]});TaskBar=new CivilWar.TaskBar();taskbar_panel=new Ext.Panel({region:'south',layout:'fit',height:32,collapsible:false,items:[{contentEl:'ux-taskbar'}]});MainMap=new CivilWar.MapPanel({});var map_panel=new Ext.Panel({region:'center',layout:'fit',items:[MainMap]});MainPanel=new Ext.Panel({layout:'border',region:'center',hideBorders:true,items:[map_panel,sidebar_panel]});viewport=new Ext.Viewport({layout:'border',hideBorders:true,items:[menubar_panel,taskbar_panel,MainPanel],renderTo:Ext.getBody()});}}
return{init:function()
{if(!GBrowserIsCompatible()){alert("Sorry, the Google Maps API is not compatible with this browser");}else{var body=Ext.getBody();BodySize=body.getSize();if(BodySize.width<750||BodySize.height<400){SmallMode=true;create_ui();}else{load_initial_view();create_ui();set_initial_view();if(Ext.isIE){CivilWar.Alert.msg(10,'Commiserations','I see you\'re viewing this with Internet Explorer.  Certain parts will consequently look substandard.  It works much better in Safari or Firefox or Google Chrome.');}}}},display_year:function(year){MonthSelector.setActiveItem('month-0',false);YearSelector.setActiveItem('year-'+year,false);},open_window_by_eventid:function(eventid,start_hidden,highlight)
{if(!EventWindows[eventid]){EventWindows[eventid]=new Ext.Window({id:'eventwin-'+eventid,title:'Loading...',cls:'cbox_content',width:750,height:300,autoScroll:true,closeAction:'close',plain:true,minimizable:true,maximizable:true,constrainHeader:true,renderTo:MainPanel.body,listeners:{close:function(){EventWindows[eventid]=null;}}});EventWindows[eventid].show();TaskBar.addTaskButton(EventWindows[eventid]);if(start_hidden){EventWindows[eventid].hide();}
EventWindows[eventid].load({url:'get_event.php',method:'GET',params:{eventid:eventid,highlight_regex:highlight},callback:function(panel,success,response){if(success){var xml=response.responseXML;var xmlevents=xml.documentElement.getElementsByTagName("event");var detail=xml.documentElement.getElementsByTagName("detail");var polydetail=xml.documentElement.getElementsByTagName("polygondetail");var textlength=xmlevents[0].getAttribute("notes").length;var hasdetail=(detail.length>0||polydetail.length>0);var dates=xmlevents[0].getAttribute("dates");var winheight;var winHTML=format_detail_window_contents(xml,eventid,hasdetail,1,0,0);var year=parseInt(xmlevents[0].getAttribute("year"),10);var sidebar_panel=Ext.getCmp('sidebar-'+year);ensure_events_loaded(sidebar_panel,true);if(hasdetail){winheight=Math.min(BodySize.height-100,Math.min(700,575+Math.round(textlength/60*10)));}else{winheight=Math.min(BodySize.height-100,Math.min(500,150+Math.round(textlength/60*10)));}
var win=Ext.getCmp('eventwin-'+eventid);win.setTitle(xmlevents[0].getAttribute("name")+" ("+dates+")");TaskBar.update_title(win.taskButton,win.title);win.setHeight(winheight);panel.update(winHTML);if(hasdetail&&!Ext.isIE){create_detail_map("event_map_"+eventid,xml);}}else{CivilWar.Alert.msg(3,'Load Failed','Error code {0}: {1}',response.status,response.statusText);EventWindows[eventid].close();EventWindows[eventid]=null;}},text:'Loading event information...',timeout:30});}else{EventWindows[eventid].show();}},open_window_by_personid:function(personid,start_hidden,highlight){if(!PersonWindows[personid]){PersonWindows[personid]=new Ext.Window({id:'personwin-'+personid,title:'Loading...',cls:'cbox_content',width:700,height:300,autoScroll:true,closeAction:'close',plain:true,minimizable:true,maximizable:true,constrainHeader:true,renderTo:MainPanel.body,listeners:{close:function(){PersonWindows[personid]=null;}}});PersonWindows[personid].show();TaskBar.addTaskButton(PersonWindows[personid]);if(start_hidden){PersonWindows[personid].hide();}
PersonWindows[personid].load({url:'get_person.php',method:'GET',params:{personid:personid,highlight_regex:highlight},callback:function(panel,success,response){if(success){var xml=response.responseXML;var bio=xml.documentElement.getElementsByTagName("bio");var wincontent=format_person_window_contents(xml,bio,0,1);var win=Ext.getCmp('personwin-'+personid);if(wincontent.match("<img ")){var winheight=Math.min(BodySize.height-100,Math.min(700,575+Math.round(bio.length/60*10)));win.setHeight(winheight);}
win.setTitle(bio[0].getAttribute("name"));TaskBar.update_title(win.taskButton,win.title);panel.update(wincontent);}else{CivilWar.Alert.msg(3,'Load Failed','Error code {0}: {1}',response.status,response.statusText);PersonWindows[personid].close();PersonWindows[personid]=null;}},text:'Loading person information...',timeout:30});}else{PersonWindows[personid].show();}}};}();Ext.onReady(CivilWar.UI.init,CivilWar.UI);
// js/displaytrack.js

function TrackData(arrow,line)
{this.arrow=arrow;this.line=line;}
function TrackPoint(mark,day,tooltip)
{this.mark=mark;this.tooltip=tooltip;this.days=[];this.days.push(day);}
var TrackIcons=[];function create_track_icon(colour)
{if(TrackIcons[colour]!==undefined){return TrackIcons[colour];}
var icon=new GIcon();icon.iconSize=new GSize(12,12);icon.shadowSize=new GSize(1,1);icon.iconAnchor=new GPoint(6,6);icon.infoWindowAnchor=new GPoint(0,0);icon.image="http://www.ecgtheow.com/~dick/arrow/"+encodeURIComponent(colour.toLowerCase())+"/track_icon.png";TrackIcons[colour]=icon;return TrackIcons[colour];}
function DisplayedTrack(personid,year)
{this.personid=personid;this.year=year;var thisobj=this;Ext.Ajax.request({url:'get_track.php',method:'GET',disableCaching:false,params:{personid:personid,year:year},success:function(response){var xml=response.responseXML;var lines=xml.documentElement.getElementsByTagName("line");var i,j,k;thisobj.trackdata=[];thisobj.trackmarkers=[];var locations=[];for(j=0;j<=12;j++){locations[j]=[];}
for(i=0;i<lines.length;i++){var colour=lines[i].getAttribute("colour");var itinerant=lines[i].getAttribute("name");var width=5;var points=lines[i].getElementsByTagName("point");var pts=[];var track_icon=create_track_icon(colour);for(j=0;j<=12;j++){pts[j]=[];}
var oldptmonth=0;var oldmark=undefined;var oldlocid=undefined;var oldttinfo=undefined;for(j=0;j<points.length;j++){var ptmonth=parseInt(points[j].getAttribute("month"),10);var day=parseInt(points[j].getAttribute("day"),10);var mark=new GLatLng(parseFloat(points[j].getAttribute("lat")),parseFloat(points[j].getAttribute("lng")));var tooltip=points[j].getAttribute("tooltip");var locid=points[j].getAttribute("locid");var arrivaldate=points[j].getAttribute("arrivaldate");pts[0].push(mark);if(ptmonth>1&&oldptmonth!==ptmonth&&oldmark!==undefined){pts[ptmonth].push(oldmark);if(locations[ptmonth][oldlocid]===undefined){locations[ptmonth][oldlocid]=new TrackPoint(oldmark,0,oldttinfo);}}
pts[ptmonth].push(mark);if(locations[0][locid]!==undefined){locations[0][locid].tooltip+="\n"+arrivaldate+" - "+tooltip;locations[0][locid].days.push(day);}else{locations[0][locid]=new TrackPoint(mark,day,itinerant+": \n\n"+arrivaldate+" - "+tooltip);}
if(locations[ptmonth][locid]!==undefined){locations[ptmonth][locid].tooltip+="\n"+arrivaldate+" - "+tooltip;locations[ptmonth][locid].days.push(day);}else{locations[ptmonth][locid]=new TrackPoint(mark,day,itinerant+": \n\n"+arrivaldate+" - "+tooltip);}
oldptmonth=ptmonth;oldmark=mark;oldlocid=locid;oldttinfo=itinerant+": \n\n"+arrivaldate+" - "+tooltip;}
for(j=0;j<=12;j++){if(pts[j].length<=1){continue;}
if(thisobj.trackdata[j]===undefined){thisobj.trackdata[j]=[];}
if(thisobj.trackmarkers[j]===undefined){thisobj.trackmarkers[j]=[];}
var arrow_tooltip="";var arrow_days=[];var plen=pts[j].length;var lastmark=pts[j][plen-1];for(k=0;k<locations[j].length;k++){if(locations[j][k]){if(locations[j][k].mark.equals(lastmark)){arrow_tooltip=locations[j][k].tooltip;arrow_days=locations[j][k].days;}else{var track_marker=new GMarker(locations[j][k].mark,{icon:track_icon,title:locations[j][k].tooltip});MainMap.addOverlay(track_marker);track_marker.hide();MainMap.getDaily().register(track_marker,locations[j][k].tooltip,null,year,j,locations[j][k].days);thisobj.trackmarkers[j].push(track_marker);}}}
var arrow=arrow_head(pts[j],colour,arrow_tooltip);var line=new GPolyline(pts[j],colour,width,0.9);thisobj.trackdata[j].push(new TrackData(arrow,line));MainMap.addOverlay(arrow);arrow.hide();MainMap.addOverlay(line);line.hide();MainMap.getDaily().register(arrow,arrow_tooltip,null,year,j,arrow_days);}}
var ym=current_year_month();if(ym.year===year){thisobj.show(ym.month);MainMap.getDaily().display();}},failure:function(response){CivilWar.Alert.msg(5,'Track Data Load Failed','Error code {0}: {1}',response.status,response.statusText);}});}
DisplayedTrack.prototype.personid=0;DisplayedTrack.prototype.year=0;DisplayedTrack.prototype.trackdata=null;DisplayedTrack.prototype.trackmarkers=null;DisplayedTrack.prototype.show=function(month)
{var i;if(this.trackmarkers){if(this.trackmarkers[month]){for(i=0;i<this.trackmarkers[month].length;i++){if(this.trackmarkers[month][i]){this.trackmarkers[month][i].show();}}}}
if(this.trackdata){if(this.trackdata[month]){for(i=0;i<this.trackdata[month].length;i++){if(this.trackdata[month][i]){this.trackdata[month][i].line.show();this.trackdata[month][i].arrow.show();}}}}};DisplayedTrack.prototype.hide=function()
{var month;if(this.trackdata){for(month=0;month<this.trackdata.length;month++){if(this.trackdata[month]){for(var track=0;track<this.trackdata[month].length;track++){if(this.trackdata[month][track]){this.trackdata[month][track].line.hide();this.trackdata[month][track].arrow.hide();}}}}}
if(this.trackmarkers){for(month=0;month<this.trackmarkers.length;month++){if(this.trackmarkers[month]){for(var marker=0;marker<this.trackmarkers[month].length;marker++){if(this.trackmarkers[month][marker]){this.trackmarkers[month][marker].hide();}}}}}};var Tracks=[];function show_track(id,year,month)
{if(Tracks[id]===undefined){Tracks[id]=[];}
if(Tracks[id][year]!==undefined){Tracks[id][year].show(month);return;}
Tracks[id][year]=new DisplayedTrack(id,year);}
function hide_track(id)
{if(Tracks[id]===undefined){return;}
for(var year=0;year<Tracks[id].length;year++){if(Tracks[id][year]){Tracks[id][year].hide();}}}
// js/alertbox.js

CivilWar.Alert=function()
{var msgCt;function createBox(t,s)
{return['<div class="msg">','<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>','<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>',t,'</h3>',s,'</div></div></div>','<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>','</div>'].join('');}
return{msg:function(timeout,title,format)
{if(!msgCt){msgCt=Ext.DomHelper.insertFirst(document.body,{id:'msg-div'},true);}
msgCt.alignTo(document,'tr-tr');var s=String.format.apply(String,Array.prototype.slice.call(arguments,2));var m=Ext.DomHelper.append(msgCt,{html:createBox(title,s)},true);m.slideIn('r').pause(timeout).ghost("l",{remove:true});}};}();
// js/daily_map_control.js

function DailyControl()
{this.overlays=[];}
function DailyMarker(marker,text,eventid)
{this.marker=marker;this.text=text;this.eventid=eventid;}
CivilWar.SliderToolTip=Ext.extend(Ext.Tip,{constructor:function(config){this.dailycontrol=config.dailycontrol;CivilWar.SliderToolTip.superclass.constructor.apply(this,arguments);},init:function(slider){slider.on('dragstart',this.onSlide,this);slider.on('drag',this.onSlide,this);slider.on('destroy',this.destroy,this);},onSlide:function(slider){this.dailycontrol.update_label(slider.getValue());}});DailyControl.prototype=new GControl(true,false);DailyControl.prototype.visibility_container=null;DailyControl.prototype.disabled=false;DailyControl.prototype.slider=null;DailyControl.prototype.overlays=null;DailyControl.prototype.highlit_overlays=null;DailyControl.prototype.map=null;DailyControl.prototype.mapsize=null;DailyControl.prototype.top_pos=0;DailyControl.prototype.zoom_check=null;DailyControl.prototype.info_check=null;DailyControl.prototype.label_content=null;DailyControl.prototype.daysinmonth=[0,31,28,31,30,31,30,31,31,30,31,30,31];DailyControl.prototype.initialize=function(map)
{var that=this;this.map=map;this.mapsize=map.getSize();this.top_pos=180;var container=document.createElement("div");container.style.width="70px";container.style.height="370px";this.visibility_container=document.createElement("div");container.appendChild(this.visibility_container);this.visibility_container.style.position="relative";map.getContainer().appendChild(container);if(this.mapsize.height<570){this.disabled=true;return(container);}
var top_with_ticks_container=document.createElement("div");this.visibility_container.appendChild(top_with_ticks_container);top_with_ticks_container.style.position="absolute";top_with_ticks_container.style.overflow="hidden";top_with_ticks_container.style.left="25px";top_with_ticks_container.style.top="23px";top_with_ticks_container.style.width="18px";top_with_ticks_container.style.height="281px";var top_with_ticks_img=document.createElement("div");top_with_ticks_container.appendChild(top_with_ticks_img);top_with_ticks_img.style.overflow="hidden";top_with_ticks_img.style.width="18px";top_with_ticks_img.style.height="281px";top_with_ticks_img.style.background="transparent url(http://maps.google.com/intl/en_ALL/mapfiles/mapcontrols2.png) no-repeat scroll 0 0";top_with_ticks_img.style.backgroundPosition="-20px -65px";var up_arrow=document.createElement("div");top_with_ticks_container.appendChild(up_arrow);up_arrow.style.position="absolute";up_arrow.style.top="0px";up_arrow.style.left="0px";up_arrow.style.height="18px";up_arrow.style.width="18px";up_arrow.style.cursor="pointer";up_arrow.title="Next Day";var bottom_container=document.createElement("div");this.visibility_container.appendChild(bottom_container);bottom_container.style.position="absolute";bottom_container.style.left="25px";bottom_container.style.top="304px";bottom_container.style.width="18px";bottom_container.style.height="23px";var bottom_img=document.createElement("div");bottom_container.appendChild(bottom_img);bottom_img.style.overflow="hidden";bottom_img.style.width="18px";bottom_img.style.height="23px";bottom_img.style.background="transparent url(http://maps.google.com/intl/en_ALL/mapfiles/mapcontrols2.png) no-repeat scroll 0 0";bottom_img.style.backgroundPosition="-20px -360px";var down_arrow=document.createElement("div");bottom_container.appendChild(down_arrow);down_arrow.style.position="absolute";down_arrow.style.top="5px";down_arrow.style.left="0px";down_arrow.style.height="18px";down_arrow.style.width="18px";down_arrow.style.cursor="pointer";down_arrow.title="Previous Day";var slider=document.createElement("div");this.visibility_container.appendChild(slider);slider.style.position="absolute";slider.style.top="49px";slider.style.left="24px";var zoom=document.createElement("div");this.visibility_container.appendChild(zoom);zoom.style.position="absolute";zoom.style.left="0px";zoom.style.top="328px";zoom.style.width="62px";zoom.style.height="18px";zoom.style.color="#000";zoom.style.backgroundColor="#ffffff";zoom.style.font="normal 10px Verdana, Arial, Helvetica";zoom.style.border="1px solid black";zoom.style.padding="1px";zoom.style.cursor="pointer";this.zoom_check=document.createElement("input");this.zoom_check.type="checkbox";this.zoom_check.defaultChecked=false;zoom.appendChild(this.zoom_check);zoom.appendChild(document.createTextNode("Zoom"));var label=document.createElement("div");this.visibility_container.appendChild(label);label.style.position="absolute";label.style.top="0px";label.style.left="0px";label.style.width="62px";label.style.height="18px";label.style.color="#000";label.style.backgroundColor="#ffffff";label.style.font="normal 10px Verdana, Arial, Helvetica";label.style.border="1px solid black";label.style.padding="1px";label.style.textAlign="center";this.label_content=document.createTextNode("No day selected");label.appendChild(this.label_content);var info=document.createElement("div");this.visibility_container.appendChild(info);info.style.position="absolute";info.style.left="0px";info.style.top="348px";info.style.width="62px";info.style.height="18px";info.style.color="#000";info.style.backgroundColor="#ffffff";info.style.font="normal 10px Verdana, Arial, Helvetica";info.style.border="1px solid black";info.style.padding="1px";info.style.cursor="pointer";this.info_check=document.createElement("input");this.info_check.type="checkbox";this.info_check.defaultChecked=false;info.appendChild(this.info_check);info.appendChild(document.createTextNode("Info"));this.slider=new Ext.Slider({renderTo:slider,height:256,vertical:true,increment:1,value:0,minValue:0,maxValue:32,cls:'daily-slider',plugins:new CivilWar.SliderToolTip({dailycontrol:this}),listeners:{beforechange:function(slider,newval,oldval){var ym=current_year_month();var max=that.daysinmonth[ym.month];if(ym.month===2&&(ym.year===1644||ym.year===1648||ym.year===9999)){max=29;}
if(newval>max){return false;}
return true;},changecomplete:function(slider,newval){that.update_label(newval);that.display();}}});GEvent.addDomListener(zoom,"click",function(){that.zoom_check.checked=!that.zoom_check.checked;});GEvent.addDomListener(this.zoom_check,"click",function(){that.zoom_check.checked=!that.zoom_check.checked;});GEvent.addDomListener(info,"click",function(){that.info_check.checked=!that.info_check.checked;});GEvent.addDomListener(this.info_check,"click",function(){that.info_check.checked=!that.info_check.checked;});GEvent.addDomListener(up_arrow,"click",function(){that.slider.setValue(that.slider.getValue()+1,true);that.slider.fireEvent('changecomplete',that,that.slider.getValue());});GEvent.addDomListener(down_arrow,"click",function(){that.slider.setValue(that.slider.getValue()-1,true);that.slider.fireEvent('changecomplete',that,that.slider.getValue());});return(container);};DailyControl.prototype.getDefaultPosition=function()
{return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(2,this.top_pos));};DailyControl.prototype.restore_display=function()
{if(this.highlit_overlays){for(var i=0;i<this.highlit_overlays.length;i++){if(this.highlit_overlays[i]){var marker=this.highlit_overlays[i];MainMap.removeOverlay(marker);}}
if(this.info_check.checked){MainMap.hide_info_window();}
this.highlit_overlays=null;}};DailyControl.prototype.display=function()
{if(this.disabled){return;}
this.restore_display();var day=this.slider.getValue();var ym=current_year_month();if(day>0&&ym.month>0){if(this.overlays[ym.year]){if(this.overlays[ym.year][ym.month]){if(this.overlays[ym.year][ym.month][day]){var highlight_overlays=this.overlays[ym.year][ym.month][day];var bounds=new GLatLngBounds();this.highlit_overlays=[];var count_highlights=0;var highlit_events=[];var i;for(i=0;i<highlight_overlays.length;i++){if(highlight_overlays[i]){var marker=highlight_overlays[i].marker;var eventid=highlight_overlays[i].eventid;if(!marker.isHidden()){count_highlights++;var highlight=MainMap.createMapMarker(marker.getLatLng(),marker.getTitle(),null,'Highlight',marker);highlight.show();this.highlit_overlays.push(highlight);bounds.extend(marker.getLatLng());if(this.info_check.checked&&eventid){highlit_events.push(eventid);}}}}
if(count_highlights>0&&this.zoom_check.checked){MainMap.setBounds(bounds);}
if(this.info_check.checked){for(i=0;i<highlit_events.length;i++){if(highlit_events[i]&&MainMap.is_event_in_view(highlit_events[i])){MainMap.show_event(highlit_events[i]);break;}}}}}}}};DailyControl.prototype.update_label=function(newval)
{if(this.disabled){return;}
if(newval===0){this.label_content.nodeValue="No day";}else{var ym=current_year_month();if(ym.year!=9999){this.label_content.nodeValue=ym.year+"/"+ym.month+"/"+newval;}else{this.label_content.nodeValue=ym.month+"/"+newval;}}};DailyControl.prototype.reset=function()
{if(this.disabled){return;}
var ym=current_year_month();if(ym.month===0){Ext.get(this.visibility_container).hide();}else{Ext.get(this.visibility_container).show();}
this.slider.setValue(0,true);this.update_label(0);this.display();};DailyControl.prototype.register=function(marker,text,eventid,year,month,days)
{if(this.disabled){return;}
if(!this.overlays[year]){this.overlays[year]=[];}
if(!this.overlays[year][month]){this.overlays[year][month]=[];}
if(Ext.isArray(days)){for(var i=0;i<days.length;i++){if(!this.overlays[year][month][days[i]]){this.overlays[year][month][days[i]]=[];}
this.overlays[year][month][days[i]].push(new DailyMarker(marker,text,eventid));}}else{if(!this.overlays[year][month][days]){this.overlays[year][month][days]=[];}
this.overlays[year][month][days].push(new DailyMarker(marker,text,eventid));}};DailyControl.prototype.register_range=function(marker,text,eventid,year,datefrom,dateto)
{if(this.disabled){return;}
var start=new Date(datefrom);var end=new Date(dateto);if(year!==9999){var earliest=new Date(year,0,1,0,0);if(start<earliest){start=earliest;}
while(start<=end&&start.getFullYear()===year){this.register(marker,text,eventid,year,start.getMonth()+1,start.getDate());start.setDate(start.getDate()+1);}}else{while(start<=end){this.register(marker,text,eventid,9999,start.getMonth()+1,start.getDate());start.setDate(start.getDate()+1);}}};
