
POLREL_ME=10;POLREL_ALLY=20;POLREL_ENEMY=30;POLREL_NEUTRAL=40;POLREL_NOTLOGGED=50;POLREL_UNOWNED=-1;CELL_PRICE=10;CELL_PRICE_GC=10;CELLCLASS_NEUTRAL='n';CELLCLASS_MINE='mine';CELLCLASS_ALTITUDE_SHORE='alts';CELLCLASS_UNOWNED='u';CELLCLASS_FIN_MINE={};for(var i=0;i<8;i++){CELLCLASS_FIN_MINE[i]='fin_mine'+i;}
CELLCLASS_MIL_ENEMY={};for(var i=0;i<7;i++){CELLCLASS_MIL_ENEMY[i]='mil_e'+i;}
CELLCLASS_MIL_NEUTRAL={};for(var i=0;i<7;i++){CELLCLASS_MIL_NEUTRAL[i]='mil_n'+i;}
CELLCLASS_MIL_ALLY={};for(var i=0;i<7;i++){CELLCLASS_MIL_ALLY[i]='mil_a'+i;}
CELLCLASS_MIL_MINE={};for(var i=0;i<7;i++){CELLCLASS_MIL_MINE[i]='mil_mine'+i;}
CELLCLASS_ALTITUDE={};for(var i=0;i<26;i++){CELLCLASS_ALTITUDE[i]='alt'+i;}
STALKERCHAR=' '+String.fromCharCode(8224);OSTALKERCHAR=' '+String.fromCharCode(8225);PRODCTRCHAR=(/MSIE (\d+\.\d+);/.test(navigator.userAgent))?' <b>'+String.fromCharCode(169)+'</b>':' <b>'+String.fromCharCode(8853)+'</b>';SHIPCHAR=' '+String.fromCharCode(8710);LAUNCHCHAR=(/MSIE (\d+\.\d+);/.test(navigator.userAgent))?' <img src="/images/char_perpB.gif" alt="">':' <b>'+String.fromCharCode(8869)+'</b>';ULAUNCHCHAR=(/MSIE (\d+\.\d+);/.test(navigator.userAgent))?' <img src="/images/char_perpW.gif" alt="">':' <span style="color:#fff">'+String.fromCharCode(8869)+'</span>';MISSILECHAR=' <b>'+String.fromCharCode(9674)+'</b>';FIELDFORTBG=' <div class="cellBg0"></div>';if(typeof TUTYPE=='undefined'){var TUTYPE=0;}
var cellW=20;var cellH=20;var prevMapCenter=null;var curMapCenter=null;var dropToolOnTBClose=false;var surveilPostsA=[];var getLandCellsCallbackFuncA=null;var getLandCellsCallbackDataA=null;if(!Array.prototype.indexOf){Array.prototype.indexOf=function(elt){var len=this.length;var from=Number(arguments[1])||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0)
from+=len;for(;from<len;from++)
{if(from in this&&this[from]===elt)
return from;}
return-1;};}
function reportAjaxError(methodName,req,resp,try_e,silent,callback){$.ajax({async:true,url:'error.php',type:'POST',data:{'do':'report-ajax-error','methodName':methodName,'request':req,'response':resp,'info_1':try_e},success:function(returnText){if(returnText!=''&&silent!=true){showMsg(returnText,5000,'red');}
if(callback){try{callback();}catch(e){}}},error:function(xhrObj,textStatus,errorThrown){if(callback){try{callback();}catch(e){}}}});}
function getCannonTargetCells(cannonObj){$.ajax({async:true,url:'bcsvr.php',type:'POST',data:{'do':'get-cannon-cells','latMin':cannonObj.latMin,'latMax':cannonObj.latMax,'lonMin':cannonObj.lonMin,'lonMax':cannonObj.lonMax,'latCan':cannonObj.parentCellLat,'lonCan':cannonObj.parentCellLon},success:function(returnText){if(returnText!=''){cbusy=true;try{eval(returnText);if(ctopoLatA.length>10000){alert("too cmany.....")
return;}
if(ctopoLatA.length<1){return;}
var i=ctopoLatA.length;while(i--){var cellKey=[ctopoLatA[i],ctopoLonA[i]];var polRel=computePolRel(cidUserA[i]);cannonObj.tCellsCache[cellKey]={'lat':ctopoLatA[i],'lon':ctopoLonA[i],'polRel':polRel,'latlng':new GLatLng(fromTopo(ctopoLatA[i])-cellDim/2,fromTopo(ctopoLonA[i])+cellDim/2)};cannonObj.tCellsByDistA.push(cellKey);}}catch(e){showMsg('error getting cannon cells; err='+e,10000,'red');}
cbusy=false;}else{showMsg('cannon cells; ajax returned text is empty ! Please report !',10000,'red');}}});}
function findCell(cannonObj,tCellsCache,tCellsByDistA,polRel){var maxIdx=tCellsByDistA.length-1;var lastIdx=cannonObj.lastAttackedCellIdx;if(maxIdx<0){return null;}
i=lastIdx;while(i!=lastIdx+1&&(i!=0||lastIdx!=maxIdx)){var cellObj=tCellsCache[tCellsByDistA[i]];if(cellObj.polRel==polRel){cannonObj.lastAttackedCellIdx=(i>0)?i-1:maxIdx;return cellObj;}
i=(i>0)?i-1:maxIdx;}
return null;}
function shouldShowCannonAttackAnimVisual(cannonObj,dLocObj){return(objCache[[cannonObj.parentCellLat,cannonObj.parentCellLon]]!=null)||(objCache[[dLocObj.lat,dLocObj.lon]]!=null);}
function removeCannonIfPresent(lat,lon){var cellKey=[lat,lon];var cannonObj=cannonsH[cellKey];if(cannonObj==null){return;}
cannonObj.stopCannonLoop();cannonObj.returnToPool(CannonPool);delete cannonsH[cellKey];var cellObj=objCache[cellKey];if(cellObj){cellObj.theDivJq.children('.cann1').remove();}
updAllyItemCounter('#remCannon',true,parseInt($$('#maxCannon').text()));}
function cannonAttack(cannonObj,dLocObj,dotJq){var showVisuals=shouldShowCannonAttackAnimVisual(cannonObj,dLocObj);var dPoint;var cannonPoint;doToolActionAttack4Cannon(showVisuals,cannonObj,dLocObj);if(showVisuals&&!moving){dPoint=map.fromLatLngToContainerPixel(dLocObj.latlng);dPoint.x-=5;dPoint.y-=5;cannonPoint=map.fromLatLngToContainerPixel(cannonObj.cannonCenterLatLng);cannonPoint.x-=5;cannonPoint.y-=5;animAttack(dotJq,cannonPoint.x,cannonPoint.y,dPoint.x,dPoint.y,2000,dLocObj.lat,dLocObj.lon);}}
function doToolActionAttack4Cannon(showVisuals,cannonObj,dLocObj){var defenderJqDiv=null;var dCell=null;var ajaxReqVars={'do':'attack-cell-with-ally-unit','lat':dLocObj.lat,'lon':dLocObj.lon,'alat':cannonObj.parentCellLat,'alon':cannonObj.parentCellLon,'aiau':1,'dDecLat':dLocObj.latlng.lat(),'dDecLng':dLocObj.latlng.lng(),'aDecLat':cannonObj.centerLat,'aDecLng':cannonObj.centerLon};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{eval(returnText);if(aUattackRes['D']==0){updateCannonTCell4AllCannons(dLocObj.lat,dLocObj.lon,POLREL_UNOWNED);}
if(showVisuals){dCell=objCache[[dLocObj.lat,dLocObj.lon]];if(dCell!=null){defenderJqDiv=dCell.theDivJq;}}else{return;}
if(aUattackRes['D']==0){if(dCell!=null){dCell.troops=0;dCell.polRel=POLREL_UNOWNED;dCell.money=0;dCell.idUser=0;var wpJqImg=defenderJqDiv.find(".waypoint");dCell.cellClass=CELLCLASS_UNOWNED;defenderJqDiv.css('background-color','').attr('class',CELLCLASS_UNOWNED).html('');if(wpJqImg.length>0){defenderJqDiv.append(wpJqImg);}
if(crtClickedCellLat==dLocObj.lat&&crtClickedCellLon==dLocObj.lon){crtClickedCellObj=dCell;crtClickedCellDiv=dCell.theDiv;crtClickedCellDivStyle=CELLCLASS_UNOWNED;paintCrtCell('crtCell');showInfoPaneDetail(dCell);}}
if(aUattackRes['nuked']=='yes'){detonateNuke(dLocObj.lat,dLocObj.lon,NUKE_AREA_WIDTH);}else{playSound('cannonMe');}}else{if(dCell!=null){dCell.troops=aUattackRes['D'];var theCellClass=calculateEnemyCellClass(dCell);defenderJqDiv.addClass(theCellClass);dCell.cellClass=theCellClass;}
playSound('cannonMe');}}catch(e){reportAjaxError('doToolActionAttack4Cannon()',JSON.stringify(ajaxReqVars),returnText,e);}},null);}
function animAttack(dotJq,sx,sy,dx,dy,duration,dlat,dlon,objToReturn){try{dotJq.css({top:sy+'px',left:sx+'px'}).fadeIn(75).animate({top:dy+'px',left:dx+'px'},duration,'linear',function(){dotJq.fadeOut(200);if(typeof objToReturn!='undefined'){CannonBulPool.returnObj(objToReturn);}
var cellObj=objCache[[dlat,dlon]];if(cellObj){cellObj.theDivJq.animate({opacity:0.9},100).animate({opacity:0.2},300).animate({opacity:(CELL_TRANSPARENCY/100)},750)}});}catch(ex){showMsg('error in animAttack'+ex,10000,'red');}}
function animCells_HighlightFastAndFadeBack(tCellsCache){try{for(var cellKey in tCellsCache){var cellObj=objCache[cellKey];if(cellObj){cellObj.theDivJq.animate({opacity:(CELL_TRANSPARENCY/2)/100},500,'linear').animate({opacity:(CELL_TRANSPARENCY/100)},400);}}}catch(ex){showMsg('error in animCells_HighlightFastAndFadeBack'+ex,10000,'red');}}
function updateCannonTCell4AllCannons(lat,lon,polRel){var cellKey=[lat,lon];for(var key in cannonsH){var cannonObj=cannonsH[key];if(cannonObj!=null){var dLocObj=cannonObj.tCellsCache[cellKey];if(dLocObj!=null){dLocObj.polRel=polRel;cannonObj.tCellsCache[cellKey]=dLocObj;cannonsH[key]=cannonObj;}}}}
function getAndCreateAllUserAllyUnits(){var ajaxReqVars={'do':'get-all-user-ally-units'};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{eval(returnText);var i=latA.length;while(i--){if(unitTypeA[i]==1){var lat=latA[i];var lon=lonA[i];var cellKey=[lat,lon];if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){var nwLat=fromTopo(lat);var nwLon=fromTopo(lon);var aCell=CellPool.getObj();aCell.reFill(new GLatLngBounds(new GLatLng(nwLat,nwLon),new GLatLng(nwLat-cellDim,nwLon+cellDim)),null,0,0,0,0,0,-1);objCache[cellKey]=aCell;if(cannonsH[cellKey]==null){createNewCannon(aCell,cellKey);}
CellPool.returnObj(objCache[cellKey]);objCache[cellKey].theDiv.innerHTML='';delete objCache[cellKey];}}
else if(unitTypeA[i]==2){var lat=latA[i];var lon=lonA[i];var cellKey=[lat,lon];if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){var nwLat=fromTopo(lat);var nwLon=fromTopo(lon);var aCell=CellPool.getObj();aCell.reFill(new GLatLngBounds(new GLatLng(nwLat,nwLon),new GLatLng(nwLat-cellDim,nwLon+cellDim)),null,0,0,0,0,0,-1);objCache[cellKey]=aCell;if(bombersH[cellKey]==null){createNewBomber(aCell,cellKey);}
CellPool.returnObj(objCache[cellKey]);objCache[cellKey].theDiv.innerHTML='';delete objCache[cellKey];}}}}catch(e){reportAjaxError('getAndCreateAllUserAllyUnits()',JSON.stringify(ajaxReqVars),returnText,e);}},null);}
function createNewCannon(cellObj,cellKey){var cannon=CannonPool.getObj();cannon.reFill(cellObj);cannonsH[cellKey]=cannon;}
function paintCannon(cannonObj,cellObj){if(cannonObj!=null){cellObj.theDivJq.append(cannonObj.cannonTmplJqObj.css('display','block'));}else{cellObj.theDivJq.append(cannonTmplJqObj.clone().css('display','block'));}}
var cannonBulZidxRestore=[];var cannonBulMouseOverExpire=750;function Cannon(){var inst=this;this.parentCellLat=0;this.parentCellLon=0;this.cannonCenterLatLng=null;this.centerLat=0;this.centerLon=0;this.lonMin=0;this.lonMax=0;this.latMin=0;this.latMax=0;this.tCellsCache={};this.tCellsByDistA=[];this.cannonTmplJqObj=null;this.lastAttackedCellIdx=0;this.dotJq=$("#dot1").clone().removeAttr('id');this.dotJq.mouseover(function(){$(this).css('display','none');cannonBulZidxRestore.push($(this));setTimeout(function(){cannonBulZidxRestore.shift().css('display','block');},cannonBulMouseOverExpire);});$$('#mapDiv').append(this.dotJq);function cannonLoop(){var dLocObj=findCell(inst,inst.tCellsCache,inst.tCellsByDistA,POLREL_ENEMY);if(dLocObj!=null){try{cannonAttack(inst,dLocObj,inst.dotJq);}catch(ex){showMsg('error in cannonAttack'+ex,10000,'red');}}}
this.startCannonLoop=function(){if(this.cannonLoopIntervObj==null){this.cannonLoopIntervObj=setInterval(cannonLoop,5000);}}}
Cannon.prototype.stopCannonLoop=function(){if(this.cannonLoopIntervObj!=null){clearInterval(this.cannonLoopIntervObj);this.cannonLoopIntervObj=null;}}
Cannon.prototype.reFill=function(newParentCell){if(newParentCell==null||typeof(newParentCell)=='undefined'){return;}
this.parentCellLat=0;this.parentCellLon=0;this.cannonCenterLatLng=null;this.centerLat=0;this.centerLon=0;this.lonMin=0;this.lonMax=0;this.latMin=0;this.latMax=0;this.tCellsCache={};this.tCellsByDistA=[];this.lastAttackedCellIdx=0;this.cannonTmplJqObj=cannonTmplJqObj.clone();newParentCell.theDivJq.append(this.cannonTmplJqObj.css('display','block'));this.cannonCenterLatLng=newParentCell.theBounds.getCenter();this.centerLat=this.cannonCenterLatLng.lat();this.centerLon=this.cannonCenterLatLng.lng();this.parentCellLat=toTopo(newParentCell.theBounds.getSouthWest().lat());this.parentCellLon=toTopo(newParentCell.theBounds.getSouthWest().lng());this.lonMin=addLon(this.parentCellLon,-CANNON_RADIUS);this.lonMax=addLon(this.parentCellLon,CANNON_RADIUS);this.latMin=addLat(this.parentCellLat,-CANNON_RADIUS);this.latMax=addLat(this.parentCellLat,CANNON_RADIUS);getCannonTargetCells(this);if(pj!=3){this.startCannonLoop();}}
Cannon.prototype.returnToPool=function(poolObj){this.stopCannonLoop();poolObj.returnObj(this);}
function createNewMover(cellObj,cellKey){showMsg('new mover at '+cellKey,3000,'yellow');var mover=MoverPool.getObj();mover.reFill(cellObj);moversH[cellKey]=mover;}
function pickToolMover(){currentTool='place-mover';}
function doToolPlaceMover(){createNewMover(crtClickedCellObj,[crtClickedCellLat,crtClickedCellLon])
currentTool='';}
function animMover(mover,duration){if(mover.moving){return;}
try{mover.moving=true;var dx=10+Math.floor(250*Math.random());var dy=10+Math.floor(250*Math.random());if(dx>50){dx*=-1;}
if(dy>50){dy*=-1;}
if(mover.moverCrtPoint.x+dx>mapW){dx*=-1;}
if(mover.moverCrtPoint.x+dx<0){dx*=-1;}
if(mover.moverCrtPoint.y+dy>mapH){dy*=-1;}
if(mover.moverCrtPoint.y+dy<0){dy*=-1;}
mover.moverUiJq.animate({top:(mover.moverCrtPoint.y+dy)+'px',left:(mover.moverCrtPoint.x+dx)+'px'},duration,'linear',function(){mover.moving=false;});mover.moverCrtPoint.x+=dx;mover.moverCrtPoint.y+=dy;}catch(ex){showMsg('error in animMover'+ex,10000,'red');mover.moving=false;}}
function Mover(){var inst=this;this.moverUiJq=moverTmplJqObj.clone();this.moverCrtPoint=null;this.moving=false;function moverLoop(){animMover(inst,1000+Math.floor(3000*Math.random()));}
this.startMoverLoop=function(){if(this.moverLoopIntervObj==null){this.moverLoopIntervObj=setInterval(moverLoop,5000);}}}
Mover.prototype.stopMoverLoop=function(){if(this.moverLoopIntervObj!=null){clearInterval(this.moverLoopIntervObj);this.moverLoopIntervObj=null;}}
Mover.prototype.reFill=function(newParentCell){if(newParentCell==null||typeof(newParentCell)=='undefined'){return;}
this.moverCrtPoint=map.fromLatLngToContainerPixel(newParentCell.swLatLng);showMsg('UNU'+this.moverCrtPoint,3000,'yellow');$$('#mapDiv').append(this.moverUiJq.css({'display':'block','left':this.moverCrtPoint.x+'px','top':this.moverCrtPoint.y+'px'}));this.startMoverLoop();}
Mover.prototype.returnToPool=function(poolObj){showMsg('returnToPool',3000,'yellow');this.stopMoverLoop();poolObj.returnObj(this);}
function BomberBomb4Me(){var dotJq=$("#dot2").clone().removeAttr('id');dotJq.mouseover(function(){$(this).css('display','none');});$$('#mapDiv').append(dotJq);return dotJq;}
function BomberBomb4Others(){var dotJq=$("#dot3").clone().removeAttr('id');dotJq.mouseover(function(){$(this).css('display','none');});$$('#mapDiv').append(dotJq);return dotJq;}
function drawRayFromBomber(bomber,gPoint){var latLng=map.fromContainerPixelToLatLng(gPoint);var rayPolyline=new GPolyline([bomber.getLatLng(false),latLng],"#05f0f0",3);map.addOverlay(rayPolyline);setTimeout(function(){map.removeOverlay(rayPolyline);},500);}
function drawWayPointsPoly(){var verticeA=[];if(waypointsA.length<2){return;}
for(var i=0;i<waypointsA.length;i++){verticeA.push(waypointsA[i].swLatLng);}
var rayPolyline=new GPolyline(verticeA,"#05f0f0",3);map.addOverlay(rayPolyline);setTimeout(function(){rayPolyline.setStrokeStyle({opacity:0.1});},500);setTimeout(function(){rayPolyline.setStrokeStyle({opacity:1});},1000);setTimeout(function(){map.removeOverlay(rayPolyline);},1500);}
var waypointsA={};var MAX_WAYPOINTS=4;var BOMBER_ANIM_SEGNO=6;var BOMBER_FLY_SPEED=2;var SAC_ANIM_BOMBER='bp';var ANIM_BOMBER_1SEG_DURATION=1000;var ANIM_OTHER_BOMBER_1SEG_DURATION=1000;var ANIM_BOMBER_BOMB_DURATION=500;var ANIM_OTHER_BOMBER_BOMB_DURATION=500;function addWaypoint(lat,lon,doStore){for(var i=0;i<waypointsA.length;i++){if(lat==waypointsA[i].lat&&lon==waypointsA[i].lon){removeWayPoint(waypointsA[i],true);drawWayPointsPoly();return;}}
var wp=new WayPoint(lat,lon);if(waypointsA.length+1>MAX_WAYPOINTS){var oldestWp=waypointsA.shift();removeWayPoint(oldestWp,false);}
waypointsA.push(wp);if(waypointsA.length==1){resetAllBombers();}
if(doStore){storeWayPoint(wp);}
drawWayPointsPoly();}
function appendWaypoint2Cell(cellobj){if(cellobj.theDivJq.find('.waypoint').size()==0){cellobj.theDivJq.append(waypointTmplJqObj.clone().css('display','block'));}}
function WayPoint(lat,lon){this.lat=lat;this.lon=lon;this.swLatLng=new GLatLng(fromTopo(lat)-cellDim/2,fromTopo(lon)+cellDim/2)
this.reFill=function(lat,lon){this.lat=lat;this.lon=lon;}
this.getPixelPoint=function(){return map.fromLatLngToContainerPixel(this.swLatLng);}
this.getID=function(){return this.lat+'-'+this.lon;}}
function removeWayPoint(wp,removeFromStruct){$.ajax({async:false,url:'bcsvr.php',type:'POST',data:{'do':'remove-waypoint','lat':wp.lat,'lon':wp.lon},success:function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){if(removeFromStruct){for(var i=0;i<waypointsA.length;i++){if(wp.lat==waypointsA[i].lat&&wp.lon==waypointsA[i].lon){waypointsA.splice(i,1);}}}
setTimeout(function(){var cellobj=objCache[[wp.lat,wp.lon]];if(cellobj!=null){cellobj.theDivJq.find('.waypoint').remove();}},500);showMsg('waypoint removed.',3000,'green');}else{showMsg('error removing waypoint;'+returnText,5000,'red');}}catch(e){showMsg('ERROR removing waypoint;'+returnText,5000,'red');}}});}
function storeWayPoint(wp){$.ajax({async:true,url:'bcsvr.php',type:'POST',data:{'do':'store-waypoint','lat':wp.lat,'lon':wp.lon},success:function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){showMsg('waypoint set.',3000,'green');}else{showMsg('error saving waypoint;'+returnText,5000,'red');}}catch(e){showMsg('ERROR saving waypoint;'+returnText,5000,'red');}}});}
function repaintWaypointsAndAirports(){var i=waypointsA.length;while(i--){var wp=waypointsA[i];var cellKey=[wp.lat,wp.lon];var cellobj=objCache[cellKey];if(cellobj!=null){appendWaypoint2Cell(cellobj);}}}
waypoints_loaded=false;function loadWaypoints(){$.ajax({async:true,url:'bcsvr.php',type:'POST',data:{'do':'get-waypoints'},success:function(returnText){if(returnText!=''){try{waypoints_loaded=true;eval(returnText);if(wpLatA.length<1){return;}
var i=wpLatA.length;while(i--){addWaypoint(wpLatA[i],wpLonA[i],false);var cellKey=[wpLatA[i],wpLonA[i]];}
repaintWaypointsAndAirports();}catch(e){showMsg('error getting waypoints; err='+e,10000,'red');}}else{showMsg('error at waypoints; ajax returned text is empty ! Please report !',10000,'red');}},error:function(xhrObj,textStatus,errorThrown){try{showMsg('bc exception='+textStatus+'; '+errorThrown,5000,'red');}catch(e){}}});}
function createNewBomber(cellObj,cellKey){var bomber=BomberPool.getObj();bomber.reFill(cellObj);bombersH[cellKey]=bomber;noOfAirports++;}
function removeAirportIfPresent(lat,lon){var cellKey=[lat,lon];var bomber=bombersH[cellKey];if(bomber==null){return;}
bomber.stopBomberLoop();bomber.returnToPool(BomberPool);delete bombersH[cellKey];var cellObj=objCache[cellKey];if(cellObj){cellObj.theDivJq.children('.airp').remove();}
updAllyItemCounter('#remBomber',true,parseInt($$('#maxBomber').text()));var airportKey='a'+(lat)+'b'+(lon);setTimeout(function(){$$('#placedAirportsDiv').find('#'+airportKey).remove();},500);noOfAirports--;}
function paintAirport(bomber,cellObj){if(bomber!=null){cellObj.theDivJq.append(bomber.airportTmplJqObj.css('display','block'));}else{cellObj.theDivJq.append(airportTmplJqObj.clone().css('display','block'));}}
function pickToolPlaceWaypoint(){changeMapCursor('waypoint');currentTool='place-waypoint';}
function doToolPlaceWaypoint(){var point=map.fromLatLngToContainerPixel(crtClickedCellObj.swLatLng);addWaypoint(crtClickedCellLat,crtClickedCellLon,true);appendWaypoint2Cell(crtClickedCellObj);cancelSubActionGui();}
function dropToolPlaceWaypoint(){currentTool='';changeMapCursor('');}
function resetAllBombers(){for(var cellKey in bombersH){var bomber=bombersH[cellKey];bomber.moving=false;bomber.crtWaypointIdx=-2;}}
function animBomber(bomber,duration){if(moving){return;}
if(bomber.moving){return;}
try{if(waypointsA.length==0){return;}
bomber.bomberUiJq.css('display','block');bomber.moving=true;if(!bomber.added2Map){var airportPoint=bomber.getAirportPixelPoint();$$('#mapDiv').append(bomber.bomberUiJq.css({'display':'block','left':airportPoint.x+'px','top':airportPoint.y+'px'}));bomber.added2Map=true;}
if(bomber.crtWaypointIdx==-2){var airportPoint=bomber.getAirportPixelPoint();bomber.bomberUiJq.css({'left':airportPoint.x+'px','top':airportPoint.y+'px'});bomber.crtWaypointIdx=-1;}
if(bomber.crtWaypointIdx==-1){bomber.crtWaypointIdx=0;}else{if(bomber.crtWaypointIdx+1>=waypointsA.length){bomber.crtWaypointIdx=-1;}else{bomber.crtWaypointIdx++;}}
animBomberSegment(bomber,BOMBER_ANIM_SEGNO,duration,true);}catch(ex){showMsg('error in animBomber'+ex,10000,'red');bomber.moving=false;}}
function animBomberSegment(bomber,noOfSegments,duration,firstAnimCall){if(noOfSegments<=0){bomber.moving=false;return;}
if(pj==3){bomber.stopBomberLoop();return;}
var nextPoint=null;var nextLat=null;var nextLon=null;if(bomber.crtWaypointIdx==-1){nextPoint=bomber.getAirportPixelPoint();nextLat=fromTopo(bomber.airportLat);nextLon=fromTopo(bomber.airportLon);}else{try{nextPoint=waypointsA[bomber.crtWaypointIdx].getPixelPoint();nextLat=fromTopo(waypointsA[bomber.crtWaypointIdx].lat);nextLon=fromTopo(waypointsA[bomber.crtWaypointIdx].lon);}catch(e){bomber.moving=false;return;}}
var crtBomberX=parseInt(bomber.bomberUiJq.css('left'));var crtBomberY=parseInt(bomber.bomberUiJq.css('top'));if(curMapCenter!=bomber.mapCenter){try{var mapCenterPoint=map.fromLatLngToContainerPixel(curMapCenter);var prevMapCenterPoint=map.fromLatLngToContainerPixel(bomber.mapCenter);var diffX=(mapCenterPoint.x-prevMapCenterPoint.x);var diffY=(mapCenterPoint.y-prevMapCenterPoint.y);crtBomberX-=diffX;crtBomberY-=diffY;bomber.bomberUiJq.css({top:crtBomberY+'px',left:crtBomberX+'px'});}catch(e){showMsg('err handling map move for bombers + '+e,5000,'red');}
bomber.mapCenter=curMapCenter;}
var zoom=map.getZoom();if(zoom!=bomber.mapZoom){try{var RATIO=(zoom-bomber.mapZoom)*3;var mapCenterPoint=map.fromLatLngToContainerPixel(curMapCenter);var diffX=(-crtBomberX+mapCenterPoint.x)/RATIO;var diffY=(-crtBomberY+mapCenterPoint.y)/RATIO;crtBomberX-=diffX;crtBomberY-=diffY;bomber.bomberUiJq.css({top:crtBomberY+'px',left:crtBomberX+'px'});}catch(e){showMsg('err handling map zoom for bombers + '+e,5000,'red');}
bomber.mapZoom=zoom;}
if(firstAnimCall){var curLatLon=bomber.getLatLng(false);var bomberTravelKm=latLonDistance(curLatLon.y,curLatLon.x,nextLat,nextLon);noOfSegments=Math.floor(bomberTravelKm/BOMBER_FLY_SPEED);var bomberBrng=Math.round(rhumbLineBearingTo(curLatLon.y,curLatLon.x,nextLat,nextLon));bomber.rotate(bomberBrng);sendSac({'suba':SAC_ANIM_BOMBER,'uid':idUser,'alat':bomber.airportLat,'alon':bomber.airportLon,'bx':curLatLon.x,'by':curLatLon.y,'nx':nextLon+0.00833333335,'ny':nextLat-0.00833333335,'segm':noOfSegments,'brng':bomberBrng});if(bomber.crtWaypointIdx==-1){playSound('bomber3');}else if(bomber.crtWaypointIdx%2==0){playSound('bomber1');}else{playSound('bomber2');}}
bomber.bomberUiJq.animate({top:parseInt(crtBomberY+(nextPoint.y-crtBomberY)/noOfSegments)+'px',left:parseInt(crtBomberX+(nextPoint.x-crtBomberX)/noOfSegments)+'px'},duration,'linear',function(){if(!moving){bomber.bomberUiJq.css('display','block');}
animBomberSegment(bomber,noOfSegments-1,duration,false);})}
var otherBombersUiJqsH={};var ROT_BOMBER_KEY='x';var ROT_BOMBER_LEG_COLOR='v';function animBomberSegment4Others(otherBomberUiJq,airportLat,airportLon,crtBomberLon,crtBomberLat,nextPointLon,nextPointLat,noOfSegments,bomberBrng,duration,legColor){if(noOfSegments<=0){return}
var crtBomberLoc=map.fromLatLngToContainerPixel(new GLatLng(crtBomberLat,crtBomberLon));var nextPointLoc=map.fromLatLngToContainerPixel(new GLatLng(nextPointLat,nextPointLon));if(!moving){otherBomberUiJq.css('display','block');}
var segmentEndY=parseInt(crtBomberLoc.y+(nextPointLoc.y-crtBomberLoc.y)/noOfSegments);var segmentEndX=parseInt(crtBomberLoc.x+(nextPointLoc.x-crtBomberLoc.x)/noOfSegments);var segmentEndLatLon=map.fromContainerPixelToLatLng(new GPoint(segmentEndX,segmentEndY));otherBomberUiJq.animate({top:segmentEndY+'px',left:segmentEndX+'px'},duration,'linear',function(){if(!moving){otherBomberUiJq.css('display','block');}
if(legColor==otherBomberUiJq.data(ROT_BOMBER_LEG_COLOR)){animBomberSegment4Others(otherBomberUiJq,airportLat,airportLon,segmentEndLatLon.x,segmentEndLatLon.y,nextPointLon,nextPointLat,noOfSegments-1,bomberBrng,duration,legColor);}});}
function doOtherBomberAnimate(userId,airportLat,airportLon,crtBomberLon,crtBomberLat,nextPointLon,nextPointLat,noOfSegments,bomberBrng){var airportCellKey=[airportLat,airportLon];var otherBomberUiJq=otherBombersUiJqsH[airportCellKey];if(otherBomberUiJq==null){otherBomberUiJq=bomber4OtherTmplJqObj.clone();otherBomberUiJq.mouseover(function(){$(this).css('display','none');});otherBomberUiJq.data(ROT_BOMBER_KEY,(otherBomberUiJq.find("img").rotateAnimation(bomberBrng))[0]);var crtBomberLoc=map.fromLatLngToContainerPixel(new GLatLng(crtBomberLat,crtBomberLon));var nextPointLoc=map.fromLatLngToContainerPixel(new GLatLng(nextPointLat,nextPointLon));$$('#mapDiv').append(otherBomberUiJq.css({top:parseInt(crtBomberLoc.y)+'px',left:parseInt(crtBomberLoc.x)+'px'}));otherBombersUiJqsH[airportCellKey]=otherBomberUiJq;}else{otherBomberUiJq.data(ROT_BOMBER_KEY).rotateAnimation(bomberBrng);}
var legColor=Math.floor(100*Math.random());otherBomberUiJq.data(ROT_BOMBER_LEG_COLOR,legColor);animBomberSegment4Others(otherBomberUiJq,airportLat,airportLon,crtBomberLon,crtBomberLat,nextPointLon,nextPointLat,noOfSegments,bomberBrng,ANIM_OTHER_BOMBER_1SEG_DURATION,legColor);}
function doOtherBomberAtackAnimate(chatTxt,airportLat,airportLon,dlat,dlon,adeclat,adeclng,ddeclat,ddeclng){try{if(!moving){var airportCellKey=[airportLat,airportLon];var otherBomberUiJq=otherBombersUiJqsH[airportCellKey];if(otherBomberUiJq==null){return;}
var dPoint=map.fromLatLngToContainerPixel(new GLatLng(ddeclat-0.007,ddeclng+0.007));var bomberPointX=parseInt(otherBomberUiJq.css('left'))-5;var bomberPointY=parseInt(otherBomberUiJq.css('top'))-5;animAttack4OthersBomber(bomberPointX,bomberPointY,dPoint.x,dPoint.y,ANIM_OTHER_BOMBER_BOMB_DURATION,dlat,dlon);}
playSound('bomberAtt2');}catch(e){showMsg('error after other b. attack ; err='+e,3000,'red');}}
function shouldShowBomberAttackAnimVisual(bomberObj,attackedCellDecLat,attackedCellDecLon){return true;}
function doToolActionAttack4Bomber(showVisuals,bomber,attackedCellLatLng,attackedCellLat,attackedCellLon,attackedCellDecLat,attackedCellDecLon){var defenderJqDiv=null;var dCell=null;bcAjax(true,'bcsvr.php',{'do':'attack-cell-with-ally-unit','lat':attackedCellLat,'lon':attackedCellLon,'alat':bomber.airportLat,'alon':bomber.airportLon,'aiau':2,'dDecLat':attackedCellDecLat,'dDecLng':attackedCellDecLon,'aDecLat':bomber.swLatLng.lat(),'aDecLng':bomber.swLatLng.lng()},function(returnText){try{eval(returnText);if(typeof aUattackRes=='undefined'){return;}
if(aUattackRes['D']==0){updateCannonTCell4AllCannons(attackedCellLat,attackedCellLon,POLREL_UNOWNED);}
if(showVisuals){dCell=objCache[[attackedCellLat,attackedCellLon]];if(dCell!=null){defenderJqDiv=dCell.theDivJq;}}else{return;}
if(aUattackRes['D']==0){if(dCell!=null){dCell.troops=0;dCell.polRel=POLREL_UNOWNED;dCell.money=0;var wpJqImg=defenderJqDiv.find(".waypoint");dCell.cellClass=CELLCLASS_UNOWNED;defenderJqDiv.css('background-color','').attr('class',CELLCLASS_UNOWNED).html('');if(wpJqImg.length>0){defenderJqDiv.append(wpJqImg);}
if(crtClickedCellLat==attackedCellLat&&crtClickedCellLon==attackedCellLon){crtClickedCellObj=dCell;crtClickedCellDiv=dCell.theDiv;crtClickedCellDivStyle=CELLCLASS_UNOWNED;paintCrtCell('crtCell');showInfoPaneDetail(dCell);}}
if(aUattackRes['nuked']=='yes'){detonateNuke(attackedCellLat,attackedCellLon,NUKE_AREA_WIDTH);}}else{if(dCell!=null){dCell.troops=aUattackRes['D'];var theCellClass=calculateEnemyCellClass(dCell);defenderJqDiv.addClass(theCellClass);dCell.cellClass=theCellClass;}}}catch(e){if(returnText.indexOf('own cell attacked')!=-1){return;}
if(returnText.indexOf('cell is not yours')!=-1){return;}
if(returnText.indexOf('defending cell is not owned')!=-1){return;}
showMsg('error during bomber attack ['+bomber.airportLat+','+bomber.airportLon+']; err='+e+'; rettext='+returnText,3000,'red');}
try{if(showVisuals&&!moving){var dPoint=map.fromLatLngToContainerPixel(attackedCellLatLng);dPoint.x-=5;dPoint.y-=5;var crtBomberX=parseInt(bomber.bomberUiJq.css('left'))-4;var crtBomberY=parseInt(bomber.bomberUiJq.css('top'))-4;animAttack4Bomber(crtBomberX,crtBomberY,dPoint.x,dPoint.y,ANIM_BOMBER_BOMB_DURATION,attackedCellLat,attackedCellLon);}}catch(e){showMsg('error after b. attack ['+bomber.airportLat+','+bomber.airportLon+']; err='+e+'; rettext='+returnText,3000,'red');}},null);}
function removeMapObjAsync(thePool,bombJq){if(bombJq==null){return;}
setTimeout(function(){try{$$('#mapDiv').remove(bombJq);}catch(e){}
try{if(thePool!=null){thePool.returnObj(bombJq);}}catch(e){}},200);}
function animAttack4Bomber(sx,sy,dx,dy,duration,dlat,dlon){var bombJq=BomberBomb4MePool.getObj();try{var cellObj=objCache[[dlat,dlon]];if(cellObj){playSound('bomberAtt');bombJq.css({top:sy+'px',left:sx+'px'}).fadeIn(75).animate({top:(dy+5)+'px',left:(dx+5)+'px'},duration,'linear',function(){bombJq.fadeOut(200);cellObj.theDivJq.animate({opacity:0.9},100).animate({opacity:0.2},300).animate({opacity:(CELL_TRANSPARENCY/100)},750,function(){removeMapObjAsync(BomberBomb4MePool,bombJq);});});}else{playSound('bomberAtt2');removeMapObjAsync(BomberBomb4MePool,bombJq);}}catch(ex){showMsg('error in animAttack4Bomber'+ex,10000,'red');}}
function animAttack4OthersBomber(sx,sy,dx,dy,duration,dlat,dlon){var bombJq=BomberBomb4OthersPool.getObj();try{var cellObj=objCache[[dlat,dlon]];if(cellObj){bombJq.css({top:sy+'px',left:sx+'px'}).fadeIn(75).animate({top:dy+'px',left:dx+'px'},duration,'linear',function(){bombJq.fadeOut(200);cellObj.theDivJq.animate({opacity:0.9},100).animate({opacity:0.2},300).animate({opacity:(CELL_TRANSPARENCY/100)},750,function(){removeMapObjAsync(BomberBomb4OthersPool,bombJq);});});}else{removeMapObjAsync(BomberBomb4OthersPool,bombJq);}}catch(ex){showMsg('error in animAttack4Bomber'+ex,10000,'red');}}
function sendSac(paraH){paraH['do']='sac';bcAjax(true,'bcsvr.php',paraH,function(returnText){try{}catch(e){showMsg('error sending sac; err='+e+'; rettext='+returnText,3000,'red');}},null);}
function bomberIconClicked(bomberImgDomObj){var cellKey=$(bomberImgDomObj).attr('id').replace(/a/,'').split('b');var bomber=bombersH[cellKey];map.panTo(bomber.swLatLng);setTimeout(function(){drawCircle(bomber.swLatLng);},1500);}
function drawCircle(latLng){var radius=2500
var points=[];with(Math){var d=radius/6378800;var lat1=(PI/180)*(latLng.lat()-0.00833333335);var lng1=(PI/180)*(latLng.lng()+0.00833333335);for(var a=0;a<361;a+=10){var tc=(PI/180)*a;var y=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));var dlng=atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));var x=((lng1-dlng+PI)%(2*PI))-PI;var point=new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));points.push(point);}}
var poly=new GPolygon(points,'#0000ff',5,0.8,'#0000ff',0.1);map.addOverlay(poly);setTimeout(function(){poly.setStrokeStyle({opacity:0.1,weight:5});},1000);setTimeout(function(){poly.setStrokeStyle({opacity:0.8,weight:5});},2000);setTimeout(function(){map.removeOverlay(poly);},3000);}
function Bomber(){var inst=this;this.bomberUiJq=bomberTmplJqObj.clone();this.rotBomber=(this.bomberUiJq.find("img").rotate(0))[0];this.moving=false;this.added2Map=false;this.mapCenter=map.getCenter();this.mapZoom=map.getZoom();this.crtWaypointIdx=-2;this.airportTmplJqObj=airportTmplJqObj.clone();this.swLatLng=null;this.centerLatLng=null;this.airportLat=null;this.airportLon=null;this.bomberUiJq.mouseover(function(){$(this).css('display','none');});function bomberLoop(){animBomber(inst,ANIM_BOMBER_1SEG_DURATION);}
function attackLoop(){inst.bomberAttack();}
this.startBomberLoop=function(){if(this.bomberLoopIntervObj==null){this.bomberLoopIntervObj=setInterval(bomberLoop,1000);}
if(this.attackLoopIntervObj==null){this.attackLoopIntervObj=setInterval(attackLoop,2000);}}
this.getAirportPixelPoint=function(){return map.fromLatLngToContainerPixel(this.centerLatLng);}
this.getLatLng=function(doRandAdj){var zoom=map.getZoom();var zoomBasedMultiplier=((12-zoom)>0)?1/(12-zoom):2+(zoom-12);var rnd1=(doRandAdj)?Math.floor(zoomBasedMultiplier*16*(Math.random()*2-1.2)):0;var rnd2=(doRandAdj)?Math.floor(zoomBasedMultiplier*16*(Math.random()*2-1.2)):-cellDim;return map.fromContainerPixelToLatLng(new GPoint(parseInt(this.bomberUiJq.css('left'))+rnd1,parseInt(this.bomberUiJq.css('top'))+rnd2));}
this.getID=function(){return this.swLatLng+'|';}
this.bomberAttack=function(){if(moving){return;}
if(waypointsA.length==0){return;}
try{var attackedCellLatLng=this.getLatLng(true);var attackedCellDecLat=attackedCellLatLng.lat();var attackedCellDecLon=attackedCellLatLng.lng();var attackedCellLat=toTopo(attackedCellDecLat);var attackedCellLon=toTopo(attackedCellDecLon);var cellObj=objCache[[attackedCellLat,attackedCellLon]];if(cellObj!=null){if(cellObj.polRel==POLREL_ME||cellObj.polRel==POLREL_UNOWNED){return;}}
var showVisuals=shouldShowBomberAttackAnimVisual(this,attackedCellLat,attackedCellLon);doToolActionAttack4Bomber(showVisuals,this,attackedCellLatLng,attackedCellLat,attackedCellLon,attackedCellDecLat,attackedCellDecLon);}catch(ex){showMsg('error in bomberAttack'+ex,10000,'red');}}
this.stopBomberLoop=function(){if(this.bomberLoopIntervObj!=null){clearInterval(this.bomberLoopIntervObj);this.bomberLoopIntervObj=null;}
if(this.attackLoopIntervObj!=null){clearInterval(this.attackLoopIntervObj);this.attackLoopIntervObj=null;}}
this.returnToPool=function(poolObj){try{this.stopBomberLoop();this.bomberUiJq.css({'display':'none'});removeMapObjAsync(null,this.bomberUiJq);removeMapObjAsync(null,this.airportTmplJqObj);removeMapObjAsync(null,this.rotBomber);poolObj.returnObj(this);}catch(e){showMsg('error in returnToPool; e='+e,10000,'red');}}
this.reFill=function(newParentCell){if(newParentCell==null||typeof(newParentCell)=='undefined'){return;}
this.crtWaypointIdx=-2;this.mapCenter=map.getCenter();this.mapZoom=map.getZoom();newParentCell.theDivJq.append(this.airportTmplJqObj.css('display','block'));this.swLatLng=newParentCell.theBounds.getSouthWest();this.centerLatLng=newParentCell.theBounds.getCenter();this.airportLat=toTopo(this.swLatLng.lat());this.airportLon=toTopo(this.swLatLng.lng());var bomberIconleft=noOfAirports*parseInt(bomberIconTmplJqObj.css('width'));var airportKey='a'+(this.airportLat)+'b'+(this.airportLon);$$('#placedAirportsDiv').append(bomberIconTmplJqObj.clone().attr('id',airportKey).css({'display':'block','left':bomberIconleft}));this.bomberUiJq.css({'top':newParentCell.theDivJq.css('top'),'left':newParentCell.theDivJq.css('left')});if(pj!=3){this.startBomberLoop();}}
this.rotate=function(bomberBrng){this.rotBomber.rotateAnimation(bomberBrng);}}
radarDotH={};radarFifoA=[];function RadarDot(){this.theDiv=document.createElement("div");this.theDivJq=$(this.theDiv);this.eventClass=null;document.getElementById('radarDotsDiv').appendChild(this.theDiv);}
RadarDot.prototype.show=function(xPos,yPos,eventClass){this.eventClass=eventClass;this.theDiv.className=this.eventClass;this.theDivJq.css('top',yPos).css('left',xPos).css('display','block');radarFifoA.push(this);setTimeout(function(){radarFifoA.shift().returnToPool(RadarPool);},10000);}
RadarDot.prototype.returnToPool=function(poolObj){this.theDivJq.fadeOut(401);poolObj.returnObj(this);}
function CannonBullet(){this.dotJq=$("#dot1").clone().removeAttr('id');this.dotJq.mouseover(function(){$(this).css('display','none');cannonBulZidxRestore.push($(this));setTimeout(function(){cannonBulZidxRestore.shift().css('display','block');},cannonBulMouseOverExpire);});$$('#mapDiv').append(this.dotJq);}
function Cell(bounds,cellClass,troops,money,alt,idUser,polRel,arrayPos){this.theBounds=bounds;this.cellClass=cellClass;this.troops=troops;this.money=money;this.alt=alt;this.idUser=idUser;this.polRel=polRel;this.arrayPos=arrayPos;this.theDiv=document.createElement("div");this.theDivJq=$(this.theDiv);this.theDivJq.single_double_click(function(){cellClicked(this);},function(){showCellCity();});this.theDivJq.bind('dblclick',function(e){e.preventDefault();});this.swLatLng=null;this.neLatLng=null;}
Cell.prototype=new GOverlay();Cell.prototype.initialize=function(map){this.theDiv.className=this.cellClass;this.theDiv.cellObj=this;this.swLatLng=this.theBounds.getSouthWest();this.neLatLng=this.theBounds.getNorthEast();mapPane.appendChild(this.theDiv);}
Cell.prototype.remove=function(){this.theDiv.parentNode.removeChild(this.theDiv);}
Cell.prototype.copy=function(){return new Cell(this.theBounds,this.cellClass,this.troops,this.money,this.alt,this.idUser,this.polRel,-1);}
Cell.prototype.redraw=function(force){if(!force)return;var c1=map.fromLatLngToDivPixel(this.swLatLng);var c2=map.fromLatLngToDivPixel(this.neLatLng);var theStyle=this.theDiv.style;theStyle.width=(c2.x-c1.x)+"px";theStyle.height=(c2.y-c1.y)+"px";theStyle.left=c1.x+"px";theStyle.top=c1.y+"px";}
Cell.prototype.reFill=function(bounds,cellClass,troops,money,alt,idUser,polRel,arrayPos){this.theBounds=bounds;this.cellClass=cellClass;this.troops=troops;this.money=money;this.alt=alt;this.idUser=idUser;this.polRel=polRel;this.arrayPos=arrayPos;}
crtRClickedCellA=[];moveOriginCellA=[];crtClickedCellObj=null;crtClickedCellDiv=null;crtClickedCellDivStyle=null;crtClickedCellLat='';crtClickedCellLon='';crtClickedCellDataA={};function clearClickedCell(){if(crtClickedCellObj&&crtClickedCellDiv){crtClickedCellDiv.className=crtClickedCellDivStyle;}
crtClickedCellObj=null;crtClickedCellDiv=null;crtClickedCellDivStyle=null;crtClickedCellLat='';crtClickedCellLon='';crtClickedCellDataA={};}
function cellClicked(crtCellDiv){if(crtRClickedCellA.length>0){if(IS_ARENA&&currentTool!='move-troops'&&currentTool!='ship-move'){clearCrtRClickedCellA();}else{stopLassoTool();}}
if(crtClickedCellDiv!=null){crtClickedCellDiv.className=crtClickedCellDivStyle;}
crtClickedCellObj=crtCellDiv.cellObj;crtClickedCellDiv=crtCellDiv;crtClickedCellDivStyle=crtCellDiv.className;crtCellDiv.className+=' cell_clicked';var cellSWLat=crtCellDiv.cellObj.theBounds.getSouthWest().lat();var cellSWLon=crtCellDiv.cellObj.theBounds.getSouthWest().lng();crtClickedCellLat=toTopo(cellSWLat);crtClickedCellLon=toTopo(cellSWLon);if(IS_ARENA){try{if(cannonsH&&cannonsH[[crtClickedCellLat,crtClickedCellLon]]){var cannonObj=cannonsH[[crtClickedCellLat,crtClickedCellLon]];animCells_HighlightFastAndFadeBack(cannonObj.tCellsCache);}}catch(e){}}else{var benefitRadius=0
if(crtClickedCellObj.theDivJq.find('.building4, .building21, .building24, .building27').size()){benefitRadius=1;}else if(crtClickedCellObj.theDivJq.find('.building5, .building7, .building22, .building25, .building28').size()){benefitRadius=2;}else if(crtClickedCellObj.theDivJq.find('.building6, .building8, .building23, .building26, .building29, .building31').size()){benefitRadius=3;}else if(crtClickedCellObj.theDivJq.find('.building9').size()){benefitRadius=4;}else if(crtClickedCellObj.theDivJq.find('.building32').size()){benefitRadius=6;}else if(crtClickedCellObj.theDivJq.find('.building33').size()){benefitRadius=9;}
crtClickedCellObj.radius=benefitRadius;if(benefitRadius&&CELL_TRANSPARENCY>0){var cellObj;var benefitCellsA=calculateCellCoordsAroundPoint(crtClickedCellLat,crtClickedCellLon,benefitRadius);$.each(benefitCellsA,function(index,value){cellObj=objCache[value];if(cellObj){cellObj.theDivJq.animate({opacity:(CELL_TRANSPARENCY/2)/100},500,'linear').animate({opacity:(CELL_TRANSPARENCY/100)},400);}});}}
cellClickCallback(crtCellDiv.cellObj);return false;}
var OBJTYPE={CELL:10,DIV:20,GLATLNG:30,CANNON:40,CANNONBUL:50,RADARDOT:60,MOVER:70,BOMBER:80,BOMBER_BOMB4ME:81,BOMBER_BOMB4OTHERS:82,CITY:83};function getNewObjPool(oType){var stack=new Array();var initialPoolSize=10;var objType=oType;function createObj(){if(objType==OBJTYPE.CELL){var cell=new Cell();if(CELL_TRANSPARENCY!=-1){cell.theDivJq.css('filter','alpha(opacity='+CELL_TRANSPARENCY+')').css('opacity',CELL_TRANSPARENCY/100)};return cell;}else if(objType==OBJTYPE.CANNON){var cannon=new Cannon();return cannon;}else if(objType==OBJTYPE.MOVER){var mover=new Mover();return mover;}else if(objType==OBJTYPE.BOMBER){var bomber=new Bomber();return bomber;}else if(objType==OBJTYPE.CANNONBUL){var cannonBullet=new CannonBullet();return cannonBullet;}else if(objType==OBJTYPE.BOMBER_BOMB4ME){var bb=new BomberBomb4Me();return bb;}else if(objType==OBJTYPE.BOMBER_BOMB4OTHERS){var bb=new BomberBomb4Others();return bb;}else if(objType==OBJTYPE.RADARDOT){var radarDot=new RadarDot();return radarDot;}else if(objType==OBJTYPE.CITY){var city=new City();return city;}}
return({returnObj:function(obj){stack.push(obj);},getObj:function(){if(stack.length<1){return createObj();}else{return stack.pop();}},getStack:function(){return stack;}});}
var CellPool=getNewObjPool(OBJTYPE.CELL);var CannonPool=getNewObjPool(OBJTYPE.CANNON);var CannonBulPool=getNewObjPool(OBJTYPE.CANNONBUL);var RadarPool=getNewObjPool(OBJTYPE.RADARDOT);var MoverPool=getNewObjPool(OBJTYPE.MOVER);var BomberPool=getNewObjPool(OBJTYPE.BOMBER);var BomberBomb4MePool=getNewObjPool(OBJTYPE.BOMBER_BOMB4ME);var BomberBomb4OthersPool=getNewObjPool(OBJTYPE.BOMBER_BOMB4OTHERS);var CityPool=getNewObjPool(OBJTYPE.CITY);function initBc(){mapOpts={mapTypes:new Array(G_HYBRID_MAP,G_PHYSICAL_MAP,G_NORMAL_MAP),draggableCursor:"crosshair"};for(i in mapOpts['mapTypes']){mapOpts['mapTypes'][i].getMinimumResolution=(IS_ARENA)?function(){return 2}:function(){return 1};mapOpts['mapTypes'][i].getMaximumResolution=function(){return 15};}
map=new GMap2(document.getElementById("mapDiv"),mapOpts);mapPane=map.getPane(G_MAP_MAP_PANE);map.disableDoubleClickZoom();curMapCenter=new GLatLng(centerY,centerX);map.setCenter(curMapCenter,11);GEvent.addListener(map,"click",function(overlay,point){changeMapCursor('');});GEvent.addListener(map,"movestart",function(overlay,point){busy=true;moving=true;lastMapMoveTime=new Date().getTime();startloaderLoop();startGcLoop();$('.cbul1').css('display','none');if(IS_ARENA){$('.bomber').css('display','none');$('.bomber4Other').css('display','none');}});GEvent.addListener(map,"moveend",function(overlay,point){queueReq(getMapTopoCoords());busy=false;moving=false;lastMapMoveTime=new Date().getTime();curMapCenter=map.getCenter();updateRadarPos(curMapCenter);});GEvent.addListener(map,"dblclick",function(overlay,latlng){map.setCenter(curMapCenter);});if(IS_ARENA){GEvent.addListener(map,"singlerightclick",function(pixel,elem){if(currentTool=='move-troops'||currentTool=='ship-move'||currentTool=='ship-load'||currentTool=='attack'||currentTool=='buy-nukes')return false;var latLng=map.fromContainerPixelToLatLng(pixel);var crtLat=toTopo(latLng.lat()+(1/120));var crtLon=toTopo(latLng.lng()-(1/120));var cellObj=objCache[[crtLat,crtLon]];if(cellObj&&!(crtClickedCellLat==crtLat&&crtClickedCellLon==crtLon)&&cellObj.polRel==POLREL_ME){var elPos=getCrtRClickedCellApos(crtLat,crtLon);if(elPos==-1){if(crtRClickedCellA.length>=10)return false;if(crtRClickedCellA.length==0&&crtClickedCellObj){if(crtClickedCellObj.polRel==POLREL_ME){crtRClickedCellA.push({lat:crtClickedCellLat,lon:crtClickedCellLon,obj:crtClickedCellObj,div:crtClickedCellDiv,style:crtClickedCellDivStyle});}else{return false;}
clearClickedCell();}
crtRClickedCellA.push({lat:crtLat,lon:crtLon,obj:cellObj,div:cellObj.theDiv,style:cellObj.theDiv.className});cellObj.theDiv.className+=' cell_clicked';}else{cellObj.theDiv.className=crtRClickedCellA[elPos]['style'];crtRClickedCellA.splice(elPos,1);}}});}
var mapSW=map.getBounds().getSouthWest();var mapNE=map.getBounds().getNorthEast();debug('mapSW='+mapSW)
debug('mapNE='+mapNE)
startloaderLoop();queueReq(getMapTopoCoords());}
function getCrtRClickedCellApos(lat,lon){for(var i in crtRClickedCellA){if(crtRClickedCellA[i]['lat']==lat&&crtRClickedCellA[i]['lon']==lon){return i;}}
return-1;}
function clearCrtRClickedCellA(){var cellObj;for(var i in crtRClickedCellA){cellObj=objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]];if(cellObj){crtRClickedCellA[i]['style']=calculateMyCellClass(crtRClickedCellA[i]['obj']);cellObj.theDiv.className=crtRClickedCellA[i]['style'];}}
crtRClickedCellA=[];}
function getLandCells(mapTopoCoords){if(crtMapView==BC_NAT_VIEW_MAP){return;}
mapSWLat=mapTopoCoords[0];mapNELat=mapTopoCoords[1];mapSWLon=mapTopoCoords[2];mapNELon=mapTopoCoords[3];var prevSurveilPostsLen=surveilPostsA.length;surveilPostsA=[];var ajaxReqVars={'do':'get-land-cells','latMin':mapSWLat,'latMax':mapNELat,'lonMin':mapSWLon,'lonMax':mapNELon};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){if(returnText!=''){var mapTopoCoords=getMapTopoCoords();var mapSWLat2=mapTopoCoords[0];var mapNELat2=mapTopoCoords[1];var mapSWLon2=mapTopoCoords[2];var mapNELon2=mapTopoCoords[3];if(Math.pow(mapSWLat+mapNELat-mapSWLat2-mapNELat2,2)+Math.pow(mapSWLon+mapNELon-mapSWLon2-mapNELon2,2)>Math.pow(mapSWLon-mapNELon,2)){return;}
busy=true;try{eval(returnText);if(topoLatA.length>10000){alert("too many.....")
return;}
if(topoLatA.length<1){return;}
var atLeastOneCell=false;var i=topoLatA.length;while(i--){atLeastOneCell=true;var nwLat=fromTopo(topoLatA[i]);var nwLon=fromTopo(topoLonA[i]);var cellKey=[topoLatA[i],topoLonA[i]];if(objCache[cellKey]){try{if(buildingsA[i]>0&&objCache[cellKey].theDiv.innerHTML==''){objCache[cellKey].theDivJq.append(buildingTmplJqObjA[buildingsA[i]].clone());}
if(idUserA[i]==idUser&&(buildingsA[i]==21||buildingsA[i]==22||buildingsA[i]==23)){surveilPostsA.push([topoLatA[i],topoLonA[i]]);}}catch(e){reportAjaxError('getLandCells(...)','','',e,true);}
objCache[cellKey].arrayPos=i;}else{var polRel=computePolRel(idUserA[i]);var theCellClass='';if(crtMapView==BC_POL_VIEW_MAP){theCellClass=calculateCellClass4PoliticalView(i,polRel);}else if(crtMapView==BC_ALT_VIEW_MAP){theCellClass=calculateCellClass4AltitudeView(i);}else if(crtMapView==BC_MIL_VIEW_MAP){theCellClass=calculateCellClass4MilitaryView(i);}else if(crtMapView==BC_FIN_VIEW_MAP){theCellClass=calculateCellClass4FinanceView(i,false);}
var aCell=null;if(theCellClass==''){if(showUnownedCells){theCellClass=CELLCLASS_UNOWNED;aCell=CellPool.getObj();aCell.reFill(new GLatLngBounds(new GLatLng(nwLat,nwLon),new GLatLng(nwLat-cellDim,nwLon+cellDim)),theCellClass,troopsA[i],moneyA[i],altA[i],idUserA[i],polRel,i);}else{}}else{aCell=CellPool.getObj();aCell.reFill(new GLatLngBounds(new GLatLng(nwLat,nwLon),new GLatLng(nwLat-cellDim,nwLon+cellDim)),theCellClass,troopsA[i],moneyA[i],altA[i],idUserA[i],polRel,i);aCell.theDiv.innerHTML='';if(buildingsA[i]>0){try{aCell.theDivJq.append(buildingTmplJqObjA[buildingsA[i]].clone());if(idUserA[i]==idUser&&(buildingsA[i]==21||buildingsA[i]==22||buildingsA[i]==23)){surveilPostsA.push([topoLatA[i],topoLonA[i]]);}}catch(e){reportAjaxError('getLandCells(...)','','',e,true);}}
if((infoA[i]&SET_FIELDFORT_MASK)){aCell.theDiv.innerHTML+=FIELDFORTBG;}
if(!(infoA[i]&SET_LAUNCHPAD_MASK)&&(infoA[i]&SET_MISSILE_MASK)&&(aCell.polRel==POLREL_ME)){aCell.theDiv.innerHTML+=ULAUNCHCHAR;}else if((infoA[i]&SET_LAUNCHPAD_MASK)&&!(infoA[i]&SET_MISSILE_MASK)&&(aCell.polRel==POLREL_ME)){aCell.theDiv.innerHTML+=LAUNCHCHAR;}else if((infoA[i]&SET_LAUNCHPAD_MASK)&&(infoA[i]&SET_MISSILE_MASK)&&(aCell.polRel==POLREL_ME)){aCell.theDiv.innerHTML+=MISSILECHAR;}
if((infoA[i]&SET_NUKE_MASK)&&(aCell.polRel==POLREL_ME)){aCell.theDiv.innerHTML+=' N';}
if((infoA[i]&SET_PRODCTR_MASK)&&(aCell.polRel==POLREL_ME)){aCell.theDiv.innerHTML+=PRODCTRCHAR;}
if(IS_ARENA){if((infoA[i]&SET_CANNON_MASK)){if(aCell.polRel==POLREL_ME){if(cannonsH[cellKey]==null){createNewCannon(aCell,cellKey)}else{paintCannon(cannonsH[cellKey],aCell);}}else{paintCannon(null,aCell);}}
try{if((infoA[i]&SET_BOMBER_MASK)){if(aCell.polRel==POLREL_ME){if(bombersH[cellKey]==null){createNewBomber(aCell,cellKey)}else{paintAirport(bombersH[cellKey],aCell);}}else{paintAirport(null,aCell);}}}catch(e){showMsg('bomber exception: '+e,5000,'red');}}}
if(aCell!=null){objCache[cellKey]=aCell;map.addOverlay(aCell);}else{}}}
if(IS_ARENA){if(!waypoints_loaded){setTimeout(loadWaypoints,300);}else{repaintWaypointsAndAirports();}}
if(atLeastOneCell&&showPaths){getCells4AllPaths(mapSWLat,mapNELat,mapSWLon,mapNELon);}
if(atLeastOneCell&&showIndividualPath){getCells4OnePath(mapSWLat,mapNELat,mapSWLon,mapNELon,shownIndividualMoveId);}
if(!moving&&atLeastOneCell&&showShips){getShips(mapSWLat,mapNELat,mapSWLon,mapNELon);}
if(!moving&&atLeastOneCell&&showStalkers){getStalkers(mapSWLat,mapNELat,mapSWLon,mapNELon);}
if(crtMapView==BC_FIN_VIEW_MAP&&(surveilPostsA.length||(surveilPostsA.length==0&&prevSurveilPostsLen>0))){var topoCoords=mapTopoCoords.slice(0);topoCoords[4]=true;queueReq(topoCoords);startloaderLoop();}}catch(e){reportAjaxError('getLandCells()',JSON.stringify(ajaxReqVars),returnText,e);}
busy=false;}else{reportAjaxError('getLandCells()',JSON.stringify(ajaxReqVars),returnText,'AJAX returned text is empty !');}
if(getLandCellsCallbackFuncA!=null){$.each(getLandCellsCallbackFuncA,function(idx,functionRef){functionRef(idx);});if(crtMapView==BC_FIN_VIEW_MAP&&(surveilPostsA.length||(surveilPostsA.length==0&&prevSurveilPostsLen>0))){}
else{getLandCellsCallbackDataA=null;getLandCellsCallbackFuncA=null;}}}});}
function paintLandCells(mapTopoCoords){var atLeastOneCell=false;var i=topoLatA.length;while(i--){var cellKey=[topoLatA[i],topoLonA[i]];if(objCache[cellKey]){var theCellClass='';if(crtMapView==BC_POL_VIEW_MAP){idUserA[objCache[cellKey].arrayPos]=objCache[cellKey].idUser;theCellClass=calculateCellClass4PoliticalView(i,computePolRel(idUserA[i]));}else if(crtMapView==BC_ALT_VIEW_MAP){theCellClass=calculateCellClass4AltitudeView(i);}else if(crtMapView==BC_MIL_VIEW_MAP){troopsA[objCache[cellKey].arrayPos]=objCache[cellKey].troops;theCellClass=calculateCellClass4MilitaryView(i);}else if(crtMapView==BC_FIN_VIEW_MAP){moneyA[objCache[cellKey].arrayPos]=objCache[cellKey].money;theCellClass=calculateCellClass4FinanceView(i,(surveilPostsA.length>0));}
if(theCellClass==''&&showUnownedCells&&crtMapView!=BC_NAT_VIEW_MAP){theCellClass=CELLCLASS_UNOWNED;}
objCache[cellKey].cellClass=theCellClass;objCache[cellKey].theDivJq.removeClass().addClass(theCellClass);}}
if(crtClickedCellObj&&!crtClickedCellObj.theDivJq.hasClass('cell_clicked')){crtClickedCellObj.theDiv.className+=' cell_clicked';}
if(getLandCellsCallbackFuncA!=null){$.each(getLandCellsCallbackFuncA,function(idx,functionRef){functionRef(idx);});getLandCellsCallbackDataA=null;getLandCellsCallbackFuncA=null;}}
function computePolRel(iduserVal){var polRel=POLREL_UNOWNED;if(idUser==-1){if(iduserVal!=0){polRel=POLREL_NOTLOGGED;}else{}}else{if(iduserVal==idUser){polRel=POLREL_ME;}else if(iduserVal!=0){if(udH[iduserVal]){if(udH[iduserVal][1].indexOf('a')!=-1){polRel=POLREL_ALLY;}else{polRel=POLREL_ENEMY;}}else{polRel=POLREL_NEUTRAL;}}}
return polRel;}
function calculateCellClass4PoliticalView(i,polRel){if(polRel==POLREL_NOTLOGGED){return CELLCLASS_NEUTRAL;}
if(polRel==POLREL_ME){return CELLCLASS_MINE;}
if(polRel==POLREL_ALLY||polRel==POLREL_ENEMY){return udH[idUserA[i]][1];}
if(polRel==POLREL_NEUTRAL){return CELLCLASS_NEUTRAL;}
return'';}
function calculateCellClass4AltitudeView(i){var cellClass='';if(infoA[i]&SET_SHORE_MASK){cellClass=CELLCLASS_ALTITUDE_SHORE;return cellClass;}
if(altA[i]<0){altA[i]=0;}
var altClassNb=Math.floor(altA[i]/50);if(altClassNb>25){altClassNb=25;}
cellClass=CELLCLASS_ALTITUDE[altClassNb];return cellClass;}
function calculateCellClass4MilitaryView(i){var cellClass='';var nbOfTroops=troopsA[i];if(nbOfTroops<0){nbOfTroops=0;}
var troopsClassNb=0;if(nbOfTroops<3){troopsClassNb=0;}else if(nbOfTroops<8){troopsClassNb=1;}else if(nbOfTroops<13){troopsClassNb=2;}else if(nbOfTroops<18){troopsClassNb=3;}else if(nbOfTroops<23){troopsClassNb=4;}else if(nbOfTroops<40){troopsClassNb=5;}else{troopsClassNb=6;}
if(idUser==-1){if(idUserA[i]!=0){cellClass=CELLCLASS_MIL_NEUTRAL[troopsClassNb];}else{}}else{if(idUserA[i]==idUser){cellClass=CELLCLASS_MIL_MINE[troopsClassNb];}else if(idUserA[i]!=0){if(udH[idUserA[i]]){if(udH[idUserA[i]][1].indexOf('a')!=-1){cellClass=CELLCLASS_MIL_ALLY[troopsClassNb];}else{cellClass=CELLCLASS_MIL_ENEMY[troopsClassNb];}}else{cellClass=CELLCLASS_MIL_NEUTRAL[troopsClassNb];}}else{}}
return cellClass;}
function calculateCellClass4FinanceView(i,enhFlag){var cellClass='';var nbOfCredits=moneyA[i];if(nbOfCredits<0){nbOfCredits=0;}
var creditsClassNb=0;if(nbOfCredits<=2){creditsClassNb=0;}else if(nbOfCredits<=7){creditsClassNb=1;}else if(nbOfCredits<=10){creditsClassNb=2;}else if(nbOfCredits<=14){creditsClassNb=3;}else if(nbOfCredits<=18){creditsClassNb=4;}else if(nbOfCredits<=19){creditsClassNb=5;}else if(nbOfCredits<=29){creditsClassNb=6;}else{creditsClassNb=7;}
if(idUser==-1){if(idUserA[i]!=0){cellClass=CELLCLASS_NEUTRAL;}else{}}else{if(idUserA[i]==idUser){cellClass=CELLCLASS_FIN_MINE[creditsClassNb];}else if(idUserA[i]!=0){cellClass=(enhFlag)?CELLCLASS_MIL_NEUTRAL[creditsClassNb]:CELLCLASS_NEUTRAL;}else{}}
return cellClass;}
function getCells4AllPaths(mapSWLat,mapNELat,mapSWLon,mapNELon){var ajaxReqVars={'do':'get-paths','latMin':mapSWLat,'latMax':mapNELat,'lonMin':mapSWLon,'lonMax':mapNELon};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{if(returnText!=''){if(IS_ARENA){oldDbPathTopoLatA=dbPathTopoLatA;oldDbPathTopoLonA=dbPathTopoLonA;oldDbPathTopoMoveIdA=dbPathTopoMoveIdA;}
eval(returnText);if(IS_ARENA){for(var pathId in oldDbPathTopoUniqueMoveIdH){if(!dbPathTopoUniqueMoveIdH[oldDbPathTopoUniqueMoveIdH[pathId]]){removePath(pathId);delete oldDbPathTopoUniqueMoveIdH[pathId];}}
oldDbPathTopoUniqueMoveIdH=dbPathTopoUniqueMoveIdH;}
if(showPathsUsingPolylines){paintPolylinePaths(dbPathTopoLatA,dbPathTopoLonA,dbPathTopoMoveIdA);}
if(showPathsUsingCells){paintCellsOnMap('clear-text',dbPathTopoLatA,dbPathTopoLonA);paintCellsOnMap('dbpath',dbPathTopoLatA,dbPathTopoLonA);paintPathsCrtPositions();}}}catch(e){reportAjaxError('getCells4AllPaths()',JSON.stringify(ajaxReqVars),returnText,e);}}});}
function getCells4OnePath(mapSWLat,mapNELat,mapSWLon,mapNELon,moveId){var ajaxReqVars={'do':'get-paths','latMin':mapSWLat,'latMax':mapNELat,'lonMin':mapSWLon,'lonMax':mapNELon,'moveId':moveId};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{if(returnText!=''){eval(returnText);paintPolylinePaths(dbPathTopoLatA,dbPathTopoLonA,dbPathTopoMoveIdA);paintCellsOnMap('clear-text',dbPathTopoLatA,dbPathTopoLonA);paintCellsOnMap('dbpath',dbPathTopoLatA,dbPathTopoLonA);paintPathsCrtPositions();}}catch(e){reportAjaxError('getCells4OnePath()',JSON.stringify(ajaxReqVars),returnText,e);}}});}
function showMoveOnMap(moveId,pathCrtPosLat,pathCrtPosLon){showPaths=false;paintCellsOnMap('clear',dbPathTopoLatA,dbPathTopoLonA);showPathsUsingCells=false;paintCellsOnMap('clear-text',dbPathTopoLatA,dbPathTopoLonA);showIndividualPath=true;shownIndividualMoveId=moveId;map.setCenter(new GLatLng(fromTopo(pathCrtPosLat),fromTopo(pathCrtPosLon)));setCB('showPathsCB',false);setCB('showCellsPathsCB',false);scheduleMapViewRefresh();}
function getPaths(){var ajaxReqVars={'do':'get-all-paths','latMin':mapSWLat,'latMax':mapNELat,'lonMin':mapSWLon,'lonMax':mapNELon};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{$$('#transitTroopsList').html('<table cellpadding=0 cellspacing=0 class=troopList>'+returnText+'</table>');}catch(e){reportAjaxError('getPaths()',JSON.stringify(ajaxReqVars),returnText,e);}}});}
function getShips(mapSWLat,mapNELat,mapSWLon,mapNELon){var ajaxReqVars={'do':'get-ships','latMin':mapSWLat,'latMax':mapNELat,'lonMin':mapSWLon,'lonMax':mapNELon};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{if(returnText!=''){eval(returnText);paintUnitsOnMap(dbShipLatA,dbShipLonA,dbShipNbA,(surveilPostsA.length>0)?1:0,SHIPCHAR);}}catch(e){reportAjaxError('getShips()',JSON.stringify(ajaxReqVars),returnText,e);}}});}
function getStalkers(mapSWLat,mapNELat,mapSWLon,mapNELon){var ajaxReqVars={'do':'get-stalkers','latMin':mapSWLat,'latMax':mapNELat,'lonMin':mapSWLon,'lonMax':mapNELon,'surveilPostsA':JSON.stringify(surveilPostsA)};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{if(returnText!=''){eval(returnText);paintUnitsOnMap(dbStalkerLatA,dbStalkerLonA,dbStalkerNbA,1,STALKERCHAR);paintUnitsOnMap(dbStalkerLatA,dbStalkerLonA,dbOtherStalkerNbA,1,OSTALKERCHAR);paintUnitsOnMap(dbStalkerLatA,dbStalkerLonA,dbNukeNbA,1,' N');paintUnitsOnMap(dbStalkerLatA,dbStalkerLonA,dbLaunchNbA,1,LAUNCHCHAR);}}catch(e){reportAjaxError('getStalkers()',JSON.stringify(ajaxReqVars),returnText,e);}}});}
function paintUnitsOnMap(dbUnitLatA,dbUnitLonA,dbUnitNbA,showAll,unitSymbol){var cellObj;for(var i=0;i<dbUnitLatA.length;i++){cellObj=objCache[[dbUnitLatA[i],dbUnitLonA[i]]];if(cellObj&&dbUnitNbA[i]>0&&(cellObj.polRel==POLREL_ME||showAll==1)){if(cellObj.theDiv.innerHTML.indexOf(unitSymbol)==-1)
cellObj.theDiv.innerHTML+=unitSymbol;}}}
function queueReq(topoCoordsA){requesterQIdx++;requestQ[requesterQIdx]=topoCoordsA;}
function startGcLoop(){if(gcLoopIntervObj==null){gcLoopIntervObj=setInterval(gcLoop,500);}}
function stopGcLoop(){if(gcLoopIntervObj!=null){clearInterval(gcLoopIntervObj);gcLoopIntervObj=null;}}
function gcLoop(){if(!busy){var mapTopoCoords=getMapTopoCoords();var mapSWLat=mapTopoCoords[0];var mapNELat=mapTopoCoords[1];var mapSWLon=mapTopoCoords[2];var mapNELon=mapTopoCoords[3];var cellObj;for(key in objCache){var idx=key.indexOf(',');var lat=key.substring(0,idx)-0;var lon=key.substring(idx+1)-0;if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){cellObj=objCache[key];map.removeOverlay(cellObj);cellObj.theDiv.innerHTML='';if(cellObj==crtClickedCellObj){clearClickedCell();}
if(crtRClickedCellA.length>0){clearCrtRClickedCellA();}
CellPool.returnObj(cellObj);delete objCache[key];}}
var crtTime=new Date().getTime();if(crtTime-lastMapMoveTime>15000){stopGcLoop();}}}
function startloaderLoop(){if(loaderLoopIntervObj==null){loaderLoopIntervObj=setInterval(loaderLoop,500);}}
function stoploaderLoop(){if(loaderLoopIntervObj!=null){clearInterval(loaderLoopIntervObj);loaderLoopIntervObj=null;}}
function loaderLoop(){busy=true;if(!moving){try{var removedNb=0;while(loaderQIdx<requesterQIdx){delete requestQ[loaderQIdx];loaderQIdx++;removedNb++;}
if(loaderQIdx==requesterQIdx){if(typeof requestQ[loaderQIdx][4]!='undefined'&&requestQ[loaderQIdx][4]){paintLandCells(requestQ[loaderQIdx]);}else{getLandCells(requestQ[loaderQIdx]);}
delete requestQ[loaderQIdx];loaderQIdx++;}}catch(e){}
var crtTime=new Date().getTime();if(crtTime-lastMapMoveTime>15000){stoploaderLoop();}}
busy=false;}
function getMapTopoCoords(){var mapBounds=map.getBounds();var mapSW=mapBounds.getSouthWest();var mapNE=mapBounds.getNorthEast();return[addLat(toTopo(mapSW.lat()),-mapBorderInCells),addLat(toTopo(mapNE.lat()),mapBorderInCells),addLon(toTopo(mapSW.lng()),-mapBorderInCells),addLon(toTopo(mapNE.lng()),mapBorderInCells)];}
function toTopo(gDecCoord){var ltz=false;if(gDecCoord<0){ltz=true;gDecCoord=-gDecCoord;}
var intPart=Math.floor(gDecCoord);intPart*=100;var decPart=gDecCoord%1.0;var minutePart=decPart*60;if(minutePart%1.0>0.5){minutePart+=1;}
minutePart=Math.floor(minutePart);if(minutePart==60){minutePart=0;intPart=intPart+100;}
intPart+=minutePart;if(ltz){intPart=-intPart;}
return intPart;}
function fromTopo(topoCoord){var ltz=false;if(topoCoord<0){ltz=true;topoCoord=-topoCoord;}
var intPart=Math.floor(topoCoord/100);var decPart=topoCoord/100;decPart=(decPart%1.0)/0.6;if(ltz){intPart=-intPart;decPart=-decPart;}
return intPart+decPart;}
function debug(content){if(idUser!=-2)return;if(top.consoleRef==null||top.consoleRef.closed){top.consoleRef=window.open('','myconsole','width=150,height=700,menubar=0,toolbar=1,status=0,scrollbars=1,resizable=1')
top.consoleRef.document.writeln("<font style='font-size:9px; font-family:tahoma'>");}
top.consoleRef.document.writeln(content+'<br>');}
function isChecked(cbId){return $$('#'+cbId+':nth(0)').attr('checked');}
function setCB(cbId,val){return $$('#'+cbId+':nth(0)').attr('checked',val);}
function changeMapCursor(cursor){if(cursor=='attack'){map.getDragObject().setDraggableCursor('url(images/attack.cur),default');}else if(cursor=='cannon'){map.getDragObject().setDraggableCursor('url(images/cannon.cur),default');}else if(cursor=='bomber'){map.getDragObject().setDraggableCursor('url(images/bomber.cur),default');}else if(cursor=='waypoint'){map.getDragObject().setDraggableCursor('url(images/waypoint.cur),default');}else{map.getDragObject().setDraggableCursor('crosshair');}}
function cellClickCallback(cellObj){if(currentTool=='attack'){doToolActionAttack();return;}else if(currentTool=='mech-attack'){doToolActionMechAttack();return;}else if(currentTool=='buy-troops'){doToolActionAcquireItem('troops');}else if(currentTool=='buy-stalker'){doToolActionAcquireItem('stalker');}else if(currentTool=='buy-launch'){doToolActionAcquireItem('launch');}else if(currentTool=='buy-missile'){doToolActionAcquireItem('missile');}else if(currentTool=='move-troops'||currentTool=='move-stalker'){doToolActionMoveTroops(crtClickedCellLat,crtClickedCellLon,[]);return;}else if(currentTool=='buy-gc-troops'){doToolActionGAcquireItem('troops');}else if(currentTool=='place-mover'){doToolPlaceMover(cellObj);}else if(currentTool=='place-waypoint'){doToolPlaceWaypoint();}else if(currentTool=='ally-cannon'||currentTool=='ally-bomber'){doToolPlaceAllyItem(cellObj);}
showBuildingActionIcon();showInfoPaneDetail(cellObj);}
function cellLassoCallback(){if(currentTool=='move-troops'||currentTool=='move-stalker'){doToolActionMoveTroops('','',crtRClickedCellA);}}
aSpinnerIsShown=false;function setCrtSpinner(spinnerJqObjL,spinnerJqObjR,actionFuncForConfirm){aSpinnerIsShown=true;crtShownSpinnerObjL=spinnerJqObjL;crtShownSpinnerObjR=spinnerJqObjR;setCrtConfirmAction(actionFuncForConfirm);}
function clearCrtSpinner(){aSpinnerIsShown=false;crtShownSpinnerObjL=null;crtShownSpinnerObjR=null;clearCrtConfirmAction();$$("#attackResOverDiv").css("display","none");}
function setCrtConfirmAction(actionFuncForConfirm){crtConfirmAction=actionFuncForConfirm;}
function clearCrtConfirmAction(){crtConfirmAction=null;}
function pickToolAttack(){if(currentTool=='attack'){return;}
if(idUser==-1){showMsg('You must be logged in !',5000,'red');return;}
if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)){if(crtRClickedCellA.length>0){showMsg('Select only <b>one</b> cell with left mouse click',5000,'yellow');}else{showMsg('Select cell that will attack',5000,'yellow');}
cancelSubActionGui();return;}
if(crtClickedCellObj.polRel!=POLREL_ME){showMsg('Select cell you <b>own</b> as attacking cell.',5000,'yellow');cancelSubActionGui();return;}
if(crtClickedCellObj.troops<=0){showMsg('You cannot attack. You have 0 troops.',5000,'yellow');cancelSubActionGui();return;}
attackingCellObj=crtClickedCellObj;attackingCellLat=crtClickedCellLat;attackingCellLon=crtClickedCellLon;currentTool='attack';changeMapCursor('attack');crtClickedCellObj.theDivJq.addClass('classA');$$('.cell-attack-class').css('display','none');$$('#attackerTroopsSpin').val('');$$('#attackSpinPlaceholder').css('display','inline');$$('#defenderTroopsSpin').val('');}
function dropToolAttack(){if(currentTool!='attack'){return;}
currentTool='';changeMapCursor('');attackingCellObj.theDivJq.removeClass('classA');attackingCellObj.theDivJq.addClass(calculateMyCellClass(attackingCellObj));crtClickedCellObj.theDivJq.removeClass('classD');attackingCellObj.theDivJq.addClass(attackingCellObj.cellClass);attackingCellObj=null;attackingCellLat='';attackingCellLon='';clearCrtSpinner();return true;}
function doToolActionAttack(){changeMapCursor('attack');if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
if(crtClickedCellObj.polRel==POLREL_ME||crtClickedCellObj.polRel==POLREL_UNOWNED){return;}
if(attackingCellObj.polRel==POLREL_ME&&crtClickedCellObj.polRel==POLREL_ALLY){showMsg('Cannot attack confirmed allies !',5000,'yellow');return;}
var aLonDec=addLon(attackingCellLon,-1);var aLonInc=addLon(attackingCellLon,1);var aLatDec=addLat(attackingCellLat,-1);var aLatInc=addLat(attackingCellLat,1);if(((crtClickedCellLat==attackingCellLat)&&((crtClickedCellLon==aLonDec)||(crtClickedCellLon==aLonInc)))||((crtClickedCellLon==attackingCellLon)&&((crtClickedCellLat==aLatDec)||(crtClickedCellLat==aLatInc)))||((crtClickedCellLon==aLonInc)&&(crtClickedCellLat==aLatInc))||((crtClickedCellLon==aLonInc)&&(crtClickedCellLat==aLatDec))||((crtClickedCellLon==aLonDec)&&(crtClickedCellLat==aLatInc))||((crtClickedCellLon==aLonDec)&&(crtClickedCellLat==aLatDec))){}else{return;}
var defenderJqDiv=crtClickedCellObj.theDivJq;var attackingJqDiv=attackingCellObj.theDivJq;var ajaxReqVars={'do':'attack-cell','lat':crtClickedCellLat,'lon':crtClickedCellLon,'alat':attackingCellLat,'alon':attackingCellLon};bcAjax(false,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('ERROR')!=-1){showMsg(returnText,5000,'yellow');cancelSubActionGui('TroopAttackCell');return;}
eval(returnText);changeMapCursor('attack');$$("#attackResOverDiv").css("display","block");$$('#attackerTroopsSpin').val(((attackRes['A']<10)?'0'+attackRes['A']:attackRes['A']));$$('#defenderTroopsSpin').val(((attackRes['D']<10)?'0'+attackRes['D']:attackRes['D']));if(attackRes['D']==0){crtClickedCellObj.theDivJq.removeClass('classD');crtClickedCellObj.troops=0;crtClickedCellObj.polRel=POLREL_ME;crtClickedCellObj.money=0;var theCellClass=calculateMyCellClass(crtClickedCellObj);crtClickedCellObj.theDivJq.addClass(theCellClass);crtClickedCellObj.cellClass=theCellClass;crtClickedCellDivStyle=theCellClass;crtClickedCellObj.idUser=idUser;if(IS_ARENA){crtClickedCellObj.theDivJq.children('.cann1, .airp').remove();}
if(attackRes['A']==0){attackingCellObj.theDivJq.removeClass('classA');attackingCellObj.troops=0;var theCellClass=calculateMyCellClass(attackingCellObj);attackingCellObj.theDivJq.addClass(theCellClass);attackingCellObj.cellClass=theCellClass;showMsg('ATTACK SUCCESS !',3000,'green');dropToolAttack();}else{attackingCellObj.theDivJq.removeClass('classA');attackingCellObj.troops=attackRes['A'];var theCellClass=calculateMyCellClass(attackingCellObj);attackingCellObj.theDivJq.attr('class',theCellClass);attackingCellObj.cellClass=theCellClass;showMsg('ATTACK SUCCESS !',3000,'green');playSound('wonCell');$$('#transferWinningTroopsDiv').css('display','block');$$('#transferWinningTroopsDiv').data('AObj',attackingCellObj);$$('#transferWinningTroopsDiv').data('DObj',crtClickedCellObj);$$('#pickToolAttackDiv').css('display','none');$$('#attackSpinPlaceholder').css('display','none');$$('.cell-attack-class').css('display','inline');dropToolAttack();setCrtSpinner($$('#attackerTroopsSpin'),$$('#defenderTroopsSpin'),function(){transferTroops2Cell()});updateCannonTCell4AllCannons(crtClickedCellLat,crtClickedCellLon,POLREL_ME);}
if(attackRes['nuked']=='yes'){detonateNuke(crtClickedCellLat,crtClickedCellLon,NUKE_AREA_WIDTH);cancelSubActionGui('TroopAttackCell');}
if(typeof(attackRes['BL'])!='undefined'){if(attackRes['SIP']!=1){if(attackRes['NPC']<attackRes['BL']){showMsg('You conquered a much smaller player; cell production reduced to <b>'+attackRes['NPC']+'</b> credits/day.',7000,'yellow');}}else{if(attackRes['NPC']<attackRes['BL']){showMsg('Duplicate signal source detected; cell production adjusted to <b>'+attackRes['NPC']+'</b> credits/day.',7000,'yellow');}}}}else{crtClickedCellObj.troops=attackRes['D'];if(attackRes['A']==0){crtClickedCellObj.theDivJq.removeClass('classD');var theCellClass=calculateEnemyCellClass(crtClickedCellObj);crtClickedCellObj.theDivJq.addClass(theCellClass);crtClickedCellObj.cellClass=theCellClass;crtClickedCellDivStyle=theCellClass;attackingCellObj.theDivJq.removeClass('classA');attackingCellObj.troops=attackRes['A'];var theCellClass=calculateMyCellClass(attackingCellObj);attackingCellObj.theDivJq.attr('class',theCellClass);attackingCellObj.cellClass=theCellClass;playSound('attackL');showMsg('YOU LOST !',3000,'yellow');cancelSubActionGui('TroopAttackCell')}else{defenderJqDiv.addClass('classD');crtClickedCellDivStyle=calculateEnemyCellClass(crtClickedCellObj);attackingJqDiv.addClass('classA');attackingCellObj.troops=attackRes['A'];playSound('attack');}}}catch(e){reportAjaxError('doToolActionAttack()',JSON.stringify(ajaxReqVars),returnText,e);cancelSubActionGui('TroopAttackCell')}},null);}
function transferTroops2Cell(){var troops=$$('#defenderTroopsSpin').val();if(troops<=0||troops>99){if(troops>99)showMsg('error condition 1001 - please report!',5000,'red');cancelSubActionGui('TroopAttackCell');return;}
clearCrtSpinner();var ajaxReqVars={'do':'transfer-troops-to-cell','troops':troops};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('SUCCESS')==-1){showMsg('error transfering troops to cell: '+returnText,5000,'red');}else{showMsg('troops transferred to new cell !',5000,'green');$$('.cell-attack-class').css('display','none');$$('#attackSpinPlaceholder').css('display','none');$$('#cellDetailTroops').html(troops);$$('#transferWinningTroopsDiv').data('AObj').troops-=troops;$$('#transferWinningTroopsDiv').data('DObj').troops=troops;setCalculatedMyCellClass($$('#transferWinningTroopsDiv').data('AObj'));var defenderCellObj=$$('#transferWinningTroopsDiv').data('DObj');var theCellClass=calculateMyCellClass(defenderCellObj);defenderCellObj.theDivJq.addClass(theCellClass);defenderCellObj.cellClass=theCellClass;crtClickedCellDivStyle=theCellClass;cancelSubActionGui('TroopAttackCell');}}catch(e){reportAjaxError('transferTroops2Cell()',JSON.stringify(ajaxReqVars),returnText,e);}},null);}
function detonateNuke(lat,lon,area_width){var nukableCellsA=calculateCellCoordsAroundPoint(lat,lon,area_width);var visibleNukableDivsA=[];var previousBgColorA=[];for(var i=0;i<nukableCellsA.length;i++){var cellObj=objCache[[nukableCellsA[i][0],nukableCellsA[i][1]]];if(cellObj){if(crtMapView!=BC_ALT_VIEW_MAP){cellObj.cellClass=CELLCLASS_UNOWNED;}
cellObj.idUser=0;cellObj.troops=0;cellObj.money=0;cellObj.polRel=POLREL_UNOWNED;var theDivjqObj=cellObj.theDivJq;if(crtMapView==BC_ALT_VIEW_MAP){previousBgColorA.push(theDivjqObj.css('background-color'));}else{previousBgColorA.push('#524F4A');}
theDivjqObj.css('background-color','orange');visibleNukableDivsA.push(theDivjqObj);if(nukableCellsA[i][0]==crtClickedCellLat&&nukableCellsA[i][1]==crtClickedCellLon){crtClickedCellDiv=null;}}
removeCannonIfPresent(nukableCellsA[i][0],nukableCellsA[i][1]);}
playSound('nuked');showMsg('NUKE EXPLOSION !!!',5000,'green');for(var i=0;i<visibleNukableDivsA.length;i++){visibleNukableDivsA[i].animate({backgroundColor:previousBgColorA[i]},2000,'swing',function(){if(IS_ARENA){var wpJqImg=$(this).find(".waypoint");$(this).css('background-color','').html('');if(wpJqImg.length>0){$(this).append(wpJqImg);}}else{$(this).css('background-color','').html('');}
if(crtMapView!=BC_ALT_VIEW_MAP)
$(this).attr('class',CELLCLASS_UNOWNED);});}}
function pickToolStalkerAction(){if(idUser==-1){showMsg('You must be logged in !',3000,'red');cancelSubActionGui();return;}
if(moveOriginCellA.length){showMsg('Select only <b>one</b> cell with left mouse click.',4000,'yellow');cancelSubActionGui();return;}
if(isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj==null){showMsg('Select a cell that contains your stalker.',4000,'yellow');cancelSubActionGui();return;}
if(cias==null||cias['cellDetailStalkers']==0){showMsg('There is no stalker on this cell.',4000,'yellow');cancelSubActionGui();return;}
var tabsItemsJqObj=$("#stalkerActionTabDiv,.thickboxTabNoItems");tabsItemsJqObj.css("display","block");$('#stalkerActionTabDiv > .prefTab').css('opacity','1');$('.stalkerActionItmTab0,.stalkerActionItmTab1').appendTo('stalkerActionHiddenDiv');for(var i=ACTIVE_UPGRADES_A.length-1;i>=0;i--){actionTblId=$('#stalkerUpgrade'+ACTIVE_UPGRADES_A[i]);if(actionTblId.length){actionClassNm=actionTblId.attr('class');tabDivId=actionClassNm.substr(actionClassNm.length-1);$('#stalkerAction'+tabDivId+' .thickboxTabNoItems').css('display','none');actionTblId.appendTo('#stalkerAction'+tabDivId+' > .sHolderHelp .scroll-paneSTALKERMENU');}}
tb_remove(true);$("#stalkerActionLink").click();$("#scroll-paneSTALKERATTACK").jScrollPane({showArrows:false,scrollbarWidth:10,scrollbarMargin:8});dropToolOnTBClose=true;}
function pickToolMechAttack(){if(currentTool=='mech-attack'){return;}
if(idUser==-1){showMsg('You must be logged in !',5000,'red');return;}
if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)){if(crtRClickedCellA.length>0){showMsg('Select only <b>one</b> cell with left mouse click',5000,'yellow');}else{showMsg('Select cell that will attack',5000,'yellow');}
cancelSubActionGui();return;}
if(crtClickedCellObj.polRel!=POLREL_ME){showMsg('Select cell you <b>own</b> as attacking cell',5000,'yellow');cancelSubActionGui();return;}
attackingCellObj=crtClickedCellObj;attackingCellLat=crtClickedCellLat;attackingCellLon=crtClickedCellLon;currentTool='mech-attack';changeMapCursor('attack');crtClickedCellObj.theDivJq.addClass('classA');crtClickedCellDivStyle+=' classA';attackingCellObj.theDivJq.find('.building7, .building8, .building9').animate({height:'100%'},300);attackingCellObj.targetCellsA=calculateCellCoordsAroundPoint(attackingCellLat,attackingCellLon,crtClickedCellObj.radius);$.each(attackingCellObj.targetCellsA,function(index,value){cellObj=objCache[value];if(cellObj){cellObj.theDivJq.addClass('whiteBorder');}});}
function dropToolMechAttack(){if(currentTool!='mech-attack'){return;}
currentTool='';changeMapCursor('');attackingCellObj.theDivJq.removeClass('classA');attackingCellObj.theDivJq.addClass(calculateMyCellClass(attackingCellObj));crtClickedCellObj.theDivJq.removeClass('classD');attackingCellObj.theDivJq.addClass(attackingCellObj.cellClass);$.each(attackingCellObj.targetCellsA,function(index,value){cellObj=objCache[value];if(cellObj){cellObj.theDivJq.removeClass('whiteBorder');}});crtClickedCellDivStyle=crtClickedCellDivStyle.replace(/whiteBorder/,'').replace(/classA/,'');attackingCellObj.theDivJq.find('.building7, .building8, .building9').css({height:'auto'});attackingCellObj=null;attackingCellLat='';attackingCellLon='';return true;}
function doToolActionMechAttack(){if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
changeMapCursor('attack');if(crtClickedCellObj.polRel==POLREL_ME||crtClickedCellObj.polRel==POLREL_UNOWNED){return;}
if(attackingCellObj.polRel==POLREL_ME&&crtClickedCellObj.polRel==POLREL_ALLY){showMsg('Cannot attack confirmed allies !',5000,'yellow');return;}
var found=false;$.each(attackingCellObj.targetCellsA,function(index,value){if(crtClickedCellObj==objCache[value])found=true;});if(!found){showMsg('Target cell is out of range!',3000,'yellow');return;}
bcAjax(false,'bcsvr.php',{'do':'attack-cell-with-mech-unit','lat':crtClickedCellLat,'lon':crtClickedCellLon,'alat':attackingCellLat,'alon':attackingCellLon,'aimu':1},function(returnText){try{if(returnText.indexOf('ERROR')!=-1){showMsg(returnText,5000,'yellow');cancelSubActionGui();return;}
eval(returnText);if(typeof updCellA!='undefined'){deductCreditsFromCellA(updCellA,lastCellMoney,attackingCellObj,'whiteBorder');}
dCell=objCache[[crtClickedCellLat,crtClickedCellLon]];if(dCell!=null){dCell.troops=attackRes['D'];var theCellClass=calculateEnemyCellClass(dCell);dCell.theDivJq.addClass(theCellClass);dCell.cellClass=theCellClass;}
doOtherCanonAnimate(fromTopo(attackingCellLat)-cellDim/2,fromTopo(attackingCellLon)+cellDim/2,fromTopo(crtClickedCellLat)-cellDim/2,fromTopo(crtClickedCellLon)+cellDim/2,crtClickedCellLat,crtClickedCellLon,'cannonMe');showInfoPaneDetail(dCell);if(razed=='yes'){alert('removing structure');crtClickedCellObj.theDivJq.find(".cellBuilding").remove();crtClickedCellDataA['building']=0;}}catch(e){showMsg('error during attack; err='+e,3000,'red');cancelSubActionGui();}},null);}
function pickToolBankCollect(){if(currentTool=='bank-collect'){return;}
if(idUser==-1){showMsg('You must be logged in !',5000,'red');return;}
if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)){if(crtRClickedCellA.length>0){showMsg('Select only <b>one</b> cell with left mouse click',5000,'yellow');}else{showMsg('Select bank cell that will collect credits',5000,'yellow');}
cancelSubActionGui();return;}
if(crtClickedCellObj.polRel!=POLREL_ME){showMsg('Select a bank cell that you <b>own</b>',5000,'yellow');cancelSubActionGui();return;}
currentTool='bank-collect';setCrtConfirmAction(confirmToolCollectCredits);attackingCellObj=crtClickedCellObj;attackingCellObj.targetCellsA=calculateCellCoordsAroundPoint(crtClickedCellLat,crtClickedCellLon,crtClickedCellObj.radius);$.each(attackingCellObj.targetCellsA,function(index,value){cellObj=objCache[value];if(cellObj){cellObj.theDivJq.addClass('whiteBorder');}});}
function dropToolBankCollect(){if(currentTool!='bank-collect'){return;}
currentTool='';$.each(attackingCellObj.targetCellsA,function(index,value){cellObj=objCache[value];if(cellObj){cellObj.theDivJq.removeClass('whiteBorder');}});crtClickedCellDivStyle=crtClickedCellDivStyle.replace(/whiteBorder/,'');attackingCellObj=null;clearCrtConfirmAction();return true;}
function confirmToolCollectCredits(){if(idUser==-1){showMsg('You must be logged in !',5000,'red');return;}
if(isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)){showMsg('Select a bank cell !',5000,'yellow');cancelSubActionGui();return;}
var ajaxReqVars={'do':'collect-bank-credits','lat':crtClickedCellLat,'lon':crtClickedCellLon};bcAjax(false,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('ERROR')!=-1){showMsg(returnText,5000,'yellow');cancelSubActionGui();return;}
eval(returnText);if(typeof updCellA!='undefined'){deductCreditsFromCellA(updCellA,lastCellMoney,attackingCellObj,'whiteBorder');}
crtClickedCellObj.money=bankCellMoney;var theCellClass=calculateMyCellClass(crtClickedCellObj);crtClickedCellObj.cellClass=theCellClass;crtClickedCellDivStyle=theCellClass;showMsg('Deposited '+bankDeposit+' credits on bank cell',5000,'green');showInfoPaneDetail(crtClickedCellObj);cancelSubActionGui();}catch(e){reportAjaxError('confirmToolCollectCredits()',JSON.stringify(ajaxReqVars),returnText,e);cancelSubActionGui();}},null);}
function bcAjax(asyncFlag,url2Use,data2Send,successFunc,errorFunc){actionInProgress=true;$.ajax({async:asyncFlag,url:url2Use,type:'POST',data:data2Send,success:function(returnText){try{successFunc(returnText);}catch(e){}
actionInProgress=false;},error:function(xhrObj,textStatus,errorThrown){try{if($.isFunction(errorFunc)){errorFunc(xhrObj,textStatus,errorThrown);}
showMsg('bc exception='+textStatus+'; '+errorThrown,5000,'red');}catch(e){}
actionInProgress=false;},timeout:AJAX_TIMEOUT});}
function pickToolAcquireCell(){if(currentTool=='buy-cells'){return;}
if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)){showMsg('select cell to buy',5000,'yellow');cancelSubActionGui();return;}
if(crtClickedCellObj.polRel!=POLREL_UNOWNED){showMsg("you cannot buy this cell; already owned",5000,'yellow');cancelSubActionGui();return;}
if(!IS_ARENA){var ajaxReqVars={'do':'get-cell-price'};$.ajax({async:true,url:'bcsvr.php',type:'GET',data:ajaxReqVars,success:function(returnText){try{if(!isNaN(returnText)&&returnText.length<6){CELL_PRICE=returnText;}}catch(e){reportAjaxError('pickToolAcquireCell()',JSON.stringify(ajaxReqVars),returnText,e);}
if($$('#globalCredits').is(":checked")){$$('#cellPrice').html(CELL_PRICE_GC);}else if($$('#randomCell').is(":checked")||$$('#creditsFromThisCell').is(":checked")){var cPrice=CELL_PRICE;if(CELL_PRICE>9999){cPrice=$().number_format(CELL_PRICE/1000,{numberOfDecimals:1,symbol:'k'});}else if(CELL_PRICE>999){cPrice=$().number_format(CELL_PRICE);}
$$('#cellPrice').html(cPrice);}}});}
currentTool='buy-cells';setCrtConfirmAction(confirmToolAcquireCell);cell2AcquireLat=crtClickedCellLat;cell2AcquireLon=crtClickedCellLon;cell2AcquireObj=crtClickedCellObj;mapCenterWhenBuyingCell=map.getCenter();mapTopoCoordsWhenBuyingCell=getMapTopoCoords();cell2AcquireObj.theDivJq.addClass('crtCell');crtClickedCellObj=null;crtClickedCellLat='';crtClickedCellLon='';crtClickedCellDiv=null;enableObj('#acquireCellConfirmBut');}
function dropToolAcquireCell(){if(currentTool!='buy-cells'){return;}
currentTool='';if(cell2AcquireObj!=null){cell2AcquireObj.theDivJq.attr('class',CELLCLASS_UNOWNED);}
cell2AcquireLat='';cell2AcquireLon='';clearClickedCell();mapCenterWhenBuyingCell=null;mapTopoCoordsWhenBuyingCell=null;cell2AcquireObj=null;payingCellLat='';payingCellLon='';clearCrtConfirmAction();return true;}
function confirmToolAcquireCell(){var pay_type='';if(!$$('#randomCell').is(":checked")&&!$$('#creditsFromThisCell').is(":checked")&&!$$('#globalCredits').is(":checked")){showMsg("please select how to pay for this cell",5000,'yellow');return;}
if($$('#creditsFromThisCell').is(":checked")){if(crtClickedCellObj==null){if(IS_ARENA){showMsg("select <B>one</B> cell from which to pay",5000,'yellow');}else{showMsg("select your region from which to pay",5000,'yellow');}
return;}
if(crtClickedCellObj.polRel!=POLREL_ME){showMsg("you must select a cell you own !",5000,'yellow');return;}
if(crtClickedCellObj.money<CELL_BUY_COST){showMsg("not enough credits on this cell !",5000,'yellow');return;}
pay_type=$$('#creditsFromThisCell').val();var payingCellLat=crtClickedCellLat;var payingCellLon=crtClickedCellLon;}else if($$('#globalCredits').is(":checked")){pay_type=$$('#globalCredits').val();}else{pay_type=$$('#randomCell').val();}
disableObj('#acquireCellConfirmBut');showMsg('buying cell...',3000,'yellow');var ajaxReqVars={'do':'buy-cell','lat':cell2AcquireLat,'lon':cell2AcquireLon,'pay_type':pay_type,'creditsFromLat':payingCellLat,'creditsFromLon':payingCellLon,'latMin':mapTopoCoordsWhenBuyingCell[0],'latMax':mapTopoCoordsWhenBuyingCell[1],'lonMin':mapTopoCoordsWhenBuyingCell[2],'lonMax':mapTopoCoordsWhenBuyingCell[3]};bcAjax(false,'bcsvr.php',ajaxReqVars,function(returnText){try{var bcOpRetStatus='';eval(returnText);if(bcOpRetStatus!='SUCCESS'){showMsg('error buying cell ! '+bcOpRetStatus,5000,'red');}else{if(mapCenterWhenBuyingCell!=map.getCenter()){map.setCenter(mapCenterWhenBuyingCell);reloadCrtMapView();}else if(typeof updCellA!='undefined'){deductCreditsFromCellA(updCellA,lastCellMoney,false,'');}
if(pay_type=='random cell'){if(IS_ARENA){var cellObj=objCache[[randomCellLat,randomCellLon]];if(cellObj){cellObj.money-=CELL_BUY_COST;var theCellClass=calculateMyCellClass(cellObj);cellObj.theDivJq.attr('class',theCellClass);if(crtClickedCellObj==cellObj){crtClickedCellDivStyle=theCellClass;}}}else{if(crtClickedCellObj){$$('#cellDetailCredits').html(crtClickedCellObj.money+' ');}}}
if(pay_type=='cell I choose'){var cellObj=objCache[[payingCellLat,payingCellLon]];if(cellObj){if(IS_ARENA){cellObj.money-=CELL_BUY_COST;$$('#cellDetailCredits').html(cellObj.money+' ');var theCellClass=calculateMyCellClass(cellObj);cellObj.theDivJq.attr('class',theCellClass);if(crtClickedCellObj==cellObj){crtClickedCellDivStyle=theCellClass;}}else{$$('#cellDetailCredits').html(cellObj.money+' ');}}}
if(pay_type=='global credits'){if(gcBalance<50){playSound('tutorialA');showMsg(NOTICE_GC_LOW,10000,'tutAr');}}
if(objCache[[cell2AcquireLat,cell2AcquireLon]]){cell2AcquireObj.theDivJq.removeClass('crtCell');var theCellClass=calculateMyCellClass(cell2AcquireObj);cell2AcquireObj.theDivJq.attr('class',theCellClass);cell2AcquireObj.reFill(cell2AcquireObj.theBounds,theCellClass,0,0,cell2AcquireObj.alt,idUser,POLREL_ME,cell2AcquireObj.arrayPos);}
cell2AcquireObj=null;if(typeof buyCellNotice!='undefined'){showMsg(buyCellNotice,6000,'tutAr');playSound('tutorial');delete buyCellNotice;window.opener.getBankPaneDetails(-1);}else{showMsg('SUCCESS',3000,'green');}
cancelSubActionGui('AcquireCell');}}catch(e){reportAjaxError('confirmToolAcquireCell()',JSON.stringify(ajaxReqVars),returnText,e);cancelSubActionGui('AcquireCell');}
enableObj('#acquireCellConfirmBut');},function(xhrObj,textStatus,errorThrown){enableObj('#acquireCellConfirmBut');});}
function calculateMyCellClass(cellObj){var theCellClass='mine';if(cellObj!=null){if(crtMapView==BC_POL_VIEW_MAP){theCellClass=CELLCLASS_MINE;}else if(crtMapView==BC_ALT_VIEW_MAP){theCellClass=CELLCLASS_MINE;}else if(crtMapView==BC_MIL_VIEW_MAP){var troopsClassNb=0;var nbOfTroops=cellObj.troops;if(nbOfTroops<3){troopsClassNb=0;}else if(nbOfTroops<8){troopsClassNb=1;}else if(nbOfTroops<13){troopsClassNb=2;}else if(nbOfTroops<18){troopsClassNb=3;}else if(nbOfTroops<23){troopsClassNb=4;}else if(nbOfTroops<40){troopsClassNb=5;}else{troopsClassNb=6;}
theCellClass=CELLCLASS_MIL_MINE[troopsClassNb];}else if(crtMapView==BC_FIN_VIEW_MAP){var creditsClassNb=0;var nbOfCredits=cellObj.money;if(nbOfCredits<=2){creditsClassNb=0;}else if(nbOfCredits<=7){creditsClassNb=1;}else if(nbOfCredits<=10){creditsClassNb=2;}else if(nbOfCredits<=14){creditsClassNb=3;}else if(nbOfCredits<=18){creditsClassNb=4;}else if(nbOfCredits<=19){creditsClassNb=5;}else if(nbOfCredits<=29){creditsClassNb=6;}else{creditsClassNb=7;}
theCellClass=CELLCLASS_FIN_MINE[creditsClassNb];}}
return theCellClass;}
function calculateEnemyCellClass(cellObj){var theCellClass='e0';if(cellObj!=null){if(crtMapView==BC_POL_VIEW_MAP){theCellClass=udH[cellObj.idUser][1];}else if(crtMapView==BC_ALT_VIEW_MAP){}else if(crtMapView==BC_MIL_VIEW_MAP){var troopsClassNb=0;var nbOfTroops=cellObj.troops;if(nbOfTroops<3){troopsClassNb=0;}else if(nbOfTroops<8){troopsClassNb=1;}else if(nbOfTroops<13){troopsClassNb=2;}else if(nbOfTroops<18){troopsClassNb=3;}else if(nbOfTroops<23){troopsClassNb=4;}else if(nbOfTroops<40){troopsClassNb=5;}else{troopsClassNb=6;}
theCellClass=CELLCLASS_MIL_ENEMY[troopsClassNb];}else if(crtMapView==BC_FIN_VIEW_MAP){theCellClass=CELLCLASS_NEUTRAL;}}
return theCellClass;}
function calculateAllyCellClass(cellObj){var theCellClass='a0';if(cellObj!=null){if(crtMapView==BC_POL_VIEW_MAP){theCellClass=udH[cellObj.idUser][1];}else if(crtMapView==BC_ALT_VIEW_MAP){}else if(crtMapView==BC_MIL_VIEW_MAP){var troopsClassNb=0;var nbOfTroops=cellObj.troops;if(nbOfTroops<3){troopsClassNb=0;}else if(nbOfTroops<8){troopsClassNb=1;}else if(nbOfTroops<13){troopsClassNb=2;}else if(nbOfTroops<18){troopsClassNb=3;}else if(nbOfTroops<23){troopsClassNb=4;}else if(nbOfTroops<40){troopsClassNb=5;}else{troopsClassNb=6;}
theCellClass=CELLCLASS_MIL_ALLY[troopsClassNb];}else if(crtMapView==BC_FIN_VIEW_MAP){theCellClass=CELLCLASS_NEUTRAL;}}
return theCellClass;}
function calculateNeutralCellClass(cellObj){var theCellClass='n';if(cellObj!=null){if(crtMapView==BC_POL_VIEW_MAP){}else if(crtMapView==BC_ALT_VIEW_MAP){}else if(crtMapView==BC_MIL_VIEW_MAP){var troopsClassNb=0;var nbOfTroops=cellObj.troops;if(nbOfTroops<3){troopsClassNb=0;}else if(nbOfTroops<8){troopsClassNb=1;}else if(nbOfTroops<13){troopsClassNb=2;}else if(nbOfTroops<18){troopsClassNb=3;}else if(nbOfTroops<23){troopsClassNb=4;}else if(nbOfTroops<40){troopsClassNb=5;}else{troopsClassNb=6;}
theCellClass=CELLCLASS_MIL_NEUTRAL[troopsClassNb];}else if(crtMapView==BC_FIN_VIEW_MAP){theCellClass=CELLCLASS_NEUTRAL;}}
return theCellClass;}
function setCalculatedMyCellClass(cellObj){var theCellClass=calculateMyCellClass(cellObj);cellObj.theDivJq.attr('class',theCellClass);cellObj.cellClass=theCellClass;}
function setCalculatedEnemyCellClass(cellObj){var theCellClass=calculateEnemyCellClass(cellObj);cellObj.theDivJq.attr('class',theCellClass);cellObj.cellClass=theCellClass;}
srcShipCount=0;shipMoveSrcCellA=[];function pickToolShipMove(){if(currentTool=='ship-move'){return;}
if(idUser==-1){showMsg('You must be logged in !',5000,'red');return;}
if(!crtRClickedCellA.length){if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj.polRel!=POLREL_ME){showMsg("Select a cell you own",3000,'yellow');cancelSubActionGui();return;}
if(cias==null){cancelSubActionGui();return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("Cell is not shore !",3000,'yellow');cancelSubActionGui();return;}
srcShipCount=cias['cellDetailShips'];}else{shroopsA=getRClickedShroops();srcShipCount=(Math.max.apply(Math,shroopsA)/100)|0;}
if(srcShipCount<=0){showMsg("No ships on this cell !",3000,'yellow');cancelSubActionGui();return;}
$$('#shipOne2MoveCB').cbCheck(false);$$('#shipTwo2MoveCB').cbCheck(false);$$('#shipOneIconDiv').css('display','block');if(srcShipCount>=2){$$('#shipTwoIconDiv').css('display','block');}else{$$('#shipTwoIconDiv').css('display','none');}
currentTool='ship-move';setCrtConfirmAction(confirmToolShipMove);if(crtRClickedCellA.length){paintCrtCell('crtCell');shipMoveSrcCellLat='';shipMoveSrcCellLon='';shipMoveSrcCellObj=null;shipMoveSrcCellIdWater='';shipMoveSrcCellA=crtRClickedCellA.slice(0);crtRClickedCellA=[];$$('#shipOneTroops,#shipTwoTroops').val('--');}else{shipMoveSrcCellLat=crtClickedCellLat;shipMoveSrcCellLon=crtClickedCellLon;shipMoveSrcCellObj=crtClickedCellObj;shipMoveSrcCellIdWater=cias['cellDetailShoreIdWater'];mapCenterShipMoveSrc=map.getCenter();shipMoveSrcCellObj.theDivJq.addClass('crtCell');var troopsOnShips=cias['cellDetailTroopsOnShips'];if(troopsOnShips>MAX_TROOPS_ON_SHIP){$$('#shipOneTroops').val(MAX_TROOPS_ON_SHIP);troopsOnShips-=MAX_TROOPS_ON_SHIP;if(troopsOnShips>MAX_TROOPS_ON_SHIP){$$('#shipTwoTroops').val(MAX_TROOPS_ON_SHIP);}else{$$('#shipTwoTroops').val(troopsOnShips);}}else{$$('#shipOneTroops').val(troopsOnShips);$$('#shipTwoTroops').val(0);}}
crtClickedCellDiv=null;enableObj('#moveShipsConfirmBut');}
function dropToolShipMove(){if(currentTool!='ship-move'&&currentTool!='ship-commandeer'){return;}
currentTool='';if(shipMoveSrcCellObj!=null){shipMoveSrcCellObj.theDivJq.attr('class',shipMoveSrcCellObj.cellClass);}
paintLandCells();clearClickedCell();stopLassoTool();shipMoveSrcCellLat='';shipMoveSrcCellLon='';clearClickedCell();mapCenterShipMoveSrc=null;shipMoveSrcCellObj=null;shipMoveSrcCellIdWater='';shipMoveSrcCellA=[];clearCrtConfirmAction();return true;}
function confirmToolShipMove(){if(!shipMoveSrcCellA.length){if(crtClickedCellObj==null){showMsg("Click a cell !",3000,'yellow');return;}
if(crtClickedCellObj.polRel==POLREL_UNOWNED){showMsg("Click an owned cell !",3000,'yellow');return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("Click on a shore cell !",3000,'yellow');return;}
if(shipMoveSrcCellIdWater!=cias['cellDetailShoreIdWater']){showMsg("Different body waters !",3000,'yellow');return;}
if(shipMoveSrcCellLat==crtClickedCellLat&&shipMoveSrcCellLon==crtClickedCellLon){showMsg("Select destination shore",3000,'yellow');return;}}else{if(shipMoveSrcCellA.length&&(crtClickedCellObj==null&&!crtRClickedCellA.length)){showMsg("Select destination shore",3000,'yellow');return;}
shipMoveSrcCellLat='';shipMoveSrcCellLon='';for(var i in shipMoveSrcCellA){shipMoveSrcCellLat+=(i>0)?','+shipMoveSrcCellA[i]['lat']:shipMoveSrcCellA[i]['lat'];shipMoveSrcCellLon+=(i>0)?','+shipMoveSrcCellA[i]['lon']:shipMoveSrcCellA[i]['lon'];}}
var itemQty=0;if($$('#shipOne2MoveCB').cbIsOn()){itemQty+=100+((shipMoveSrcCellA.length)?10:($$('#shipOneTroops').val()-0));}
if($$('#shipTwo2MoveCB').cbIsOn()){itemQty+=100+((shipMoveSrcCellA.length)?10:($$('#shipTwoTroops').val()-0));}
if(!itemQty){showMsg("Which ship to move ?",3000,'yellow');return;}
if(crtRClickedCellA.length){crtClickedCellLat='';crtClickedCellLon='';for(var i in crtRClickedCellA){crtClickedCellLat+=(i>0)?','+crtRClickedCellA[i]['lat']:crtRClickedCellA[i]['lat'];crtClickedCellLon+=(i>0)?','+crtRClickedCellA[i]['lon']:crtRClickedCellA[i]['lon'];}}
disableObj('#moveShipsConfirmBut');showMsg('Moving ship(s)...',3000,'yellow');var ajaxReqVars={'do':'move-ships','olat':shipMoveSrcCellLat,'olon':shipMoveSrcCellLon,'dlat':crtClickedCellLat,'dlon':crtClickedCellLon,'grp_size':itemQty};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('SUCCESS')==-1&&returnText.indexOf('NOTICE')!=-1){showMsg(returnText,4000,'yellow');return;}
var bcOpRetStatus='';var mesgTxt='';var shipsA=[];eval(returnText);if(bcOpRetStatus=='SUCCESS'){showMsg(mesgTxt,3000,'green');scheduleMapViewRefresh();if(shipMoveSrcCellA.length>0){for(var i in shipMoveSrcCellA){if(shipsA[i]==0){updateCellShips(shipMoveSrcCellA[i]['lat'],shipMoveSrcCellA[i]['lon'],0);}}}else{if(srcShipCount==((itemQty/100)|0)){updateCellShips(shipMoveSrcCellLat,shipMoveSrcCellLon,0);}}}else if(mesgTxt.length){showMsg(mesgTxt,3000,'yellow');}else{reportAjaxError('confirmToolShipMove()',JSON.stringify(ajaxReqVars),returnText,'BCSVR ACTION FAILED: bcOpRetStatus != SUCCESS');}}catch(e){reportAjaxError('confirmToolShipMove()',JSON.stringify(ajaxReqVars),returnText,e);}
enableObj('#moveShipsConfirmBut');cancelSubActionGui();},function(xhrObj,textStatus,errorThrown){reportAjaxError('confirmToolShipMove()',JSON.stringify(ajaxReqVars),textStatus,errorThrown);enableObj('#moveShipsConfirmBut');});}
misTargCoord={};function pickToolStalkerLaser(){tb_remove(true);crtSubActionGui='StalkerLaser';$$('#subactionStalkerActionIconOn').css('display','block');$$('#subactionStalkerActionIconOff').css('display','none');misTargCoord={'lat':crtClickedCellLat,'lon':crtClickedCellLon};$('#subactionStalkerLaserLegendDiv').css('display','block');showMsg('Select launch complex and press [m] to launch.',5000,'green');}
function dropToolStalkerLaser(){misTargCoord={};}
stalkerOpTargCoord={};function pickToolStalkerCommandeer(){if(idUser==-1){showMsg('You must be logged in !',5000,'red');return;}
if(cias==null){cancelSubActionGui();return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("Cell is not shore !",3000,'yellow');cancelSubActionGui();return;}
if(cias==null||cias['cellDetailStalkers']==0){showMsg('There is no stalker on this cell.',4000,'yellow');cancelSubActionGui();return;}
srcShipCount=cias['cellDetailShips'];if(srcShipCount<=0){showMsg("No ships on this cell !",3000,'yellow');cancelSubActionGui();return;}
tb_remove(true);crtSubActionGui='StalkerCommandeer';$$('#subactionStalkerActionIconOn').css('display','block');$$('#subactionStalkerActionIconOff').css('display','none');$$('#subactionStalkerCommandeerLegendDiv').css('display','block');currentTool='ship-commandeer';setCrtConfirmAction(confirmToolStalkerCommandeer);shipMoveSrcCellLat=crtClickedCellLat;shipMoveSrcCellLon=crtClickedCellLon;shipMoveSrcCellObj=crtClickedCellObj;shipMoveSrcCellIdWater=cias['cellDetailShoreIdWater'];mapCenterShipMoveSrc=map.getCenter();shipMoveSrcCellObj.theDivJq.addClass('crtCell');crtClickedCellDiv=null;$$('#shipOneTroops').val((cias['cellDetailTroopsOnShips']>MAX_TROOPS_ON_SHIP)?MAX_TROOPS_ON_SHIP:cias['cellDetailTroopsOnShips']);enableObj('#commandeerShipsConfirmBut');}
function dropToolStalkerCommandeer(){$$('#subactionStalkerActionIconOn').css('display','none');if(crtActionGui=='Troop')$$('#subactionStalkerActionIconOff').css('display','block');dropToolShipMove();}
function confirmToolStalkerCommandeer(){if(crtClickedCellObj==null){showMsg("Click a cell !",3000,'yellow');return;}
if(crtClickedCellObj.polRel==POLREL_UNOWNED){showMsg("Click an owned cell !",3000,'yellow');return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("Click on a shore cell !",3000,'yellow');return;}
if(shipMoveSrcCellIdWater!=cias['cellDetailShoreIdWater']){showMsg("Different body waters !",3000,'yellow');return;}
if(shipMoveSrcCellLat==crtClickedCellLat&&shipMoveSrcCellLon==crtClickedCellLon){showMsg("Select destination shore",3000,'yellow');return;}
var itemQty=$$('#shipOneTroops').val()-0+100;disableObj('#stalkerCommandeerConfirmBut');showMsg('Commandeering ship...',3000,'yellow');var ajaxReqVars={'do':'commandeer-ship','olat':shipMoveSrcCellLat,'olon':shipMoveSrcCellLon,'dlat':crtClickedCellLat,'dlon':crtClickedCellLon,'grp_size':itemQty};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('SUCCESS')==-1&&returnText.indexOf('NOTICE')!=-1){showMsg(returnText,4000,'yellow');return;}
var bcOpRetStatus='';var mesgTxt='';var shipsA=[];eval(returnText);if(bcOpRetStatus=='SUCCESS'){showMsg(mesgTxt,3000,'green');scheduleMapViewRefresh();if(srcShipCount==1){updateCellShips(shipMoveSrcCellLat,shipMoveSrcCellLon,0);}
if(stalkerCntA[shipMoveSrcCellLat+','+shipMoveSrcCellLon]==0){updatecellStalkers(shipMoveSrcCellLat,shipMoveSrcCellLon,0,0);}}else{reportAjaxError('confirmToolStalkerCommandeer()',JSON.stringify(ajaxReqVars),returnText,'BCSVR ACTION FAILED: bcOpRetStatus != SUCCESS');}}catch(e){reportAjaxError('confirmToolStalkerCommandeer()',JSON.stringify(ajaxReqVars),returnText,e);}
enableObj('#stalkerCommandeerConfirmBut');cancelSubActionGui();},function(xhrObj,textStatus,errorThrown){reportAjaxError('confirmToolStalkerCommandeer()',JSON.stringify(ajaxReqVars),textStatus,errorThrown);enableObj('#stalkerCommandeerConfirmBut');});}
function pickToolAcquireItem(itemNm){if(currentTool=='buy-'+itemNm){return;}
currentTool='buy-'+itemNm;if(idUser==-1){showMsg('you must be logged in !',3000,'red');return;}
atLeastOneMine=false;if(crtRClickedCellA.length>0){for(var i in crtRClickedCellA){if(crtRClickedCellA[i]['obj'].polRel==POLREL_ME){atLeastOneMine=true;}}}
if((crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj.polRel!=POLREL_ME)&&(crtRClickedCellA.length==0||!atLeastOneMine||(itemNm!='troops'&&itemNm!='ships'))){if(crtRClickedCellA.length>0){showMsg("Select only <b>one</b> cell with left mouse click",3000,'yellow');}else{showMsg("Select a cell you own",3000,'yellow');}
cancelSubActionGui();return;}
if(itemNm=='ships'){if(cias==null){cancelSubActionGui();return;}
if($$('#cellDetailShore').html()!='yes'&&crtRClickedCellA.length==0){showMsg("Cell is not shore !",3000,'yellow');cancelSubActionGui();return;}}
if(itemNm=='missile'){if(cias==null){cancelSubActionGui();return;}
if(crtClickedCellObj.theDiv.innerHTML.indexOf(ULAUNCHCHAR)>-1){showMsg("Launch complex is under construction.",3000,'yellow');cancelSubActionGui();return;}
if(crtClickedCellObj.theDiv.innerHTML.indexOf(MISSILECHAR)>-1){showMsg("Cell already has a missile.",3000,'yellow');cancelSubActionGui();return;}
if(crtClickedCellObj.theDiv.innerHTML.indexOf(LAUNCHCHAR)==-1){showMsg("Missile requires launch complex on cell.",3000,'yellow');cancelSubActionGui();return;}}
$$('#'+itemNm+'AvailableSpin').val('');$$('#'+itemNm+'BoughtSpin').val('');setCrtSpinner($$('#'+itemNm+'AvailableSpin'),$$('#'+itemNm+'BoughtSpin'),function(){confirmToolAcquireItem(itemNm)});var availableItems2Buy=getMaxSpinAcquireItem(itemNm);$$('#'+itemNm+'AvailableSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#'+itemNm+'BoughtSpin').val('00');enableObj('#'+itemNm+'ConfirmBut');paintCrtCell('crtCell');}
function dropToolAcquireItem(itemNm){if(currentTool!='buy-'+itemNm){return;}
paintCrtCell('clear');currentTool='';clearCrtSpinner();return true;}
function doToolActionAcquireItem(itemNm){atLeastOneMine=false;if(crtRClickedCellA.length>0){for(var i in crtRClickedCellA){if(crtRClickedCellA[i]['obj'].polRel==POLREL_ME){atLeastOneMine=true;}}}
if((crtClickedCellObj==null||crtClickedCellObj.polRel!=POLREL_ME)&&(crtRClickedCellA.length==0||!atLeastOneMine||(itemNm!='troops'&&itemNm!='ships'))){showMsg("select a cell you own",3000,'yellow');$$('#'+itemNm+'AvailableSpin').val('');$$('#'+itemNm+'BoughtSpin').val('');disableObj('#'+itemNm+'ConfirmBut');return;}
if(itemNm=='ships'){if(cias==null&&!crtRClickedCellA.length){cancelSubActionGui();return;}
if((crtRClickedCellA.length==0||!atLeastOneMine)&&$$('#cellDetailShore').html()!='yes'){showMsg("cell is not shore !",3000,'yellow');disableObj('#'+itemNm+'ConfirmBut');return;}}
if(itemNm=='missile'){if(cias==null){cancelSubActionGui();return;}
if(crtClickedCellObj.theDiv.innerHTML.indexOf(ULAUNCHCHAR)>-1){showMsg("Launch complex is under construction.",3000,'yellow');disableObj('#'+itemNm+'ConfirmBut');return;}
if(crtClickedCellObj.theDiv.innerHTML.indexOf(MISSILECHAR)>-1){showMsg("Cell already has a missile.",3000,'yellow');disableObj('#'+itemNm+'ConfirmBut');return;}
if(crtClickedCellObj.theDiv.innerHTML.indexOf(LAUNCHCHAR)==-1){showMsg("Missile requires launch complex on cell.",3000,'yellow');disableObj('#'+itemNm+'ConfirmBut');return;}}
var availableItems2Buy=getMaxSpinAcquireItem(itemNm);$$('#'+itemNm+'AvailableSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#'+itemNm+'BoughtSpin').val('00');enableObj('#'+itemNm+'ConfirmBut');}
function confirmToolAcquireItem(itemNm){var itemQty=$$('#'+itemNm+'BoughtSpin').val();if(itemQty!='0'&&('|'+itemQty).indexOf('|0')!=-1){itemQty=itemQty.substring(1);}
itemQty=parseInt(itemQty);if(itemQty<=0){showMsg('How many '+itemNm+' to buy ?',3000,'yellow');return;}
disableObj('#'+itemNm+'ConfirmBut');var savedCellObj=null;var savedCellLat='';var savedCellLon='';var savedCellA=[];if(crtRClickedCellA.length){savedCellA=crtRClickedCellA.concat([]);for(var i in crtRClickedCellA){savedCellLat+=(i==0)?crtRClickedCellA[i]['lat']:','+crtRClickedCellA[i]['lat'];savedCellLon+=(i==0)?crtRClickedCellA[i]['lon']:','+crtRClickedCellA[i]['lon'];}
showMsg('Buying '+itemNm+' in <b>'+crtRClickedCellA.length+'</b> cells...',3000,'yellow');}else{savedCellObj=crtClickedCellObj;savedCellLat=crtClickedCellLat;savedCellLon=crtClickedCellLon;showMsg('Buying <b>'+itemQty+'</b> '+itemNm+'...',3000,'yellow');}
var ajaxReqVars={'do':'buy-item','itemNm':itemNm,'lat':savedCellLat,'lon':savedCellLon,'itemQty':itemQty};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{var bcOpRetStatus='';eval(returnText);if(bcOpRetStatus!='SUCCESS'){showMsg('error buying '+itemNm+'; '+bcOpRetStatus,3000,'red');}else{var itr_lat;var itr_lat_min=0;var itr_lat_max=0;var itr_lon;var itr_lon_min=0;var itr_lon_max=0;if(itemNm=='troops'){if(crtRClickedCellA.length>0){for(var i in savedCellA){if(objCache[[savedCellA[i]['lat'],savedCellA[i]['lon']]]){savedCellA[i]['obj'].troops=parseInt(savedCellA[i]['obj'].troops)+updCellsItemQtyA[i];savedCellA[i]['obj'].money-=(updCellsItemQtyA[i]*TROOP_BUY_COST);$$('#cellDetailCredits').html(savedCellA[i]['obj'].money+' ');}}}else{if(objCache[[savedCellLat,savedCellLon]]){savedCellObj.troops=parseInt(savedCellObj.troops)+itemQty;savedCellObj.money-=(itemQty*TROOP_BUY_COST);$$('#cellDetailCredits').html(savedCellObj.money+' ');}}
$$('#cellDetailTroops').html(parseInt($$('#cellDetailTroops').html())+itemQty);$$('#detailPlayerTotalTroops').html(parseInt($$('#detailPlayerTotalTroops').html())+itemQty);}else if(itemNm=='stalker'){if(objCache[[savedCellLat,savedCellLon]]){savedCellObj.money-=(itemQty*STALKER_COST);$$('#cellDetailCredits').html(' '+savedCellObj.money+' ');vicinityObj=objCache[[savedCellLat,savedCellLon]];vicinityObj.theDiv.innerHTML+='<span style="color:#000">'+STALKERCHAR+'</span>';}}else if(itemNm=='ships'){if(crtRClickedCellA.length>0){itemQty=0;for(var i in savedCellA){if(objCache[[savedCellA[i]['lat'],savedCellA[i]['lon']]]){savedCellA[i]['obj'].money-=(updCellsItemQtyA[i]*SHIP_BUY_COST);$$('#cellDetailCredits').html(savedCellA[i]['obj'].money+' ');itemQty+=updCellsItemQtyA[i]
if(updCellsItemQtyA[i]>0){updateCellShips(savedCellA[i]['lat'],savedCellA[i]['lon'],updCellsItemQtyA[i]);}}}
$$('#cellDetailShips').html((parseInt($$('#cellDetailShips').html())+itemQty>2)?2:parseInt($$('#cellDetailShips').html())+itemQty);$$('#detailPlayerTotalShips').html(parseInt($$('#detailPlayerTotalShips').html())+itemQty);}else{if(objCache[[savedCellLat,savedCellLon]]){savedCellObj.money-=(itemQty*SHIP_BUY_COST);$$('#cellDetailCredits').html(' '+savedCellObj.money+' ');updateCellShips(savedCellLat,savedCellLon,itemQty);}
$$('#cellDetailShips').html(parseInt($$('#cellDetailShips').html())+itemQty);$$('#detailPlayerTotalShips').html(parseInt($$('#detailPlayerTotalShips').html())+itemQty);}}else if(itemNm=='nukes'){if(objCache[[savedCellLat,savedCellLon]]){savedCellObj.money-=(itemQty*NUKE_BUY_COST);$$('#cellDetailCredits').html(' '+savedCellObj.money+' ');vicinityObj=objCache[[savedCellLat,savedCellLon]];vicinityObj.theDiv.innerHTML+=' N';}
$$('#cellDetailNuke').html('yes');}else if(itemNm=='launch'){var vicinityObj;itr_lat_min=-2;itr_lat_max=2;itr_lon_min=-2;itr_lon_max=2;for(itr_lat=itr_lat_min;itr_lat<=itr_lat_max;itr_lat++){for(itr_lon=itr_lon_min;itr_lon<=itr_lon_max;itr_lon++){if(objCache[[addLat(savedCellLat,itr_lat),addLon(savedCellLon,itr_lon)]]){vicinityObj=objCache[[addLat(savedCellLat,itr_lat),addLon(savedCellLon,itr_lon)]];vicinityObj.money=0;}}}
if(objCache[[savedCellLat,savedCellLon]]){$$('#cellDetailCredits').html('0 ');vicinityObj=objCache[[savedCellLat,savedCellLon]];vicinityObj.theDiv.innerHTML+=ULAUNCHCHAR;}}else if(itemNm=='missile'){var vicinityObj;itr_lat_min=-1;itr_lat_max=1;itr_lon_min=-1;itr_lon_max=1;for(itr_lat=itr_lat_min;itr_lat<=itr_lat_max;itr_lat++){for(itr_lon=itr_lon_min;itr_lon<=itr_lon_max;itr_lon++){if(objCache[[addLat(savedCellLat,itr_lat),addLon(savedCellLon,itr_lon)]]){vicinityObj=objCache[[addLat(savedCellLat,itr_lat),addLon(savedCellLon,itr_lon)]];vicinityObj.money=0;}}}
if(objCache[[savedCellLat,savedCellLon]]){$$('#cellDetailCredits').html('0 ');vicinityObj=objCache[[savedCellLat,savedCellLon]];vicinityObj.theDiv.innerHTML=vicinityObj.theDiv.innerHTML.replace(LAUNCHCHAR,MISSILECHAR);}}else if(itemNm=='fieldfort'){if(objCache[[savedCellLat,savedCellLon]]&&(infoA[objCache[[savedCellLat,savedCellLon]].arrayPos]&SET_FIELDFORT_MASK)==0){objCache[[savedCellLat,savedCellLon]].theDiv.innerHTML+=FIELDFORTBG;infoA[objCache[[savedCellLat,savedCellLon]].arrayPos]=infoA[objCache[[savedCellLat,savedCellLon]].arrayPos]|SET_FIELDFORT_MASK;}
if(typeof updCellA!='undefined'){deductCreditsFromCellA(updCellA,lastCellMoney,false,'');}}
var availableItems2Buy=getMaxSpinAcquireItem(itemNm);$$('#'+itemNm+'AvailableSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#'+itemNm+'BoughtSpin').val('00');if(crtRClickedCellA.length>0){for(var i in savedCellA){if(savedCellA[i]['obj'].polRel==POLREL_ME&&objCache[[savedCellA[i]['lat'],savedCellA[i]['lon']]]){vicinityObj=objCache[[savedCellA[i]['lat'],savedCellA[i]['lon']]];var theCellClass=calculateMyCellClass(savedCellA[i]['obj']);vicinityObj.cellClass=theCellClass;if(crtRClickedCellA[i]['obj']==vicinityObj){crtRClickedCellA[i]['style']=theCellClass;}else{vicinityObj.theDivJq.attr('class',theCellClass);}}}}else{for(itr_lat=itr_lat_min;itr_lat<=itr_lat_max;itr_lat++){for(itr_lon=itr_lon_min;itr_lon<=itr_lon_max;itr_lon++){if(objCache[[addLat(savedCellLat,itr_lat),addLon(savedCellLon,itr_lon)]]){vicinityObj=objCache[[addLat(savedCellLat,itr_lat),addLon(savedCellLon,itr_lon)]];var theCellClass=calculateMyCellClass(savedCellObj);vicinityObj.cellClass=theCellClass;if(crtClickedCellObj==vicinityObj){crtClickedCellDivStyle=theCellClass;}else{vicinityObj.theDivJq.attr('class',theCellClass);}}}}}
showMsg(bcOpRetStatus,3000,'green');}}catch(e){reportAjaxError('confirmToolAcquireItem()',JSON.stringify(ajaxReqVars),returnText,e);}
enableObj('#'+itemNm+'ConfirmBut');},function(xhrObj,textStatus,errorThrown){enableObj('#'+itemNm+'ConfirmBut');});}
function pickToolAcquireBuilding(){if(idUser==-1){showMsg('You must be logged in !',3000,'red');return;}
if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj.polRel!=POLREL_ME){if(crtRClickedCellA.length>0){showMsg("Select only <b>one</b> cell with left mouse click",3000,'yellow');}else{showMsg("Select a cell you own",3000,'yellow');}
cancelSubActionGui();return;}
curMapCenter=map.getCenter();var zoom=map.getZoom();var RATIO=(zoom>11)?1/Math.pow(2,zoom-11):Math.pow(2,11-zoom);var panAmt=(TUTYPE==1)?11:12;map.setCenter(new GLatLng(curMapCenter.lat(),fromTopo(addLon(crtClickedCellLon,panAmt*RATIO))));scheduleMapViewRefresh();$$(".cellBuild1,.cellBuild,.cellBuildNoUpgrade").css("display","none");var tabsItemsJqObj=$$("#buildCityTab,#buildMilTab,#buildEconTab,#buildIntelTab,.cellBuildItm");tabsItemsJqObj.css("display","none");tb_remove(true);$("#buildingLink").click();if(crtClickedCellDataA['building']==0){$$(".cellBuild1").css("display","inline");tabsItemsJqObj.css("display","block");}else if(crtClickedCellDataA['building']<3){$$("#buildMilTab,#cellBuildBunk").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);$$("#bunk"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==3){$$("#buildMilTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(4<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<6){$$("#buildMilTab,#cellBuildTrainCamp").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);$$("#traincamp"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==6){$$("#buildMilTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(7<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<9){$$("#buildMilTab,#cellBuildCannon").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);$$("#cannon"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==9){$$("#buildMilTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(crtClickedCellDataA['building']==10){$$("#buildMilTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(11<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<19){$$("#buildEconTab,#cellBuildFactory").css("display","block");$("#buildingTabDiv > ul").tabs("select",2);$$("#factory"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==19){$$("#buildEconTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(21<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<23){$$("#buildIntelTab,#cellBuildSurveillance").css("display","block");$("#buildingTabDiv > ul").tabs("select",3);$$("#surveillance"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==23){$$("#buildIntelTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",3);}else if(24<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<26){$$("#buildMilTab,#cellBuildAntiMissile").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);$$("#antimissile"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==26){$$("#buildMilTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(27<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<29){$$("#buildEconTab,#cellBuildBank").css("display","block");$("#buildingTabDiv > ul").tabs("select",2);$$("#bank"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==29){$$("#buildEconTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",2);}else if(31<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<33){$$("#buildMilTab,#cellBuildNukeDepot").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);$$("#nukedepot"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==33){$$("#buildMilTab,.cellBuildNoUpgrade").css("display","block");$("#buildingTabDiv > ul").tabs("select",1);}else if(34<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<36){$$("#buildCityTab,#cellBuildCity").css("display","block");$("#buildingTabDiv > ul").tabs("select",0);$$("#city"+(crtClickedCellDataA['building']-0+1)).css("display","inline");}else if(crtClickedCellDataA['building']==36){$$("#buildCityTab,#cellBuildCity").css("display","block");$("#buildingTabDiv > ul").tabs("select",0);$$("#city"+(crtClickedCellDataA['building'])).css("display","inline");}else if(37<=crtClickedCellDataA['building']&&crtClickedCellDataA['building']<39){$$("#buildCityTab,#cellBuildCity").css("display","block");$("#buildingTabDiv > ul").tabs("select",0);$$("#city"+(crtClickedCellDataA['building']-2)).css("display","inline");}else if(crtClickedCellDataA['building']==39){$$("#buildCityTab,#cellBuildCity").css("display","block");$("#buildingTabDiv > ul").tabs("select",0);$$("#city"+(crtClickedCellDataA['building'])).css("display","inline");}
$("#scroll-paneCITY").jScrollPane({showArrows:false,scrollbarWidth:10,scrollbarMargin:8});dropToolOnTBClose=true;}
function confirmToolAcquireBuilding(buildingType){if(crtClickedCellObj==null){showMsg('Select a cell you own !',5000,'yellow');tb_remove();return;}
if(buildingType=='city34'||buildingType=='city35'||buildingType=='city36'){tb_remove();cancelActionGui();showCellCity();return;}
var mapTopoCoordsWhenBuilding=getMapTopoCoords();var ajaxReqVars={'do':'build-building','bType':buildingType,'pay_type':$("#build1 .buildingPaySelect").val(),'lat':crtClickedCellLat,'lon':crtClickedCellLon,'latMin':mapTopoCoordsWhenBuilding[0],'latMax':mapTopoCoordsWhenBuilding[1],'lonMin':mapTopoCoordsWhenBuilding[2],'lonMax':mapTopoCoordsWhenBuilding[3]};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{eval(returnText)
if(returnText.indexOf('SUCCESS')==-1){showMsg('BUILD FAILURE: '+bcOpRetStatus,5000,'yellow');}else{crtClickedCellObj.theDivJq.find(".cellBuilding").remove();crtClickedCellObj.theDivJq.append(buildingTmplJqObjA[newBuildingType].clone());crtClickedCellDataA['building']=newBuildingType;if(11<=newBuildingType&&newBuildingType<=19){$$('#cellDetailProdRate').html(parseInt($$('#cellDetailProdRate').text())+1);}
if(typeof updCellA!='undefined'){deductCreditsFromCellA(updCellA,lastCellMoney,false,'');}
if($("#build1 .buildingPaySelect").val()==1){window.opener.getBankPaneDetails(-1);if(gcBalance<50){playSound('tutorialA');showMsg(NOTICE_GC_LOW,10000,'tutAr');}}
showMsg("Upgrade Successful!",3000,'green');}}catch(e){reportAjaxError('confirmToolAcquireBuilding()',JSON.stringify(ajaxReqVars),returnText,e);}},null);tb_remove();}
function deductCreditsFromCellA(updCellA,lastCellMoney,doNotToTouchCellObj,optionalExtraClass){for(elPos in updCellA){if(objCache[[updCellA[elPos][0],updCellA[elPos][1]]]){vicinityObj=objCache[[updCellA[elPos][0],updCellA[elPos][1]]];vicinityObj.money=(elPos==updCellA.length-1)?lastCellMoney:0;var theCellClass=calculateMyCellClass(vicinityObj);if(vicinityObj!=doNotToTouchCellObj){vicinityObj.cellClass=theCellClass;if(crtClickedCellObj==vicinityObj){crtClickedCellDivStyle=theCellClass;if(optionalExtraClass.length){crtClickedCellDivStyle+=' '+optionalExtraClass;}}else{vicinityObj.theDivJq.attr('class',theCellClass)
if(optionalExtraClass.length){vicinityObj.theDivJq.addClass(optionalExtraClass);}}}}}}
function pickToolGAcquireItem(itemNm){if(currentTool=='buy-gc-'+itemNm){return;}
currentTool='buy-gc-'+itemNm;if(idUser==-1){showMsg('You must be logged in !',3000,'red');return;}
if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj.polRel!=POLREL_ME){if(crtRClickedCellA.length>0){showMsg("Select only <b>one</b> cell with left mouse click",3000,'yellow');}else{showMsg("Select a cell you own",3000,'yellow');}
cancelSubActionGui();return;}
if(itemNm=='ships'){if(cias==null){cancelSubActionGui();return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("cell is not shore !",3000,'yellow');cancelSubActionGui();return;}}
$$('#'+itemNm+'GAvailableSpin').val('');$$('#'+itemNm+'GBoughtSpin').val('');setCrtSpinner($$('#'+itemNm+'GAvailableSpin'),$$('#'+itemNm+'GBoughtSpin'),function(){confirmToolGAcquireItem(itemNm)});var availableItems2Buy=getMaxSpinGAcquireItem(itemNm);$$('#'+itemNm+'GAvailableSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#'+itemNm+'GBoughtSpin').val('00');enableObj('#'+itemNm+'GConfirmBut');paintCrtCell('crtCell');}
function dropToolGAcquireItem(itemNm){if(currentTool!='buy-gc-'+itemNm){return;}
paintCrtCell('clear');currentTool='';clearCrtSpinner();return true;}
function doToolActionGAcquireItem(itemNm){if(crtClickedCellObj==null||crtClickedCellObj.polRel!=POLREL_ME){if(crtRClickedCellA.length>0){showMsg("Select only <b>one</b> cell with left mouse click",3000,'yellow');}else{showMsg("Select a cell you own",3000,'yellow');}
$$('#'+itemNm+'GAvailableSpin').val('');$$('#'+itemNm+'GBoughtSpin').val('');disableObj('#'+itemNm+'GConfirmBut');return;}
if(itemNm=='ships'){if(cias==null){cancelSubActionGui();return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("Cell is not shore !",3000,'yellow');disableObj('#'+itemNm+'GConfirmBut');return;}}
var availableItems2Buy=getMaxSpinGAcquireItem(itemNm);$$('#'+itemNm+'GAvailableSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#'+itemNm+'GBoughtSpin').val('00');enableObj('#'+itemNm+'GConfirmBut');}
function confirmToolGAcquireItem(itemNm){var itemQty=$$('#'+itemNm+'GBoughtSpin').val();if(itemQty!='0'&&('|'+itemQty).indexOf('|0')!=-1){itemQty=itemQty.substring(1);}
itemQty=parseInt(itemQty);if(itemQty<=0){showMsg('How many '+itemNm+' to buy ?',3000,'yellow');return;}
showMsg('Buying '+itemQty+' '+itemNm+' with global credits',3000,'yellow');disableObj('#'+itemNm+'GConfirmBut');var savedCellObj=crtClickedCellObj;var savedCellLat=crtClickedCellLat;var savedCellLon=crtClickedCellLon;bcAjax(true,'bcsvr.php',{'do':'buy-gc-item','itemNm':itemNm,'lat':savedCellLat,'lon':savedCellLon,'itemQty':itemQty},function(returnText){try{var bcOpRetStatus='';eval(returnText);if(bcOpRetStatus!='SUCCESS'){showMsg('error buying '+itemNm+' with global credits; '+bcOpRetStatus,3000,'red');}else{if(itemNm=='troops'){if(objCache[[savedCellLat,savedCellLon]]){savedCellObj.troops=parseInt(savedCellObj.troops)+itemQty;}
$$('#detailPlayerTotalGCredits').html(parseInt($$('#detailPlayerTotalGCredits').html())-itemQty*TROOP_BUY_COST);$$('#cellDetailTroops').html(parseInt($$('#cellDetailTroops').html())+itemQty);$$('#detailPlayerTotalTroops').html(parseInt($$('#detailPlayerTotalTroops').html())+itemQty);}
if(itemNm=='ships'){$$('#detailPlayerTotalGCredits').html(parseInt($$('#detailPlayerTotalGCredits').html())-itemQty*SHIP_BUY_COST);$$('#cellDetailShips').html(parseInt($$('#cellDetailShips').html())+itemQty);$$('#detailPlayerTotalShips').html(parseInt($$('#detailPlayerTotalShips').html())+itemQty);updateCellShips(savedCellLat,savedCellLon,itemQty);}
if(itemNm=='nukes'){$$('#detailPlayerTotalGCredits').html(parseInt($$('#detailPlayerTotalGCredits').html())-itemQty*NUKE_BUY_COST);$$('#cellDetailNuke').html('yes');if(objCache[[savedCellLat,savedCellLon]]){vicinityObj=objCache[[savedCellLat,savedCellLon]];vicinityObj.theDiv.innerHTML+=' N';}}
if($$('#detailPlayerTotalGCredits').text()<50){playSound('tutorialA');showMsg(NOTICE_GC_LOW,10000,'tutAr');}
var availableItems2Buy=getMaxSpinGAcquireItem(itemNm);$$('#'+itemNm+'GAvailableSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#'+itemNm+'GBoughtSpin').val('00');if(objCache[[savedCellLat,savedCellLon]]){var theCellClass=calculateMyCellClass(savedCellObj);savedCellObj.cellClass=theCellClass;if(crtClickedCellObj==savedCellObj){crtClickedCellDivStyle=theCellClass;}else{savedCellObj.theDivJq.attr('class',theCellClass);}}
showMsg(bcOpRetStatus,3000,'green');}}catch(e){showMsg('error buying '+itemNm+' with global credits; err='+e,5000,'red');}
enableObj('#'+itemNm+'GConfirmBut');},function(xhrObj,textStatus,errorThrown){enableObj('#'+itemNm+'GConfirmBut');});}
var shroopsA=[];function pickToolShipLoad(){if(currentTool=='ship-load'){return;}
currentTool='ship-load';if(idUser==-1){showMsg('you must be logged in !',3000,'red');return;}
if(cias==null&&!crtRClickedCellA.length){cancelSubActionGui();return;}
if(crtRClickedCellA.length==0){if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj.polRel!=POLREL_ME){showMsg("select a cell you own",3000,'yellow');cancelSubActionGui();return;}
if($$('#cellDetailShore').html()!='yes'){showMsg("cell is not shore !",3000,'yellow');cancelSubActionGui();return;}
if(parseInt($$('#cellDetailShips').html())<=0){showMsg("no ships on this cell !",3000,'yellow');cancelSubActionGui();return;}}
$$('#troopsAvail2LoadInShipSpin').val('');$$('#troops2BLoadedInShipSpin').val('');setCrtSpinner($$('#troopsAvail2LoadInShipSpin'),$$('#troops2BLoadedInShipSpin'),function(){confirmToolShipLoad()});if(crtRClickedCellA.length>0){shroopsA=getRClickedShroops();totAvailableItems2Buy=0;for(var i in crtRClickedCellA){var shipsOnCell=((shroopsA[i]/100)|0);var maxTroopsOnAllShips=shipsOnCell*MAX_TROOPS_ON_SHIP;var troopsOnCell=parseInt(crtRClickedCellA[i]['obj'].troops);var troopsAlreadyOnShips=shroopsA[i]%100;var availableItems2Buy=Math.min(maxTroopsOnAllShips-troopsAlreadyOnShips,troopsOnCell);if(totAvailableItems2Buy<availableItems2Buy+troopsAlreadyOnShips){totAvailableItems2Buy=availableItems2Buy+troopsAlreadyOnShips;}}
$$('#troopsAvail2LoadInShipSpin').val(((totAvailableItems2Buy<10)?'0'+totAvailableItems2Buy:totAvailableItems2Buy));$$('#troops2BLoadedInShipSpin').val('00');}else{var shipsOnCell=parseInt($$('#cellDetailShips').html());var maxTroopsOnAllShips=shipsOnCell*MAX_TROOPS_ON_SHIP;var troopsOnCell=parseInt(crtClickedCellObj.troops);var troopsAlreadyOnShips=parseInt($$('#cellDetailTroopsOnShips').html());var availableItems2Buy=Math.min(maxTroopsOnAllShips-troopsAlreadyOnShips,troopsOnCell);$$('#troopsAvail2LoadInShipSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#troops2BLoadedInShipSpin').val(((troopsAlreadyOnShips<10)?'0'+troopsAlreadyOnShips:troopsAlreadyOnShips));}
enableObj('#loadShipConfirmBut');paintCrtCell('crtCell');}
function getRClickedShroops(){if(!crtRClickedCellA.length){showMsg('ERROR: multiple-selected cell array is empty!',2000,'red');return;}
srcCellLat='';srcCellLon='';for(var i in crtRClickedCellA){srcCellLat+=(i>0)?','+crtRClickedCellA[i]['lat']:crtRClickedCellA[i]['lat'];srcCellLon+=(i>0)?','+crtRClickedCellA[i]['lon']:crtRClickedCellA[i]['lon'];}
var ajaxReqVars={'do':'get-shroops','lat':srcCellLat,'lon':srcCellLon};bcAjax(false,'bcsvr.php',ajaxReqVars,function(returnText){try{eval(returnText);}catch(e){reportAjaxError('getRClickedShroops()',JSON.stringify(ajaxReqVars),returnText,e);}},function(xhrObj,textStatus,errorThrown){});return shroopsA;}
function dropToolShipLoad(){if(currentTool!='ship-load'){return;}
paintCrtCell('clear');currentTool='';clearCrtSpinner();return true;}
function doToolActionShipLoad(){if(cias==null){cancelSubActionGui();return;}
if(crtRClickedCellA.length>0){totAvailableItems2Buy=0;for(var i in crtRClickedCellA){var shipsOnCell=((shroopsA[i]/100)|0);var maxTroopsOnAllShips=shipsOnCell*MAX_TROOPS_ON_SHIP;var troopsOnCell=parseInt(crtRClickedCellA[i]['obj'].troops);var troopsAlreadyOnShips=shroopsA[i]%100;var availableItems2Buy=Math.min(maxTroopsOnAllShips-troopsAlreadyOnShips,troopsOnCell);if(totAvailableItems2Buy<availableItems2Buy+troopsAlreadyOnShips){totAvailableItems2Buy=availableItems2Buy+troopsAlreadyOnShips;}}
$$('#troopsAvail2LoadInShipSpin').val(((totAvailableItems2Buy<10)?'0'+totAvailableItems2Buy:totAvailableItems2Buy));$$('#troops2BLoadedInShipSpin').val('00');}else{if(crtClickedCellObj==null||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj.polRel!=POLREL_ME){showMsg("select a cell you own",3000,'yellow');$$('#troopsAvail2LoadInShipSpin').val('');$$('#troops2BLoadedInShipSpin').val('');disableObj('#loadShipConfirmBut');return;}
if(isNaN($$('#cellDetailShips').html())||parseInt($$('#cellDetailShips').html())<=0){showMsg("no ships on this cell !",3000,'yellow');$$('#troopsAvail2LoadInShipSpin').val('');$$('#troops2BLoadedInShipSpin').val('');disableObj('#loadShipConfirmBut');return;}
var shipsOnCell=parseInt($$('#cellDetailShips').html());var maxTroopsOnAllShips=shipsOnCell*MAX_TROOPS_ON_SHIP;var troopsOnCell=parseInt(crtClickedCellObj.troops);var troopsAlreadyOnShips=parseInt($$('#cellDetailTroopsOnShips').html());var availableItems2Buy=Math.min(maxTroopsOnAllShips-troopsAlreadyOnShips,troopsOnCell);$$('#troopsAvail2LoadInShipSpin').val(((availableItems2Buy<10)?'0'+availableItems2Buy:availableItems2Buy));$$('#troops2BLoadedInShipSpin').val(((troopsAlreadyOnShips<10)?'0'+troopsAlreadyOnShips:troopsAlreadyOnShips));}
enableObj('#loadShipConfirmBut');}
function confirmToolShipLoad(){var itemQty=$$('#troops2BLoadedInShipSpin').val();if(itemQty!='0'&&('|'+itemQty).indexOf('|0')!=-1){itemQty=itemQty.substring(1);}
itemQty=parseInt(itemQty);if(isNaN(itemQty)){itemQty=0;}
var troopsAlreadyOnShips=parseInt($$('#cellDetailTroopsOnShips').html());if(crtRClickedCellA.length==0){if(troopsAlreadyOnShips==itemQty){showMsg('Troop counts remain unchanged.',3000,'yellow');return;}}
var shipAction='Load';if(itemQty<troopsAlreadyOnShips){shipAction='Unload';showMsg(shipAction+'ing '+(troopsAlreadyOnShips-itemQty)+' troops...',3000,'yellow');}else{showMsg(shipAction+'ing '+(itemQty-troopsAlreadyOnShips)+' troops...',3000,'yellow');}
disableObj('#loadShipConfirmBut');rClicked=0;if(crtRClickedCellA.length){rClicked=1;luClickedCellLat='';luClickedCellLon='';for(var i in crtRClickedCellA){luClickedCellLat+=(i==0)?crtRClickedCellA[i]['lat']:','+crtRClickedCellA[i]['lat'];luClickedCellLon+=(i==0)?crtRClickedCellA[i]['lon']:','+crtRClickedCellA[i]['lon'];}}else{luClickedCellLat=crtClickedCellLat;luClickedCellLon=crtClickedCellLon;}
var ajaxReqVars={'do':'ship-load-unload','lat':luClickedCellLat,'lon':luClickedCellLon,'itemQty':itemQty,'rclicked':rClicked};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('SUCCESS')==-1&&returnText.indexOf('NOTICE')!=-1){showMsg(returnText,4000,'yellow');return;}
eval(returnText);var theCellClass=null;if(crtRClickedCellA.length){$$('#cellDetailTroops').html('-- ');$$('#cellDetailTroopsOnShips').html('-- ');var cellObj=null;for(var i in crtRClickedCellA){cellObj=objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]];if(cellObj){cellObj.troops=troopsOnCell[i];theCellClass=calculateMyCellClass(cellObj);cellObj.cellClass=theCellClass;}}
stopLassoTool();}else{crtClickedCellObj.troops=troopsOnCell[0];$$('#cellDetailTroops').html(troopsOnCell[0]+' ');$$('#cellDetailTroopsOnShips').html(troopsOnShips[0]+' ');theCellClass=calculateMyCellClass(crtClickedCellObj);crtClickedCellObj.cellClass=theCellClass;crtClickedCellDivStyle=theCellClass;}
showMsg(shipAction+'ing complete',3000,'green');}catch(e){reportAjaxError('confirmToolShipLoad()',JSON.stringify(ajaxReqVars),returnText,e);}
enableObj('#loadShipConfirmBut');cancelSubActionGui();},function(xhrObj,textStatus,errorThrown){enableObj('#loadShipConfirmBut');});}
function repaintCrtMapView(){clearClickedCell();clearCrtRClickedCellA();var topoCoords=getMapTopoCoords();topoCoords.push(true);queueReq(topoCoords);startloaderLoop();cancelSubActionGui('');return false;}
function reloadCrtMapView(){clearClickedCell();clearMapAndCache();clearCrtRClickedCellA();scheduleMapViewRefresh();cancelSubActionGui('');return false;}
function clearMapAndCache(){for(key in objCache){var x=objCache[key];map.removeOverlay(x);x.theDiv.innerHTML='';CellPool.returnObj(x);delete objCache[key];}
objCache={};removePolylinePaths();}
function toggleDetailsPane(){if($$('#detailsPane').css('width')=='0px'){$$('#detailsPane').css('width','145px');$$('#detailsPane').css('display','block');var mapW=parseInt($$('#mapDiv').css('width'));$$('#mapDiv').css('width',(mapW-145)+'px');map.checkResize();queueReq(getMapTopoCoords());}else{$$('#detailsPane').css('width','0px');$$('#detailsPane').css('display','none');var mapW=parseInt($$('#mapDiv').css('width'));$$('#mapDiv').css('width',(mapW+145)+'px');map.checkResize();queueReq(getMapTopoCoords());}}
function showMsg2(){if(arguments.length<3){return};var txt="";for(var i=2;i<arguments.length;i++){txt+=arguments[i]+'_';}
showMsg(txt,arguments[0],arguments[1]);}
function latLonDistance(lat1,lon1,lat2,lon2){rad=0.0174532925;lon1*=rad;lat1*=rad;lon2*=rad;lat2*=rad;dist=Math.acos(Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1));if(dist<0){dist+=3.14159265;}
dist*=6378.137;return dist;}
origPathView=false;function pickToolMoveTroops(requestedTool){if(currentTool=='move-troops'||currentTool=='move-stalker'){return;}
if(idUser==-1){showMsg('You must be logged in !',5000,'yellow');return;}
if((isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)||crtClickedCellObj==null)&&crtRClickedCellA.length==0){showMsg('Select cell you own as origin',5000,'yellow');cancelSubActionGui();return;}
if(crtClickedCellObj!=null&&crtClickedCellObj.polRel!=POLREL_ME&&cias['cellDetailStalkers']==0){showMsg('Select cell you own as origin',5000,'yellow');cancelSubActionGui();return;}
if($$('#transitPathsWithCellsIconOn').css('display')=='none'){origPathView=false;}else{origPathView=true;showPathsWithCells(false);}
paintCrtCell('crtCell');if(crtRClickedCellA.length>0){moveOriginCellA=crtRClickedCellA.slice(0);crtRClickedCellA=[];}else{moveOriginCellLat=crtClickedCellLat;moveOriginCellLon=crtClickedCellLon;moveOriginCellObj=crtClickedCellObj;moveOriginCellTroops=moveOriginCellObj.troops;}
dbPathTopoLatA=[];dbPathTopoLonA=[];moveDestCellLat='';moveDestCellLon='';if(cias!=null&&cias['cellDetailStalkers']>0&&moveOriginCellA.length==0&&(moveOriginCellTroops==0||moveOriginCellObj.polRel!=POLREL_ME)){$$('.subactionTroopMoveLegendSelImg').css("background-position","-13px -20px");$$('#sTMLSt, #sTMLSs').css('display','none');currentTool='move-stalker';}else{if(cias==null||cias['cellDetailStalkers']==0||moveOriginCellA.length){$$('.subactionTroopMoveLegendSelImg').css("background-position","18px 0px");$$('#sTMLSt, #sTMLSs').css('display','none');currentTool='move-troops';}else{currentTool=requestedTool;if(currentTool=='move-troops'){$$('.subactionTroopMoveLegendSelImg').css("background-position","0px 0px");$$('#sTMLSt').css('display','none');$$('#sTMLSs').css('display','block');}else{$$('.subactionTroopMoveLegendSelImg').css("background-position","0px -20px");$$('#sTMLSt').css('display','block');$$('#sTMLSs').css('display','none');}}}
var availTroops2Move=(currentTool=='move-troops')?getMaxSpinMoveTroops():cias['cellDetailStalkers'];$$('#avail2MoveTroopsSpin').val('');$$('#wished2MoveTroopsSpin').val('');setCrtSpinner($$('#avail2MoveTroopsSpin'),$$('#wished2MoveTroopsSpin'),function(){confirmToolMoveTroops()});$$('#avail2MoveTroopsSpin').val(((availTroops2Move<10)?'0'+availTroops2Move:availTroops2Move));$$('#wished2MoveTroopsSpin').val('00');enableObj('#moveTroopsConfirmBut');}
function switchToolMoveTroops(utype){if(utype==0){$$('.subactionTroopMoveLegendSelImg').css("background-position","0px 0px");currentTool='move-troops';$$('#sTMLSt').css('display','none');$$('#sTMLSs').css('display','block');var availTroops2Move=getMaxSpinMoveTroops();}else if(utype==2){$$('.subactionTroopMoveLegendSelImg').css("background-position","0px -20px");currentTool='move-stalker';$$('#sTMLSt').css('display','block');$$('#sTMLSs').css('display','none');var availTroops2Move=cias['cellDetailStalkers'];}
$$('#avail2MoveTroopsSpin').val(((availTroops2Move<10)?'0'+availTroops2Move:availTroops2Move));$$('#wished2MoveTroopsSpin').val('00');if(moveOriginCellLat!=crtClickedCellLat&&moveOriginCellLon!=crtClickedCellLon){doToolActionMoveTroops(crtClickedCellLat,crtClickedCellLon,crtRClickedCellA);}}
function dropToolMoveTroops(){if(currentTool!='move-troops'&&currentTool!='move-stalker'){return;}
currentTool='';paintLandCells();clearClickedCell();stopLassoTool();moveOriginCellLat='';moveOriginCellLon='';moveOriginCellObj=null;moveDestCellLat='';moveDestCellLon='';moveOriginCellTroops=0;moveOriginCellA=[];clearCrtSpinner();if(origPathView){showPathsWithCells(true);}
return true;}
function doToolActionMoveTroops(dlat,dlon,moveDestCellA){if(moveDestCellA.length){if(currentTool=='move-stalker'){paintCellsOnMap('clear',pathTopoLatA,pathTopoLonA);paintCellsOnMap('crtCell',[moveOriginCellLat],[moveOriginCellLon]);showMsg('Stalker supports only single destination.',3000,'yellow');return;}}else if((crtClickedCellObj.polRel!=POLREL_ME&&crtClickedCellObj.polRel!=POLREL_ALLY&&currentTool!='move-stalker')||crtClickedCellObj.polRel==POLREL_UNOWNED){paintCellsOnMap('clear',pathTopoLatA,pathTopoLonA);var cellObj=objCache[[moveOriginCellLat,moveOriginCellLon]];if(cellObj){cellObj.theDivJq.attr('class','crtCell');}
showMsg('Invalid destination !',2000,'yellow');return;}
etaMsg='Troops ETA: ';if(currentTool=='move-stalker'){vsDest=false;itr_lat_min=-1;itr_lat_max=1;itr_lon_min=-1;itr_lon_max=1;for(itr_lat=itr_lat_min;itr_lat<=itr_lat_max;itr_lat++){for(itr_lon=itr_lon_min;itr_lon<=itr_lon_max;itr_lon++){if(dlat==addLat(moveOriginCellLat,itr_lat)&&dlon==addLon(moveOriginCellLon,itr_lon)){vsDest=true;}}}
if(!vsDest&&$.inArray(3,ACTIVE_UPGRADES_A)==-1){showMsg('Stalker destination must be adjacent cell!',5000,'yellow');showMsg('Get the inertial navigation upgrade for extended stalker movement.',7000,'tut');return;}
etaMsg='Stalker ETA: ';}
var distBetweenCells=0;if(moveOriginCellA.length>0){if(moveDestCellA.length){for(var i in moveOriginCellA){for(var j in moveDestCellA){tmpDist=latLonDistance(fromTopo(moveOriginCellA[i]['lat']),fromTopo(moveOriginCellA[i]['lon']),fromTopo(moveDestCellA[j]['lat']),fromTopo(moveDestCellA[j]['lon']));if(tmpDist>distBetweenCells){distBetweenCells=tmpDist;}}}}else{for(var i in moveOriginCellA){tmpDist=latLonDistance(fromTopo(moveOriginCellA[i]['lat']),fromTopo(moveOriginCellA[i]['lon']),fromTopo(dlat),fromTopo(dlon));if(tmpDist>distBetweenCells){distBetweenCells=tmpDist;}}}}else{if(moveDestCellA.length){for(var j in moveDestCellA){tmpDist=latLonDistance(fromTopo(moveOriginCellLat),fromTopo(moveOriginCellLon),fromTopo(moveDestCellA[j]['lat']),fromTopo(moveDestCellA[j]['lon']));if(tmpDist>distBetweenCells){distBetweenCells=tmpDist;}}}else{distBetweenCells=latLonDistance(fromTopo(moveOriginCellLat),fromTopo(moveOriginCellLon),fromTopo(dlat),fromTopo(dlon));}}
if(distBetweenCells>TROOP_MOVE_MAX_ALLOWED_DISTANCE){showMsg('Destination too far. max is '+TROOP_MOVE_MAX_ALLOWED_DISTANCE+' km ! ',3000,'yellow');return;}
showMsg('Calculating shortest path...',1000,'yellow');if(moveOriginCellA.length>0){moveOriginCellLat='';moveOriginCellLon='';for(var i in moveOriginCellA){moveOriginCellLat+=(i==0)?moveOriginCellA[i]['lat']:','+moveOriginCellA[i]['lat'];moveOriginCellLon+=(i==0)?moveOriginCellA[i]['lon']:','+moveOriginCellA[i]['lon'];}}
if(moveDestCellA.length){dlat='';dlon='';for(var i in moveDestCellA){dlat+=(i==0)?moveDestCellA[i]['lat']:','+moveDestCellA[i]['lat'];dlon+=(i==0)?moveDestCellA[i]['lon']:','+moveDestCellA[i]['lon'];}}
var ajaxReqVars={'do':currentTool,'mode':'preview','olat':moveOriginCellLat,'olon':moveOriginCellLon,'dlat':dlat,'dlon':dlon};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{paintCellsOnMap('clear',pathTopoLatA,pathTopoLonA);pathTopoLatA=[];try{eval(returnText);}catch(e){showMsg(returnText,4000,'yellow');return;}
if(pathTopoLatA.length==0){showMsg('No valid path found...',4000,'yellow');moveDestCellLat='';moveDestCellLon='';return;}
paintCellsOnMap('path_preview',pathTopoLatA,pathTopoLonA);moveDestCellLat=dlat;moveDestCellLon=dlon;showMsg(etaMsg+troopsMoveETA,3000,'yellow');if(allyTranText!=''){showMsg(allyTranText,5000,'yellow');}}catch(e){reportAjaxError('doToolActionMoveTroops()',JSON.stringify(ajaxReqVars),returnText,e);cancelSubActionGui('TroopMove');}},null);}
function confirmToolMoveTroops(){if(crtRClickedCellA.length){}else{if((crtClickedCellObj.polRel!=POLREL_ME&&crtClickedCellObj.polRel!=POLREL_ALLY&&currentTool!='move-stalker')||crtClickedCellObj.polRel==POLREL_UNOWNED){showMsg('Invalid destination !',2000,'yellow');return;}
if(isNaN(moveDestCellLon)||isNaN(moveDestCellLat)){showMsg('Select destination cell first',2000,'yellow');return;}}
var itemQty=$$('#wished2MoveTroopsSpin').val();if(itemQty!='0'&&('|'+itemQty).indexOf('|0')!=-1){itemQty=itemQty.substring(1);}
itemQty=parseInt(itemQty);if(itemQty<=0){showMsg('How many units to move ?',3000,'yellow');return;}
disableObj('#moveTroopsConfirmBut');var ajaxReqVars={'do':currentTool,'mode':'execute','olat':moveOriginCellLat,'olon':moveOriginCellLon,'dlat':moveDestCellLat,'dlon':moveDestCellLon,'grp_size':itemQty};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){if(currentTool=='move-troops'){if(moveOriginCellA.length>0){for(var i in moveOriginCellA){if((infoA[moveOriginCellA[i]['obj'].arrayPos]&SET_FIELDFORT_MASK)==0){moveOriginCellA[i]['obj'].troops=Math.max(parseInt(moveOriginCellA[i]['obj'].troops)-itemQty,0);var theCellClass=calculateMyCellClass(moveOriginCellA[i]['obj']);moveOriginCellA[i]['style']=theCellClass;}}}else{moveOriginCellObj.troops=parseInt(moveOriginCellObj.troops)-itemQty;var theCellClass=calculateMyCellClass(moveOriginCellObj);moveOriginCellObj.theDivJq.addClass(theCellClass);moveOriginCellObj.cellClass=theCellClass;}
showMsg('troops marching !',3000,'green');scheduleMapViewRefresh();}else if(currentTool=='move-stalker'){showMsg('stalker moving !',3000,'green');}
if(moveOriginCellA.length>0){clearCrtRClickedCellA();}
cancelSubActionGui();}else{showMsg('error creating path ! '+returnText,5000,'red');}}catch(e){reportAjaxError('confirmToolMoveTroops()',JSON.stringify(ajaxReqVars),returnText,e);}
enableObj('#moveTroopsConfirmBut');},function(xhrObj,textStatus,errorThrown){enableObj('#moveTroopsConfirmBut');});if(origPathView){showPathsWithCells(true);}}
function paintCellsOnMap(mode,pathTopoLatA,pathTopoLonA){if(mode=='clear'){for(var i=0;i<pathTopoLatA.length;i++){var cellObj=objCache[[pathTopoLatA[i],pathTopoLonA[i]]];if(cellObj){cellObj.theDiv.className=cellObj.cellClass;}}
return;}
if(mode=='clear-text'){for(var i=0;i<pathTopoLatA.length;i++){var cellObj=objCache[[pathTopoLatA[i],pathTopoLonA[i]]];if(cellObj){cellObj.theDiv.innerHTML='';}}
return;}
for(var i=0;i<pathTopoLatA.length;i++){var cellObj=objCache[[pathTopoLatA[i],pathTopoLonA[i]]];if(cellObj){cellObj.theDiv.className=mode;}}
return;}
function paintPathsCrtPositions(){for(var key in dbPathsH){var pathInfoA=dbPathsH[key];var cellObj=objCache[[pathInfoA[0],pathInfoA[1]]];if(cellObj){cellObj.theDiv.className='dbpath_crtpos';cellObj.theDiv.innerHTML+='&nbsp;'+pathInfoA[2]+'<br>';}}}
function removePolylinePaths(){for(var key in polylineCache){map.removeOverlay(polylineCache[key]);}}
function paintPolylinePaths(pathTopoLatA,pathTopoLonA,cellInfoA){removePolylinePaths();var polyLines={};var polyOpt={clickable:false};for(var i=0;i<pathTopoLatA.length;i++){var cellObj=objCache[[pathTopoLatA[i],pathTopoLonA[i]]];if(cellObj){var plPoints=polyLines[cellInfoA[i]];if(!plPoints){plPoints=[];polyLines[cellInfoA[i]]=plPoints;}
plPoints.push(cellObj.theBounds.getCenter());}}
var nbOfColors=pathPolyLineColors.length;for(var key in polyLines){var plPoints=polyLines[key];if(plPoints.length>0){var polyWidth=dbPathsH[key][2];polyWidth=polyWidth?polyWidth:2;polyWidth=(polyWidth>15)?15:polyWidth;var polyColor='#282828';var polyOpacity=1;if(dbPathsH[key][3]!=0){polyColor=pathPolyLineColorsShip;polyOpacity=1;}
var polyline=new GPolyline(plPoints,polyColor,polyWidth,polyOpacity,polyOpt);map.addOverlay(polyline);polylineCache[key]=polyline;}}}
function paintCrtCell(mode){if(mode=='clear'){if(crtClickedCellObj!=null){crtClickedCellObj.theDivJq.removeClass('crtCell');crtClickedCellObj.theDiv.className=crtClickedCellObj.cellClass;}
if(crtRClickedCellA.length>0){for(var i in crtRClickedCellA){if(objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]]){crtRClickedCellA[i]['obj']=objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]];crtRClickedCellA[i]['obj'].theDivJq.removeClass('crtCell');}}}
return;}
if(mode=='crtCell'){if(crtClickedCellObj!=null){crtClickedCellObj.theDivJq.addClass('crtCell');}
if(crtRClickedCellA.length>0){for(var i in crtRClickedCellA){if(objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]]){crtRClickedCellA[i]['obj']=objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]];crtRClickedCellA[i]['obj'].theDivJq.addClass('crtCell');}}}
return;}
if(crtClickedCellObj!=null){crtClickedCellObj.theDiv.className=mode;}}
function showPathsWithCells(onOff){if(onOff){$$('#transitPathsWithCellsIconOff').css('display','none');$$('#transitPathsWithCellsIconOn').css('display','block');showPaths=true;if(showIndividualPath){showIndividualPath=false;paintCellsOnMap('clear',dbPathTopoLatA,dbPathTopoLonA);paintCellsOnMap('clear-text',dbPathTopoLatA,dbPathTopoLonA);}
showPathsUsingCells=true;scheduleMapViewRefresh();try{startAbgLoop4Paths();}catch(ex){}}else{$$('#transitPathsWithCellsIconOff').css('display','block');$$('#transitPathsWithCellsIconOn').css('display','none');if(!showPathsUsingPolylines){showPaths=false;}
showPathsUsingCells=false;paintCellsOnMap('clear',dbPathTopoLatA,dbPathTopoLonA);paintCellsOnMap('clear-text',dbPathTopoLatA,dbPathTopoLonA);scheduleMapViewRefresh();}}
function showPathsWithPolyLines(onOff){if(onOff){$$('#transitPathsWithPolyLinesIconOff').css('display','none');$$('#transitPathsWithPolyLinesIconOn').css('display','block');showPaths=true;if(showIndividualPath){showIndividualPath=false;removePolylinePaths();}
showPathsUsingPolylines=true;scheduleMapViewRefresh();}else{$$('#transitPathsWithPolyLinesIconOff').css('display','block');$$('#transitPathsWithPolyLinesIconOn').css('display','none');if(!showPathsUsingCells){showPaths=false;}
showPathsUsingPolylines=false;removePolylinePaths();scheduleMapViewRefresh();}}
function setShowUnownedCells(onOff){if(onOff){$$('#unownedCellsOff').css('display','none');$$('#unownedCellsOn').css('display','block');showUnownedCells=true;scheduleMapViewRefresh();}else{$$('#unownedCellsOff').css('display','block');$$('#unownedCellsOn').css('display','none');showUnownedCells=false;reloadCrtMapView();}}
function toggleUnowned(){if(isChecked('showUnownedCB')){showUnownedCells=true;scheduleMapViewRefresh();}else{showUnownedCells=false;reloadCrtMapView();}}
function scheduleMapViewRefresh(){queueReq(getMapTopoCoords());startloaderLoop();}
function accoClosedTrooptTransit(){paintCellsOnMap('clear',dbPathTopoLatA,dbPathTopoLonA);paintCellsOnMap('clear-text',dbPathTopoLatA,dbPathTopoLonA);removePolylinePaths();showIndividualPath=false;dbPathTopoLatA={};dbPathTopoLonA={};}
function doToggleSound(){if(playSounds){playSounds=false;$('#soundIconOff').css('display','block');$('#soundIconOn').css('display','none');if(typeof window.opener!='undefined'&&typeof window.opener.playBgSound!='undefined'){window.opener.playSounds=false;window.opener.playBgSound(0);}}else{playSounds=true;$('#soundIconOff').css('display','none');$('#soundIconOn').css('display','block');if(typeof window.opener!='undefined'&&typeof window.opener.playBgSound!='undefined'){window.opener.playSounds=true;window.opener.playBgSound(window.opener.bg_sound_level);}}}
var playSounds=true;var SOUNDS={};SOUNDS['message_recv']={'v4':"/jwc/sounds/message_recv.swf",'v5':{'id':'snd_msgrecv','fn':"/jwc/sounds/message_recv.ogg",'fn2':"/jwc/sounds/message_recv.mp3"}};SOUNDS['message_queue']={'v4':"/jwc/sounds/message_queue.swf",'v5':{'id':'snd_msgqueue','fn':"/jwc/sounds/message_queue.ogg",'fn2':"/jwc/sounds/message_queue.mp3"}};SOUNDS['chat_recv']={'v4':"/jwc/sounds/chat_recv.swf",'v5':{'id':'snd_chatrecv','fn':"/jwc/sounds/chat_recv.ogg",'fn2':"/jwc/sounds/chat_recv.mp3"}};SOUNDS['chat_queue']={'v4':"/jwc/sounds/chat_queue.swf",'v5':{'id':'snd_chatqueue','fn':"/jwc/sounds/chat_queue.ogg",'fn2':"/jwc/sounds/chat_queue.mp3"}};SOUNDS['online']={'v4':"/jwc/sounds/online.swf",'v5':{'id':'snd_online','fn':"/jwc/sounds/online.ogg",'fn2':"/jwc/sounds/online.mp3"}};SOUNDS['offline']={'v4':"/jwc/sounds/offline.swf",'v5':{'id':'snd_offline','fn':"/jwc/sounds/offline.ogg",'fn2':"/jwc/sounds/offline.mp3"}};SOUNDS['tutorial']={'v4':"/jwc/sounds/tut.swf",'v5':{'id':'snd_tutorial','fn':"/jwc/sounds/tut.ogg",'fn2':"/jwc/sounds/tut.mp3"}};SOUNDS['tutorialA']={'v4':"/jwc/sounds/tutA.swf",'v5':{'id':'snd_tutorialA','fn':"/jwc/sounds/tutA.ogg",'fn2':"/jwc/sounds/tutA.mp3"}};SOUNDS['startup']={'v4':"/jwc/sounds/startup.swf",'v5':{'id':'snd_startup','fn':"/jwc/sounds/startup.ogg",'fn2':"/jwc/sounds/startup.mp3"}};SOUNDS['connected']={'v4':"/jwc/sounds/connected.swf",'v5':{'id':'snd_startup','fn':"/jwc/sounds/connected.ogg",'fn2':"/jwc/sounds/connected.mp3"}};SOUNDS['telemetry']={'v4':"/sounds/telemetry.swf",'v5':{'id':'snd_telemetry','fn':"/sounds/telemetry.ogg",'fn2':"/sounds/telemetry.mp3"}};SOUNDS['mLaunch']={'v4':"/sounds/missileLaunch.swf",'v5':{'id':'snd_mLaunch','fn':"/sounds/missileLaunch.ogg",'fn2':"/sounds/missileLaunch.mp3"}};SOUNDS['mTrack']={'v4':"/sounds/missileTrack.swf",'v5':{'id':'snd_mTrack','fn':"/sounds/missileTrack.ogg",'fn2':"/sounds/missileTrack.mp3"}};SOUNDS['mStrike']={'v4':"/sounds/missileStrike.swf",'v5':{'id':'snd_mStrike','fn':"/sounds/missileStrike.ogg",'fn2':"/sounds/missileStrike.mp3"}};SOUNDS['mStrikeF']={'v4':"/sounds/missileStrikeFail.swf",'v5':{'id':'snd_mStrikeF','fn':"/sounds/missileStrikeFail.ogg",'fn2':"/sounds/missileStrikeFail.mp3"}};SOUNDS['invalid']={'v4':"/sounds/invalid.swf",'v5':{'id':'snd_invalid','fn':"/sounds/invalid.ogg",'fn2':"/sounds/invalid.mp3"}};SOUNDS['zoom']={'v4':"/sounds/zoom.swf",'v5':{'id':'snd_zoom','fn':"/sounds/zoom.ogg",'fn2':"/sounds/zoom.mp3"}};SOUNDS['gameStart']={'v4':"/sounds/gameStart.swf",'v5':{'id':'snd_gameStart','fn':"/sounds/gameStart.ogg",'fn2':"/sounds/gameStart.mp3"}};SOUNDS['gameEnd']={'v4':"/sounds/gameStart.swf",'v5':{'id':'snd_gameEnd','fn':"/sounds/gameStart.ogg",'fn2':"/sounds/gameStart.mp3"}};SOUNDS['wonCell']={'v4':"/sounds/wonCell.swf",'v5':{'id':'snd_wonCell','fn':"/sounds/wonCell.ogg",'fn2':"/sounds/wonCell.mp3"}};SOUNDS['lostCell']={'v4':"/sounds/lostCell.swf",'v5':{'id':'snd_lostCell','fn':"/sounds/lostCell.ogg",'fn2':"/sounds/lostCell.mp3"}};SOUNDS['nuked']={'v4':"/sounds/nuked.swf",'v5':{'id':'snd_nuked','fn':"/sounds/nuked.ogg",'fn2':"/sounds/nuked.mp3"}};SOUNDS['joined']={'v4':"/sounds/joined.swf",'v5':{'id':'snd_joined','fn':"/sounds/joined.ogg",'fn2':"/sounds/joined.mp3"}};SOUNDS['left']={'v4':"/sounds/left.swf",'v5':{'id':'snd_left','fn':"/sounds/left.ogg",'fn2':"/sounds/left.mp3"}};SOUNDS['groupMsg']={'v4':"/sounds/groupMsg.swf",'v5':{'id':'snd_groupMsg','fn':"/sounds/groupMsg.ogg",'fn2':"/sounds/groupMsg.mp3"}};SOUNDS['attack']={'v4':"/sounds/attack.swf",'v5':{'id':'snd_attack','fn':"/sounds/attack.ogg",'fn2':"/sounds/attack.mp3"}};SOUNDS['attackL']={'v4':"/sounds/attack.swf",'v5':{'id':'snd_attackL','fn':"/sounds/attack.ogg",'fn2':"/sounds/attack.mp3"}};SOUNDS['cannonMe']={'v4':"/sounds/cannonMe.swf",'v5':{'id':'snd_cannonMe','fn':"/sounds/cannonMe.ogg",'fn2':"/sounds/cannonMe.mp3"}};SOUNDS['cannonOtr']={'v4':"/sounds/cannonOther.swf",'v5':{'id':'snd_cannonOtr','fn':"/sounds/cannonOther.ogg",'fn2':"/sounds/cannonOther.mp3"}};SOUNDS['bomber1']={'v4':"/sounds/bomberAirp.swf",'v5':{'id':'snd_b1','fn':"/sounds/bomberAirp.ogg",'fn2':"/sounds/bomberAirp.mp3"}};SOUNDS['bomber2']={'v4':"/sounds/bomberCheck.swf",'v5':{'id':'snd_b2','fn':"/sounds/bomberCheck.ogg",'fn2':"/sounds/bomberCheck.mp3"}};SOUNDS['bomber3']={'v4':"/sounds/bomberDistant.swf",'v5':{'id':'snd_b3','fn':"/sounds/bomberDistant.ogg",'fn2':"/sounds/bomberDistant.mp3"}};SOUNDS['bomberAtt']={'v4':"/sounds/bomberAttack.swf",'v5':{'id':'snd_bomberAtt','fn':"/sounds/bomberAttack.ogg",'fn2':"/sounds/bomberAttack.mp3"}};SOUNDS['bomberAtt2']={'v4':"/sounds/bomberAttDist.swf",'v5':{'id':'snd_bomberAtt2','fn':"/sounds/bomberAttDist.ogg",'fn2':"/sounds/bomberAttDist.mp3"}};SOUNDS['confirm']={'v4':"/sounds/moveConfirm.swf",'v5':{'id':'snd_confirm','fn':"/sounds/moveConfirm.ogg",'fn2':"/sounds/moveConfirm.mp3"}};var soundPlaying=false;var soundPlaying2=false;var soundActiveA=[];function soundLoaded(){soundPlaying=false;for(var action in SOUNDS){soundActiveA[action]=false;}}
function supports_video(){return!!document.createElement('video').canPlayType;}
function supports_h264_baseline_video(){if(!supports_video()){return false;}
var v=document.createElement("video");return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');}
function supports_ogg_theora_video(){if(!supports_video()){return false;}
var v=document.createElement("video");return v.canPlayType('video/ogg; codecs="theora, vorbis"');}
function playSound(action){if(!playSounds){return;}
if(!SOUNDS[action]){return;}
if(soundPlaying){return;}
if(soundActiveA[SOUNDS[action]['v5']['id']]){if(SOUNDS[action]['v5']['obj']&&SOUNDS[action]['v5']['obj'].volume==0){SOUNDS[action]['v5']['obj'].volume=1;}
return;}
if(!supp_h264&&!supp_ogg){var sndFn=SOUNDS[action]['v4'];soundPlaying=true;var frameD=frames["mainmap_sound"].document;var html="<embed src=\""+sndFn+"\" width=\"1\" height=\"1\" quality=\"high\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\">";frameD.open();frameD.write(html);frameD.close();}else{try{soundPlaying=true;soundActiveA[SOUNDS[action]['v5']['id']]=true;var audioObj=SOUNDS[action]['v5']['obj'];if(audioObj!=null){audioObj.play();}else{var audioFn=(supp_h264)?SOUNDS[action]['v5']['fn2']:SOUNDS[action]['v5']['fn'];var audioObj=new Audio(audioFn);audioObj.setAttribute('id',SOUNDS[action]['v5']['id']);audioObj.addEventListener('ended',function(){soundActiveA[this.id]=false;},false);SOUNDS[action]['v5']['obj']=audioObj;audioObj.play();}}catch(e){}
soundPlaying=false;}}
function stopSound(action){if(!SOUNDS[action]){return;}
if(!soundPlaying&&!soundActiveA[SOUNDS[action]['v5']['id']]){return;}
if(!supp_h264&&!supp_ogg){var frameD=frames["mainmap_sound"].document;frameD.open();frameD.write('');frameD.close();}else{var audioObj=SOUNDS[action]['v5']['obj'];if(audioObj!=null){audioObj.pause();try{audioObj.currentTime=0;}catch(e){}
soundActiveA[SOUNDS[action]['v5']['id']]=false;}}}
var supp_h264=false;var supp_ogg=false;var soundPosNmA=[];function loadNextSound(pos){if(SOUNDS[soundPosNmA[pos]]['v5']['obj']){if(pos+1<soundPosNmA.length){loadNextSound(pos+1);}
return;}else{var audioFn=(supp_h264)?SOUNDS[soundPosNmA[pos]]['v5']['fn2']:SOUNDS[soundPosNmA[pos]]['v5']['fn'];var audioObj=new Audio(audioFn);SOUNDS[soundPosNmA[pos]]['v5']['obj']=audioObj;}
audioObj.setAttribute('id',SOUNDS[soundPosNmA[pos]]['v5']['id']);$(audioObj).data('pos',pos);audioObj.addEventListener('ended',function(){soundActiveA[this.id]=false;this.volume=1;var nextPos=$(this).data('pos')+1;$(this).removeData('pos');if(nextPos<soundPosNmA.length){loadNextSound(nextPos);}},false);soundActiveA[audioObj.id]=true;audioObj.volume=0;audioObj.play();}
function preloadSounds(){supp_h264=supports_h264_baseline_video();supp_ogg=supports_ogg_theora_video();if(navigator.userAgent.indexOf('Safari')!=-1&&navigator.userAgent.indexOf('Chrome')==-1){playSounds=false;return;}
if(!supp_h264&&!supp_ogg){return;}
for(var action in SOUNDS){soundPosNmA.push(action);}
loadNextSound(0);}
function showMsg(txt,lifeTime,bkg){if(bkg=='aqua'&&$.cookie('hideInvites')==1){return;}
$$('#showMsgDiv').jGrowl(txt,{theme:bkg,life:lifeTime});}
var globalCredits=0;function getPlayerGc(playerId,callback){bcAjax(false,'/bcsvr.php',{'do':'get-hq-bank'},function(returnText){if(returnText.length>0){try{contentA=JSON.parse(returnText);globalCredits=contentA['numericGc'];if(callback)callback();}catch(e){}}},null);}
function typeit(msg2Type,targetElement,callback){var appendChar,count=0,maxspeed=50;function character(start,end,text){return msg2Type.substring(start,end);}
function typer(){appendChar=character(count,++count,msg2Type);if(appendChar=='~'){stopSound('telemetry');setTimeout(function(){playSound('telemetry');typer();},500);}else{targetElement.append(appendChar);if(count<msg2Type.length){setTimeout(typer,~~(Math.random()*maxspeed));}else{stopSound('telemetry');if(callback)callback();}}}
playSound('telemetry');typer();}
var TUTSTEPS=[[0,1,2,3,4,5,6,7,8,9,10],[0,1,2,3,4,5,6,7,8,9,10]];var TUTSTEPREV=[[0,1,2,3,4,5,6,7,8,9,10],[0,1,2,3,4,5,6,7,8,9,10]];function tut(stepNb,prevStep){if(IS_ARENA){return;}
if(typeof crtTutStep=='undefined'){if(TSTEP<=0){crtTutStep=0;}else{crtTutStep=TSTEP;}}
if(prevStep==1){stepNb=TUTSTEPREV[TUTYPE][stepNb];}else{stepNb=TUTSTEPS[TUTYPE][stepNb];}
$('#tutorialBack,#tutorialNext,#tutorialEnd').css('display','none');$('.tutorialAux').remove();if(stepNb==0){$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');typeit(TR_TUT_STEP0,$("#tutorialMsg"),function(){playSound('tutorialA');$('#tutorialNext').css('display','block');});}
if(stepNb==1){$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');typeit(TR_TUT_STEP1,$("#tutorialMsg"),function(){$('body').append(TR_TUT_STEP1A);playSound('tutorialA');$('#tutorialBack,#tutorialNext').css('display','block');});updateTutStep(stepNb);}
if(stepNb==2){showMapViewGui('Mil',false);$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');typeit(TR_TUT_STEP2,$("#tutorialMsg"),function(){$('body').append(TR_TUT_STEP2A);playSound('tutorialA');$('#tutorialBack,#tutorialNext').css('display','block');});updateTutStep(stepNb);}
if(stepNb==3){$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');$$("#detailsAccordion").accordion('activate',0);setTimeout(function(){$$("#detailsAccordion").accordion('activate',3);},4000);typeit(TR_TUT_STEP3,$("#tutorialMsg"),function(){$$("#detailsAccordion").accordion('activate',1);$('body').append(TR_TUT_STEP3A);playSound('tutorialA');$('#tutorialBack,#tutorialNext').css('display','block');});updateTutStep(stepNb);}
if(stepNb==4){$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);cancelSubActionGui();cancelActionGui();playSound('message_recv');typeit(TR_TUT_STEP4,$("#tutorialMsg"),function(){$('body').append(TR_TUT_STEP4A);playSound('tutorialA');$('#tutorialBack,#tutorialNext').css('display','block');});updateTutStep(stepNb);getPlayerGc(idUser);}
if(stepNb==5){$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');typeit(TR_TUT_STEP5.replace(/XX/,globalCredits),$("#tutorialMsg"),function(){$('body').append(TR_TUT_STEP5A);playSound('tutorialA');$('#tutorialBack,#tutorialNext').css('display','block');});updateTutStep(stepNb);}
if(stepNb==6){$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');typeit(TR_TUT_STEP6.replace(/XX/,globalCredits),$("#tutorialMsg"),function(){if(!chatShown){showActionGui('Chat');}
$('body').append(TR_TUT_STEP6A);playSound('tutorialA');$('#tutorialBack,#tutorialNext').css('display','block');});updateTutStep(stepNb);}
if(stepNb==7){if(crtSubActionGui!=''){cancelSubActionGui(crtSubActionGui);}
if(crtActionGui!=''){cancelActionGui(crtActionGui);}
$$("#tutorialMsgBubble").css('display','none');$$("#tutorialMsg").html('<b>INBOUND MESSAGE:</b> ');$$("#tutorialMsgBubble").fadeIn(100);playSound('message_recv');typeit(TR_TUT_STEP7.replace(/XX/,globalCredits),$("#tutorialMsg"),function(){$$("#tutorialMsg").append(' &nbsp; &nbsp; <B>::TRANSMISSION END::</B>');playSound('tutorialA');$('#tutorialBack,#tutorialEnd').css('display','block');});updateTutStep(stepNb);}
if(stepNb==8){updateTutStep(stepNb);}}
function updateTutStep(nextStep){var ajaxReqVars={'do':'update-tut-step','nextStep':nextStep};$.ajax({async:false,url:'/bcsvr.php',type:'GET',data:ajaxReqVars,success:function(returnText){try{if(returnText.indexOf('SUCCESS')==-1){reportAjaxError('updateTutStep()',JSON.stringify(ajaxReqVars),returnText,'');}}catch(e){reportAjaxError('updateTutStep()',JSON.stringify(ajaxReqVars),returnText,e);}},error:function(xhrObj,textStatus,errorThrown){reportAjaxError('updateTutStep()',JSON.stringify(ajaxReqVars),errorThrown,textStatus);}});}
function getInvitesCount(){var totalInvites=0;$.ajax({async:false,url:'/bcsvr.php',type:'POST',data:{'do':'get-invites-count'},success:function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){var idx=returnText.indexOf('<sep>');if(idx!=-1){var jsRetStr=returnText.substring(0,idx-1);try{eval(jsRetStr);}catch(e){}}}else{showMsg('error getting invite count '+nextStep+'; '+returnText,5000,'red');}}catch(e){}},error:function(xhrObj,textStatus,errorThrown){try{showMsg('bc exception='+textStatus+'; '+errorThrown,5000,'red');}catch(e){}}});return totalInvites;}
function getStarted(startPos){if(startPos==0){TSTEP=0;crtTutStep=TSTEP;tut(0);}else{if(typeof crtTutStep=='undefined'){if(TSTEP<=0){crtTutStep=0;}else{crtTutStep=TSTEP;}
tut(crtTutStep);}else{tut(crtTutStep,1);}}}
function arena_tut(stepNb){var TUT_TEXT;var soundName='tutorialA';if(stepNb==4&&pj!=4){stepNb=3;showMsg('You must set the arena center to proceed!',5000,'yellow');soundName='invalid';}
if(stepNb==5&&crtMapViewGui!='Mil'){stepNb=4;showMsg('Switch to the military view to proceed!',5000,'yellow');soundName='invalid';}
if(stepNb==1){TUT_TEXT=A_TUT_STEP1;$$('#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut1').fadeIn('301');}
if(stepNb==2){TUT_TEXT=A_TUT_STEP2;$$('#atut1,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut2').fadeIn('301');}
if(stepNb==3){TUT_TEXT=A_TUT_STEP3;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');}
if(stepNb==4){TUT_TEXT=A_TUT_STEP4;$$('#atut1,#atut2,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut3').fadeIn('301');}
if(stepNb==5){$$("#detailsAccordion").accordion('activate',1);TUT_TEXT=A_TUT_STEP5;$$('#atut1,#atut2,#atut3,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut4a,#atut4b,#atut4c').fadeIn('301');}
if(stepNb==6){TUT_TEXT=A_TUT_STEP6;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut5').fadeIn('301');}
if(stepNb==7){TUT_TEXT=A_TUT_STEP7;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut5').fadeIn('301');}
if(stepNb==8){TUT_TEXT=A_TUT_STEP8;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');$$('#atut5').fadeIn('301');}
if(stepNb==9){TUT_TEXT=A_TUT_STEP9;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut9,#atut10').fadeOut('301');$$('#atut8').fadeIn('301');}
if(stepNb==10){TUT_TEXT=A_TUT_STEP10;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut10').fadeOut('301');$$('#atut9').fadeIn('301');}
if(stepNb==11){TUT_TEXT=A_TUT_STEP11;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9').fadeOut('301');$$('#atut10').fadeIn('301');}
if(stepNb==12){TUT_TEXT=A_TUT_STEP12;$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');bcAjax(true,'bcsvr.php',{'do':'set-arena-tutorial-done'},null,null);}
$('.tutAr').remove();if(stepNb==13){return;}
bcAjax(true,'bcsvr.php',{'do':'set-arena-tutorial-mode','active':'true'},null,null);$$('#tutMsgDiv').jGrowl(TUT_TEXT,{theme:'tutAr',sticky:true,close:function(e,m,o){$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').fadeOut('301');bcAjax(true,'bcsvr.php',{'do':'set-arena-tutorial-mode','active':'false'},null,null);}});playSound(soundName);$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').click(function(){$$('#atut1,#atut2,#atut3,#atut4a,#atut4b,#atut4c,#atut5,#atut6,#atut7,#atut8,#atut9,#atut10').css('display','none');});}
function toggleChat(){var chatIFrmJqObj=$$('#chatIFrm');if(chatIFrmJqObj.css('display')=='none'){showActionGui('Chat');}else{cancelActionGui('Chat');}}
function showChat(){playSound('startup');$$('#chatIFrm').animate({left:"0px"},700);chatShown=true;$('.sea').fadeOut(500);}
function hideChat(){$$('#chatIFrm').animate({left:"-335px"},700);$$('#smallMapImg').parent().focus();chatShown=false;}
function loadChat(){$$('#chatIFrm').attr('src','/jwc/jwc.php');chatLoaded=true;}
function chatCallback(txt){chatConnected=true;$$('#detailPlayerContact').removeAttr('disabled');$$('#detailPlayerContact').removeClass('bcButDisabled');$$('#detailPlayerContact').addClass('bcBut');}
function chatCellOwner(){if(crtClickedCellObj==null){return;}
$.ajax({async:true,url:'bcsvr.php',type:'POST',data:{'do':'get-username','id_user':crtClickedCellObj.idUser},success:function(returnText){try{$$('#chatIFrm')[0].contentWindow.showDirectMsg(returnText+'@battlecell.com');}catch(e){showMsg('error getting cell owner username; err='+e,3000,'red');}}});if(!chatShown){showActionGui('Chat');}}
function showProfileWindow(){if(crtClickedCellObj==null){return;}
$.ajax({async:true,url:'bcsvr.php',type:'POST',data:{'do':'get-username','id_user':crtClickedCellObj.idUser},success:function(returnText){try{var winPopRes=window.opener.WinPop('/profile/'+returnText,'bcwin_profile',3,null,'',true);switch(winPopRes){case 0:showMsg(MSGwinPopFail,15000,'yellow');break;case 1:break;case 2:window.opener.focus();if(window.opener.fullScreenMapActive){window.opener.shrinkFullScreenMap();}
break;}}catch(e){showMsg('error getting cell owner username; err='+e,3000,'red');}}});}
function pickToolUpgradeEmpire(){if(idUser==-1){showMsg('You must be logged in !',3000,'red');return;}
var tabsItemsJqObj=$$(".cellBuildItm,#upgradeTabDiv");tabsItemsJqObj.css({'display':'block','opacity':'1'});$('#upgradeTabDiv > .prefTab').css('opacity','1');$('.empireUpgrade, #upgradeActiveNoItems').css('display','inline-block');$('.upgradeActiveItem,.upgradeActiveNotice').css('display','none');for(var i=ACTIVE_UPGRADES_A.length-1;i>=0;i--){$('#upgradeItem'+ACTIVE_UPGRADES_A[i]).css('opacity','0.30');$('#upgradeActiveNoItems, #doUpgrade'+ACTIVE_UPGRADES_A[i]).css('display','none');$('#upgradeActive'+ACTIVE_UPGRADES_A[i]).css('display','inline');$('#upgradeActiveItem'+ACTIVE_UPGRADES_A[i]).css('display','inline-block');}
tb_remove(true);$("#upgradeLink").click();$("#scroll-paneINTERFACE,#scroll-paneSTALKER").jScrollPane({showArrows:false,scrollbarWidth:10,scrollbarMargin:8});dropToolOnTBClose=true;$("#cityCounts").html('-- Available / -- Total');var ajaxReqVars={'do':'get-player-city-counts'};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{var cityCntA=JSON.parse(returnText);$("#cityCounts").html((cityCntA.total-cityCntA.alloc)+' available / '+cityCntA.total+' total');}catch(e){reportAjaxError('pickToolUpgradeEmpire()',JSON.stringify(ajaxReqVars),returnText,e);}},error:function(xhrObj,textStatus,errorThrown){reportAjaxError('pickToolUpgradeEmpire()',JSON.stringify(ajaxReqVars),textStatus,errorThrown);}});}
function confirmToolUpgradeempire(upgradeType){if(idUser==-1){showMsg('You must be logged in !',3000,'red');return;}
showMsg('Upgrading empire...',3000,'green');var ajaxReqVars={'do':'upgrade-empire','upgradeType':upgradeType};bcAjax(true,'bcsvr.php',ajaxReqVars,function(returnText){try{var responseA=JSON.parse(returnText);if(responseA['upgrade_type']==-1){playSound('invalid');showMsg(responseA['msg'],5000,'yellow');}else{if(responseA['active_upgrades']){ACTIVE_UPGRADES_A=responseA['active_upgrades'];playSound('tutorialA');showMsg(responseA['msg'],5000,'green');}else{reportAjaxError('confirmToolUpgradeempire()',JSON.stringify(ajaxReqVars),returnText,'ACTIVE_UPGRADES_A update not received');}}}catch(e){reportAjaxError('confirmToolUpgradeempire()',JSON.stringify(ajaxReqVars),returnText,e);}},null);tb_remove();}
function showBuildingActionIcon(){if(crtActionGui=='Acquire'){$$('#subactionMechAttackIconOff,#subactionMechAttackIconOn,#subactionBankCollectIconOff,#subactionBankCollectIconOn').css('display','none');if(crtClickedCellObj!=null&&crtClickedCellObj.polRel==POLREL_ME){if(crtClickedCellObj.theDivJq.find('.building7, .building8, .building9').size()){$$('#subactionMechAttackIconOff').css('display','block');}else if(crtClickedCellObj.theDivJq.find('.building27, .building28, .building29').size()){$$('#subactionBankCollectIconOff').css('display','block');}}}}
function showMapViewGui(mapViewNm,doReload){if(typeof doReload=='undefined'){doReload=true;}
if(crtMapViewGui!=''){$$('#mapView'+crtMapViewGui+'IconOn').css('display','none');$$('#mapView'+crtMapViewGui+'LegendImg').css('display','none');$$('#mapView'+crtMapViewGui+'IconOff').css('display','block');$$('#mapView'+crtMapViewGui+'DescrDiv').css('display','none');}
$$('#mapView'+mapViewNm+'IconOn').css('display','block');$$('#mapView'+mapViewNm+'LegendImg').css('display','block');$$('#mapView'+mapViewNm+'IconOff').css('display','none');$$('#mapView'+mapViewNm+'DescrDiv').css('display','block');crtMapViewGui=mapViewNm;if(mapViewNm=='Pol'){crtMapView=BC_POL_VIEW_MAP;}
else if(mapViewNm=='Mil'){crtMapView=BC_MIL_VIEW_MAP;}
else if(mapViewNm=='Alt'){crtMapView=BC_ALT_VIEW_MAP;}
else if(mapViewNm=='Fin'){crtMapView=BC_FIN_VIEW_MAP;}
else if(mapViewNm=='Nat'){crtMapView=BC_NAT_VIEW_MAP;}
if(doReload){reloadCrtMapView();}else{repaintCrtMapView();}}
function showActionGui(actionNm){changeMapCursor('');if(crtSubActionGui!=''){cancelSubActionGui(crtSubActionGui);}
if(crtActionGui!=''){$$('#action'+crtActionGui+'IconOn').css('display','none');$$('#action'+crtActionGui+'IconOff').css('display','block');$$('#action'+crtActionGui+'DescrDiv').css('display','none');}
$$('#action'+actionNm+'IconOn').css('display','block');$$('#action'+actionNm+'IconOff').css('display','none');$$('#action'+actionNm+'DescrDiv').css('display','block');crtActionGui=actionNm;$$('.subaction').css('display','none');if(actionNm=='AllyUnit'){$$('#subactionDiv').css({display:'block'});$$('#subactionAcquireCannonIconOff').css('display','block');$$('#subactionAcquireBomberIconOff').css('display','block');$$('#subactionPlaceWaypointIconOff').css('display','block');$$('#allyCannonStatDiv').css('display','block');$$('#allyBomberStatDiv').css('display','block');hideChat();return;}
if(actionNm=='Acquire'){$$('#subactionDiv').css({display:'block'});$$('#subactionAcquireCellIconOff').css('display','block');$$('#subactionAcquireBuildingIconOff').css('display','block');$$('#subactionGAcquireNukeIconOff').css('display','block');$$('#subactionAcquireLaunchIconOff').css('display','block');$$('#subactionAcquireMissileIconOff').css('display','block');$$('#subactionLaunchMissileIconOff').css('display','block');$$('#subactionAcquireMissileIconOff').css('display','block');$$('#subactionAcquireFieldfortIconOff').css('display','block');showBuildingActionIcon();$$('#subactionPlaceWaypointIconOff').css('display','block');$$('#dividerDiv').css("background-position","0px -6px");hideChat();return;}
if(actionNm=='Upgrade'){$$('#subactionDiv').css({display:'none'});pickToolUpgradeEmpire();return;}
if(actionNm=='Chat'){$$('#subactionDiv').css({display:'none'});if(idUser!=-1){showChat();}else{setTimeout("cancelActionGui('Chat');",1000);}
return;}
if(actionNm=='Ship'){$$('#subactionDiv').css({display:'block'});$$('#subactionShipMoveIconOff').css('display','block');$$('#subactionShipLoadIconOff').css('display','block');$$('#subactionAcquireShipIconOff').css('display','block');$$('#subactionGAcquireShipIconOff').css('display','block');$$('#dividerDiv').css("background-position","0px -3px");hideChat();return;}
if(actionNm=='Troop'){$$('#subactionDiv').css({display:'block'});$$('#subactionTroopMoveIconOff').css('display','block');$$('#subactionTroopAttackCellIconOff').css('display','block');$$('#subactionAcquireTroopIconOff').css('display','block');$$('#subactionAcquireStalkerIconOff').css('display','block');$$('#subactionStalkerActionIconOff').css('display','block');$$('#subactionGAcquireTroopIconOff').css('display','block');$$('#dividerDiv').css("background-position","0px 0px");hideChat();return;}}
function showSubActionGui(subactionNm){changeMapCursor('');if(crtSubActionGui!=''){cancelSubActionGui();}
switch(subactionNm){case'StalkerMove':subactionDomNm='TroopMove';break;default:subactionDomNm=subactionNm;}
$$('#subaction'+subactionDomNm+'IconOn').css('display','block');$$('#subaction'+subactionDomNm+'IconOff').css('display','none');$$('#subaction'+subactionDomNm+'LegendDiv').css('display','block');crtSubActionGui=subactionNm;if(subactionNm=='TroopAttackCell'){$$('#transferWinningTroopsDiv').css('display','none');$$('#pickToolAttackDiv').css('display','block');$$('.cell-attack-class').css('display','none');$$('#attackSpinPlaceholder').css('display','none');pickToolAttack();return;}
if(subactionNm=='StalkerAction'){pickToolStalkerAction();return;}
if(subactionNm=='MechAttack'){if(!crtClickedCellObj.theDivJq.find('.building7, .building8, .building9').size()){showMsg('No eligible building on cell.',3000,'yellow');cancelSubActionGui(subactionNm);return;}
pickToolMechAttack();return;}
if(subactionNm=='BankCollect'){if(!crtClickedCellObj.theDivJq.find('.building27, .building28, .building29').size()){showMsg('No eligible building on cell.',3000,'yellow');cancelSubActionGui(subactionNm)
return;}
pickToolBankCollect();return;}
if(subactionNm=='AcquireCell'){pickToolAcquireCell();return;}
if(subactionNm=='AcquireTroop'){pickToolAcquireItem('troops');return;}
if(subactionNm=='AcquireShip'){pickToolAcquireItem('ships');return;}
if(subactionNm=='AcquireNuke'){pickToolAcquireItem('nukes');return;}
if(subactionNm=='AcquireLaunch'){pickToolAcquireItem('launch');return;}
if(subactionNm=='AcquireMissile'){pickToolAcquireItem('missile');return;}
if(subactionNm=='AcquireFieldfort'){pickToolAcquireItem('fieldfort');return;}
if(subactionNm=='AcquireStalker'){pickToolAcquireItem('stalker');return;}
if(subactionNm=='TroopMove'){pickToolMoveTroops('move-troops');return;}
if(subactionNm=='StalkerMove'){pickToolMoveTroops('move-stalker');return;}
if(subactionNm=='ShipLoad'){pickToolShipLoad();return;}
if(subactionNm=='ShipMove'){pickToolShipMove();return;}
if(subactionNm=='AcquireBuilding'){pickToolAcquireBuilding();return;}
if(subactionNm=='LaunchMissile'){showMissile();return;}
if(subactionNm=='GAcquireTroop'){pickToolGAcquireItem('troops');return;}
if(subactionNm=='GAcquireShip'){pickToolGAcquireItem('ships');return;}
if(subactionNm=='GAcquireNuke'){pickToolGAcquireItem('nukes');return;}
if(subactionNm=='AcquireCannon'){pickToolAllyItem('cannon');return;}
if(subactionNm=='AcquireBomber'){pickToolAllyItem('bomber');return;}
if(subactionNm=='PlaceWaypoint'){pickToolPlaceWaypoint();return;}
if(subactionNm=='StalkerCommandeer'){pickToolStalkerCommandeer();return;}}
function cancelSubActionGui(){if(crtSubActionGui=='')return;switch(crtSubActionGui){case'StalkerMove':subactionDomNm='TroopMove';break;default:subactionDomNm=crtSubActionGui;}
$$('#subaction'+subactionDomNm+'IconOn').css('display','none');$$('#subaction'+subactionDomNm+'IconOff').css('display','block');$$('#subaction'+subactionDomNm+'LegendDiv').css('display','none');crtSubActionGui='';dropToolAttack();dropToolMechAttack();dropToolBankCollect();dropToolAcquireCell();dropToolMoveTroops();dropToolAcquireItem('troops');dropToolAcquireItem('stalker');dropToolAcquireItem('ships');dropToolAcquireItem('nukes');dropToolAcquireItem('launch');dropToolAcquireItem('missile');dropToolGAcquireItem('troops');dropToolGAcquireItem('ships');dropToolGAcquireItem('nukes');dropToolShipLoad();dropToolShipMove();dropToolAllyItem('cannon');dropToolAllyItem('bomber');dropToolPlaceWaypoint();dropToolStalkerLaser();dropToolStalkerCommandeer();showBuildingActionIcon();}
function cancelActionGui(actionNm){$$('#subactionDiv').css({display:'none'});$$('.subaction').css('display','none');$$('#action'+crtActionGui+'IconOn').css('display','none');$$('#action'+crtActionGui+'IconOff').css('display','block');$$('#action'+crtActionGui+'DescrDiv').css('display','none');$$('#dividerDiv').css("background-position","0px 3px");crtActionGui='';hideChat();dropToolAttack();dropToolMechAttack();dropToolAcquireCell();dropToolMoveTroops();dropToolAcquireItem('troops');dropToolAcquireItem('stalker');dropToolAcquireItem('ships');dropToolAcquireItem('nukes');dropToolAcquireItem('launch');dropToolAcquireItem('missile');dropToolShipLoad();dropToolShipMove();dropToolAllyItem('cannon');dropToolAllyItem('bomber');}
function pickToolAllyItem(itemNm){if(currentTool=='ally-'+itemNm){return;}
if(idUser==-1&&!IS_ARENA){showMsg('Invalid request !',3000,'red');return;}
if(id_ALO3!==null){linkAllyItem(itemNm,id_ALO3);return;}
if(pj!=2&&pj!=4){return;}
if(typeof(FB_ARENA_MODE)!='undefined'){if(crtSubActionGui!=''){cancelSubActionGui(crtSubActionGui);}
if(crtActionGui!=''){cancelActionGui(crtActionGui);}}
if(currentTool.indexOf('ally-')!=-1){dropToolAllyItem('');}
if(itemNm=='cannon'){if(parseInt($$('#remCannon').text())<1){if(typeof(FB_ARENA_MODE)!='undefined'){$$('#allyPaneNotifDiv').jGrowl('All cannons have been deployed!',{theme:'allyUnitNotif',life:6000,glue:'before'});}else{showMsg('All cannons have been deployed!',6000,'yellow');}
playSound('invalid');return;}else if(parseInt($$('#linkedCannonCnt').text())<1&&parseInt($$('#remCannon').text())!=parseInt($$('#maxCannon').text())){if(typeof(FB_ARENA_MODE)!='undefined'){$$('#allyPaneNotifDiv').jGrowl('Ally cannons exhausted. Select ally, then cannon icon to proceed.',{theme:'allyUnitNotif',life:6000,glue:'before'});}else{showMsg('Ally cannons exhausted.',6000,'yellow');}
playSound('invalid');return;}}else if(itemNm=='bomber'){if(parseInt($$('#remBomber').text())<1){if(typeof(FB_ARENA_MODE)!='undefined'){$$('#allyPaneNotifDiv').jGrowl('All bombers have been deployed!',{theme:'allyUnitNotif',life:6000,glue:'before'});$$('#allyPaneNotifDiv').jGrowl('Press SHIFT+B to place waypoints.',{theme:'allyUnitNotif',life:6000,glue:'before'});}else{showMsg('All bombers have been deployed!',6000,'yellow');}
playSound('invalid');return;}else if(parseInt($$('#linkedBomberCnt').text())<1&&parseInt($$('#remBomber').text())!=parseInt($$('#maxBomber').text())){if(typeof(FB_ARENA_MODE)!='undefined'){$$('#allyPaneNotifDiv').jGrowl('Ally bombers exhausted. Select ally, then bomber icon to proceed.',{theme:'allyUnitNotif',life:6000,glue:'before'});}else{showMsg('Ally bombers exhausted.',6000,'yellow');}
playSound('invalid');return;}}
currentTool='ally-'+itemNm;switch(itemNm){case'cannon':{$$('#allyCannonDiv').css("background-position","-50px -42px");break;}
case'bomber':{$$('#allyBomberDiv').css("background-position","-151px -36px");break;}
default:return;}
changeMapCursor(itemNm);}
function dropToolAllyItem(itemNm){if(currentTool.indexOf('ally-')==-1){return;}
currentTool='';changeMapCursor('');$$('#allyCannonDiv').css("background-position","0 -42px");$$('#allyBomberDiv').css("background-position","-100px -36px");cancelSubActionGui();}
function doToolPlaceAllyItem(cellObj,itemNm){if(currentTool.indexOf('ally-')!=0&&typeof itemNm==='undefined'){return;}
if(cannonsH[[crtClickedCellLat,crtClickedCellLon]]!=null){return;}
if(typeof itemNm==='undefined'){itemNm=currentTool.substring(5);}
var errorsFound=false;if(currentTool.indexOf('ally-')==0){showMsg('Placing '+itemNm+'...',3000,'green');$.ajax({async:false,url:'bcsvr.php',type:'POST',data:{'do':'place-ally-item','item':itemNm,'lat':crtClickedCellLat,'lon':crtClickedCellLon},success:function(returnText){if(returnText.indexOf('SUCCESS')==-1){showMsg(returnText,5000,'yellow');errorsFound=true;}}});}
if(currentTool.indexOf('ally-')==0){dropToolAllyItem('');}
if(errorsFound){return;}
switch(itemNm){case'cannon':{createNewCannon(cellObj,[crtClickedCellLat,crtClickedCellLon]);updAllyItemCounter('#remCannon',false);updAllyItemCounter('#linkedCannonCnt',false);break;}
case'bomber':{createNewBomber(cellObj,[crtClickedCellLat,crtClickedCellLon]);updAllyItemCounter('#remBomber',false);updAllyItemCounter('#linkedBomberCnt',false);$$('#allyPaneNotifDiv').jGrowl('Press SHIFT+B to place waypoints.',{theme:'allyUnitNotif',life:6000,glue:'before'});break;}
default:{showMsg('Ally Item ('+itemNn+') not found !',5000,'red');}}}
function linkAllyItem(itemNm,allyEntryId){$.ajax({async:false,url:'bcsvr.php',type:'POST',data:{'do':'link-ally-item','item':itemNm,'allyId':allyEntryId.replace('bcid','')},success:function(returnText){try{eval(returnText);if(returnText.indexOf('SUCCESS')!=-1){updAllyItemCounter('#linkedCannonCnt',true,'9999');switch(itemNm){case'cannon':{jq_ALO3.attr('class',unitTypeClass).unbind('click');break;}
case'bomber':{jq_ALO3.attr('class',unitTypeClass).unbind('click');break;}
default:return;}
jq_ALO3=null;id_ALO3=null;$('.closeALn').parent().parent().trigger('jGrowl.close');showMsg(msg,5000,'green');}else{showMsg(msg,5000,'yellow');}}catch(e){showMsg('error processing link request; err='+e,10000,'red');}}});}
function updAllyItemCounter(divId,increment,maxAmt){var cnt=parseInt($$(divId).text());if(cnt>0&&!increment){cnt--;$$(divId).text(cnt);}else if(cnt<maxAmt&&increment){cnt++;$$(divId).text(cnt);}}
function showInfoPaneDetail(clickedCellObj){cias=null;$$('#LOGusername').blur();$$('#LOGpassword').blur();$$('#addrSearch').blur();$$('#grpChatInput').blur();$$('.playerDetailGlass').css('display','none');$$('.playerDetailText').css('display','none');$$('.cardbkg').css('display','none');$$('.transitDetailGlass').css('display','none');$$('.playerCardArea').css('display','none');$$('.PshuttleShadow').css("background-position","6px 18px");$$('.CshuttleShadow').css("background-position","6px 18px");var glassDisplayed=false;if(clickedCellObj.polRel==POLREL_ALLY){$$('.PshuttleShadow').css("background-position","6px -18px");$$('.CshuttleShadow').css("background-position","6px -77px");$$('#glassPlayerDetailsImgAlly').css('display','block');$$('#cardBkgImgAlly').css('display','block');glassDisplayed=true;}else if(clickedCellObj.polRel==POLREL_ENEMY){$$('.PshuttleShadow').css("background-position","6px -54px");$$('.CshuttleShadow').css("background-position","6px -100px");$$('#glassPlayerDetailsImgEnemy').css('display','block');$$('#cardBkgImgEnemy').css('display','block');glassDisplayed=true;}else if(clickedCellObj.polRel==POLREL_ME){$$('.PshuttleShadow').css("background-position","6px 0px");$$('.CshuttleShadow').css("background-position","6px -71px");$$('#glassPlayerDetailsImgMe').css('display','block');$$('#cardBkgImgMe').css('display','block');$$('.transitDetailGlass').css('display','block');glassDisplayed=true;}else if(clickedCellObj.polRel==POLREL_NEUTRAL||clickedCellObj.polRel==POLREL_NOTLOGGED){$$('.PshuttleShadow').css("background-position","6px -36px");$$('.CshuttleShadow').css("background-position","6px -94px");$$('#glassPlayerDetailsImgNeutral').css('display','block');$$('#cardBkgImgNeutral').css('display','block');glassDisplayed=true;}else if(clickedCellObj.polRel==-1){}
if(glassDisplayed){$$('.playerDetailText').css({display:'block'});}
var ajaxReqVars={'do':'get-cell-info-and-stats','id_user':crtClickedCellObj.idUser,'lat':crtClickedCellLat,'lon':crtClickedCellLon};$.ajax({async:false,url:'bcsvr.php',type:'GET',data:ajaxReqVars,success:function(returnText){try{cias=JSON.parse(returnText);$$('#playerNm').html(cias['first_name']+' '+cias['last_name']);$$('#playerNm').attr('title',cias['first_name']+' '+cias['last_name']);$$('#playerLoc').html(cias['city']+', '+cias['country']);$$('#playerLoc').attr('title',cias['city']+', '+cias['country']);$$('#detailPlayerRank').text(cias['detailPlayerRank']);$$('#detailPlayerTotalPlayers').text(cias['totalPlayers']);$$('#detailPlayerTotalCells').text(cias['detailPlayerTotalCells']);$$('#detailPlayerTotalTroops').text(cias['detailPlayerTotalTroops']);$$('#detailPlayerTotalShips').text(cias['detailPlayerTotalShips']);$$('#detailPlayerTotalPower').text(cias['detailPlayerTotalPower']);$$('#detailPlayerTotalGCredits').text(cias['detailPlayerTotalGCredits']);$$('#cellDetailShips').text(cias['cellDetailShips']);$$('#cellDetailTroopsOnShips').text(cias['cellDetailTroopsOnShips']);$$('#cellDetailNuke').html(cias['cellDetailNuke']);$$('#cellDetailShore').html(cias['cellDetailShore']);$$('#cellDetailProdRate').text(cias['cellDetailProdRate']);crtMinTroopsOnCell=(buildingsA[crtClickedCellObj.arrayPos]&&buildingsA[crtClickedCellObj.arrayPos]>0&&buildingsA[crtClickedCellObj.arrayPos]<4)?MIN_TROOPS_ON_CELL+parseInt(TROOP_MAINT_BONUS_A[buildingsA[crtClickedCellObj.arrayPos]]):MIN_TROOPS_ON_CELL;if(crtClickedCellObj.troops<=crtMinTroopsOnCell){$$('#cellDetailDeathRate4Troop').text(0);}else if(crtClickedCellObj.troops<crtMinTroopsOnCell+TROOP_DAILY_DEATH_RATE){$$('#cellDetailDeathRate4Troop').text((crtClickedCellObj.troops-crtMinTroopsOnCell));}else{$$('#cellDetailDeathRate4Troop').text(TROOP_DAILY_DEATH_RATE);}
crtClickedCellDataA['building']=cias['cellBuilding'];if(currentTool=='buy-ships'){doToolActionAcquireItem('ships');}else if(currentTool=='buy-nukes'){doToolActionAcquireItem('nukes');}else if(currentTool=='ship-load'){doToolActionShipLoad();}else if(currentTool=='buy-gc-ships'){doToolActionGAcquireItem('ships');}else if(currentTool=='buy-gc-nukes'){doToolActionGAcquireItem('nukes');}
if(clickedCellObj.idUser>0){var rnd='';if(clickedCellObj.polRel==POLREL_ME){rnd=myPicRnd;}
if($$('#playerPic').attr('src')!=cias['playerPic'])$$('#playerPic').css('display','none');$$('#playerPic').attr('src',cias['playerPic']+rnd);$$('.playerCardArea').css('display','block');}
$('#subactionAcquireLaunchIconOff,#subactionAcquireLaunchIconOn,#subactionAcquireMissileIconOff,#subactionAcquireMissileIconOn,#subactionLaunchMissileIconOff,#subactionLaunchMissileIconOn').css('visibility','hidden');if(cias['missileStatus']==0){var missileETA=(cias['missileStatusETA']/3600).toFixed(1);$$('#subactionAcquireLaunchIconOff,#subactionAcquireLaunchIconOn').css({"visibility":"visible"}).attr({"title":"missile launch complex under construction. ETA is "+missileETA+" hours"});}else if(cias['missileStatus']==2){var missileETA=(cias['missileStatusETA']/3600).toFixed(1);$$('#subactionAcquireMissileIconOff,#subactionAcquireMissileIconOn').css({"visibility":"visible"}).attr({"title":"missile attack in progress. ETA is "+missileETA+" hours"});}else if(cias['missileStatus']==4&&crtClickedCellObj.idUser==idUser){$$('#subactionAcquireLaunchIconOff,#subactionAcquireLaunchIconOn').css({"visibility":"visible"}).attr({"title":"build missile launch complex"});}else if(cias['missileStatus']==5){$$('#subactionAcquireMissileIconOff,#subactionAcquireMissileIconOn').css({"visibility":"visible"}).attr({"title":"buy missile"});}else if(cias['missileStatus']==6){$$('#subactionLaunchMissileIconOff,#subactionLaunchMissileIconOn').css({"visibility":"visible"}).attr({"title":"launch/track missile [m]"});}}catch(e){reportAjaxError('showInfoPaneDetail()',JSON.stringify(ajaxReqVars),returnText,e);}}});$$('#cellDetailLatLon').html(crtClickedCellLat+','+crtClickedCellLon);$$('#cellDetailTroops').html(' '+clickedCellObj.troops);$$('#cellDetailCredits').html(' '+clickedCellObj.money);$$('#cellDetailAlt').html(clickedCellObj.alt);}
function doMapCmd(cmdNm){if(cmdNm=='hybrid'){map.setMapType(G_HYBRID_MAP);return;}
if(cmdNm=='satellite'){map.setMapType(G_NORMAL_MAP);return;}
if(cmdNm=='terrain'){map.setMapType(G_PHYSICAL_MAP);return;}
if(cmdNm=='zoomin'){playSound('zoom');map.setZoom(map.getZoom()+1);return;}
if(cmdNm=='zoomout'){var crtZoom=map.getZoom();if(crtZoom<=10){playSound('invalid');return;}
playSound('zoom');map.setZoom(crtZoom-1);scheduleMapViewRefresh();return;}}
function getLocation(){if(google.loader.ClientLocation==null){return'';}
return google.loader.ClientLocation.address.city+', '+google.loader.ClientLocation.address.region+', '+google.loader.ClientLocation.address.country}
function saveUserInfo(){$.ajax({async:false,url:'bcsvr.php',type:'POST',data:{'do':'save-user-info','last_lat':map.getCenter().lat(),'last_lon':map.getCenter().lng()},success:function(returnText){},error:function(xhrObj,textStatus,errorThrown){try{}catch(e){}}});}
function setWindowState(winId,winState){$.ajax({async:false,url:'bcsvr.php',type:'POST',data:{'do':'set-window-state','win':winId,'state':winState},success:function(returnText){},error:function(xhrObj,textStatus,errorThrown){try{}catch(e){}}});}
function spinCallbackAttackerTroops(v){var theV=getMaxSpinAttackerTroops()-v;theV=theV<10?'0'+theV:theV;$$('#defenderTroopsSpin').val(theV);}
function getMaxSpinAttackerTroops(){return attackRes['A'];}
function getMinSpinAttackerTroops(){return 0;}
function spinCallbackAcquireItem(itemNm){return function(v){var theV=getMaxSpinAcquireItem(itemNm)-v;theV=theV<10?'0'+theV:theV;$$('#'+itemNm+'BoughtSpin').val(theV);};}
function getMaxSpinAcquireItem(itemNm){if(itemNm=='troops'){var canBuy=0;var existingItems;if(crtRClickedCellA.length>0){var cellBuy;for(var i in crtRClickedCellA){cellBuy=((crtRClickedCellA[i]['obj'].money/TROOP_BUY_COST)|0);existingItems=parseInt(crtRClickedCellA[i]['obj'].troops);if(cellBuy+existingItems>MAX_TROOPS_ON_CELL){cellBuy=MAX_TROOPS_ON_CELL-existingItems;}
if(canBuy<cellBuy){canBuy=cellBuy;}}}else{canBuy=((crtClickedCellObj.money/TROOP_BUY_COST)|0);existingItems=parseInt(crtClickedCellObj.troops);if(canBuy+existingItems>MAX_TROOPS_ON_CELL){canBuy=MAX_TROOPS_ON_CELL-existingItems;}}
if(canBuy<0){canBuy=0;}
return canBuy;}
if(itemNm=='stalker'){var canBuy=((crtClickedCellObj.money/STALKER_COST)|0);var existingItems=cias['detailPlayerTotalStalkers']-0;var maxStalkers=Math.ceil(cias['detailPlayerTotalCells']/CELLS_PER_STALKER);if(canBuy+existingItems>maxStalkers){canBuy=maxStalkers-existingItems;}
if(canBuy<0){canBuy=0;}
return canBuy;}
if(itemNm=='ships'){if(crtRClickedCellA.length>0){return 2;}else{var canBuy=((crtClickedCellObj.money/SHIP_BUY_COST)|0);var existingItems=parseInt($$('#cellDetailShips').html());if(canBuy+existingItems>MAX_SHIPS_ON_CELL){canBuy=MAX_SHIPS_ON_CELL-existingItems;}
if(canBuy<0){canBuy=0;}
return canBuy;}}
if(itemNm=='nukes'){var canBuy=((crtClickedCellObj.money/NUKE_BUY_COST)|0);var existingItems=0;if($$('#cellDetailNuke').html()=='yes'){existingItems=1;}
if(canBuy+existingItems>MAX_NUKES_ON_CELL){canBuy=MAX_NUKES_ON_CELL-existingItems;}
if(canBuy<0){canBuy=0;}
return canBuy;}
if(itemNm=='launch'||itemNm=='missile'||itemNm=='fieldfort'){var canBuy=0;switch(itemNm){case'launch':var cost=LAUNCH_COST;break;case'missile':var cost=MISSILE_COST;break;case'fieldfort':var cost=FIELDFORT_COST;break;}
var ajaxReqVars={'do':'get-max-spin-acquire-'+itemNm,'lat':crtClickedCellLat,'lon':crtClickedCellLon};$.ajax({async:false,url:'bcsvr.php',type:'GET',data:ajaxReqVars,success:function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){var idx=returnText.indexOf('<sep>');if(idx!=-1){var jsRetStr=returnText.substring(0,idx-1);try{eval(jsRetStr);}catch(e){}}}else{reportAjaxError('getMaxSpinAcquireItem()',JSON.stringify(ajaxReqVars),returnText,'SUCCESS not received');}}catch(e){reportAjaxError('getMaxSpinAcquireItem()',JSON.stringify(ajaxReqVars),returnText,e);}},error:function(xhrObj,textStatus,errorThrown){}});canBuy=((canBuy/cost)|0);if(canBuy<0){canBuy=0;}
return canBuy;}}
function getMinSpinAcquireItem(itemNm){return 0;}
function spinCallbackGAcquireItem(itemNm){return function(v){var theV=getMaxSpinGAcquireItem(itemNm)-v;theV=theV<10?'0'+theV:theV;$$('#'+itemNm+'GBoughtSpin').val(theV);};}
function getMaxSpinGAcquireItem(itemNm){var gCredits=parseInt($$('#detailPlayerTotalGCredits').html());if(isNaN(gCredits)||gCredits<0){gCredits=0;}
if(itemNm=='troops'){var canBuy=((gCredits/TROOP_BUY_COST)|0);var existingItems=parseInt(crtClickedCellObj.troops);if(canBuy+existingItems>MAX_TROOPS_ON_CELL){canBuy=MAX_TROOPS_ON_CELL-existingItems;}
if(canBuy<0){canBuy=0;}
return canBuy;}
if(itemNm=='ships'){var canBuy=((gCredits/SHIP_BUY_COST)|0);var existingItems=parseInt($$('#cellDetailShips').html());if(canBuy+existingItems>MAX_SHIPS_ON_CELL){canBuy=MAX_SHIPS_ON_CELL-existingItems;}
if(canBuy<0){canBuy=0;}
return canBuy;}
if(itemNm=='nukes'){var canBuy=((gCredits/NUKE_BUY_COST)|0);var existingItems=0;if($$('#cellDetailNuke').html()=='yes'){existingItems=1;}
if(canBuy+existingItems>MAX_NUKES_ON_CELL){canBuy=MAX_NUKES_ON_CELL-existingItems;}
if(canBuy<0){canBuy=0;}
return canBuy;}}
function getMinSpinGAcquireItem(itemNm){return 0;}
function getMaxSpinMoveTroops(){if(currentTool=='move-stalker')return cias['cellDetailStalkers'];if(moveOriginCellA.length>0){var maxFound=0;for(var i in moveOriginCellA){if(moveOriginCellA[i]['obj'].troops>maxFound){maxFound=moveOriginCellA[i]['obj'].troops;}}
return maxFound;}
return moveOriginCellTroops;}
function getMinSpinMoveTroops(){return 0;}
function spinCallbackMoveTroops(v){var theV=getMaxSpinMoveTroops()-v;theV=theV<10?'0'+theV:theV;$$('#wished2MoveTroopsSpin').val(theV);}
function getMinSpinShipLoad(){return 0;}
function getMaxSpinShipLoad(){if(crtRClickedCellA.length>0){totAvailableItems2Buy=0;for(var i in crtRClickedCellA){var shipsOnCell=((shroopsA[i]/100)|0);var maxTroopsOnAllShips=shipsOnCell*MAX_TROOPS_ON_SHIP;var troopsOnCell=parseInt(crtRClickedCellA[i]['obj'].troops);var troopsAlreadyOnShips=shroopsA[i]%100;var availableItems2Buy=Math.min(maxTroopsOnAllShips-troopsAlreadyOnShips,troopsOnCell);if(totAvailableItems2Buy<availableItems2Buy+troopsAlreadyOnShips){totAvailableItems2Buy=availableItems2Buy+troopsAlreadyOnShips;}}
return totAvailableItems2Buy;}else{var shipsOnCell=parseInt($$('#cellDetailShips').html());var maxTroopsOnAllShips=shipsOnCell*MAX_TROOPS_ON_SHIP;var troopsOnCell=parseInt(crtClickedCellObj.troops);var troopsAlreadyOnShips=parseInt($$('#cellDetailTroopsOnShips').html());var availableItems2Buy=Math.min(maxTroopsOnAllShips-troopsAlreadyOnShips,troopsOnCell);return Math.min(maxTroopsOnAllShips,troopsAlreadyOnShips+availableItems2Buy);}}
function spinCallbackShipLoad(v){var theV=getMaxSpinShipLoad()-v;theV=theV<10?'0'+theV:theV;$$('#troops2BLoadedInShipSpin').val(theV);}
function disableObj(idStr){$$(idStr).attr("disabled","disabled");}
function enableObj(idStr){$$(idStr).removeAttr('disabled');}
function getFirstCell(){if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
if(crtClickedCellObj==null){showMsg('click a cell !',5000,'yellow');return;}
disableObj('#confirmFirstCellBut');showMsg('finding a cell...',5000,'yellow');var ajaxReqVars={'do':'get-first-cell','lat':crtClickedCellLat,'lon':crtClickedCellLon};bcAjax(false,'bcsvr.php',ajaxReqVars,function(returnText){try{var status='';var firstCellLat='';var firstCellLon='';eval(returnText);if(status=='SUCCESS'){if(firstCellLat!=''&&firstCellLon!=''){showMsg('Success ! First cell secured !',5000,'green');$$('#firstCellDiv').css('display','none');map.setCenter(new GLatLng(fromTopo(firstCellLat),fromTopo(addLon(firstCellLon,-2))));map.openInfoWindowHtml(new GLatLng(fromTopo(firstCellLat),fromTopo(firstCellLon)),GMAPfirstCellBubble,{noCloseOnClick:true,pixelOffset:new GSize(20,10)});reloadCrtMapView();}}else if(status=='ALL_TAKEN'){showMsg('No cell available. Choose another region.',5000,'yellow');}else if(status=='ALREADY_CHOSEN'){showMsg('You already have a cell. Try reloading the browser page.',5000,'yellow');}
enableObj('#confirmFirstCellBut');}catch(e){reportAjaxError('getFirstCell()',JSON.stringify(ajaxReqVars),returnText,e);enableObj('#confirmFirstCellBut');}},null);}
function addLat($inLat,$toAdd){if($inLat>=0){$minute=$inLat%100;}else{$minute=-(-$inLat%100);}
$degree=($inLat-$minute)/100;$MINUTES=$degree*60+$minute;$MINUTES=$MINUTES+$toAdd;if($MINUTES>=0){$minute=$MINUTES%60;}else{$minute=-(-$MINUTES%60);}
$degree=($MINUTES-$minute)/60;$outLat=($degree*100)+$minute;return $outLat;}
function addLon($inLon,$toAdd){if($inLon>=0){$minute=$inLon%100;}else{$minute=-(-$inLon%100);}
$degree=($inLon-$minute)/100;$MINUTES=$degree*60+$minute;$MINUTES=$MINUTES+$toAdd;if($MINUTES>10800){$MINUTES-=21600;}
if($MINUTES<-10799){$MINUTES+=21600;}
if($MINUTES>=0){$minute=$MINUTES%60;}else{$minute=-(-$MINUTES%60);}
$degree=($MINUTES-$minute)/60;$outLon=($degree*100)+$minute;return $outLon;}
function keydownHandler(event){if($.inArray(0,ACTIVE_UPGRADES_A)>-1){if(event.keyCode==16){startLassoTool();return false;}else if(event.shiftKey&&event.keyCode!=90&&event.keyCode!=88){stopLassoTool();}}
if(($.browser.msie&&(event.keyCode==32))||($.browser.mozilla&&(event.keyCode==32))||($.browser.safari&&(event.keyCode==32))){if(!actionInProgress&&crtConfirmAction!=null){crtConfirmAction();}
return false;}
if(aSpinnerIsShown){if(($.browser.mozilla&&(event.keyCode==90))||($.browser.msie&&(event.keyCode==90))||($.browser.safari&&(event.keyCode==90))){var spinfunc=crtShownSpinnerObjL.data('spinfunc');spinfunc((event.shiftKey)?10:1);return false;}
if(($.browser.mozilla&&(event.keyCode==88))||($.browser.msie&&(event.keyCode==88))||($.browser.safari&&(event.keyCode==88))){var spinfunc=crtShownSpinnerObjL.data('spinfunc');spinfunc((event.shiftKey)?-10:-1);return false;}}
if(($.browser.msie&&(event.keyCode==109||event.keyCode==189))||($.browser.mozilla&&(event.keyCode==109))||($.browser.safari&&(event.keyCode==109||event.keyCode==189))){doMapCmd('zoomout');return false;}
if(($.browser.msie&&(event.keyCode==107||event.keyCode==187))||($.browser.mozilla&&(event.keyCode==107))||($.browser.safari&&(event.keyCode==107||event.keyCode==187))){doMapCmd('zoomin');return false;}
if(($.browser.msie&&(event.keyCode==9))||($.browser.mozilla&&(event.keyCode==9))||($.browser.safari&&(event.keyCode==9))){if(typeof(FB_ARENA_MODE)=='undefined'){if(!chatShown){showActionGui('Chat');}else{cancelActionGui('Chat');}}
return false;}
if(($.browser.msie&&(event.keyCode==65))||($.browser.mozilla&&(event.keyCode==65))||($.browser.safari&&(event.keyCode==65))){if(event.shiftKey){showActionGui('Acquire');if(crtClickedCellObj.theDivJq.find('.building7, .building8, .building9').size()){showSubActionGui('MechAttack');}else if(crtClickedCellObj.theDivJq.find('.building27, .building28, .building29').size()){showSubActionGui('BankCollect');}else{showMsg('No eligible building on cell.',3000,'yellow');}}else{showActionGui('Troop');showSubActionGui('TroopAttackCell');}
return false;}
if(($.browser.msie&&(event.keyCode==84))||($.browser.mozilla&&(event.keyCode==84))||($.browser.safari&&(event.keyCode==84))){showActionGui('Troop');showSubActionGui('AcquireTroop');return false;}
if(($.browser.msie&&(event.keyCode==89))||($.browser.mozilla&&(event.keyCode==89))||($.browser.safari&&(event.keyCode==89))){showActionGui('Troop');if(event.shiftKey){showSubActionGui('StalkerMove');}else{showSubActionGui('TroopMove');}
return false;}
if(($.browser.msie&&(event.keyCode==79))||($.browser.mozilla&&(event.keyCode==79))||($.browser.safari&&(event.keyCode==79))){showActionGui('Troop');showSubActionGui('StalkerAction');return false;}
if(($.browser.msie&&(event.keyCode==67))||($.browser.mozilla&&(event.keyCode==67))||($.browser.safari&&(event.keyCode==67))){showActionGui('Acquire');showSubActionGui('AcquireCell');return false;}
if(($.browser.msie&&(event.keyCode==78))||($.browser.mozilla&&(event.keyCode==78))||($.browser.safari&&(event.keyCode==78))){showActionGui('Acquire');if(IS_ARENA){showSubActionGui('AcquireNuke');}else{showSubActionGui('GAcquireNuke');}
return false;}
if((($.browser.msie&&(event.keyCode==85))||($.browser.mozilla&&(event.keyCode==85))||($.browser.safari&&(event.keyCode==85)))&&!IS_ARENA){if(event.shiftKey){showCellCity();}else{showActionGui('Acquire');showSubActionGui('AcquireBuilding');}
return false;}
if(($.browser.msie&&(event.keyCode==83))||($.browser.mozilla&&(event.keyCode==83))||($.browser.safari&&(event.keyCode==83))){showActionGui('Ship');showSubActionGui('AcquireShip');return false;}
if(($.browser.msie&&(event.keyCode==68))||($.browser.mozilla&&(event.keyCode==68))||($.browser.safari&&(event.keyCode==68))){showActionGui('Ship');showSubActionGui('ShipMove');return false;}
if(($.browser.msie&&(event.keyCode==70))||($.browser.mozilla&&(event.keyCode==70))||($.browser.safari&&(event.keyCode==70))){showActionGui('Ship');showSubActionGui('ShipLoad');return false;}
if(($.browser.msie&&(event.keyCode==71))||($.browser.mozilla&&(event.keyCode==71))||($.browser.safari&&(event.keyCode==71))){if(event.shiftKey){$$("#helpWinOpenKB").click();}else{$$("#helpWinOpenLink").click();}
return false;}
if((($.browser.msie&&(event.keyCode==81))||($.browser.mozilla&&(event.keyCode==81))||($.browser.safari&&(event.keyCode==81)))&&IS_ARENA){if(typeof(FB_ARENA_MODE)=='undefined'){showActionGui('AllyUnit');showSubActionGui('AcquireCannon');}else{pickToolAllyItem('cannon');}
return false;}
if((($.browser.msie&&(event.keyCode==66))||($.browser.mozilla&&(event.keyCode==66))||($.browser.safari&&(event.keyCode==66)))&&IS_ARENA){if(event.shiftKey){if(typeof(FB_ARENA_MODE)=='undefined'){showActionGui('AllyUnit');showSubActionGui('PlaceWaypoint');}else{showActionGui('Acquire');showSubActionGui('PlaceWaypoint');}}else{if(typeof(FB_ARENA_MODE)=='undefined'){showActionGui('AllyUnit');showSubActionGui('AcquireBomber');}else{pickToolAllyItem('bomber');}}
return false;}
if(($.browser.msie&&(event.keyCode==191))||($.browser.mozilla&&(event.keyCode==191))||($.browser.safari&&(event.keyCode==191))){if($$('#transitPathsWithCellsIconOn').css('display')=='none'){showPathsWithCells(true);}else{showPathsWithCells(false);}
return false;}
if(($.browser.msie&&(event.keyCode==220))||($.browser.mozilla&&(event.keyCode==220))||($.browser.safari&&(event.keyCode==220))){if($$('#transitPathsWithPolyLinesIconOn').css('display')=='none'){showPathsWithPolyLines(true);}else{showPathsWithPolyLines(false);}
return false;}
if((($.browser.msie&&(event.keyCode==77))||($.browser.mozilla&&(event.keyCode==77))||($.browser.safari&&(event.keyCode==77)))&&!IS_ARENA){showActionGui('Acquire');showSubActionGui('LaunchMissile');return false;}
if(event.shiftKey&&(($.browser.msie&&event.keyCode==188)||($.browser.mozilla&&event.keyCode==188)||($.browser.safari&&event.keyCode==188))){setPlacemark(event.keyCode,1);return false;}
if(event.shiftKey&&(($.browser.msie&&event.keyCode==190)||($.browser.mozilla&&event.keyCode==190)||($.browser.safari&&event.keyCode==190))){setPlacemark(event.keyCode,2);return false;}
if(event.shiftKey&&(($.browser.msie&&event.keyCode==186)||($.browser.mozilla&&event.keyCode==59)||($.browser.safari&&event.keyCode==186))){setPlacemark(event.keyCode,3);return false;}
if(event.shiftKey&&(($.browser.msie&&event.keyCode==222)||($.browser.mozilla&&event.keyCode==222)||($.browser.safari&&event.keyCode==222))){setPlacemark(event.keyCode,4);return false;}
if(event.shiftKey&&(($.browser.msie&&event.keyCode==219)||($.browser.mozilla&&event.keyCode==219)||($.browser.safari&&event.keyCode==219))){setPlacemark(event.keyCode,5);return false;}
if(event.shiftKey&&(($.browser.msie&&event.keyCode==221)||($.browser.mozilla&&event.keyCode==221)||($.browser.safari&&event.keyCode==221))){setPlacemark(event.keyCode,6);return false;}
if(($.browser.msie&&event.keyCode==188)||($.browser.mozilla&&event.keyCode==188)||($.browser.safari&&event.keyCode==188)){gotoPm(1);return false;}
if(($.browser.msie&&event.keyCode==190)||($.browser.mozilla&&event.keyCode==190)||($.browser.safari&&event.keyCode==190)){gotoPm(2);return false;}
if(($.browser.msie&&event.keyCode==186)||($.browser.mozilla&&event.keyCode==59)||($.browser.safari&&event.keyCode==186)){gotoPm(3);return false;}
if(($.browser.msie&&event.keyCode==222)||($.browser.mozilla&&event.keyCode==222)||($.browser.safari&&event.keyCode==222)){gotoPm(4);return false;}
if(($.browser.msie&&event.keyCode==219)||($.browser.mozilla&&event.keyCode==219)||($.browser.safari&&event.keyCode==219)){gotoPm(5);return false;}
if(($.browser.msie&&event.keyCode==221)||($.browser.mozilla&&event.keyCode==221)||($.browser.safari&&event.keyCode==221)){gotoPm(6);return false;}
if(event.shiftKey&&(($.browser.msie&&(event.keyCode==80))||($.browser.mozilla&&(event.keyCode==80))||($.browser.safari&&(event.keyCode==80))&&!IS_ARENA)){tb_remove(true);$$('#screenshotLink').click();return false;}
switch(event.keyCode){case 37:{handleArrowKey(event.keyCode);break;}
case 38:{handleArrowKey(event.keyCode);break;}
case 39:{handleArrowKey(event.keyCode);break;}
case 40:{handleArrowKey(event.keyCode);break;}
case 27:{tb_remove();if(crtSubActionGui!=''){cancelSubActionGui(crtSubActionGui);break;}
if(crtActionGui!=''){cancelActionGui(crtActionGui);break;}
if(currentTool.indexOf('ally-')!=-1){dropToolAllyItem('');break;}
if($$('#bcityFrm').css("display")=="block"){hideCellCity();}
break;}
case 36:{$$("#detailsAccordion").accordion('activate',0);break;}
case 33:{$$("#detailsAccordion").accordion('activate',1);break;}
case 34:{$$("#detailsAccordion").accordion('activate',2);break;}
case 35:{$$("#detailsAccordion").accordion('activate',3);break;}
case 49:{if(event.shiftKey){showMapViewGui('Pol',false);}else{showMapViewGui('Pol');}break;}
case 50:{if(event.shiftKey){showMapViewGui('Mil',false);}else{showMapViewGui('Mil');}break;}
case 51:{if(event.shiftKey){showMapViewGui('Alt',false);}else{showMapViewGui('Alt');}break;}
case 52:{if(event.shiftKey){showMapViewGui('Fin',false);}else{showMapViewGui('Fin');}break;}
case 53:{if(event.shiftKey){showMapViewGui('Nat',false);}else{showMapViewGui('Nat');}break;}
case 54:{if(showUnownedCells){setShowUnownedCells(false);}else{setShowUnownedCells(true);}
break;}
case 56:{setTimeout("doMapCmd('hybrid');",100);break;}
case 57:{setTimeout("doMapCmd('satellite');",100);break;}
case 48:{setTimeout("doMapCmd('terrain');",100);break;}
case 87:{tb_remove(true);$$('#navMapOpenLink').click();break;}
case 80:{tb_remove(true);$$('#prefWinOpenLink').click();break;}
default:return true;}
return false;}
function keyupHandler(event){if(event.keyCode==16&&lassoToolShown&&!selectableTarget){stopLassoTool();}}
function assignUserColor(colorNb){if(crtClickedCellObj==null||crtClickedCellObj.idUser<=0){showMsg("select someone's cell",3000,'yellow');return;}
if(crtClickedCellObj.idUser==idUser){showMsg("it's your cell !",3000,'yellow');return;}
if(crtClickedCellObj.polRel==POLREL_NEUTRAL){showMsg("color assignments not supported for NEUTRAL yet",3000,'yellow');return;}
$.ajax({async:true,url:'bcsvr.php',type:'POST',data:{'do':'assign-user-color','id_other':crtClickedCellObj.idUser,'polRel':crtClickedCellObj.polRel,'colorNb':colorNb},success:function(returnText){try{if(returnText.indexOf('SUCCESS')==-1){showMsg('error assigning color',5000,'red');}else{showMsg('SUCCESS; color assigned',3000,'green');reloadCrtMapView();}}catch(e){showMsg('error assigning color; err='+e,5000,'red');}}});}
function setUserPolRel(polRel){if(crtClickedCellObj==null||crtClickedCellObj.idUser<=0){showMsg("select someone's cell",3000,'yellow');return;}
if(crtClickedCellObj.idUser==idUser){showMsg("it's your cell !",3000,'yellow');return;}
var ajaxReqVars={'do':'set-user-polrel','id_other':crtClickedCellObj.idUser,'polRel':polRel};$.ajax({async:true,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{if(returnText.indexOf('SUCCESS')==-1){showMsg('NOTICE: '+returnText,5000,'yellow');}else{if(polRel==POLREL_ALLY){showMsg('SUCCESS: ally request sent',3000,'green');}else if(polRel==POLREL_ENEMY){showMsg('SUCCESS: user marked as enemy',3000,'green');}else if(polRel==POLREL_NEUTRAL){showMsg('SUCCESS: user marked as neutral',3000,'green');}
reloadCrtMapView();}}catch(e){reportAjaxError('setUserPolRel()',JSON.stringify(ajaxReqVars),returnText,e);}}});}
function savePref(prefNm,prefVal){var ajaxReqVars={'do':'save-pref','prefNm':prefNm,'prefVal':prefVal};$.ajax({async:false,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){if(prefNm=='pref_lang'){UINFO_PREF_LANG_CD=getPrefLangCd(prefVal);}
showMsg('saved.',3000,'green');}else{reportAjaxError('savePref()',JSON.stringify(ajaxReqVars),returnText,'');}}catch(e){reportAjaxError('savePref()',JSON.stringify(ajaxReqVars),returnText,e);}},error:function(xhrObj,textStatus,errorThrown){reportAjaxError('savePref()',JSON.stringify(ajaxReqVars),errorThrown,textStatus);}});}
function getPrefLangCd(langIdx){var i=1;var trLangA={};trLangA[i++]='ar';trLangA[i++]='bg';trLangA[i++]='zh-CN';trLangA[i++]='zh-TW';trLangA[i++]='ca';trLangA[i++]='hr';trLangA[i++]='cs';trLangA[i++]='da';trLangA[i++]='nl';trLangA[i++]='en';trLangA[i++]='tl';trLangA[i++]='fi';trLangA[i++]='fr';trLangA[i++]='de';trLangA[i++]='el';trLangA[i++]='iw';trLangA[i++]='hi';trLangA[i++]='id';trLangA[i++]='it';trLangA[i++]='ja';trLangA[i++]='ko';trLangA[i++]='lv';trLangA[i++]='lt';trLangA[i++]='no';trLangA[i++]='pl';trLangA[i++]='pt-PT';trLangA[i++]='ro';trLangA[i++]='ru';trLangA[i++]='es';trLangA[i++]='sr';trLangA[i++]='sk';trLangA[i++]='sl';trLangA[i++]='sv';trLangA[i++]='uk';trLangA[i++]='vi';return trLangA[langIdx];}
var ownCellsRectsLayerJqObj=null;var ownCellsRects=false;function MyControls(){}
MyControls.prototype=new GControl();MyControls.prototype.initialize=function(map){var container;var jqObj=$("<div id=ownCellsLayerDiv class=pointerhand></div>");jqObj.append("<div id=ownCellsControlDiv> <input id=ownCellsCB type=checkbox onClick='showOwnCellsRectsLayer();' class=pointerhand><LABEL ID=\"lbForownCellsCB\" FOR=\"ownCellsCB\" class=pointerhand> Mine </LABEL></div>");jqObj.append("<div id=ownCellsInstructDiv>"+titleWwMapInstr+"</div>");jqObj.append("<div id=ownCellsLayerGridDiv><table width='100%' height='100%' border=0 cellpadding=0 cellspacing=0></table></div>");ownCellsRectsLayerJqObj=jqObj;if(ownCellsRects){$('#ownCellsCB',ownCellsRectsLayerJqObj).attr('checked','checked');}
for(var i=0;i<5;i++){$('table',jqObj).append('<tr></tr>');}
for(var i=0;i<6;i++){$('tr',jqObj).append('<td>&nbsp;</td>');}
$('td',jqObj).attr('class','brd1').attr('title',titleWwMapInstr).dblclick(rectClicked).each(function(idx){$(this).data('idx',idx);});jqObj.each(function(){container=this;});map.getContainer().appendChild(container);return container;}
MyControls.prototype.getDefaultPosition=function(){return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,7));}
ownCellsRectsBoundsH=[];ownCellsRectsMaxLatA=[];ownCellsRectsMinLatA=[];ownCellsRectsMinLonA=[];ownCellsRectsMaxLonA=[];ownCellsRectNWLats=[-159,-91,-23,45,113,181];ownCellsRectNWLons=[-255,-170,-85,0,85,170,255];function createOwnCellsRectsBounds(){ownCellsRectsBoundsH=[];ownCellsRectsMaxLatA=[];ownCellsRectsMinLatA=[];ownCellsRectsMinLonA=[];ownCellsRectsMaxLonA=[];var nwLat,seLat,nwLon,seLon;var theZoom=wwMap.getZoom();var theProjection=wwMap.getCurrentMapType().getProjection();var point=theProjection.fromLatLngToPixel(wwMap.getCenter(),theZoom);var centerY=point.y;var centerX=point.x;for(var i=0;i<ownCellsRectNWLats.length;i++){if(i==0){seLat=theProjection.fromPixelToLatLng(new GPoint(centerX,+centerY+ownCellsRectNWLats[i]),theZoom,true).lat();}else{nwLat=seLat;seLat=theProjection.fromPixelToLatLng(new GPoint(centerX,+centerY+ownCellsRectNWLats[i]),theZoom,true).lat();for(var j=0;j<ownCellsRectNWLons.length;j++){if(j==0){seLon=theProjection.fromPixelToLatLng(new GPoint(+centerX+ownCellsRectNWLons[j],point.y),theZoom,true).lng();}else{nwLon=seLon;seLon=theProjection.fromPixelToLatLng(new GPoint(+centerX+ownCellsRectNWLons[j],point.y),theZoom,true).lng();if(nwLon>180)nwLon-=360;if(nwLon<-180)nwLon+=360;if(seLon>180)seLon-=360;if(seLon<-180)seLon+=360;var rectBounds=new GLatLngBounds(new GLatLng(nwLat,nwLon),new GLatLng(seLat,seLon))
ownCellsRectsBoundsH.push(rectBounds);ownCellsRectsMaxLatA.push(toTopo(nwLat));ownCellsRectsMinLatA.push(toTopo(seLat));ownCellsRectsMinLonA.push(toTopo(nwLon));ownCellsRectsMaxLonA.push(toTopo(seLon));}}}}}
function showOwnCellsRectsLayer(){var layerDivJqObj=$('#ownCellsLayerGridDiv',ownCellsRectsLayerJqObj);if($('#ownCellsCB',ownCellsRectsLayerJqObj).attr('checked')){if($('#othersCellsCB',othersCellsRectsLayerJqObj).attr('checked')){$('#othersCellsCB').attr('checked',false);showOthersCellsRectsLayer();}
wwMap.disableDragging();wwMap.disableContinuousZoom();wwMap.disableScrollWheelZoom();wwMap.removeControl(wwMapGSmallZoomControl);ownCellsRects=true;wwMap.setCenter(new GLatLng(49,12),1);layerDivJqObj.css('display','block');$('#ownCellsInstructDiv').css('display','block');createOwnCellsRectsBounds();retrieveOwnCellsRectsColors(layerDivJqObj,wwMap.getZoom());}else{wwMap.enableDragging();wwMap.enableContinuousZoom();wwMap.enableScrollWheelZoom();wwMap.addControl(wwMapGSmallZoomControl);ownCellsRects=false;layerDivJqObj.css('display','none');$('#ownCellsInstructDiv').css('display','none');}}
function rectClicked(evt){if(!$(this).hasClass('hasMyCellsRect')){return;}
if(ownCellsRectsMaxLatA[0]==ownCellsRectsMinLatA[0]){return;}
var layerDivJqObj=$('#ownCellsLayerGridDiv',ownCellsRectsLayerJqObj);var rectBounds=ownCellsRectsBoundsH[$(this).data('idx')];if(wwMap.getZoom()>8){map.setCenter(rectBounds.getCenter());scheduleMapViewRefresh();plotPoint(map.getBounds().getSouthWest().lat(),map.getBounds().getSouthWest().lng());$('#ownCellsCB').attr('checked',false);showOwnCellsRectsLayer();tb_remove();return false;}
wwMap.setZoom(wwMap.getBoundsZoomLevel(rectBounds));wwMap.setCenter(rectBounds.getCenter());createOwnCellsRectsBounds();retrieveOwnCellsRectsColors(layerDivJqObj,wwMap.getZoom());return false;}
function retrieveOwnCellsRectsColors(layerDivJqObj,zoom){if(idUser==-1){showMsg('you must be logged in!',5000,'red');return;}
bcAjax(true,'bcsvr.php',{'do':'get-own-cells-rects','zoom':zoom,'maxLatA':ownCellsRectsMaxLatA.toString(),'minLatA':ownCellsRectsMinLatA.toString(),'minLonA':ownCellsRectsMinLonA.toString(),'maxLonA':ownCellsRectsMaxLonA.toString()},function(returnText){try{var bcOpRetStatus='';var ownCellsRectsA=[];eval(returnText);if(bcOpRetStatus=='SUCCESS'){colorOwnCellsRects(layerDivJqObj,ownCellsRectsA);}else{showMsg('cannot get own cells rects',5000,'yellow');}}catch(e){showMsg('error getting own cells rects; err='+e,5000,'red');}},null);}
function colorOwnCellsRects(layerDivJqObj,ownCellsRectsA){$('td',layerDivJqObj).each(function(idx){if(idx<ownCellsRectsA.length){if(ownCellsRectsA[idx]==1){$(this).attr('class','hasMyCellsRect');}else{$(this).attr('class','noneMyCellsRect');}
this.focus();}});}
var othersCellsRectsLayerJqObj=null;var othersCellsRects=false;function OthersCellsControl(){}
OthersCellsControl.prototype=new GControl();OthersCellsControl.prototype.initialize=function(map){var container;var jqObj=$("<div id=othersCellsLayerDiv class=pointerhand></div>");jqObj.append("<div id=othersCellsControlDiv> <input id=othersCellsCB type=checkbox onClick='showOthersCellsRectsLayer();' class=pointerhand><LABEL ID=\"lbForothersCellsCB\" FOR=\"othersCellsCB\" class=pointerhand> Others </LABEL></div>");jqObj.append("<div id=othersCellsInstructDiv>"+titleWwMapInstr+"</div>");jqObj.append("<div id=othersCellsLayerGridDiv><table width='100%' height='100%' border=0 cellpadding=0 cellspacing=0></table></div>");othersCellsRectsLayerJqObj=jqObj;if(othersCellsRects){$('#othersCellsCB',othersCellsRectsLayerJqObj).attr('checked','checked');}
for(var i=0;i<5;i++){$('table',jqObj).append('<tr></tr>');}
for(var i=0;i<6;i++){$('tr',jqObj).append('<td>&nbsp;</td>');}
$('td',jqObj).attr('class','brd1').attr('title',titleWwMapInstr).dblclick(rectClickedOthers).each(function(idx){$(this).data('idx',idx);});jqObj.each(function(){container=this;});map.getContainer().appendChild(container);return container;}
OthersCellsControl.prototype.getDefaultPosition=function(){return new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(77,7));}
othersCellsRectsBoundsH=[];othersCellsRectsMaxLatA=[];othersCellsRectsMinLatA=[];othersCellsRectsMinLonA=[];othersCellsRectsMaxLonA=[];othersCellsRectNWLats=[-159,-91,-23,45,113,181];othersCellsRectNWLons=[-255,-170,-85,0,85,170,255];function createOthersCellsRectsBounds(){othersCellsRectsBoundsH=[];othersCellsRectsMaxLatA=[];othersCellsRectsMinLatA=[];othersCellsRectsMinLonA=[];othersCellsRectsMaxLonA=[];var nwLat,seLat,nwLon,seLon;var theZoom=wwMap.getZoom();var theProjection=wwMap.getCurrentMapType().getProjection();var point=theProjection.fromLatLngToPixel(wwMap.getCenter(),theZoom);var centerY=point.y;var centerX=point.x;for(var i=0;i<othersCellsRectNWLats.length;i++){if(i==0){seLat=theProjection.fromPixelToLatLng(new GPoint(centerX,+centerY+othersCellsRectNWLats[i]),theZoom,true).lat();}else{nwLat=seLat;seLat=theProjection.fromPixelToLatLng(new GPoint(centerX,+centerY+othersCellsRectNWLats[i]),theZoom,true).lat();for(var j=0;j<othersCellsRectNWLons.length;j++){if(j==0){seLon=theProjection.fromPixelToLatLng(new GPoint(+centerX+othersCellsRectNWLons[j],point.y),theZoom,true).lng();}else{nwLon=seLon;seLon=theProjection.fromPixelToLatLng(new GPoint(+centerX+othersCellsRectNWLons[j],point.y),theZoom,true).lng();if(nwLon>180)nwLon-=360;if(nwLon<-180)nwLon+=360;if(seLon>180)seLon-=360;if(seLon<-180)seLon+=360;var rectBounds=new GLatLngBounds(new GLatLng(nwLat,nwLon),new GLatLng(seLat,seLon))
othersCellsRectsBoundsH.push(rectBounds);othersCellsRectsMaxLatA.push(toTopo(nwLat));othersCellsRectsMinLatA.push(toTopo(seLat));othersCellsRectsMinLonA.push(toTopo(nwLon));othersCellsRectsMaxLonA.push(toTopo(seLon));}}}}}
function showOthersCellsRectsLayer(){var layerDivJqObj=$('#othersCellsLayerGridDiv',othersCellsRectsLayerJqObj);if($('#othersCellsCB',othersCellsRectsLayerJqObj).attr('checked')){if($('#ownCellsCB',ownCellsRectsLayerJqObj).attr('checked')){$('#ownCellsCB').attr('checked',false);showOwnCellsRectsLayer();}
wwMap.disableDragging();wwMap.disableContinuousZoom();wwMap.disableScrollWheelZoom();wwMap.removeControl(wwMapGSmallZoomControl);othersCellsRects=true;wwMap.setCenter(new GLatLng(49,12),1);layerDivJqObj.css('display','block');$('#othersCellsInstructDiv').css('display','block');createOthersCellsRectsBounds();retrieveOthersCellsRectsColors(layerDivJqObj,wwMap.getZoom());}else{wwMap.enableDragging();wwMap.enableContinuousZoom();wwMap.enableScrollWheelZoom();wwMap.addControl(wwMapGSmallZoomControl);othersCellsRects=false;layerDivJqObj.css('display','none');$('#othersCellsInstructDiv').css('display','none');}}
function rectClickedOthers(evt){if(!$(this).hasClass('hasOthersCellsRect')){return;}
if(othersCellsRectsMaxLatA[0]==othersCellsRectsMinLatA[0]){return;}
var layerDivJqObj=$('#othersCellsLayerGridDiv',othersCellsRectsLayerJqObj);var rectBounds=othersCellsRectsBoundsH[$(this).data('idx')];if(wwMap.getZoom()>8){map.setCenter(rectBounds.getCenter());scheduleMapViewRefresh();plotPoint(map.getBounds().getSouthWest().lat(),map.getBounds().getSouthWest().lng());$('#othersCellsCB').attr('checked',false);showOthersCellsRectsLayer();tb_remove();return false;}
wwMap.setZoom(wwMap.getBoundsZoomLevel(rectBounds));wwMap.setCenter(rectBounds.getCenter());createOthersCellsRectsBounds();retrieveOthersCellsRectsColors(layerDivJqObj,wwMap.getZoom());return false;}
function retrieveOthersCellsRectsColors(layerDivJqObj,zoom){if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
bcAjax(true,'bcsvr.php',{'do':'get-others-cells-rects','zoom':zoom,'maxLatA':othersCellsRectsMaxLatA.toString(),'minLatA':othersCellsRectsMinLatA.toString(),'minLonA':othersCellsRectsMinLonA.toString(),'maxLonA':othersCellsRectsMaxLonA.toString()},function(returnText){try{var bcOpRetStatus='';var othersCellsRectsA=[];eval(returnText);if(bcOpRetStatus=='SUCCESS'){colorOthersCellsRects(layerDivJqObj,othersCellsRectsA);}else{showMsg('cannot get others cells rects',5000,'yellow');}}catch(e){showMsg('error getting others cells rects; err='+e,5000,'red');}},null);}
function colorOthersCellsRects(layerDivJqObj,othersCellsRectsA){$('td',layerDivJqObj).each(function(idx){if(idx<othersCellsRectsA.length){if(othersCellsRectsA[idx]==1){$(this).attr('class','hasOthersCellsRect');}else{$(this).attr('class','noneOthersCellsRect');}
this.focus();}});}
function calculateCellCoordsAroundPoint(pointLat,pointLon,radius){var resA=[];for(var i=-radius;i<=radius;i++){var lat=addLat(pointLat,i);for(var j=-radius;j<=radius;j++){var lon=addLon(pointLon,j);resA.push([lat,lon]);}}
return resA;}
function countMyStats(statName){if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
$$('#myTotalCells').html('<font color=#ddd>counting...</font>');bcAjax(true,'bcsvr.php',{'do':'count-user-'+statName},function(returnText){try{var bcOpRetStatus='';var userTotalCount=0;eval(returnText);if(bcOpRetStatus=='SUCCESS'){$$('#myTotalCells').html(" <font color=#ddd>You have "+userTotalCount+" "+statName+".</font>");if(statName=='cells'){if(userTotalCount==0){$$('#firstCellDiv').css('display','block');}else{$$('#firstCellDiv').css('display','none');}}}else{showMsg('failed to count your stats',5000,'yellow');$$('#myTotalCells').html('error');}}catch(e){showMsg('error counting your stats; err='+e,5000,'red');$$('#myTotalCells').html('error');}},null);}
function changeMyPass(){if(idUser==-1){showMsg('you must be logged in!',5000,'red');return;}
if($('#crtPass').val()==''){$$('#passChangeResult').html('Unable to complete request. Existing password is required.');return;}
if($('#newPass').val()==''){$$('#passChangeResult').html('Unable to complete request. New password is required.');return;}
if($('#newPass').val()!=$('#newPassB').val()){$$('#passChangeResult').html('New passwords do not match. Please correct.');return;}
$$('#passChangeResult').html('wait...');bcAjax(true,'bcsvr.php',{'do':'change-pass','crtPass':$('#crtPass').val(),'newPass':$('#newPass').val()},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){$$('#passChangeResult').html("Password changed.");$$('.passchange').val('');}else{showMsg('unable to change password',5000,'yellow');$$('#passChangeResult').html('<font color=red>'+returnText+'</font>');}}catch(e){showMsg('error changing password; err='+e,5000,'red');}},null);}
function saveNotifInfo(){var smsPhone=$.trim($('#smsPhone').val());var carrier=$.trim($('#carrier').val());var normalEmailSms=$.trim($('#normalEmailSms').val());var emailFilter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;var phoneFilter=/^([0-9\s])+$/;if(smsPhone==''&&normalEmailSms==''){$('#emailSmsChangeResult').html('<font color=red>specify either phone number or phone email !</font>');return;}
var email_sms='';if(smsPhone!=''){email_sms=smsPhone;if(!phoneFilter.test(smsPhone)){$('#emailSmsChangeResult').html('<font color=red>not a valid phone number (only numbers and spaces) !</font>');return;}
if(carrier==''){$('#emailSmsChangeResult').html('<font color=red>select a carrier from the list!</font>');return;}}else if(normalEmailSms!=''){email_sms=normalEmailSms;if(!emailFilter.test(normalEmailSms)){$('#emailSmsChangeResult').html('<font color=red>not a valid email address!</font>');return;}}
$('#emailSmsChangeResult').html('wait...');bcAjax(true,'bcsvr.php',{'do':'save-notif-info','email_sms':email_sms,'carrier':carrier,'quietTimeStart':0,'quietTimeEnd':0},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){$('#emailSmsChangeResult').html("Contact data saved. You will receive a numeric confirmation code on your phone. Enter it below to activate your SMS alerts.");$('#email_sms').html(email_sms+' <span style="color:gray; font-size:11px;">(inactive; not confirmed)</span>');$('#SMSnotifAddress').val(email_sms);$('#code2ConfirmDiv').css('display','block');}else{showMsg('cannot save notif info',9000,'yellow');$('#emailSmsChangeResult').html('<font color=red>'+returnText+'</font>');}}catch(e){showMsg('error saving notif info; err='+e,9000,'red');$('#emailSmsChangeResult').html('error');}},null);}
function confirmSmsCode(){var code=$.trim($('#smsCode2Confirm').val());var codeFilter=/^([0-9])+$/;if(code==''){$('#smsCode2ConfirmResult').html('<font color=gray>No code entered.</font>');return;}
if(!codeFilter.test(code)){$('#emailSmsChangeResult').html('<font color=red>Format is not valid. Use this format: 9999</font>');return;}
$('#smsCode2ConfirmResult').html('wait...');bcAjax(true,'bcsvr.php',{'do':'confirm-notif-code','code':code},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){$('#smsCode2ConfirmResult').html("<font color=gray>SMS contact confirmed.</font>");setTimeout(function(){$('#smsCode2ConfirmResult').html('');$('#emailSmsChangeResult').html('');$('#code2ConfirmDiv').css('display','none');$('#phoneSmsDiv').css('display','none');$('#normalEmailSmsDiv').css('display','none');},3000);$('#email_sms').html($('#SMSnotifAddress').val());}else{showMsg('cannot confirm code',5000,'yellow');$('#smsCode2ConfirmResult').html('<font color=red>'+returnText+'</font>');}}catch(e){showMsg('error confirming code; err='+e,5000,'red');$('#smsCode2ConfirmResult').html('error');}},null);}
function setNotifStatus(){bcAjax(true,'bcsvr.php',{'do':'set-notif-status','status':$('#isActiveSms').val()},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){if($('#isActiveSms').val()=='Y'){$('#notifSmsDetailsDiv').css('display','block');}else{$('#notifSmsDetailsDiv').css('display','none');}}else{showMsg('cannot set notif status:'+returnText,9000,'yellow');}}catch(e){showMsg('error setting notif status; err='+e,9000,'red');}},null);}
function setQuietTimeSms(){bcAjax(true,'bcsvr.php',{'do':'set-quiet-time','quietTmStart':$('#quietTmStart').val(),'quietTmEnd':$('#quietTmEnd').val(),'timezone':$('#timezone').val()},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){}else{showMsg('cannot set quiet time'+returnText,9000,'yellow');}}catch(e){showMsg('error setting quiet time; err='+e,9000,'red');}},null);}
function opacifyCells(opacityVal){if(opacityVal==-1){return;}
for(key in objCache){var cellJqObjDiv=objCache[key].theDivJq;cellJqObjDiv.css('filter','alpha(opacity='+opacityVal+')').css('opacity',opacityVal/100);}
var stack=CellPool.getStack();for(var i=0;i<stack.length;i++){stack[i].theDivJq.css('filter','alpha(opacity='+opacityVal+')').css('opacity',opacityVal/100);}}
function showCellBubble(lat,lon){if(typeof map=='undefined'||map==null){return;}
if(crtSubActionGui=='EditCity'){hideCellCity();}
map.setCenter(new GLatLng(fromTopo(lat),fromTopo(lon)));plotPoint(fromTopo(lat),fromTopo(lon));map.openInfoWindowHtml(map.getCenter(),"<font style='color:black;'><b>Target cell at designated coordinates<br>identified below:<br><br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ("+lat+", "+lon+")</b></font>",{noCloseOnClick:true,pixelOffset:new GSize(20,10)});reloadCrtMapView();}
function showSendInvite(){if(crtClickedCellObj==null||crtClickedCellObj.polRel!=POLREL_ME){showMsg("Select one of your cells to link to a friend.",6000,'yellow');return;}
bcAjax(true,'bcsvr.php',{'do':'check-cell-linked','lat':crtClickedCellLat,'lon':crtClickedCellLon},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){showMsg('This cell is already linked to an existing friend. Select another cell.',6000,'yellow');}else{$$('#sendInviteLink').click();}}catch(e){showMsg('Error checking cell; err='+e,6000,'red');}},null);}
var p1;function showMissile(){if(crtClickedCellObj==null||crtClickedCellObj.polRel!=POLREL_ME){showMsg("Select one of your cells with a missile.",6000,'yellow');return;}
bcAjax(true,'bcsvr.php',{'do':'check-missile-status','lat':crtClickedCellLat,'lon':crtClickedCellLon},function(returnText){try{if(returnText.indexOf('ERROR')!=-1){showMsg(returnText,6000,'yellow');}else if(returnText.indexOf('SUCCESS')!=-1){tb_remove(true);var destLatLonParam=(isNaN(misTargCoord.lat)||isNaN(misTargCoord.lon))?'':'&dlat='+misTargCoord.lat+'&dlon='+misTargCoord.lon;$$('#missileLink').attr('href','missilePanel.php?lat='+crtClickedCellLat+'&lon='+crtClickedCellLon+destLatLonParam+'&TB_iframe=true').click();dropToolOnTBClose=true;}else if(returnText.indexOf('inFlight')!=-1){try{eval(returnText);p1=new LatLon(fromTopo(mOLat),fromTopo(mOLon));timeDist=calcFlightMetrics(mAngle*1,mPower*100);p2=p1.destPoint(mAzimuth-0,timeDist[1]);LtoSDelta=parseInt(new Date().getTime().toString().substring(0,10))-nTs;$$('#missileGMapLink').click();}catch(e){showMsg('Error getting trajectory; err='+e,6000,'red');}}}catch(e){showMsg('Error checking cell; err='+e,6000,'red');}},null);}
function launchMissile(olat,olon){var cellObj=objCache[[olat,olon]];cellObj.theDiv.innerHTML=cellObj.theDiv.innerHTML.replace(MISSILECHAR,LAUNCHCHAR);tb_remove();setTimeout("showMissile()",500);}
function doSetPlacemark(keyCode,extraTxt,theIdx){var center=map.getCenter();var lat=center.lat();var lon=center.lng();bcAjax(true,'bcsvr.php',{'do':'set-placemark','lat':toTopo(lat),'lon':toTopo(lon),'extraTxt':extraTxt,'idx':theIdx},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){var jqObj=$$('#pmBut'+theIdx);jqObj.data('lat',lat);jqObj.data('lon',lon);jqObj.attr('class','pmBut');jqObj.attr('title',extraTxt);showMsg('placemark set !',4000,'green');}else{showMsg('cannot set placemark !',5000,'red');}}catch(e){showMsg('Error setting placemark; err='+e,6000,'red');}},null);}
function setPlacemark(keyCode,theIdx){var extraTxt='';geocoder.getLocations(map.getCenter(),function(response){if(!response||response.Status.code!=200){}else{place=response.Placemark[0];extraTxt=place.address;}
doSetPlacemark(keyCode,extraTxt,theIdx);});}
function getPlacemarks(){bcAjax(true,'bcsvr.php',{'do':'get-placemarks'},function(returnText){try{eval(returnText);for(var i=0;i<pmIdxA.length;i++){var jqObj=$$('#pmBut'+pmIdxA[i]);jqObj.data('lat',fromTopo(pmLatA[i])).data('lon',fromTopo(pmLonA[i])).attr('class','pmBut').attr('title',pmCommentA[i]);}}catch(e){showMsg('Error getting placemarks; err='+e,6000,'red');}},null);}
function gotoPm(pmIdx){var jqObj=$$('#pmBut'+pmIdx);var lat=jqObj.data('lat');var lon=jqObj.data('lon');if(typeof(lat)!='undefined'&&lat!=''&&typeof(lon)!='undefined'&&lon!=''){if(crtSubActionGui=='EditCity'){hideCellCity();}
map.setCenter(new GLatLng(lat,lon),map.getZoom());clearMapAndCache();scheduleMapViewRefresh();plotPoint(lat,lon);}}
function setIndustCtr(){if(crtClickedCellObj==null||crtClickedCellObj.polRel!=POLREL_ME){showMsg("Select one of your cells first.",6000,'yellow');return;}
bcAjax(true,'bcsvr.php',{'do':'set-indust-center','lat':crtClickedCellLat,'lon':crtClickedCellLon},function(returnText){try{if(returnText.indexOf('SET')==-1){showMsg(returnText,6000,'yellow');}else{if(returnText.indexOf('UNSET')!=-1){showMsg("Industrial Center cleared!",6000,'green');if(objCache[[crtClickedCellLat,crtClickedCellLon]]){vicinityObj=objCache[[crtClickedCellLat,crtClickedCellLon]];vicinityObj.theDiv.innerHTML=vicinityObj.theDiv.innerHTML.replace(PRODCTRCHAR,'');}}else{showMsg("Industrial Center set!",6000,'green');if(objCache[[crtClickedCellLat,crtClickedCellLon]]){vicinityObj=objCache[[crtClickedCellLat,crtClickedCellLon]];vicinityObj.theDiv.innerHTML=vicinityObj.theDiv.innerHTML.replace(PRODCTRCHAR,'');vicinityObj.theDiv.innerHTML+=PRODCTRCHAR;}}}}catch(e){showMsg('Error checking cell; err='+e,6000,'red');}},null);}
function setArenaCenter(){if(crtClickedCellObj==null){showMsg('click a cell near the shore!',5000,'yellow');return;}
disableObj('#confirmArenaCellBut');showMsg('setting arena map...',5000,'yellow');bcAjax(true,'bcsvr.php',{'do':'set-arena-center','lat':crtClickedCellLat,'lon':crtClickedCellLon,'fb_arena_mode':(typeof(FB_ARENA_MODE)!='undefined')?FB_ARENA_MODE:'','be_arena_mode':(typeof(BE_ARENA_MODE)!='undefined')?BE_ARENA_MODE:''},function(returnText){try{eval(returnText);if(msgTxt.indexOf('SUCCESS')!=-1){if((typeof(FB_ARENA_MODE)!='undefined'&&FB_ARENA_MODE=='bot')||(typeof(BE_ARENA_MODE)!='undefined'&&BE_ARENA_MODE=='bot')){id_game=idGame;setTimeout(startAIBotGame,1000);}else{showMsg(msgTxt,5000,'green');$$('#newArenaDiv').css('display','none');$$('#welcomeDiv').html(W2DIVTXT);$$('#firstCellDiv').css('display','block');$$('#mmIntro').click();$('#TB_window').css('zIndex','10000');expireTime=expireSec;startDate.setYear(startYear);startDate.setMonth(startMonth);startDate.setDate(startDay);startDate.setHours(startHour);startDate.setMinutes(startMinute);startDate.setSeconds(startSecond);initRadarDotsDiv();id_game=idGame;pj=1;}}else if(msgTxt.indexOf('WARNING')!=-1){showMsg(msgTxt,5000,'yellow');}else if(msgTxt.indexOf('ERROR')!=-1){showMsg(msgTxt,5000,'red');}
enableObj('#confirmArenaCellBut');}catch(e){showMsg('error setting arena map; err='+e,5000,'red');enableObj('#confirmArenaCellBut');}},null);}
function setArenaFirstCell(){if(idUser==-1){showMsg('you must be logged in !',5000,'red');return;}
if(crtClickedCellObj==null){showMsg('click a cell near the shore!',5000,'yellow');return;}
if(crtClickedCellObj.polRel!=POLREL_UNOWNED){showMsg("you cannot use this cell; already owned",5000,'yellow');return;}
disableObj('#confirmFirstCellBut');showMsg('setting empire center...',3000,'yellow');bcAjax(true,'bcsvr.php',{'do':'set-arena-first-cell','lat':crtClickedCellLat,'lon':crtClickedCellLon},function(returnText){try{if(returnText.indexOf('SUCCESS')!=-1){showMsg(returnText,5000,'green');$$('#firstCellDiv').css('display','none');$$('#leaveGameDiv').css('display','block');var cellObj=objCache[[crtClickedCellLat,crtClickedCellLon]];if(cellObj){cellObj.theDivJq.removeClass('crtCell');var theCellClass=calculateMyCellClass(cellObj);cellObj.theDivJq.attr('class',theCellClass);cellObj.reFill(cellObj.theBounds,theCellClass,0,0,cellObj.alt,idUser,POLREL_ME,cellObj.arrayPos);}}else if(returnText.indexOf('WARNING')!=-1){showMsg(returnText,5000,'yellow');}else if(returnText.indexOf('ERROR')!=-1){showMsg(returnText,5000,'red');}
enableObj('#confirmFirstCellBut');}catch(e){showMsg('error setting empire center; err='+e,5000,'red');enableObj('#confirmFirstCellBut');}},null);}
function startAIBotGame(){pCnt=0;for(var i=1;i<9;i++){if($$('#aPlNm'+i).text()!=''){pCnt++;}}
if(pCnt>1){showMsg('Other players detected. Cannot start robot game.',5000,'yellow');playSound('invalid');return;}
bcAjax(true,'bcsvr.php',{'do':'start-arena-bot-game'},function(returnText){try{if(returnText.indexOf('SUCCESS')==-1){showMsg(returnText,5000,'yellow');}else{eval(returnText);}}catch(e){showMsg('error starting bot game; err='+e,5000,'red');}},null);}
function startArenaTimer(){setInterval(showArenaTimer,1700);}
var bGnV=false;var aGsV=false;function showArenaTimer(){if(typeof(startDate)=='undefined'||startDate.getFullYear()==-1){return;}
var rightNow=new Date().getTime()-(LtoSDelta*1000);if(timerDirection=='+'){elapsedTime=rightNow-startDate.getTime();if(elapsedTime>=expireTime){elapsedTime=expireTime;}}else{elapsedTime=expireTime-(rightNow-startDate.getTime());if(elapsedTime<=0){elapsedTime=0;}
else if(elapsedTime<=30000){playSound('mTrack');}}
elapsedDays=Math.floor(elapsedTime/one_day);milliSecondsRemaining=elapsedTime%one_day;elapsedHours=Math.floor(milliSecondsRemaining/one_hour);milliSecondsRemaining=milliSecondsRemaining%one_hour;elapsedMinutes=Math.floor(milliSecondsRemaining/one_minute);milliSecondsRemaining=milliSecondsRemaining%one_minute;elapsedSeconds=Math.round(milliSecondsRemaining/one_second);elapsedHours=(elapsedHours<0)?0:elapsedHours;elapsedMinutes=(elapsedMinutes<0)?0:elapsedMinutes;elapsedSeconds=(elapsedSeconds<0)?0:elapsedSeconds;elapsedSeconds=(elapsedSeconds>=60)?59:elapsedSeconds;elapsedDays=(elapsedDays<10)?'0'+elapsedDays:elapsedDays;elapsedHours=(elapsedHours<10)?'0'+elapsedHours:elapsedHours;elapsedMinutes=(elapsedMinutes<10)?'0'+elapsedMinutes:elapsedMinutes;elapsedSeconds=(elapsedSeconds<10)?'0'+elapsedSeconds:elapsedSeconds;$$('#arenaTimer').html(timerDirection+elapsedHours+':'+elapsedMinutes+':'+elapsedSeconds);rightNow=null;if(timerDirection=='+'&&$$('#newArenaDiv').css('display')!='block'&&bGnV==false){$$('#showMsgDiv').jGrowl('Please wait for other players to join, or<br><br><span class="clickHereClass pointerhand closeBGn" onclick="startAIBotGame()">...click here to play against the computer.</span>',{theme:'aqua',sticky:true,open:function(e,m,o){bGnV=true;},close:function(e,m,o){bGnV=false;}});}
if(timerDirection=='-'&&pj==1&&!VOTE_TO_START&&aGsV==false){$$('#showMsgDiv').jGrowl('You can vote to start game immediately. Unanimous vote required.<br><br><span class="clickHereClass pointerhand closeBGn" onclick="voteToStartArena()">...vote to start now.</span>',{theme:'aqua',sticky:true,open:function(e,m,o){aGsV=true;},close:function(e,m,o){aGsV=false;}});}
if(timerDirection=='-'&&pj<3&&$$('#groupChatDiv').css('display')=='none'){$$('#groupChatDiv').fadeIn(501);}
if((timerDirection=='+'||pj==4||pj=='')&&$$('#groupChatDiv').css('display')!='none'){$$('#groupChatDiv').fadeOut(501);}
if((timerDirection=='+'&&elapsedTime>=expireTime)||(timerDirection=='-'&&elapsedTime<=0)){startDate.setYear(-1);bcAjax(true,'bcsvr.php',{'do':'expire-arena-timer'},function(returnText){if(returnText.indexOf('SUCCESS')==-1){showMsg('failed to report game timer expiration',5000,'red');}
if(returnText.indexOf('cmd=8')!=-1){setTimeout(window.close(),1100);}},null);}}
function setOnlineStatus(status){bcAjax(true,'bcsvr.php',{'do':'set-arena-online-status','online':status},function(returnText){if(returnText.indexOf('SUCCESS')==-1&&status==1){showMsg('failed to set online status',5000,'red');}},null);}
function sendArenaInvites(){showMsg('Inviting players from Main Map screen.',3000,'green');bcAjax(true,'bcsvr.php',{'do':'send-arena-invites'},function(returnText){},null);$('#sendGameInvitesBut').fadeOut(400);setTimeout(function(){$('#sendGameInvitesBut').fadeIn(400);},300000);}
function voteToStartArena(){bcAjax(true,'bcsvr.php',{'do':'vote-to-start-arena-game'},function(returnText){if(returnText.indexOf('SUCCESS')!=-1){VOTE_TO_START=true;showMsg('Request sent. Other players must click [START GAME NOW].',5000,'green');}},null);$('#voteToStartBut').fadeOut(400);}
function leaveArenaGame(){showMsg('Removing player records from game.',5000,'green');bcAjax(true,'bcsvr.php',{'do':'leave-arena-game','reqAllyUnitStats':(typeof(FB_ARENA_MODE)!='undefined')?'true':'false'},function(returnText){if(typeof(FB_ARENA_MODE)=='undefined'){window.close();}
$$('#firstCellDiv,#leaveGameDiv,#leaveGameEndDiv').css('display','none');$$('#newArenaDiv').css('display','block');$('.closeBGn').parent().parent().trigger('jGrowl.close');$$('#finalText').text('');for(slot=1;slot<=8;slot++){updateSlotName(slot,'');updateSlotCellCnt(slot,'');updateSlotImg(slot,'');}
startDate.setYear(-1);pj='';$$('#groupChatDiv').fadeOut(501);$$('#arenaTimer').html('+00:00:00');setTimeout(function(){showMapViewGui('Pol');},1000);playSound('left');$$('#addrSearchImg,#addrSearch').fadeIn(1000);$$('#arenaPlayerTbl2').fadeOut(1000);radarVisible(0);$$('#welcomeDiv').text('');$$('#welcomeDiv').html(WDIVTXT);$$('#mmIntro').click();$('#TB_window').css('zIndex','10000');aLat='';aLon='';aLat2='';aLon2='';waypointsA.length=0;try{eval(returnText);$$('#linkedCannonCnt').text(lau1);$$('#remCannon,#maxCannon').text(cmax);$$('#linkedBomberCnt').text(lau2);$$('#remBomber,#maxBomber').text(bmax);}catch(e){showMsg('unable to reset ally unit counts; err='+e,5000,'red');}},null);}
function startAbgLoop(){if(abgLoopIntervObj==null){abgLoopIntervObj=setInterval(abgLoop,ABG_LOOP_INTERVAL*1000);}}
function stopAbgLoop(){if(abgLoopIntervObj!=null){clearInterval(abgLoopIntervObj);abgLoopIntervObj=null;}}
deadTroopsNotSubstracted=0;moneyNotIncreased=0;abgLoopCnt4Paths=0;function abgLoop(){var cellObj;var theCellClass='';var prevTroops;var newTroops;var prevMoney;var newMoney;abgLoopCnt4Paths++;var haveAtLeastOneCellInView=false;deadTroopsNotSubstracted+=(ABG_LOOP_INTERVAL*TROOP_DEATHS_PER_SECOND);var troops2DieThisStep=(deadTroopsNotSubstracted|0);if(troops2DieThisStep>0){deadTroopsNotSubstracted-=troops2DieThisStep;}
moneyNotIncreased+=(ABG_LOOP_INTERVAL*CREDITS_PER_SECOND);var money2GrowThisStep=(moneyNotIncreased|0);if(money2GrowThisStep>0){moneyNotIncreased-=money2GrowThisStep;}
for(key in objCache){cellObj=objCache[key];theCellClass='';if(cellObj.idUser==idUser){haveAtLeastOneCellInView=true;}
prevTroops=cellObj.troops;newTroops=calcTimeAdjustedTroops(cellObj,troops2DieThisStep);prevMoney=cellObj.money;newMoney=calcTimeAdjustedMoney(cellObj,money2GrowThisStep);if(cellObj.theDiv.className=='cell_clicked'){$$('#cellDetailTroops').html(newTroops.toString());$$('#cellDetailCredits').html(newMoney.toString());}
if(crtMapView==BC_POL_VIEW_MAP){}else if(crtMapView==BC_ALT_VIEW_MAP){}else if(crtMapView==BC_MIL_VIEW_MAP){if(prevTroops!=newTroops&&!isPathCell(cellObj)){theCellClass=calculateCellClass4MilitaryViewFromCellobj(cellObj);cellObj.className=theCellClass;if(cellObj==crtClickedCellObj){crtClickedCellDivStyle=theCellClass;}else if(cellObj.theDiv.className=='cell_clicked'){}else{cellObj.theDiv.className=theCellClass;}}}else if(crtMapView==BC_FIN_VIEW_MAP){if(cellObj.idUser==idUser){if(prevMoney!=newMoney&&!isPathCell(cellObj)){theCellClass=calculateCellClass4FinanceViewFromCellobj(cellObj);cellObj.className=theCellClass;if(cellObj==crtClickedCellObj){crtClickedCellDivStyle=theCellClass;}else{cellObj.theDiv.className=theCellClass;}}}}}
if(crtMapView==BC_MIL_VIEW_MAP){}else if(crtMapView==BC_FIN_VIEW_MAP){if(!haveAtLeastOneCellInView){moneyNotIncreased=0;}}
if(showPaths&&abgLoopCnt4Paths>3){try{if(oldDbPathTopoLatA.length>0){removeAllOrphanPathCells();}}catch(ex){}
abgLoopCnt4Paths=0;}}
function calcTimeAdjustedMoney(cellobj,money2GrowThisStep){cellobj.money+=money2GrowThisStep;if(cellobj.money<0){cellobj.money=0;return cellobj.money;}
if(cellobj.money>MAX_CREDITS_ON_CELL){cellobj.money=MAX_CREDITS_ON_CELL;return cellobj.money;}
return cellobj.money;}
function calcTimeAdjustedTroops(cellobj,troops2DieThisStep){if(cellobj.troops<=MIN_TROOPS_ON_CELL){return cellobj.troops;}
cellobj.troops-=troops2DieThisStep;if(cellobj.troops<MIN_TROOPS_ON_CELL){cellobj.troops=MIN_TROOPS_ON_CELL;return cellobj.troops;}
return cellobj.troops;}
function calculateCellClass4FinanceViewFromCellobj(cellobj){var cellClass='';var nbOfCredits=cellobj.money;if(nbOfCredits<0){nbOfCredits=0;}
var creditsClassNb=0;if(nbOfCredits<=2){creditsClassNb=0;}else if(nbOfCredits<=7){creditsClassNb=1;}else if(nbOfCredits<=10){creditsClassNb=2;}else if(nbOfCredits<=14){creditsClassNb=3;}else if(nbOfCredits<=18){creditsClassNb=4;}else if(nbOfCredits<=19){creditsClassNb=5;}else if(nbOfCredits<=29){creditsClassNb=6;}else{creditsClassNb=7;}
var cellIdUser=cellobj.idUser;if(idUser==-1){if(cellIdUser!=0){cellClass=CELLCLASS_NEUTRAL;}else{}}else{if(cellIdUser==idUser){cellClass=CELLCLASS_FIN_MINE[creditsClassNb];}else if(cellIdUser!=0){cellClass=CELLCLASS_NEUTRAL;}else{}}
return cellClass;}
function calculateCellClass4MilitaryViewFromCellobj(cellobj){var cellClass=CELLCLASS_UNOWNED;var nbOfTroops=cellobj.troops;if(nbOfTroops<0){nbOfTroops=0;}
var troopsClassNb=0;if(nbOfTroops<3){troopsClassNb=0;}else if(nbOfTroops<8){troopsClassNb=1;}else if(nbOfTroops<13){troopsClassNb=2;}else if(nbOfTroops<18){troopsClassNb=3;}else if(nbOfTroops<23){troopsClassNb=4;}else if(nbOfTroops<40){troopsClassNb=5;}else{troopsClassNb=6;}
var cellIdUser=cellobj.idUser;if(idUser==-1){if(cellIdUser!=0){cellClass=CELLCLASS_MIL_NEUTRAL[troopsClassNb];}else{}}else{if(cellIdUser==idUser){cellClass=CELLCLASS_MIL_MINE[troopsClassNb];}else if(cellIdUser!=0){if(udH[cellIdUser]){if(udH[cellIdUser][1].indexOf('a')!=-1){cellClass=CELLCLASS_MIL_ALLY[troopsClassNb];}else{cellClass=CELLCLASS_MIL_ENEMY[troopsClassNb];}}else{cellClass=CELLCLASS_MIL_NEUTRAL[troopsClassNb];}}else{}}
return cellClass;}
function startAbgLoop4Paths(){if(abgLoop4PathsIntervObj==null){abgLoop4PathsIntervObj=setInterval(abgLoop4Paths,ABG_LOOP4PATHS_INTERVAL*1000);}}
function stopAbgLoop4Paths(){if(abgLoop4PathsIntervObj!=null){clearInterval(abgLoop4PathsIntervObj);abgLoop4PathsIntervObj=null;}}
function abgLoop4Paths(){if(!showPaths){stopAbgLoop4Paths();return;}
refreshPaths();try{if(oldDbPathTopoLatA.length>0){removeAllOrphanPathCells();}}catch(ex){}}
function refreshPaths(){var mapTopoCoords=getMapTopoCoords();if(showPaths){getCells4AllPaths(mapTopoCoords[0],mapTopoCoords[1],mapTopoCoords[2],mapTopoCoords[3]);}}
function removePath(pathId){for(var i=0;i<oldDbPathTopoLatA.length;i++){if(pathId==oldDbPathTopoMoveIdA[i]){var cellObj=objCache[[oldDbPathTopoLatA[i],oldDbPathTopoLonA[i]]];if(cellObj){if(cellObj==crtClickedCellObj){crtClickedCellDivStyle=cellObj.cellClass;}else{cellObj.theDiv.className=cellObj.cellClass;}
cellObj.theDiv.innerHTML='';}}}
try{delete oldDbPathTopoUniqueMoveIdH[pathId];map.removeOverlay(polylineCache[pathId]);}catch(ex){}
try{if(oldDbPathTopoLatA.length>0){removeAllOrphanPathCells();}}catch(ex){}}
function removeAllOrphanPathCells(){for(key in objCache){var someCellObj=objCache[key];if(isPathCell(someCellObj)){var isOrphan=true;for(var i=0;i<dbPathTopoLatA.length;i++){var cellObj=objCache[[dbPathTopoLatA[i],dbPathTopoLonA[i]]];if(cellObj==someCellObj){isOrphan=false;break;}}
if(isOrphan){if(someCellObj==crtClickedCellObj){someCellObj.theDiv.className=someCellObj.cellClass;crtClickedCellDivStyle=someCellObj.cellClass;}else{someCellObj.theDiv.className=someCellObj.cellClass;}
someCellObj.theDiv.innerHTML='';showMsg('ORPHAN removed: '+someCellObj.cellClass,5000,'yellow');}}}}
function isPathCell(cellobj){if(cellobj.className=='dbpath'||cellobj.className=='dbpath_crtpos'||(cellobj==crtClickedCellObj&&(crtClickedCellDivStyle=='dbpath'||crtClickedCellDivStyle=='dbpath_crtpos'))){return true;}
return false;}
var pulsIntervObj=null;function startPulsLoop(){if(pulsIntervObj==null){pulsIntervObj=setInterval(doPuls,700);doPuls();}}
function stopPulsLoop(){if(pulsIntervObj!=null){clearInterval(pulsIntervObj);pulsIntervObj=null;}}
crtMapView4puls='';function doPuls(){if(crtMapView4puls==''){crtMapView4puls=crtMapView;}
if(crtMapView4puls!=''&&crtMapView4puls!=crtMapView){if(objCache.length!=0){detectSelectedCells();crtMapView4puls=crtMapView;}}
var len=crtRClickedCellA.length;if(len==0&&crtClickedCellObj!=null){var cellDivJq=crtClickedCellObj.theDivJq;if(cellDivJq.attr('className')=='cell_clicked'){cellDivJq.attr('className',crtClickedCellObj.cellClass);}else{cellDivJq.attr('className','cell_clicked');}}else if(crtRClickedCellA.length>0){var cellDivJq=crtRClickedCellA[0]['obj'].theDivJq;var crtBlinkClass='cell_clicked';if(cellDivJq.attr('className')=='cell_clicked'){crtBlinkClass=crtRClickedCellA[0]['obj'].cellClass;}
for(var i=0;i<len;i++){crtRClickedCellA[i]['obj'].theDivJq.attr('className',crtBlinkClass);}}}
function arcAnim(sx,sy,dx,dy,duration){$$("#dot1").css({top:(sy-2)+'px',left:(sx-2)+'px',display:'block'}).animate({top:(dy-2)+'px',left:(dx-2)+'px'},duration,'linear',function(){$$("#dot1").css({display:'none'});});}
function detectSelectedCells(){var len=crtRClickedCellA.length;if(len==0&&crtClickedCellObj!=null){}else{for(var i=0;i<len;i++){var cellObj=objCache[[crtRClickedCellA[i]['lat'],crtRClickedCellA[i]['lon']]];crtRClickedCellA[i]['obj']=cellObj;crtRClickedCellA[i]['style']=cellObj.cellClass;}}}

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by www.bitethebullet.co.uk to display
 * Google Maps in a modal window
 */
var tb_pathToImage="images/loadingAnimation.gif";var wwMap=null;jQuery(document).ready(function(){tb_init('a.thickbox, area.thickbox, input.thickbox');imgLoader=new Image();imgLoader.src=tb_pathToImage;});function tb_init(domChunk){jQuery(domChunk).click(function(){var t=this.title||this.name||null;var a=this.href||this.alt;var g=this.rel||false;tb_show(t,a,g);this.blur();return false;});}
function tb_show(caption,url,imageGroup){try{if(document.getElementById("TB_overlay")===null){$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");$("#TB_overlay").click(tb_remove);}
if(caption===null){caption="";}
$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");$('#TB_load').show();var baseURL;if(url.indexOf("?")!==-1){baseURL=url.substr(0,url.indexOf("?"));}else{baseURL=url;}
var urlString=/\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;var urlType=baseURL.toLowerCase().match(urlString);if(urlType=='.jpg'||urlType=='.jpeg'||urlType=='.png'||urlType=='.gif'||urlType=='.bmp'){TB_PrevCaption="";TB_PrevURL="";TB_PrevHTML="";TB_NextCaption="";TB_NextURL="";TB_NextHTML="";TB_imageCount="";TB_FoundURL=false;if(imageGroup){TB_TempArray=jQuery("a[@rel="+imageGroup+"]").get();for(TB_Counter=0;((TB_Counter<TB_TempArray.length)&&(TB_NextHTML===""));TB_Counter++){var urlTypeTemp=TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);if(!(TB_TempArray[TB_Counter].href==url)){if(TB_FoundURL){TB_NextCaption=TB_TempArray[TB_Counter].title;TB_NextURL=TB_TempArray[TB_Counter].href;TB_NextHTML="<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";}else{TB_PrevCaption=TB_TempArray[TB_Counter].title;TB_PrevURL=TB_TempArray[TB_Counter].href;TB_PrevHTML="<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";}}else{TB_FoundURL=true;TB_imageCount="Image "+(TB_Counter+1)+" of "+(TB_TempArray.length);}}}
imgPreloader=new Image();imgPreloader.onload=function(){imgPreloader.onload=null;var pagesize=tb_getPageSize();var x=pagesize[0]-150;var y=pagesize[1]-150;var imageWidth=imgPreloader.width;var imageHeight=imgPreloader.height;if(imageWidth>x){imageHeight=imageHeight*(x/imageWidth);imageWidth=x;if(imageHeight>y){imageWidth=imageWidth*(y/imageHeight);imageHeight=y;}}else if(imageHeight>y){imageWidth=imageWidth*(y/imageHeight);imageHeight=y;if(imageWidth>x){imageHeight=imageHeight*(x/imageWidth);imageWidth=x;}}
TB_WIDTH=imageWidth+30;TB_HEIGHT=imageHeight+60;jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>"+"<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>"+TB_imageCount+TB_PrevHTML+TB_NextHTML+"</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");jQuery("#TB_closeWindowButton").click(tb_remove);if(!(TB_PrevHTML==="")){function goPrev(){if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
jQuery("#TB_window").remove();jQuery("body").append("<div id='TB_window'></div>");tb_show(TB_PrevCaption,TB_PrevURL,imageGroup);return false;}
jQuery("#TB_prev").click(goPrev);}
if(!(TB_NextHTML==="")){function goNext(){jQuery("#TB_window").remove();jQuery("body").append("<div id='TB_window'></div>");tb_show(TB_NextCaption,TB_NextURL,imageGroup);return false;}
jQuery("#TB_next").click(goNext);}
tb_position();jQuery("#TB_load").remove();jQuery("#TB_ImageOff").click(tb_remove);jQuery("#TB_window").css({display:"block"});};imgPreloader.src=url;}else{var queryString=url.replace(/^[^\?]+\??/,'');var params=tb_parseQuery(queryString);TB_WIDTH=(params['width']*1)+30||620;TB_HEIGHT=(params['height']*1)+40||460;ajaxContentW=TB_WIDTH-58;ajaxContentH=TB_HEIGHT-58;if(url.indexOf('TB_iframe')!=-1){urlNoQuery=url.split('TB_');$("#TB_iframeContent").remove();if(params['modal']!="true"){$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close' style='color: #FFF; text-shadow: #000 0 0 4px;'>close</a>&nbsp;&nbsp;</div></div><iframe allowtransparency='true' scrolling='no' frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW+29)+"px;height:"+(ajaxContentH+17)+"px;' > </iframe>");}else{$("#TB_overlay").unbind();$("#TB_window").append("<iframe allowtransparency='true' scrolling='no' frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW+29)+"px;height:"+(ajaxContentH+17)+"px;'> </iframe>");}}else{if($("#TB_window").css("display")!="block"){if(params['modal']!="true"){$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' style='color: #FFF; text-shadow: #000 0 0 4px;'>close</a>&nbsp;&nbsp;</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");}else{$("#TB_overlay").unbind();$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");}}else{$("#TB_ajaxContent")[0].style.width=ajaxContentW+"px";$("#TB_ajaxContent")[0].style.height=ajaxContentH+"px";$("#TB_ajaxContent")[0].scrollTop=0;$("#TB_ajaxWindowTitle").html(caption);}}
$("#TB_closeWindowButton").click(tb_remove);if(params['HideOverlay']!=1){if(tb_detectMacXFF()){$("#TB_overlay").addClass("TB_overlayMacFFBGHack");}else{$("#TB_overlay").addClass("TB_overlayBG");}}
if(url.indexOf('TB_inline')!=-1){srcId='#'+params['inlineId'];$("#TB_ajaxContent").append($(srcId).children());$("#TB_window").unload(function(){$(srcId).append($("#TB_ajaxContent").children());});$('#TB_ajaxContent').css({overflow:"hidden"});$(srcId).css({width:ajaxContentW,height:ajaxContentH});tb_position();$("#TB_load").remove();$("#TB_window").css({display:"block"});}else if(url.indexOf('TB_googleMap')!=-1){var mapDiv=document.createElement('div');mapDiv.id='googleMap';var underDiv=document.createElement('div');$(underDiv).attr('class','underDiv');$(underDiv).append(mapDiv);$('#TB_ajaxContent').append(underDiv);$('#TB_ajaxContent').css({overflow:"hidden"});$('#googleMap').css({width:ajaxContentW,height:ajaxContentH});$('#TB_window').unload(function(){$("#googleMap").remove();wwMap=null;});tb_position();$("#TB_load").remove();$("#TB_window").css({display:"block"});loadGoogleMap(params["zoom"],params["markerText"],params);if(params["arena"]==1&&aLat!=''&&aLon!=''&&aLat2!=''&&aLon2!=''){arenaRect=new GPolygon([new GLatLng(fromTopo(aLat),fromTopo(aLon)),new GLatLng(fromTopo(aLat2),fromTopo(aLon)),new GLatLng(fromTopo(aLat2),fromTopo(aLon2)),new GLatLng(fromTopo(aLat),fromTopo(aLon2)),new GLatLng(fromTopo(aLat),fromTopo(aLon))],"#000000",1,0.3,"#999999",0.3,{clickable:false});wwMap.addOverlay(arenaRect);}}else if(url.indexOf('TB_missileGMap')!=-1){var mapDiv=document.createElement('div');mapDiv.id='googleMap';var underDiv=document.createElement('div');$(underDiv).attr('class','underDiv');$(underDiv).append(mapDiv);$('#TB_ajaxContent').append(underDiv);$('#TB_ajaxContent').css({overflow:"hidden"});$('#googleMap').css({width:ajaxContentW,height:ajaxContentH});$('#TB_window').unload(function(){$("#googleMap").remove();wwMap=null;});tb_position();$("#TB_load").remove();$("#TB_window").css({display:"block"});loadMissileGMap(params["zoom"],params["markerText"],params);}else if(url.indexOf('TB_iframe')!=-1){tb_position();if($.browser.safari){$("#TB_load").remove();$("#TB_window").css({display:"block"});}}else{$("#TB_ajaxContent").load(url+="&random="+(new Date().getTime()),function(){tb_position();$("#TB_load").remove();tb_init("#TB_ajaxContent a.thickbox");$("#TB_window").css({display:"block"});});}}}catch(e){}}
function loadGoogleMap(zoom,html,params){if(GBrowserIsCompatible()){if(wwMap==null){wwMap=new GMap2(document.getElementById("googleMap"),{backgroundColor:"#9DB3CA"});wwMap.enableScrollWheelZoom();if(typeof idUser!='undefined'){if(idUser!=-1){wwMap.addControl(new MyControls());wwMap.addControl(new OthersCellsControl());}}
wwMapGSmallZoomControl=new GSmallZoomControl();wwMap.addControl(wwMapGSmallZoomControl);wwMap.addControl(new GMapTypeControl());if($.browser.msie&&$.browser.version>=8){GEvent.addListener(wwMap,"mousemove",function(point){ie8SavedPoint=point;});GEvent.addListener(wwMap,"click",function(overlay,point){if($('#ownCellsCB',ownCellsRectsLayerJqObj).attr('checked')){return;}
tb_remove();map.setCenter(ie8SavedPoint);scheduleMapViewRefresh();plotPoint(ie8SavedPoint.y,ie8SavedPoint.x);});}else{GEvent.addListener(wwMap,"click",function(overlay,point){if($('#ownCellsCB',ownCellsRectsLayerJqObj).attr('checked')){return;}
tb_remove();map.setCenter(point);scheduleMapViewRefresh();plotPoint(point.y,point.x);});}}
var point=map.getCenter();wwMap.setCenter(point,0);wwMap.clearOverlays();var bounds=new GLatLngBounds();var marker=createMarker(point,'you are here');wwMap.addOverlay(marker);if(zoom!=null){wwMap.setZoom(parseInt(zoom));}else{wwMap.setZoom(wwMap.getBoundsZoomLevel(bounds));}
showOwnCellsRectsLayer();showOthersCellsRectsLayer();}}
var mCrossHair;var mPoint;function loadMissileGMap(zoom,html,params){if(GBrowserIsCompatible()){if(wwMap==null){wwMap=new GMap2(document.getElementById("googleMap"),{backgroundColor:"#9DB3CA"});wwMap.addControl(new GMapTypeControl());}
mPoint=getCurMissileLoc(mOLat,mOLon,mTs,LtoSDelta,mAzimuth,mAngle,mPower);var point=new GLatLng(toDeg(mPoint.lat),toDeg(mPoint.lon));GEvent.addListener(wwMap,"dragstart",function(){aUTskipUpdate=true;wwMap.removeOverlay(mCrossHair[0]);wwMap.removeOverlay(mCrossHair[1]);wwMap.removeOverlay(mCrossHair[2]);wwMap.removeOverlay(mCrossHair[3]);});GEvent.addListener(wwMap,"dragend",function(){mCrossHair=createMissileCross(toDeg(mPoint.lat),toDeg(mPoint.lon));wwMap.addOverlay(mCrossHair[0]);wwMap.addOverlay(mCrossHair[1]);wwMap.addOverlay(mCrossHair[2]);wwMap.addOverlay(mCrossHair[3]);aUTskipUpdate=false;});var polylineTraj=GPolyline.fromEncoded({color:'#F00',weight:1,opacity:0.8,points:GPLPoints,zoomFactor:GPLZoomFactor,levels:GPLLevels,numLevels:GPLNumLevels});var polylineTrajNc=GPolyline.fromEncoded({color:'#000',weight:1,opacity:0.8,points:GPLPointsNc,zoomFactor:GPLZoomFactorNc,levels:GPLLevelsNc,numLevels:GPLNumLevelsNc});var bounds=polylineTraj.getBounds();var mapZoom=wwMap.getBoundsZoomLevel(bounds);if(mapZoom<zoom)mapZoom=zoom;wwMap.setCenter(point,mapZoom-0);wwMap.clearOverlays();point=map.getCenter();var marker=createMarker(point,'you are here');wwMap.addOverlay(marker);mCrossHair=createMissileCross(toDeg(mPoint.lat),toDeg(mPoint.lon));wwMap.addOverlay(polylineTrajNc);wwMap.addOverlay(polylineTraj);wwMap.addOverlay(mCrossHair[0]);wwMap.addOverlay(mCrossHair[1]);wwMap.addOverlay(mCrossHair[2]);wwMap.addOverlay(mCrossHair[3]);autoUpdateTrajectory(true);}}
var aUTstat=false;var aUTskipUpdate=false;var mStrikeNotice=[];function autoUpdateTrajectory(firstRun){if(aUTstat&&firstRun)return;aUTstat=true;if(!aUTskipUpdate){playSound('mTrack');wwMap.removeOverlay(mCrossHair[0]);wwMap.removeOverlay(mCrossHair[1]);wwMap.removeOverlay(mCrossHair[2]);wwMap.removeOverlay(mCrossHair[3]);mPoint=getCurMissileLoc(mOLat,mOLon,mTs,LtoSDelta,mAzimuth,mAngle,mPower);if(mPoint.strike_area_width!=0){var point=new GLatLng(fromTopo(mPoint.lat),fromTopo(mPoint.lon));map.setCenter(point,11);reloadCrtMapView();tb_remove();aUTstat=false;doMissileStrikeAnimation(mPoint.lat,mPoint.lon,mPoint.strike_area_width-1)
return;}
if(!wwMap.getBounds().contains(new GLatLng(toDeg(mPoint.lat),toDeg(mPoint.lon))))
wwMap.setCenter(new GLatLng(toDeg(mPoint.lat),toDeg(mPoint.lon)));mCrossHair=createMissileCross(toDeg(mPoint.lat),toDeg(mPoint.lon));wwMap.addOverlay(mCrossHair[0]);wwMap.addOverlay(mCrossHair[1]);wwMap.addOverlay(mCrossHair[2]);wwMap.addOverlay(mCrossHair[3]);}
setTimeout(function(){if(wwMap){autoUpdateTrajectory(false);}else{aUTstat=false;if(mStrikeNotice.length){doCronDaemonMStrikeNotice(mStrikeNotice[0],mStrikeNotice[1],mStrikeNotice[2]);}}},15000);}
function doMissileStrikeAnimation(lat,lon,strike_area_width){setTimeout(function(){if(busy){doMissileStrikeAnimation(lat,lon,strike_area_width);}else if(strike_area_width<0){setTimeout("playSound('mStrikeF')",2000);setTimeout(function(){showMsg('Missile intercepted and destroyed at: '+lat+', '+lon,5000,'green');var cellObj=objCache[[lat,lon]];if(cellObj){var theDivjqObj=$(cellObj.theDiv);var origClass=theDivjqObj.attr("class");theDivjqObj.css('background-color','orange');theDivjqObj.animate({backgroundColor:'#000000'},2000,'swing',function(){$(this).css('background-color','').removeClass().addClass(origClass);});}
crtClickedCellDiv=null;},3000);}else{setTimeout("playSound('mStrike')",2000);setTimeout(function(){var strikableCellsA=calculateCellCoordsAroundPoint(lat,lon,strike_area_width);var visibleStrikableDivsA=[];var previousBgColorA=[];for(var i=0;i<strikableCellsA.length;i++){var cellObj=objCache[[strikableCellsA[i][0],strikableCellsA[i][1]]];if(cellObj){cellObj.cellClass=CELLCLASS_UNOWNED;cellObj.idUser=0;cellObj.troops=0;cellObj.money=0;var theDivjqObj=$(cellObj.theDiv);if(crtMapView==BC_ALT_VIEW_MAP){previousBgColorA.push(theDivjqObj.css('background-color'));}else{previousBgColorA.push('#524F4A');}
theDivjqObj.css('background-color','orange');visibleStrikableDivsA.push(theDivjqObj);}}
showMsg('Missile hit at: '+lat+', '+lon,5000,'green');for(var i=0;i<visibleStrikableDivsA.length;i++){visibleStrikableDivsA[i].animate({backgroundColor:previousBgColorA[i]},2000,'swing',function(){$(this).css('background-color','').html('');if(crtMapView!=BC_ALT_VIEW_MAP){$(this).attr('class',CELLCLASS_UNOWNED);}});}
crtClickedCellDiv=null;},3000);}},500);}
function doCronDaemonMStrikeNotice(msg,jGclass,snd){if(wwMap&&aUTstat){mStrikeNotice=[msg,jGclass,snd];return;}
showMsg(msg.replace(/`:\]/g,'<').replace(/\[:`/g,'>'),5000,jGclass);playSound(snd);mStrikeNotice=[];}
function toRad(deg){return deg*Math.PI/180;}
function toDeg(rad){deg=rad*180/Math.PI;if(deg>180)deg-=360;if(deg<-180)deg+=360;return deg;}
function toBrng(rad){return(toDeg(rad)+360)%360;}
LatLon.prototype.destPoint=function(brng,d){var R=6371;var lat1=toRad(this.lat),lon1=toRad(this.lon);brng=toRad(brng);var lat2=Math.asin(Math.sin(lat1)*Math.cos(d/R)+
Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng));var lon2=lon1+Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));if(isNaN(lat2)||isNaN(lon2))return null;return new LatLon(lat2,lon2,0);}
function LatLon(lat,lon,done){this.lat=lat;this.lon=lon;this.strike_area_width=done;}
function calcFlightMetrics(angle,vh){var vx=vh*Math.cos(toRad(angle));var vy=vh*Math.sin(toRad(angle));var ge=9.80665;var geB=ge/2;var rsA=new Array();rsA[0]=vy/geB;rsA[1]=vx*rsA[0]/1000;return rsA;}
function getCurMissileLoc(olat,olon,tsStrike,tsDelta,azimuth,angle,power){var sTs=parseInt(new Date().getTime().toString().substring(0,10))-tsDelta;var tjComplete=0;var timeDist=calcFlightMetrics(angle*1,power*100);if(sTs>tsStrike){tjComplete=1;var ajaxReqVars={'do':'check-missile-strike','lat':olat,'lon':olon};bcAjax(false,'bcsvr.php',ajaxReqVars,function(returnText){try{if(returnText.indexOf('ERROR')!=-1){showMsg(returnText,6000,'yellow');}else if(returnText.indexOf('interceptNow')!=-1){eval(returnText);p2=new LatLon(mDLat,mDLon,-1);}else if(returnText.indexOf('strikeNow')!=-1){eval(returnText);getLandCellsCallbackDataA=[];getLandCellsCallbackDataA[0]=origStatsA;getLandCellsCallbackFuncA=[];getLandCellsCallbackFuncA[0]=function(elPos){if(crtMapView==BC_ALT_VIEW_MAP||getLandCellsCallbackDataA[elPos].length==0)return;$.each(getLandCellsCallbackDataA[elPos],function(idx,cellDataA){var cellKey=[cellDataA["lat"],cellDataA["lon"]];if(objCache[cellKey]){objCache[cellKey].troops=cellDataA["troops"];objCache[cellKey].money=cellDataA["money"];objCache[cellKey].idUser=cellDataA["id_user"];objCache[cellKey].polRel=computePolRel(cellDataA["id_user"]);var theCellClass;switch(objCache[cellKey].polRel){case POLREL_ME:theCellClass=calculateMyCellClass(objCache[cellKey]);break;case POLREL_ALLY:theCellClass=calculateAllyCellClass(objCache[cellKey]);break;case POLREL_ENEMY:theCellClass=calculateEnemyCellClass(objCache[cellKey]);break;case POLREL_NEUTRAL:theCellClass=calculateNeutralCellClass(objCache[cellKey]);break;default:theCellClass=CELLCLASS_UNOWNED;}
objCache[cellKey].cellClass=theCellClass;objCache[cellKey].theDivJq.removeClass().addClass(theCellClass);}});};p2=new LatLon(mDLat,mDLon,strikeRadius);}else{eval(returnText);sTs=parseInt(new Date().getTime().toString().substring(0,10))-nTs;launchTs=mTs-timeDist[0];flownTime=sTs-launchTs;tjComplete=flownTime/timeDist[0];}}catch(e){reportAjaxError('getCurMissileLoc()',JSON.stringify(ajaxReqVars),returnText,e);}},null);}else{launchTs=tsStrike-timeDist[0];flownTime=sTs-launchTs;tjComplete=flownTime/timeDist[0];}
if(p2.strike_area_width!=0)return p2;var flownDist=timeDist[1]*tjComplete;p2=p1.destPoint(azimuth-0,flownDist);return p2;}
function createMissileCross(lat,lon){var mCrossHair=new Array();var crossOffset=-0.185*wwMap.getZoom()+2;if(crossOffset<0.05)crossOffset=0.05;mCrossHair[0]=new GPolyline([new GLatLng(lat+crossOffset,lon),new GLatLng(90,lon)],'#000',1,.7);mCrossHair[1]=new GPolyline([new GLatLng(lat-crossOffset,lon),new GLatLng(-90,lon)],'#000',1,.7);mCrossHair[2]=new GPolyline([new GLatLng(lat,lon+crossOffset),new GLatLng(lat,lon+40),new GLatLng(lat,wwMap.getBounds().getNorthEast().lng()+10)],'#000',1,.7);mCrossHair[3]=new GPolyline([new GLatLng(lat,wwMap.getBounds().getSouthWest().lng()-10),new GLatLng(lat,lon-40),new GLatLng(lat,lon-crossOffset)],'#000',1,.7);return mCrossHair;}
var hereIcon=new GIcon();hereIcon.image="images/skins/glass/05_UI_Whole_Map_hereIcon.png"
hereIcon.iconSize=new GSize(8,8);hereIcon.iconAnchor=new GPoint(4,4);function createMarker(point,text){var marker=new GMarker(point,{icon:hereIcon});if(text&&text!=''){GEvent.addListener(marker,"click",function(){marker.openInfoWindowHtml(text);});}
return marker;}
function tb_showIframe(){$("#TB_load").remove();$("#TB_window").css({display:"block"});}
function tb_remove(doFast){$("#TB_imageOff").unbind("click");$("#TB_closeWindowButton").unbind("click");if(doFast){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}else{$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});}
$("#TB_load").remove();if(crtActionGui=='Upgrade'&&dropToolOnTBClose){cancelActionGui();dropToolOnTBClose=false;}else if(crtSubActionGui!=''&&dropToolOnTBClose){cancelSubActionGui(crtSubActionGui);dropToolOnTBClose=false;}
return false;}
function tb_position(){jQuery("#TB_window").css({marginLeft:'-'+parseInt((TB_WIDTH/2),10)+'px',width:TB_WIDTH+'px',height:TB_HEIGHT+'px'});if(!(jQuery.browser.msie&&jQuery.browser.version<7)){$("#TB_window").css({marginTop:'-'+parseInt((TB_HEIGHT/2),10)+'px'});}}
function tb_parseQuery(query){var Params={};if(!query){return Params;}
var Pairs=query.split(/[;&]/);for(var i=0;i<Pairs.length;i++){var KeyVal=Pairs[i].split('=');if(!KeyVal||KeyVal.length!=2){continue;}
var key=unescape(KeyVal[0]);var val=unescape(KeyVal[1]);val=val.replace(/\+/g,' ');Params[key]=val;}
return Params;}
function tb_getPageSize(){var de=document.documentElement;var w=window.innerWidth||self.innerWidth||(de&&de.clientWidth)||document.body.clientWidth;var h=window.innerHeight||self.innerHeight||(de&&de.clientHeight)||document.body.clientHeight;arrayPageSize=[w,h];return arrayPageSize;}
function tb_detectMacXFF(){var userAgent=navigator.userAgent.toLowerCase();if(userAgent.indexOf('mac')!=-1&&userAgent.indexOf('firefox')!=-1){return true;}}
function doChatCmd(chatTxt){try{chatTxtCmdA=chatTxt.split("~");for(cmdId in chatTxtCmdA){eval(chatTxtCmdA[cmdId]);switch(ccmd){case 1:updateCellOwner(clat,clon,cval1,cval2);break;case 2:updateCellTroops(clat,clon,cval1);break;case 3:updateCellShips(clat,clon,cval1);break;case 4:detonateNuke(clat,clon,cval1);break;case 5:resetArenaTimer(cval1,cval2);break;case 6:cval1=cval1.replace(/`:\]/g,'<').replace(/\[:`/g,'>');showMsg(cval1,5000,cval2);break;case 7:playSound(cval1);break;case 8:closeArenaWindow();break;case 9:showMapViewGui(cval1);break;case 10:hideLeaveGameDiv();break;case 11:updateSlotName(cval1,cval2);break;case 12:removePath(cval1);break;case 13:updateSlotCellCnt(cval1,cval2);break;case 14:doArenaEndTbPane(cval1,cval2);break;case 15:$$('#leaveGameEndDiv').css('display','block');break;case 16:finalScores();break;case 17:if(typeof(FB_ARENA_MODE)=='undefined')window.opener.setBankPaneUpdateTimeout(id_game,cval1);break;case 18:showMsg(cval1+'<br><br><a href="beArena.php" class="clickHereClass">...CLICK HERE TO GO TO ARENA MAP</a>',(cval2=='aqua')?10000:5000,cval2);break;case 19:pj=cval1;break;case 20:showGroupMsg(cval1,cval2);break;case 21:showNukeGiftBut();break;case 22:updateSlotImg(cval1,cval2);break;case 23:doOtherCanonAnimate(cval1,cval2,cval3,cval4,clat,clon,'cannonOtr');break;case 24:placeOtherAllyItem(clat,clon,cval1);break;case 25:doOtherBomberAnimate(uid,alat,alon,bx,by,nx,ny,segm,brng);break;case 26:doOtherBomberAtackAnimate(chatTxt,alat,alon,dlat,dlon,adeclat,adeclng,ddeclat,ddeclng);break;case 27:doCronDaemonMStrikeNotice(cval1,cval2,cval3);break;case 28:loadCellCityBg(clat,clon,cval1,cval2);break;case 29:break;case 30:doCityPingRespond();break;case 31:updateCellCredits(clat,clon,cval1);break;case 32:getEmpireUpgrades();break;default:showMsg('Invalid data feed command !<br>'+chatTxtCmdA[cmdId]+'',4000,'red');}}}catch(e){reportAjaxError('doChatCmd()',chatTxt,'Unable to decode data feed.',e);return;}}
function rhumbLineBearingTo(lat1,lon1,lat2,lon2){var dLon=toRad(lon2)-toRad(lon1);dPhi=Math.log(Math.tan(toRad(lat2)/2+Math.PI/4)/Math.tan(toRad(lat1)/2+Math.PI/4));if(Math.abs(dLon)>Math.PI){if(dLon>0){dLon=(2*Math.PI-dLon)*-1;}
else{dLon=2*Math.PI+dLon;}}
return(toDeg(Math.atan2(dLon,dPhi))+360)%360;}
function bearingTo(slat,slon,dlat,dlon){var lat1=toRad(slat);var lat2=toRad(dlat);var dRad=toRad(dlon-slon);var y=Math.sin(dRad)*Math.cos(lat2);var x=Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(dRad);var brng=Math.atan2(y,x);return(toDeg(brng)+360)%360;}
crtLostCellEventNb=0;lostCellEventsA=[];function signalLostCell(attackerId,lat,lon){var lostCellDecLat=fromTopo(lat);var lostCellDecLon=fromTopo(lon);var offSetA=(typeof(FB_ARENA_MODE)!='undefined')?[-8,-1,-21,-12]:[-8,2,-16,-4];var latLng=map.getCenter();var bearing=bearingTo(latLng.lat(),latLng.lng(),lostCellDecLat,lostCellDecLon);var xleft=mapL;var xtop=mapT;var angle1=0;var angle2=0;if(bearing<=90){angle1=bearing;xleft=parseInt(mapL+mapW*0.5+mapH*0.5*Math.tan(toRad(angle1)));angle2=90-bearing;xtop=parseInt(mapT+mapH*0.5-mapW*0.5*Math.tan(toRad(angle2)));}else if(bearing>90&&bearing<=180){angle1=180-bearing;xleft=parseInt(mapL+mapW*0.5+mapH*0.5*Math.tan(toRad(angle1)));angle2=bearing-90;xtop=parseInt(mapT+mapH*0.5+mapW*0.5*Math.tan(toRad(angle2)));}else if(bearing>180&&bearing<=270){angle1=bearing-180;xleft=parseInt(mapL+mapW*0.5-mapH*0.5*Math.tan(toRad(angle1)));angle2=270-bearing;xtop=parseInt(mapT+mapH*0.5+mapW*0.5*Math.tan(toRad(angle2)));}else{angle1=360-bearing;xleft=parseInt(mapL+mapW*0.5-mapH*0.5*Math.tan(toRad(angle1)));angle2=bearing-270;xtop=parseInt(mapT+mapH*0.5-mapW*0.5*Math.tan(toRad(angle2)));}
if(xleft>mapL+mapW){xleft=mapL+mapW+offSetA[1];}
if(xleft<mapL){xleft=mapL+offSetA[0];}
if(xtop>mapT+mapH){xtop=mapT+mapH+offSetA[3];}
if(xtop<mapT){xtop=mapT+offSetA[2];}
lostCellEventsA.push({xtop:xtop,xleft:xleft,lat:lostCellDecLat,lon:lostCellDecLon,idx:crtLostCellEventNb});startLostCellMarkersLoop();showDirectionMarkerGlow(xtop,xleft);crtLostCellEventNb+=1;if(crtLostCellEventNb>totalNbOfLostCellMarkers){crtLostCellEventNb=0;}}
var lostCellIntervObj=null;function startLostCellMarkersLoop(){if(lostCellIntervObj==null){lostCellIntervObj=setInterval(showLostCellMarkers,500);}}
function stopLostCellMarkersLoop(){if(lostCellIntervObj!=null){clearInterval(lostCellIntervObj);lostCellIntervObj=null;}}
function showLostCellMarkers(){while(lostCellEventsA.length>0){var task=lostCellEventsA.pop();$$('#lcm'+task['idx']).css({top:task['xtop'],left:task['xleft']}).css('display','block').data('lat',task['lat']).data('lon',task['lon']).fadeOut(8000);}
stopLostCellMarkersLoop();}
function showDirectionMarkerGlow(xtop,xleft){if(xtop<=200&&xleft<=220){$$('#tlm1g,#tlm2g,#tlex').css('display','block').fadeOut(2000);}else
if(xtop<=200&&xleft>220&&xleft<=555){$$('#tcmg,#tcex').css('display','block').fadeOut(2000);}else
if(xtop<=200&&xleft>555){$$('#trm1g,#trm2g,#trex').css('display','block').fadeOut(2000);}else
if(xtop>200&&xtop<=390&&xleft<=220){$$('#mlmg,#mlex').css('display','block').fadeOut(2000);}else
if(xtop>200&&xtop<=390&&xleft>555){$$('#mrmg,#mrex').css('display','block').fadeOut(2000);}else
if(xtop>390&&xleft<=220){$$('#blm1g,#blm2g,#blex').css('display','block').fadeOut(2000);}else
if(xtop>390&&xleft>220&&xleft<=555){$$('#bcmg,#bcex').css('display','block').fadeOut(2000);}else
if(xtop>390&&xleft>555){$$('#brm1g,#brm2g,#brex').css('display','block').fadeOut(2000);}}
function gotoLostCell(lat,lon){if(typeof(lat)!='undefined'&&lat!=''&&typeof(lon)!='undefined'&&lon!=''){map.setCenter(new GLatLng(lat,lon),map.getZoom());clearMapAndCache();scheduleMapViewRefresh();plotPoint(lat,lon);}}
function updateCellOwner(lat,lon,id,prevId){updateCannonTCell4AllCannons(lat,lon,computePolRel(id));if(prevId==idUser){playSound('lostCell');placeRadarDot(lat,lon,'radarAttack');if(typeof(FB_ARENA_MODE)!='undefined'){$$('#mapAreaAlertDiv').css('display','block');$$('#mapAreaAlertDiv').fadeOut(1500);}
removeCannonIfPresent(lat,lon);removeAirportIfPresent(lat,lon);}else{placeRadarDot(lat,lon,'radarAttack2');}
if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){if(prevId==idUser){signalLostCell(id,lat,lon);}}else{var cellObj=objCache[[lat,lon]];if(cellObj){var forceInfoPaneUpd=0;if((lat==crtClickedCellLat&&lon==crtClickedCellLon)||(typeof shipMoveSrcCellLat!="undefined"&&lat==shipMoveSrcCellLat&&lon==shipMoveSrcCellLon)||(typeof moveOriginCellLat!="undefined"&&lat==moveOriginCellLat&&lon==moveOriginCellLon)){if(lat==crtClickedCellLat&&lon==crtClickedCellLon){forceInfoPaneUpd=1;}
if(crtSubActionGui!=''){cancelSubActionGui(crtSubActionGui);}else{paintCrtCell('clear');}}
if(crtRClickedCellA.length>0){var elId='';for(var i in crtRClickedCellA){if(elId==''&&lat==crtRClickedCellA[i]['lat']&&lon==crtRClickedCellA[i]['lon']){elId=i;}}
if(elId!=''){crtRClickedCellA.splice(elId,1);}}
var theCellClass;cellObj.troops=0;cellObj.money=0;cellObj.idUser=id;idUserA[cellObj.arrayPos]=id;if(id==-1||id==0){cellObj.polRel=POLREL_UNOWNED;theCellClass='u';var wpJqImg=cellObj.theDivJq.find(".waypoint");cellObj.theDivJq.css('background-color','').attr('class',CELLCLASS_UNOWNED).html('');if(wpJqImg.length>0){cellObj.theDivJq.append(wpJqImg);}}else if(id==idUser){cellObj.polRel=POLREL_ME;theCellClass=calculateMyCellClass(cellObj);}else{if(udH[id]){if(udH[id][1].indexOf('a')!=-1){cellObj.polRel=POLREL_ALLY;theCellClass=calculateAllyCellClass(cellObj);}else{cellObj.polRel=POLREL_ENEMY;theCellClass=calculateEnemyCellClass(cellObj);}}else{cellObj.polRel=POLREL_NEUTRAL;theCellClass=calculateNeutralCellClass(cellObj);}}
cellObj.theDivJq.removeClass(cellObj.cellClass);cellObj.theDivJq.addClass(theCellClass);cellObj.cellClass=theCellClass;if(forceInfoPaneUpd==1){crtClickedCellObj=cellObj;crtClickedCellDiv=cellObj.theDiv;crtClickedCellDivStyle=theCellClass;paintCrtCell('crtCell');showInfoPaneDetail(cellObj);}
cellObj.theDivJq.children('.cann1, .airp').remove();}}}
function updateCellTroops(lat,lon,count){placeRadarDot(lat,lon,'radarTroops');if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){}else{cellObj=objCache[[lat,lon]];if(cellObj){var theCellClass;var id=cellObj.idUser;cellObj.troops=(count<0)?cellObj.troops+count:count;troopsA[cellObj.arrayPos]=cellObj.troops;if(id==-1||id==0){cellObj.theDivJq.css('background-color','').attr('class',CELLCLASS_UNOWNED).html('');}else if(id==idUser){theCellClass=calculateMyCellClass(cellObj);}else if(id!=0){if(udH[id]){if(udH[id][1].indexOf('a')!=-1){theCellClass=calculateAllyCellClass(cellObj);}else{theCellClass=calculateEnemyCellClass(cellObj);}}else{theCellClass=calculateNeutralCellClass(cellObj);}}
cellObj.theDivJq.removeClass(cellObj.cellClass);cellObj.theDivJq.addClass(theCellClass);cellObj.cellClass=theCellClass;if(lat==crtClickedCellLat&&lon==crtClickedCellLon){crtClickedCellObj=cellObj;crtClickedCellDiv=cellObj.theDiv;crtClickedCellDivStyle=theCellClass;paintCrtCell('crtCell');showInfoPaneDetail(cellObj);}
if(crtRClickedCellA.length>0){var elId='';for(var i in crtRClickedCellA){if(elId==''&&lat==crtRClickedCellA[i]['lat']&&lon==crtRClickedCellA[i]['lon']){elId=i;}}
if(elId!=''){crtRClickedCellA[elId]['obj']=cellObj;crtRClickedCellA[elId]['div']=cellObj.theDiv;crtRClickedCellA[elId]['style']=theCellClass;paintCrtCell('crtCell');}}}}}
function updateCellShips(lat,lon,count){placeRadarDot(lat,lon,'radarShips');if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){}else{cellObj=objCache[[lat,lon]];if(cellObj){if(count==0){cellObj.theDiv.innerHTML=cellObj.theDiv.innerHTML.replace(SHIPCHAR,'');}else{dbShipLatA[0]=lat;dbShipLonA[0]=lon;dbShipNbA[0]=count;paintUnitsOnMap(dbShipLatA,dbShipLonA,dbShipNbA,0,SHIPCHAR);}}}}
function updatecellStalkers(lat,lon,count,oCount){if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){}else{cellObj=objCache[[lat,lon]];if(cellObj){if(count==0){cellObj.theDiv.innerHTML=cellObj.theDiv.innerHTML.replace(STALKERCHAR,'');}else if(count>0){paintUnitsOnMap([lat],[lon],[count],0,STALKERCHAR);}
if(oCount==0){cellObj.theDiv.innerHTML=cellObj.theDiv.innerHTML.replace(OSTALKERCHAR,'');}else if(oCount>0){paintUnitsOnMap([lat],[lon],[count],0,OSTALKERCHAR);}}}}
function closeArenaWindow(){if(IS_ARENA){if(typeof(FB_ARENA_MODE)=='undefined'){setTimeout(window.close(),1100);}else{tb_remove();leaveArenaGame();$$('#windowClosedSplash').fadeIn('1000');}}}
function resetArenaTimer(offset,direction){offset=offset*1000;timerDirection=direction;startDate=new Date();startDate.setTime(startDate.getTime()-(LtoSDelta*1000));expireTime=offset;if(offset==2700000&&direction=='+'){$$('#sendGameInvitesBut').fadeIn(400);}else{$$('#sendGameInvitesBut').fadeOut(400);}}
function updateSlotName(slot,name){if($$('#finalText').text()==''){$$('#aPlNm'+slot+',#aPlNmT'+slot).html(name);}
$('.closeBGn').parent().parent().trigger('jGrowl.close');}
function updateSlotCellCnt(slot,cnt){if($$('#finalText').text()==''){$$('#aPlCnt'+slot+',#aPlCntT'+slot).text(cnt);}}
function updateSlotImg(slot,img){if($$('#finalText').text()==''){if(img==''){$$('#aPlImgT'+slot).attr('src','/images/pixel.gif');}else{$$('#aPlImgT'+slot).attr('src',img);}}}
function hideLeaveGameDiv(){$$('#firstCellDiv,#leaveGameDiv,#newArenaDiv').css('display','none');$('.closeBGn').parent().parent().trigger('jGrowl.close');$$('#addrSearchImg,#addrSearch').fadeOut(1000);$$('#arenaPlayerTbl2').fadeIn(1000);radarVisible(1);}
function doArenaEndTbPane(content,encodedVar){if(content=='-1'){tb_remove();$('.closeBGn').parent().parent().trigger('jGrowl.close');return;}
$$('#welcomeDiv').text('');$$('#welcomeDiv').html(W2DIVTXTE);if(encodedVar.length>0){encSectionA=encodedVar.split("`");encUserNamA=encSectionA[0].split("&");encCellCntA=encSectionA[1].split("&");encGCRewrdA=encSectionA[2].split("&");var cnt;for(playerId in encUserNamA){$('#aPlNmB'+playerId).text(encUserNamA[playerId]);$('#aPlCntB'+playerId).text(encCellCntA[playerId]);$('#aPlRwrdB'+playerId).text(encGCRewrdA[playerId]);}}
$$('#mmIntro').click();$('#TB_window').css('zIndex','10000');}
function finalScores(){$$('#arenaPlayerTbl td').css('color','#b9130f');$$('#finalText').text('FINAL');for(var key in cannonsH){var cannonObj=cannonsH[key];if(cannonObj!=null)cannonObj.stopCannonLoop();}}
function sendGrpChatMsg(){bcAjax(true,'bcsvr.php',{'do':'send-arena-group-msg','message':$$('#grpChatInput').val()},function(returnText){if(returnText.indexOf('SUCCESS')==-1){showMsg('Failed to send message to group.',5000,'red');}else{$$('#grpChatInput').val('');}},null);}
function showGroupMsg(msg,sender){playSound('groupMsg');$$('#groupMsgDiv').jGrowl('<span style="color: yellow;">&lt;'+cval2+'&gt;</span> '+cval1,{theme:'groupMsgEntry',life:60000,glue:'before'});}
function showNukeGiftBut(){if(typeof(FB_ARENA_MODE)=='undefined'){return;}
setTimeout(function(){$('.mTD').append(W2DIVTXTNK);},1500);}
function doOtherCanonAnimate(aDecLat,aDecLng,dDecLat,dDecLng,dlat,dlon,soundName){var alat=toTopo(aDecLat+cellDim/2);var alon=toTopo(aDecLng-cellDim/2);if((dlat<mapSWLat||(dlat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(dlon>mapNELon||(mapSWLon-dlon)>cellDim))||(mapNELon<mapSWLon&&(dlon>mapNELon&&(mapSWLon-dlon)>cellDim)))&&(alat<mapSWLat||(alat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(alon>mapNELon||(mapSWLon-alon)>cellDim))||(mapNELon<mapSWLon&&(alon>mapNELon&&(mapSWLon-alon)>cellDim)))){}else{if(!moving){bullet=CannonBulPool.getObj();dPoint=map.fromLatLngToContainerPixel(new GLatLng(dDecLat,dDecLng));dPoint.x-=5;dPoint.y-=5;cannonPoint=map.fromLatLngToContainerPixel(new GLatLng(aDecLat,aDecLng));cannonPoint.x-=5;cannonPoint.y-=5;animAttack(bullet.dotJq,cannonPoint.x,cannonPoint.y,dPoint.x,dPoint.y,2000,dlat,dlon,bullet);}
playSound(soundName);}}
function placeOtherAllyItem(lat,lon,itemNm){var cellObj=objCache[[lat,lon]];if(cellObj){switch(itemNm){case'cannon':{cellObj.theDivJq.append(cannonTmplJqObj.clone().css('display','block'));break;}
case'bomber':{cellObj.theDivJq.append(airportTmplJqObj.clone().css('display','block'));break;}
default:return;}}}
function updateCellCredits(lat,lon,count){if(lat<mapSWLat||(lat-mapNELat)>cellDim||(mapNELon>=mapSWLon&&(lon>mapNELon||(mapSWLon-lon)>cellDim))||(mapNELon<mapSWLon&&(lon>mapNELon&&(mapSWLon-lon)>cellDim))){}else{cellObj=objCache[[lat,lon]];if(cellObj){var theCellClass;var id=cellObj.idUser;cellObj.money=(count<0)?cellObj.money+count:count;moneyA[cellObj.arrayPos]=cellObj.money;if(id==-1||id==0){cellObj.theDivJq.css('background-color','').attr('class',CELLCLASS_UNOWNED).html('');}else if(id==idUser){theCellClass=calculateMyCellClass(cellObj);}else if(id!=0){if(udH[id]){if(udH[id][1].indexOf('a')!=-1){theCellClass=calculateAllyCellClass(cellObj);}else{theCellClass=calculateEnemyCellClass(cellObj);}}else{theCellClass=calculateNeutralCellClass(cellObj);}}
cellObj.theDivJq.removeClass(cellObj.cellClass);cellObj.theDivJq.addClass(theCellClass);cellObj.cellClass=theCellClass;if(lat==crtClickedCellLat&&lon==crtClickedCellLon){crtClickedCellObj=cellObj;crtClickedCellDiv=cellObj.theDiv;crtClickedCellDivStyle=theCellClass;paintCrtCell('crtCell');showInfoPaneDetail(cellObj);}
if(crtRClickedCellA.length>0){var elId='';for(var i in crtRClickedCellA){if(elId==''&&lat==crtRClickedCellA[i]['lat']&&lon==crtRClickedCellA[i]['lon']){elId=i;}}
if(elId!=''){crtRClickedCellA[elId]['obj']=cellObj;crtRClickedCellA[elId]['div']=cellObj.theDiv;crtRClickedCellA[elId]['style']=theCellClass;paintCrtCell('crtCell');}}}}}
function getEmpireUpgrades(){var ajaxReqVars={'do':'get-empire-upgrades'};$.ajax({async:false,url:'bcsvr.php',type:'POST',data:ajaxReqVars,success:function(returnText){try{ACTIVE_UPGRADES_A=JSON.parse(returnText);}catch(e){reportAjaxError('getEmpireUpgrades()',JSON.stringify(ajaxReqVars),returnText,e);}},error:function(xhrObj,textStatus,errorThrown){reportAjaxError('getEmpireUpgrades()',JSON.stringify(ajaxReqVars),errorThrown,textStatus);}});}
function initRadarDotsDiv(){if(!IS_ARENA||aLat==''||aLon==''){return;}
if(parseInt(aLon2)>parseInt(aLon)){xDist=2*Math.floor((fromTopo(aLon2)-fromTopo(aLon))/cellDim);}else{xDist=2*Math.floor((fromTopo(aLon2)-fromTopo(aLon)+360)/cellDim);xDist=99;}
yDist=2*Math.floor((fromTopo(aLat)-fromTopo(aLat2))/cellDim);$$("#radarDotsDiv").css('width',xDist+'px').css('height',yDist+'px');}
function placeRadarDot(lat,lon,eventClass){if(!IS_ARENA||aLat==''||aLon==''){return;}
var cellKey=[lat,lon];var xPos;var yPos;if(lon>parseInt(aLon)){xPos=2*Math.floor((fromTopo(lon)-fromTopo(aLon))/cellDim);}else{xPos=2*Math.floor((fromTopo(lon)-fromTopo(aLon)+360)/cellDim);}
yPos=2*Math.floor((fromTopo(aLat)-fromTopo(lat))/cellDim);dot=RadarPool.getObj();dot.show(xPos,yPos,eventClass);radarDotH[cellKey]=dot;}
function updateRadarPos(gMapCenter){if(!IS_ARENA||aLat==''||aLon==''){return;}
lat=gMapCenter.lat();lon=gMapCenter.lng();var xPos;var yPos;if(toTopo(lon)+500>parseInt(aLon)){xPos=2*Math.floor((lon-fromTopo(aLon))/cellDim);}else{xPos=2*Math.floor((lon-fromTopo(aLon)+360)/cellDim);}
yPos=2*Math.floor((fromTopo(aLat)-lat)/cellDim);$$("#radarDotsDiv").css({top:62-yPos,left:62-xPos});}
function radarVisible(show){if(!$$('#radarPaneDiv').length){return;}
if(show==1){$$("#radarPaneContainerDiv").css("display","block");$$('#radarPaneDiv').animate({bottom:"-5px"},260,'linear');}else{$$('#radarPaneDiv').animate({bottom:"-142px"},260,'linear',function(){$$("#radarPaneContainerDiv").css("display","none");});}}
lassoToolShown=false;selectableTarget=false;selectedCellCnt=0;function startLassoTool(){if(IS_ARENA||lassoToolShown||topoLatA.length==0||typeof objCache[[topoLatA[0],topoLonA[0]]]=='undefined'){return;}
lassoToolShown=true;map.disableDragging();objCache[[topoLatA[0],topoLonA[0]]].theDivJq.parent().selectable({filter:'.mine, .mil_mine0, .mil_mine1, .mil_mine2, .mil_mine3, .mil_mine4, .mil_mine5, .mil_mine6, .fin_mine0, .fin_mine1, .fin_mine2, .fin_mine3, .fin_mine4, .fin_mine5, .fin_mine6, .fin_mine7',start:function(event,ui){clearClickedCell();selectableTarget=$(this);if(!event.shiftKey){stopLassoTool();}
selectedCellCnt=0;},stop:function(event,ui){crtRClickedCellA=[];$(".ui-selected",this).each(function(){crtRClickedCellA.push({lat:toTopo($(this)[0].cellObj.swLatLng.lat()),lon:toTopo($(this)[0].cellObj.swLatLng.lng()),obj:$(this)[0].cellObj,div:$(this)[0].cellObj.theDiv,style:$(this)[0].cellObj.theDiv.className});});if(crtRClickedCellA.length){cellLassoCallback();}
map.enableDragging();},selecting:function(event,ui){if(++selectedCellCnt>100){if(selectedCellCnt==101)showMsg('Max 100 cell selection limit reached.',5000,'yellow');$(ui.selecting).removeClass('ui-selecting');}},unselecting:function(event,ui){selectedCellCnt--;}});}
function stopLassoTool(){if(IS_ARENA){return;}
objCache[[topoLatA[0],topoLonA[0]]].theDivJq.parent().selectable('disable').selectable('destroy');paintLandCells();map.enableDragging();selectableTarget=false;lassoToolShown=false;crtRClickedCellA=[];}

/**
 * jQuery-Plugin "preloadCssImages"
 * by Scott Jehl, scott@filamentgroup.com
 * http://www.filamentgroup.com
 * reference article: http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
 * demo page: http://www.filamentgroup.com/examples/preloadImages/index_v2.php
 * 
 * Copyright (c) 2008 Filament Group, Inc
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 */
;jQuery.preloadCssImages=function(settings){settings=jQuery.extend({statusTextEl:null,statusBarEl:null,errorDelay:999,simultaneousCacheLoading:2},settings);var allImgs=[],loaded=0,imgUrls=[],thisSheetRules,errorTimer;function onImgComplete(){clearTimeout(errorTimer);if(imgUrls&&imgUrls.length&&imgUrls[loaded]){loaded++;if(settings.statusTextEl){var nowloading=(imgUrls[loaded])?'Now Loading: <span>'+imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length-1]:'Loading complete';jQuery(settings.statusTextEl).html('<span class="numLoaded">'+loaded+'</span> of <span class="numTotal">'+imgUrls.length+'</span> loaded (<span class="percentLoaded">'+(loaded/imgUrls.length*100).toFixed(0)+'%</span>) <span class="currentImg">'+nowloading+'</span></span>');}
if(settings.statusBarEl){var barWidth=jQuery(settings.statusBarEl).width();jQuery(settings.statusBarEl).css('background-position',-(barWidth-(barWidth*loaded/imgUrls.length).toFixed(0))+'px 50%');}
loadImgs();}}
function loadImgs(){if(imgUrls&&imgUrls.length&&imgUrls[loaded]){var img=new Image();img.src=imgUrls[loaded];if(!img.complete){jQuery(img).bind('error load onreadystatechange',onImgComplete);}else{onImgComplete();}
errorTimer=setTimeout(onImgComplete,settings.errorDelay);}}
function parseCSS(sheets,urls){var w3cImport=false,imported=[],importedSrc=[],baseURL;var sheetIndex=sheets.length;while(sheetIndex--){var cssPile='';if(urls&&urls[sheetIndex]){baseURL=urls[sheetIndex];}else{var csshref=(sheets[sheetIndex].href)?sheets[sheetIndex].href:'window.location.href';var baseURLarr=csshref.split('/');baseURLarr.pop();baseURL=baseURLarr.join('/');if(baseURL){baseURL+='/';}}
if(sheets[sheetIndex].cssRules||sheets[sheetIndex].rules){thisSheetRules=(sheets[sheetIndex].cssRules)?sheets[sheetIndex].cssRules:sheets[sheetIndex].rules;var ruleIndex=thisSheetRules.length;while(ruleIndex--){if(thisSheetRules[ruleIndex].style&&thisSheetRules[ruleIndex].style.cssText){var text=thisSheetRules[ruleIndex].style.cssText;if(text.toLowerCase().indexOf('url')!=-1){cssPile+=text;}}else if(thisSheetRules[ruleIndex].styleSheet){imported.push(thisSheetRules[ruleIndex].styleSheet);w3cImport=true;}}}
var tmpImage=cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);if(tmpImage){var i=tmpImage.length;while(i--){var imgSrc=(tmpImage[i].charAt(0)=='/'||tmpImage[i].match('://'))?tmpImage[i]:baseURL+tmpImage[i];if(jQuery.inArray(imgSrc,imgUrls)==-1){imgUrls.push(imgSrc);}}}
if(!w3cImport&&sheets[sheetIndex].imports&&sheets[sheetIndex].imports.length){for(var iImport=0,importLen=sheets[sheetIndex].imports.length;iImport<importLen;iImport++){var iHref=sheets[sheetIndex].imports[iImport].href;iHref=iHref.split('/');iHref.pop();iHref=iHref.join('/');if(iHref){iHref+='/';}
var iSrc=(iHref.charAt(0)=='/'||iHref.match('://'))?iHref:baseURL+iHref;importedSrc.push(iSrc);imported.push(sheets[sheetIndex].imports[iImport]);}}}
if(imported.length){parseCSS(imported,importedSrc);return false;}
var downloads=settings.simultaneousCacheLoading;while(downloads--){setTimeout(loadImgs,downloads);}}
parseCSS(document.styleSheets);return imgUrls;};
/**
 *  jquery.spin-button
 *  (c) 2008 Semooh (http://semooh.jp/)
 *
 *  Dual licensed under the MIT (MIT-LICENSE.txt)
 *  and GPL (GPL-LICENSE.txt) licenses.
 *
 **/
(function($){$.fn.extend({spin:function(opt){return this.each(function(){opt=$.extend({imageBasePath:'/img/spin/',spinBtnImage:'spin-button.png',spinUpImage:'spin-up.png',spinDownImage:'spin-down.png',interval:1,fmax:null,fmin:null,timeInterval:200,wrapInterval:350,timeBlink:200,upBtnTop:'0px',upBtnLeft:'0px',spinClass:'myspin',callback:null,rightTxtId:null},opt||{});var txt=$(this);var spinBtnImage=opt.imageBasePath+opt.spinBtnImage;var btnSpin=new Image();btnSpin.src=spinBtnImage;var spinUpImage=opt.imageBasePath+opt.spinUpImage;var btnSpinUp=new Image();btnSpinUp.src=spinUpImage;var spinDownImage=opt.imageBasePath+opt.spinDownImage;var btnSpinDown=new Image();btnSpinDown.src=spinDownImage;var btn=$(document.createElement('img'));btn.attr('src',spinBtnImage);btn.css({cursor:'pointer',verticalAlign:'bottom',padding:0,margin:0,position:'relative',top:opt.upBtnTop,left:opt.upBtnLeft});btn.addClass(opt.spinClass);txt.after(btn);txt.css({marginRight:0,paddingRight:0});function spin(vector){var val=txt.val();if(!isNaN(val)){if(val!='0'&&('|'+val).indexOf('|0')!=-1){val=val.substring(1);}
val=parseInt(val)+(vector*opt.interval);var min=opt.fmin();var max=opt.fmax();if(val<min){val=max;}
if(val>max){val=min;}
if(val!=txt.val()){txt.val(val<10?'0'+val:val);txt.change();opt.callback(val);src=(vector>0?spinUpImage:spinDownImage);btn.attr('src',src);if(opt.timeBlink<opt.timeInterval)
setTimeout(function(){btn.attr('src',spinBtnImage);},opt.timeBlink);}}}
btn.mousedown(function(e){var pos=e.pageX-btn.offset().left;var vector=(btn.width()/2>pos?1:-1);(function(){spin(vector);var tk=setTimeout(arguments.callee,(txt.val()==opt.fmax()||txt.val()==opt.fmin())?opt.wrapInterval:opt.timeInterval);$(document).one('mouseup',function(){clearTimeout(tk);btn.attr('src',spinBtnImage);});})();return false;});txt.mousedown(function(e){(function(){spin(1);var tk=setTimeout(arguments.callee,(txt.val()==opt.fmax())?opt.wrapInterval:opt.timeInterval);$(document).one('mouseup',function(){clearTimeout(tk);btn.attr('src',spinBtnImage);});})();return false;});txt.data('spinfunc',spin);if(opt.rightTxtId!=null){$(opt.rightTxtId).mousedown(function(e){(function(){spin(-1);var tk=setTimeout(arguments.callee,(txt.val()==opt.fmin())?opt.wrapInterval:opt.timeInterval);$(document).one('mouseup',function(){clearTimeout(tk);btn.attr('src',spinBtnImage);});})();return false;});$(opt.rightTxtId).data('spinfunc',spin);}});}});})(jQuery);
/**
 * jGrowl 1.2.4
 *
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Written by Stan Lemon <stosh1985@gmail.com>
 */
(function($){$.jGrowl=function(m,o){if($('#jGrowl').size()==0)
$('<div id="jGrowl"></div>').addClass($.jGrowl.defaults.position).appendTo('body');$('#jGrowl').jGrowl(m,o);};$.fn.jGrowl=function(m,o){if($.isFunction(this.each)){var args=arguments;return this.each(function(){var self=this;if($(this).data('jGrowl.instance')==undefined){$(this).data('jGrowl.instance',$.extend(new $.fn.jGrowl(),{notifications:[],element:null,interval:null}));$(this).data('jGrowl.instance').startup(this);}
if($.isFunction($(this).data('jGrowl.instance')[m])){$(this).data('jGrowl.instance')[m].apply($(this).data('jGrowl.instance'),$.makeArray(args).slice(1));}else{$(this).data('jGrowl.instance').create(m,o);}});};};$.extend($.fn.jGrowl.prototype,{defaults:{pool:0,header:'',group:'',sticky:false,position:'top-right',glue:'after',theme:'default',corners:'10px',check:250,life:3000,speed:'normal',easing:'swing',closer:true,closeTemplate:'&times;',closerTemplate:'<div>[ close all ]</div>',log:function(e,m,o){},beforeOpen:function(e,m,o){},open:function(e,m,o){},beforeClose:function(e,m,o){},close:function(e,m,o){},animateOpen:{opacity:'show'},animateClose:{opacity:'hide'}},notifications:[],element:null,interval:null,create:function(message,o){var o=$.extend({},this.defaults,o);this.notifications.push({message:message,options:o});o.log.apply(this.element,[this.element,message,o]);},render:function(notification){var self=this;var message=notification.message;var o=notification.options;var notification=$('<div class="jGrowl-notification ui-state-highlight ui-corner-all'+
((o.group!=undefined&&o.group!='')?' '+o.group:'')+'">'+'<div class="close">'+o.closeTemplate+'</div>'+'<div class="header">'+o.header+'</div>'+'<div class="message">'+message+'</div></div>').data("jGrowl",o).addClass(o.theme).children('div.close').bind("click.jGrowl",function(){$(this).parent().trigger('jGrowl.close');}).parent();$(notification).bind("mouseover.jGrowl",function(){$('div.jGrowl-notification',self.element).data("jGrowl.pause",true);}).bind("mouseout.jGrowl",function(){$('div.jGrowl-notification',self.element).data("jGrowl.pause",false);}).bind('jGrowl.beforeOpen',function(){if(o.beforeOpen.apply(notification,[notification,message,o,self.element])!=false){$(this).trigger('jGrowl.open');}}).bind('jGrowl.open',function(){if(o.open.apply(notification,[notification,message,o,self.element])!=false){if(o.glue=='after'){$('div.jGrowl-notification:last',self.element).after(notification);}else{$('div.jGrowl-notification:first',self.element).before(notification);}
$(this).animate(o.animateOpen,o.speed,o.easing,function(){if($.browser.msie&&(parseInt($(this).css('opacity'),10)===1||parseInt($(this).css('opacity'),10)===0))
this.style.removeAttribute('filter');$(this).data("jGrowl").created=new Date();});}}).bind('jGrowl.beforeClose',function(){if(o.beforeClose.apply(notification,[notification,message,o,self.element])!=false)
$(this).trigger('jGrowl.close');}).bind('jGrowl.close',function(){$(this).data('jGrowl.pause',true);$(this).animate(o.animateClose,o.speed,o.easing,function(){$(this).remove();var close=o.close.apply(notification,[notification,message,o,self.element]);if($.isFunction(close))
close.apply(notification,[notification,message,o,self.element]);});}).trigger('jGrowl.beforeOpen');if($.fn.corner!=undefined)$(notification).corner(o.corners);if($('div.jGrowl-notification:parent',self.element).size()>1&&$('div.jGrowl-closer',self.element).size()==0&&this.defaults.closer!=false){$(this.defaults.closerTemplate).addClass('jGrowl-closer ui-state-highlight ui-corner-all').addClass(this.defaults.theme).appendTo(self.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){$(this).siblings().children('div.close').trigger("click.jGrowl");if($.isFunction(self.defaults.closer)){self.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);}});};},update:function(){$(this.element).find('div.jGrowl-notification:parent').each(function(){if($(this).data("jGrowl")!=undefined&&$(this).data("jGrowl").created!=undefined&&($(this).data("jGrowl").created.getTime()+$(this).data("jGrowl").life)<(new Date()).getTime()&&$(this).data("jGrowl").sticky!=true&&($(this).data("jGrowl.pause")==undefined||$(this).data("jGrowl.pause")!=true)){$(this).trigger('jGrowl.beforeClose');}});if(this.notifications.length>0&&(this.defaults.pool==0||$(this.element).find('div.jGrowl-notification:parent').size()<this.defaults.pool))
this.render(this.notifications.shift());if($(this.element).find('div.jGrowl-notification:parent').size()<2){$(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose,this.defaults.speed,this.defaults.easing,function(){$(this).remove();});}},startup:function(e){this.element=$(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');this.interval=setInterval(function(){$(e).data('jGrowl.instance').update();},this.defaults.check);if($.browser.msie&&parseInt($.browser.version)<7&&!window["XMLHttpRequest"]){$(this.element).addClass('ie6');}},shutdown:function(){$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();clearInterval(this.interval);},close:function(){$(this.element).find('div.jGrowl-notification').each(function(){$(this).trigger('jGrowl.beforeClose');});}});$.jGrowl.defaults=$.fn.jGrowl.prototype.defaults;})(jQuery);jQuery.fn.crimirCheckbox=function(opt){opt=jQuery.extend({imgOn:'',imgOff:'',cursor:'pointer'},opt);var onImgTxt='url('+opt.imgOn+')';var offImgTxt='url('+opt.imgOff+')';$(this).each(function(){$(this).css({backgroundRepeat:'no-repeat',backgroundImage:offImgTxt,cursor:opt.cursor}).click(function(){if($(this).css('backgroundImage').indexOf(opt.imgOn)!=-1){$(this).css({backgroundImage:offImgTxt});}else{$(this).css({backgroundImage:onImgTxt});}}).data('onImgTxt',onImgTxt).data('offImgTxt',offImgTxt).data('onImgStr',opt.imgOn);});};jQuery.fn.cbCheck=function(onOff){$(this).each(function(){if(onOff){$(this).css({backgroundImage:$(this).data('onImgTxt')});}else{$(this).css({backgroundImage:$(this).data('offImgTxt')});}});};jQuery.fn.cbIsOn=function(){var on=false;$(this).each(function(){if($(this).css('backgroundImage').indexOf($(this).data('onImgStr'))!=-1){on=true;}
return false;});return on;};
/*
 * jQuery Form Plugin
 * version: 2.18 (06-JAN-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
;(function($){$.fn.ajaxSubmit=function(options){if(!this.length){log('ajaxSubmit: skipping submit process - no element selected');return this;}
if(typeof options=='function')
options={success:options};options=$.extend({url:this.attr('action')||window.location.toString(),type:this.attr('method')||'GET'},options||{});var veto={};this.trigger('form-pre-serialize',[this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');return this;}
if(options.beforeSerialize&&options.beforeSerialize(this,options)===false){log('ajaxSubmit: submit aborted via beforeSerialize callback');return this;}
var a=this.formToArray(options.semantic);if(options.data){options.extraData=options.data;for(var n in options.data){if(options.data[n]instanceof Array){for(var k in options.data[n])
a.push({name:n,value:options.data[n][k]})}
else
a.push({name:n,value:options.data[n]});}}
if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){log('ajaxSubmit: submit aborted via beforeSubmit callback');return this;}
this.trigger('form-submit-validate',[a,this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-submit-validate trigger');return this;}
var q=$.param(a);if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null;}
else
options.data=q;var $form=this,callbacks=[];if(options.resetForm)callbacks.push(function(){$form.resetForm();});if(options.clearForm)callbacks.push(function(){$form.clearForm();});if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){$(options.target).html(data).each(oldSuccess,arguments);});}
else if(options.success)
callbacks.push(options.success);options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++)
callbacks[i].apply(options,[data,status,$form]);};var files=$('input:file',this).fieldValue();var found=false;for(var j=0;j<files.length;j++)
if(files[j])
found=true;if(options.iframe||found){if($.browser.safari&&options.closeKeepAlive)
$.get(options.closeKeepAlive,fileUpload);else
fileUpload();}
else
$.ajax(options);this.trigger('form-submit-notify',[this,options]);return this;function fileUpload(){var form=$form[0];if($(':input[name=submit]',form).length){alert('Error: Form elements must not be named "submit".');return;}
var opts=$.extend({},$.ajaxSettings,options);var s=jQuery.extend(true,{},$.extend(true,{},$.ajaxSettings),opts);var id='jqFormIO'+(new Date().getTime());var $io=$('<iframe id="'+id+'" name="'+id+'" />');var io=$io[0];if($.browser.msie||$.browser.opera)
io.src='javascript:false;document.write("");';$io.css({position:'absolute',top:'-1000px',left:'-1000px'});var xhr={aborted:0,responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;$io.attr('src','about:blank');}};var g=opts.global;if(g&&!$.active++)$.event.trigger("ajaxStart");if(g)$.event.trigger("ajaxSend",[xhr,opts]);if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;return;}
if(xhr.aborted)
return;var cbInvoked=0;var timedOut=0;var sub=form.clk;if(sub){var n=sub.name;if(n&&!sub.disabled){options.extraData=options.extraData||{};options.extraData[n]=sub.value;if(sub.type=="image"){options.extraData[name+'.x']=form.clk_x;options.extraData[name+'.y']=form.clk_y;}}}
setTimeout(function(){var t=$form.attr('target'),a=$form.attr('action');$form.attr({target:id,method:'POST',action:opts.url});if(!options.skipEncodingOverride){$form.attr({encoding:'multipart/form-data',enctype:'multipart/form-data'});}
if(opts.timeout)
setTimeout(function(){timedOut=true;cb();},opts.timeout);var extraInputs=[];try{if(options.extraData)
for(var n in options.extraData)
extraInputs.push($('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />').appendTo(form)[0]);$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);form.submit();}
finally{$form.attr('action',a);t?$form.attr('target',t):$form.removeAttr('target');$(extraInputs).remove();}},10);function cb(){if(cbInvoked++)return;io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var operaHack=0;var ok=true;try{if(timedOut)throw'timeout';var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;if(doc.body==null&&!operaHack&&$.browser.opera){operaHack=1;cbInvoked--;setTimeout(cb,100);return;}
xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;xhr.getResponseHeader=function(header){var headers={'content-type':opts.dataType};return headers[header];};if(opts.dataType=='json'||opts.dataType=='script'){var ta=doc.getElementsByTagName('textarea')[0];xhr.responseText=ta?ta.value:xhr.responseText;}
else if(opts.dataType=='xml'&&!xhr.responseXML&&xhr.responseText!=null){xhr.responseXML=toXml(xhr.responseText);}
data=$.httpData(xhr,opts.dataType);}
catch(e){ok=false;$.handleError(opts,xhr,'error',e);}
if(ok){opts.success(data,'success');if(g)$.event.trigger("ajaxSuccess",[xhr,opts]);}
if(g)$.event.trigger("ajaxComplete",[xhr,opts]);if(g&&!--$.active)$.event.trigger("ajaxStop");if(opts.complete)opts.complete(xhr,ok?'success':'error');setTimeout(function(){$io.remove();xhr.responseXML=null;},100);};function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(s);}
else
doc=(new DOMParser()).parseFromString(s,'text/xml');return(doc&&doc.documentElement&&doc.documentElement.tagName!='parsererror')?doc:null;};};};$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().bind('submit.form-plugin',function(){$(this).ajaxSubmit(options);return false;}).each(function(){$(":submit,input:image",this).bind('click.form-plugin',function(e){var form=this.form;form.clk=this;if(this.type=='image'){if(e.offsetX!=undefined){form.clk_x=e.offsetX;form.clk_y=e.offsetY;}else if(typeof $.fn.offset=='function'){var offset=$(this).offset();form.clk_x=e.pageX-offset.left;form.clk_y=e.pageY-offset.top;}else{form.clk_x=e.pageX-this.offsetLeft;form.clk_y=e.pageY-this.offsetTop;}}
setTimeout(function(){form.clk=form.clk_x=form.clk_y=null;},10);});});};$.fn.ajaxFormUnbind=function(){this.unbind('submit.form-plugin');return this.each(function(){$(":submit,input:image",this).unbind('click.form-plugin');});};$.fn.formToArray=function(semantic){var a=[];if(this.length==0)return a;var form=this[0];var els=semantic?form.getElementsByTagName('*'):form.elements;if(!els)return a;for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n)continue;if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});continue;}
var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++)
a.push({name:n,value:v[j]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:n,value:v});}
if(!semantic&&form.clk){var inputs=form.getElementsByTagName("input");for(var i=0,max=inputs.length;i<max;i++){var input=inputs[i];var n=input.name;if(n&&!input.disabled&&input.type=="image"&&form.clk==input)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}}
return a;};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic));};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n)return;var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++)
a.push({name:n,value:v[i]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:this.name,value:v});});return $.param(a);};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))
continue;v.constructor==Array?$.merge(val,v):val.push(v);}
return val;};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))
return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=$.browser.msie&&!(op.attributes['value'].specified)?op.text:op.value;if(one)return v;a.push(v);}}
return a;}
return el.value;};$.fn.clearForm=function(){return this.each(function(){$('input,select,textarea',this).clearFields();});};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=='text'||t=='password'||tag=='textarea')
this.value='';else if(t=='checkbox'||t=='radio')
this.checked=false;else if(tag=='select')
this.selectedIndex=-1;});};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=='function'||(typeof this.reset=='object'&&!this.reset.nodeType))
this.reset();});};$.fn.enable=function(b){if(b==undefined)b=true;return this.each(function(){this.disabled=!b});};$.fn.selected=function(select){if(select==undefined)select=true;return this.each(function(){var t=this.type;if(t=='checkbox'||t=='radio')
this.checked=select;else if(this.tagName.toLowerCase()=='option'){var $sel=$(this).parent('select');if(select&&$sel[0]&&$sel[0].type=='select-one'){$sel.find('option').selected(false);}
this.selected=select;}});};function log(){if($.fn.ajaxSubmit.debug&&window.console&&window.console.log)
window.console.log('[jquery.form] '+Array.prototype.join.call(arguments,''));};})(jQuery);
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};
/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.4
*/
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";$.fn.single_double_click=function(single_click_callback,double_click_callback,timeout){return this.each(function(){var clicks=0,self=this;jQuery(this).click(function(event){clicks++;if(clicks==1){setTimeout(function(){if(clicks==1){single_click_callback.call(self,event);}else{single_click_callback.call(self,event);double_click_callback.call(self,event);}
clicks=0;},timeout||300);}});});}
var prevCrtClickedCellLat=null;var prevCrtClickedCellLon=null;var hArrowKeyInProgress=false;function handleArrowKey(keyCode){if(hArrowKeyInProgress){return;}
hArrowKeyInProgress=true;try{var nextCellLat=crtClickedCellLat;var nextCellLon=crtClickedCellLon;if(!isACellSelected()){if(!wasACellSelected()){return;}else{nextCellLat=prevCrtClickedCellLat;nextCellLon=prevCrtClickedCellLon;}}
if(keyCode==37){nextCellLon=addLon(nextCellLon,-1);}else if(keyCode==39){nextCellLon=addLon(nextCellLon,+1);}else if(keyCode==38){nextCellLat=addLat(nextCellLat,+1);}else if(keyCode==40){nextCellLat=addLat(nextCellLat,-1);}
var nextCellObj=objCache[[nextCellLat,nextCellLon]];if(nextCellObj!=null){prevCrtClickedCellLat=nextCellLat;prevCrtClickedCellLon=nextCellLon;cellClicked(nextCellObj.theDiv);}}catch(e){}
hArrowKeyInProgress=false;}
function isACellSelected(){if(crtClickedCellObj==null||crtClickedCellLat==''||crtClickedCellLon==''||isNaN(crtClickedCellLat)||isNaN(crtClickedCellLon)){return false;}
return true;}
function wasACellSelected(){if(prevCrtClickedCellLat==null||prevCrtClickedCellLon==null||prevCrtClickedCellLat==''||prevCrtClickedCellLon==''||isNaN(prevCrtClickedCellLat)||isNaN(prevCrtClickedCellLon)){return false;}
return true;}
function showNewMsgBubble(nick,msg){if(!chatShown){showMsg(nick+': '+msg,10000,'sea');}else{}
try{window.opener.showMsg(nick+': '+msg,10000,'sea');}catch(exc){}}
var citiesH={};var postBenchCityLocA=null;function showCellCity(skipAnim){if(IS_ARENA||idUser==-1||TUTYPE){return;}
if(crtSubActionGui!=''){cancelSubActionGui(crtSubActionGui);return;}
if(crtClickedCellObj==null){showMsg('Cannot edit city. Select a cell first.',4000,'yellow');$('#cityCellAnim').remove();return;}
if(crtClickedCellObj.idUser!=idUser){showMsg('Cannot edit city. Cell is not yours.',4000,'yellow');$('#cityCellAnim').remove();return;}
if(crtClickedCellDataA['building']>0&&(crtClickedCellDataA['building']<34||crtClickedCellDataA['building']>39)){showMsg('This cell already has a structure !',4000,'yellow');$('#cityCellAnim').remove();return;}
if(skipAnim!=true){var c1=map.fromLatLngToDivPixel(map.getBounds().getSouthWest());var c2=map.fromLatLngToDivPixel(map.getBounds().getNorthEast());var tempY=c1.y;c1.y=c2.y;c2.y=tempY;var animCell=crtClickedCellObj.theDivJq.clone().removeClass().html('').attr('id','cityCellAnim').css({'position':'absolute','background-color':'#032A2F','opacity':0.2,'top':$(crtClickedCellObj.theDivJq).css('top'),'left':$(crtClickedCellObj.theDivJq).css('left'),'height':$(crtClickedCellObj.theDivJq).css('height'),'width':$(crtClickedCellObj.theDivJq).css('width'),'z-index':1000});$(crtClickedCellObj.theDivJq).after(animCell);animCell.animate({'left':c1.x+"px",'top':c1.y+"px",'height':(c2.y-c1.y)+"px",'width':(c2.x-c1.x)+'px','opacity':1},300,function(){});}
$$("#helpWinOpenLink").css("display","none");$$("#cityHelpWinOpenLink").css("display","inline");if(!$.cookie("bcBench")){$(window).unbind('keydown');loadCellCityBg(9000,0,1,'benchmark');postBenchCityLocA=[crtClickedCellLat,crtClickedCellLon];$$("#cityHelpWinOpenLink").click();return;}
cancelActionGui();crtSubActionGui='EditCity';crtActionGui='EditCity';$('#mapViewPaneContent,#mapActionPaneContent,#butMapCmdHybrid,#butMapCmdSatellite,#butMapCmdTerrain,#butMapCmdZoomIn,#butMapCmdZoomOut').css('display','none');$('#cityViewPaneContent,#cityActionPaneContent,#cityViewPaneContent > .mapViewDescr,#cityScrollTrack').css('display','block');$('#cityViewPaneContent > .mapViewDescr > span').html(crtClickedCellLat+','+crtClickedCellLon);$('#actionCityDescrDiv').html('');$('#bcCityDiv').css("visibility","visible");var cityKey=[crtClickedCellLat,crtClickedCellLon];var cityObj=citiesH[cityKey];if(cityObj){cityObj.setSimulationMode(0);cellCityKeyBindings(true);}else{var city=CityPool.getObj();city.reFill(crtClickedCellLat,crtClickedCellLon,0,'',0);citiesH[cityKey]=city;}
$("#cityActionPaneContent .cityActionBut").click(function(){if($(this).attr('id')=='cityReset'){$('#bcityFrm')[0].contentWindow.doCityAction('');selectCellCityReset();}else if($(this).attr('id')=='cityExit'){$('#bcityFrm')[0].contentWindow.doCityAction('');cancelCellCityReset();hideCellCity();}else{cancelCellCityReset();$('#bcityFrm')[0].contentWindow.doCityAction($(this).attr('id').replace('city',''));}});return false;}
bgProcMode=1;function hideCellCity(forceRemove){$('#addrSearch').focus().blur();$('#bcCityDiv').css('visibility','hidden');$('#cityViewPaneContent,#cityActionPaneContent,#cityScrollTrack').css('display','none');cellCityKeyBindings(false);$("#cityActionPaneContent > .cityActionBut").unbind('click');$('#mapViewPaneContent,#mapActionPaneContent,#butMapCmdHybrid,#butMapCmdSatellite,#butMapCmdTerrain,#butMapCmdZoomIn,#butMapCmdZoomOut').css('display','block');$$("#helpWinOpenLink").css("display","inline");$$("#cityHelpWinOpenLink").css("display","none");var cityKey=[crtClickedCellLat,crtClickedCellLon];if((forceRemove!=true)&&($('#bcityFrm')[0].contentWindow.bgProcId||(objCache[cityKey]&&objCache[cityKey].polRel==POLREL_ME))){var removeAfterSave=false;for(var citiesKey in citiesH){if(citiesH[citiesKey].bgProc==1&&citiesH[citiesKey].bgProcId==""){removeAfterSave=true;break;}}
$('#bcityFrm')[0].contentWindow.forceCitySave(removeAfterSave);var latLonA=$('#bcCityDiv > #bcityFrm').data('coords');citiesH[[latLonA.lat,latLonA.lon]].setSimulationMode(bgProcMode);}else{removeCellCity(crtClickedCellLat,crtClickedCellLon);}
crtSubActionGui='';crtActionGui='';}
function removeCellCity(lat,lon){if([lat,lon]in citiesH){citiesH[[lat,lon]].returnToPool(CityPool);delete citiesH[[lat,lon]];if(postBenchCityLocA){crtClickedCellLat=postBenchCityLocA[0];crtClickedCellLon=postBenchCityLocA[1];postBenchCityLocA=null;showCellCity(true);}}}
function selectCellCityReset(){$("#cityReset").css('display','none');$("#cityResetNotice").css("display","block");$("#actionCityDescrDiv").html('Reset City');}
function confirmCellCityReset(){$('#bcityFrm')[0].contentWindow.game.reset();$("#cityReset").css('display','block');$("#cityResetNotice").css("display","none");}
function cancelCellCityReset(){$('#bcityFrm')[0].contentWindow.doCityAction('');$("#cityReset").css('display','block');$("#cityResetNotice").css("display","none");}
function cellCityKeyBindings(state){if(!$('#bcityFrm').is('*')){return;}
if(state){$(window).unbind('keydown').keydown($('#bcityFrm')[0].contentWindow.keydownHandler);if(document.attachEvent){document.detachEvent("onkeydown",keydownHandler);document.attachEvent("onkeydown",$('#bcityFrm')[0].contentWindow.keydownHandler);}
$('#bcityFrm').removeClass('bcCityFrmHidden');$('#cityCellAnim').remove();}else{$(window).unbind('keydown').keydown(keydownHandler);if(document.attachEvent){document.detachEvent("onkeydown",$('#bcityFrm')[0].contentWindow.keydownHandler);document.attachEvent("onkeydown",keydownHandler);}}}
function loadCellCityBg(lat,lon,runTime,bgProcId){var cityKey=[lat,lon];var cityObj=citiesH[cityKey];if(cityObj)return;var city=CityPool.getObj();city.reFill(lat,lon,1,bgProcId,runTime);citiesH[cityKey]=city;}
function doCityPingRespond(){var pingResponseA={};var d=new Date();var nowtime=d.getTime();for(var cityKey in citiesH){pingResponseA[citiesH[cityKey].lat+','+citiesH[cityKey].lon]={'lat':citiesH[cityKey].lat,'lon':citiesH[cityKey].lon,'rt':nowtime-citiesH[cityKey].startTs};}
$.ajax({async:true,url:'bcsvr_city.php',type:'POST',data:{'do':'city-ping-respond','citylist':JSON.stringify(pingResponseA)},success:function(returnText){}});}
function City(){var inst=this;this.lat=0;this.lon=0;this.ts=0;this.bgProc=0;this.bgProcId='';this.id_user=0;this.iframeJqObj=null;}
City.prototype.reFill=function(lat,lon,bgProc,bgProcId,runTime){var d=new Date();this.startTs=d.getTime();this.lat=lat;this.lon=lon;this.bgProc=bgProc;this.bgProcId=bgProcId;this.runTime=runTime;this.iframeJqObj=$(document.createElement("iframe")).css({'width':'681px','height':'381px','background-color':'#000'}).attr({frameborder:'0',scrolling:'no'}).addClass('bcCityFrmHidden');this.iframeJqObj.data('coords',{'lat':lat,'lon':lon});function loadCellCity(lat,lon,bgProc,iFrmJqObj,bgProcId,runTime){var centerCoordLat=fromTopo(lat)-(cellDim/2);var centerCoordLon=fromTopo(lon)+(cellDim/2);smZoom=12;smWidth=49;smHeight=Math.floor(48.5/Math.cos(toRad(centerCoordLat)));iFrmJqObj.attr('src','city/bcCity.php?lat='+lat+'&lon='+lon+'&center='+centerCoordLat+','+centerCoordLon+'&smZoom='+smZoom+'&smWidth='+smWidth+'&smHeight='+smHeight+'&bgProc='+bgProc+'&bgProcId='+bgProcId+'&rt='+runTime);}
if(bgProc==1&&bgProcId=='benchmark'){this.iframeJqObj.addClass('bcCityFrmHidden');$('#bcCityDiv').append(this.iframeJqObj);this.iframeJqObj.attr('src','city/bcCityBench.php');}else if(bgProc==1){$('#bcCityDiv').append(this.iframeJqObj);loadCellCity(lat,lon,1,this.iframeJqObj,bgProcId,runTime);}else{this.iframeJqObj.attr({id:'bcityFrm',name:'bcityFrm'});$('#bcCityDiv').append(this.iframeJqObj);loadCellCity(lat,lon,0,this.iframeJqObj,'',300);}}
City.prototype.returnToPool=function(poolObj){this.iframeJqObj.remove();this.lat=0;this.lon=0;this.ts=0;this.bgProc=0;this.bgProcId='';this.id_user=0;this.iframeJqObj=null;poolObj.returnObj(this);}
City.prototype.setSimulationMode=function(bgProc){if(bgProc){this.iframeJqObj.removeAttr('id').removeAttr('name').addClass('bcCityFrmHidden');}else{this.iframeJqObj.removeClass('bcCityFrmHidden').attr({id:'bcityFrm',name:'bcityFrm',frameborder:'0',scrolling:'no'});}
this.iframeJqObj[0].contentWindow.bgProc=bgProc;this.bgProc=bgProc;}
$(function(){(function($){$.widget("ui.selectable",$.extend({},$.ui.mouse,{init:function(){var self=this;this.element.addClass("ui-selectable");this.dragged=false;var selectees;this.refresh=function(){selectees=$(self.options.filter,self.element[0]);selectees.each(function(){var $this=$(this);var pos=$this.offset();$.data(this,"selectable-item",{element:this,$element:$this,left:pos.left,top:pos.top,right:pos.left+$this.width(),bottom:pos.top+$this.height(),startselected:false,selected:$this.hasClass('ui-selected'),selecting:$this.hasClass('ui-selecting'),unselecting:$this.hasClass('ui-unselecting')});});};this.refresh();this.selectees=selectees.addClass("ui-selectee");this.mouseInit();this.helper=$(document.createElement('div')).addClass('ui-selectable-helper');},toggle:function(){if(this.options.disabled){this.enable();}else{this.disable();}},destroy:function(){this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this.mouseDestroy();},mouseStart:function(e){var self=this;this.opos=[e.pageX,e.pageY];if(this.options.disabled)
return;var options=this.options;this.selectees=$(options.filter,this.element[0]);this.element.triggerHandler("selectablestart",[e,{"selectable":this.element[0],"options":options}],options.start);$('body').append(this.helper);this.helper.css({"z-index":100,"position":"absolute","left":e.clientX,"top":e.clientY,"width":0,"height":0});if(options.autoRefresh){this.refresh();}
this.selectees.filter('.ui-selected').each(function(){var selectee=$.data(this,"selectable-item");selectee.startselected=true;if(!e.ctrlKey){selectee.$element.removeClass('ui-selected');selectee.selected=false;selectee.$element.addClass('ui-unselecting');selectee.unselecting=true;self.element.triggerHandler("selectableunselecting",[e,{selectable:self.element[0],unselecting:selectee.element,options:options}],options.unselecting);}});var isSelectee=false;$(e.target).parents().andSelf().each(function(){if($.data(this,"selectable-item"))isSelectee=true;});return this.options.keyboard?!isSelectee:true;},mouseDrag:function(e){var self=this;this.dragged=true;if(this.options.disabled)
return;var options=this.options;var x1=this.opos[0],y1=this.opos[1],x2=e.pageX,y2=e.pageY;if(x1>x2){var tmp=x2;x2=x1;x1=tmp;}
if(y1>y2){var tmp=y2;y2=y1;y1=tmp;}
this.helper.css({left:x1,top:y1,width:x2-x1,height:y2-y1});this.selectees.each(function(){var selectee=$.data(this,"selectable-item");if(!selectee||selectee.element==self.element[0])
return;var hit=false;if(options.tolerance=='touch'){hit=(!(selectee.left>x2||selectee.right<x1||selectee.top>y2||selectee.bottom<y1));}else if(options.tolerance=='fit'){hit=(selectee.left>x1&&selectee.right<x2&&selectee.top>y1&&selectee.bottom<y2);}
if(hit){if(selectee.selected){selectee.$element.removeClass('ui-selected');selectee.selected=false;}
if(selectee.unselecting){selectee.$element.removeClass('ui-unselecting');selectee.unselecting=false;}
if(!selectee.selecting){selectee.$element.addClass('ui-selecting');selectee.selecting=true;self.element.triggerHandler("selectableselecting",[e,{selectable:self.element[0],selecting:selectee.element,options:options}],options.selecting);}}else{if(selectee.selecting){if(e.ctrlKey&&selectee.startselected){selectee.$element.removeClass('ui-selecting');selectee.selecting=false;selectee.$element.addClass('ui-selected');selectee.selected=true;}else{selectee.$element.removeClass('ui-selecting');selectee.selecting=false;if(selectee.startselected){selectee.$element.addClass('ui-unselecting');selectee.unselecting=true;}
self.element.triggerHandler("selectableunselecting",[e,{selectable:self.element[0],unselecting:selectee.element,options:options}],options.unselecting);}}
if(selectee.selected){if(!e.ctrlKey&&!selectee.startselected){selectee.$element.removeClass('ui-selected');selectee.selected=false;selectee.$element.addClass('ui-unselecting');selectee.unselecting=true;self.element.triggerHandler("selectableunselecting",[e,{selectable:self.element[0],unselecting:selectee.element,options:options}],options.unselecting);}}}});return false;},mouseStop:function(e){var self=this;this.dragged=false;var options=this.options;$('.ui-unselecting',this.element[0]).each(function(){var selectee=$.data(this,"selectable-item");selectee.$element.removeClass('ui-unselecting');selectee.unselecting=false;selectee.startselected=false;self.element.triggerHandler("selectableunselected",[e,{selectable:self.element[0],unselected:selectee.element,options:options}],options.unselected);});$('.ui-selecting',this.element[0]).each(function(){var selectee=$.data(this,"selectable-item");selectee.$element.removeClass('ui-selecting').addClass('ui-selected');selectee.selecting=false;selectee.selected=true;selectee.startselected=true;self.element.triggerHandler("selectableselected",[e,{selectable:self.element[0],selected:selectee.element,options:options}],options.selected);});this.element.triggerHandler("selectablestop",[e,{selectable:self.element[0],options:this.options}],this.options.stop);this.helper.remove();return false;}}));$.extend($.ui.selectable,{defaults:{distance:1,delay:0,cancel:":input",appendTo:'body',autoRefresh:true,filter:'*',tolerance:'touch'}});})(jQuery);});
