var CRENDER_DEBUG=false;function ImagesPreloader()
{var self=this;this.curItem=-1;this.loadedImages={};this.data=null;this.endCallback=null;this.processCallback=null;this.load=function(data,endCallback,processCallback)
{this.data=data;this.endCallback=endCallback;this.processCallback=processCallback;for(var i=0;i<this.data.length;i++)
{var item=this.data[i];var img=new Image();img.src=item.src;this.loadedImages[item.name]=img;}
wait();};function wait()
{var itemsLoaded=0;var itemsTotal=0;for(var key in self.loadedImages)
{if(self.loadedImages[key].complete)itemsLoaded++;itemsTotal++;}
if(itemsLoaded>=itemsTotal)
{if(self.endCallback)self.endCallback(self.loadedImages);return;}
else
{if(self.processCallback)self.processCallback(Math.floor(itemsLoaded/itemsTotal*100));setTimeout(wait,50);}}}
var Utils={touchScreen:("ontouchstart"in window),globalScale:1,setCookie:function(name,value)
{try
{window.localStorage.setItem(name,value);}
catch(e)
{var exp=new Date();exp.setDate(exp.getDate()+365*10);document.cookie=name+"="+value+"; expires="+exp.toUTCString();}},getCookie:function(name)
{var ret;try
{ret=window.localStorage.getItem(name);}
catch(e)
{var prefix=name+"=";var cookieStartIndex=document.cookie.indexOf(prefix);if(cookieStartIndex==-1)return null;var cookieEndIndex=document.cookie.indexOf(";",cookieStartIndex+prefix.length);if(cookieEndIndex==-1)cookieEndIndex=document.cookie.length;ret=unescape(document.cookie.substring(cookieStartIndex+prefix.length,cookieEndIndex));}
return ret;},bindEvent:function(el,eventName,eventHandler)
{if(el.addEventListener)
{el.addEventListener(eventName,eventHandler,false);}
else if(el.attachEvent)
{el.attachEvent('on'+eventName,eventHandler);}},getObjectLeft:function(element)
{var result=element.offsetLeft;if(element.offsetParent)result+=Utils.getObjectLeft(element.offsetParent);return result;},getObjectTop:function(element)
{var result=element.offsetTop;if(element.offsetParent)result+=Utils.getObjectTop(element.offsetParent);return result;},parseGet:function()
{var get={};var s=new String(window.location);var p=s.indexOf("?");var tmp,params;if(p!=-1)
{s=s.substr(p+1,s.length);params=s.split("&");for(var i=0;i<params.length;i++)
{tmp=params[i].split("=");get[tmp[0]]=tmp[1];}}
return get;},globalPixelScale:1,getMouseCoord:function(event,object)
{var e=event||window.event;if(e.touches)e=e.touches[0];if(!e)return{x:0,y:0};var x=0;var y=0;var mouseX=0;var mouseY=0;if(object)
{x=Utils.getObjectLeft(object);y=Utils.getObjectTop(object);}
if(e.pageX||e.pageY)
{mouseX=e.pageX;mouseY=e.pageY;}
else if(e.clientX||e.clientY)
{mouseX=e.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)-document.documentElement.clientLeft;mouseY=e.clientY+(document.documentElement.scrollTop||document.body.scrollTop)-document.documentElement.clientTop;}
var retX=(mouseX-x);var retY=(mouseY-y);return{x:retX,y:retY};},extend:function(Child,Parent)
{var F=function(){};F.prototype=Parent.prototype;Child.prototype=new F();Child.prototype.constructor=Child;Child.superclass=Parent.prototype;},removeFromArray:function(arr,item)
{var tmp=[];for(var i=0;i<arr.length;i++)
{if(arr[i]!=item)tmp.push(arr[i]);}
return tmp;},showLoadProgress:function(val)
{var scl=Utils.globalScale;var s='Loading: '+val+'%';s+='<br><br>';s+='<div style="display: block; background: #000; width: '+(val*scl*2)+'px; height: '+(10*scl)+'px;">&nbsp;</div>';document.getElementById('progress').innerHTML=s;},hideAddressBarLock:false,mobileHideAddressBar:function()
{if(Utils.hideAddressBarLock)return;window.scrollTo(0,1);},mobileCheckIphone4:function()
{if(window.devicePixelRatio)
{if(navigator.userAgent.indexOf('iPhone')!=-1&&window.devicePixelRatio==2)return true;}
return false;},mobileCheckBrokenGalaxyPhones:function()
{if(window.devicePixelRatio)
{if(navigator.userAgent.indexOf('GT-I9300')!=-1||navigator.userAgent.indexOf('GT-I8190')!=-1||navigator.userAgent.indexOf('Android 4.')!=-1)return true;}
return false;},checkSpilgamesEnvironment:function()
{return(typeof ExternalAPI!="undefined"&&ExternalAPI.type=="Spilgames"&&ExternalAPI.check());},mobileCorrectPixelRatio:function()
{var meta=document.createElement('meta');meta.name="viewport";var content="target-densitydpi=device-dpi, user-scalable=0";if(Utils.checkSpilgamesEnvironment())
{if(window.devicePixelRatio>1)content+=", initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5";else content+=", initial-scale=1, maximum-scale=1, minimum-scale=1";}
else
{if(Utils.mobileCheckIphone4())content+=", initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5";else content+=", initial-scale=1, maximum-scale=1, minimum-scale=1";}
meta.content=content;document.getElementsByTagName('head')[0].appendChild(meta);},getMobileScreenResolution:function(landscape)
{var scale=1;var w=0;var h=0;var scales=[{scale:1,width:320,height:480},{scale:1.5,width:480,height:720},{scale:2,width:640,height:960}];var container={width:0,height:0};var prop="";if(Utils.touchScreen)
{container.width=Math.min(window.innerWidth,window.innerHeight);container.height=Math.max(window.innerWidth,window.innerHeight);prop="height";}
else
{container.width=window.innerWidth;container.height=window.innerHeight;prop="height";}
var min=Number.MAX_VALUE;for(var i=0;i<scales.length;i++)
{var diff=Math.abs(container[prop]-scales[i][prop]);if(min>diff)
{min=diff;scale=scales[i].scale;}}
return Utils.getScaleScreenResolution(scale,landscape);},getScaleScreenResolution:function(scale,landscape)
{var w,h;w=Math.round(320*scale);h=Math.round(480*scale);if(landscape)
{var tmp=w;w=h;h=tmp;}
return{width:w,height:h,scale:scale};},imagesRoot:'images',initialResolution:{width:320,height:480,scale:1},createLayout:function(container,resolution,debug,ignoreCanvas)
{var scl=Utils.globalScale;Utils.initialResolution=resolution;var height=window.innerHeight;if("orientation"in window)height=2048;else document.body.style.overflow="hidden";var s="";s+='<div id="progress_container" align="center" style="width: 100%; height: '+height+'px; display: block; width: 100%; position: absolute; left: 0px; top: 0px;">';s+='<table cellspacing="0" cellpadding="0"><tr><td id="progress" align="center" valign="middle" style="width: '+resolution.width+'px; height: '+resolution.height+'px; color: #000; background: #fff; font-weight: bold; font-family: Verdana; font-size: '+(12*scl)+'px; vertical-align: middle;"></td></tr></table>';s+='</div>';s+='<div id="screen_background_container" align="center" style="width: 100%; height: '+height+'px; position: absolute; left: 0px; top: 0px; display: none; z-index: 2;">'
s+='<div id="screen_background_wrapper" style="width: '+resolution.width+'px; height: '+resolution.height+'px; overflow: hidden; position: relative;">';if(!ignoreCanvas)s+='<canvas id="screen_background" width="'+resolution.width+'" height="'+resolution.height+'"></canvas>';s+='</div>';s+='</div>';s+='<div id="screen_container" align="center" style="width: 100%; height: '+height+'px; position: absolute; left: 0px; top: 0px; display: none; z-index: 3;">';s+='<div id="screen_wrapper" width="'+resolution.width+'" height="'+resolution.height+'" style="width: '+resolution.width+'px; height: '+resolution.height+'px; overflow: hidden; position: relative;">';if(!ignoreCanvas)s+='<canvas id="screen" style="position: absolute; left: 0px; top: 0px; z-index: 1000000;" width="'+resolution.width+'" height="'+resolution.height+'">You browser does not support this application :(</canvas>';s+='</div>';s+='</div>';container.innerHTML=s;var p=document.createElement("div");p.setAttribute("id","p2l_container");p.setAttribute("align","center");var w=resolution.width;p.setAttribute("style","width: 100%; height: "+height+"px; position: absolute; left: 0px; top: 0px; display: none; z-index: 1000; background: #fff;");p.innerHTML='<img id="p2l" src="'+Utils.imagesRoot+'/p2l.jpg" style="padding-top: '+((w-240)/2)+'px" />';document.body.appendChild(p);},preventEvent:function(e)
{e.preventDefault();e.stopPropagation();e.cancelBubble=true;e.returnValue=false;return false;},addMobileListeners:function(landscape,ignoreIOS7)
{if(ignoreIOS7||!navigator.userAgent.match(/(iPad|iPhone|iPod).*CPU.*OS 7_\d/i))
{Utils.bindEvent(document.body,"touchstart",Utils.preventEvent);}
Utils.bindEvent(window,"scroll",function(e)
{setTimeout(Utils.mobileHideAddressBar,300);});setInterval("Utils.checkOrientation("+(landscape?"true":"false")+")",500);setTimeout(Utils.mobileHideAddressBar,500);},storeOrient:null,checkOrientation:function(landscape)
{if(!Utils.touchScreen)return;if(!document.getElementById('screen_container'))return;var getParams=Utils.parseGet();if(getParams.nocheckorient==1)return;var orient=false;if(window==window.parent)
{orient=(window.innerWidth>window.innerHeight);}
else
{var longSide=Math.max(screen.width,screen.height);var shortSide=Math.min(screen.width,screen.height);var lc=Math.abs(window.innerWidth-longSide);var sc=Math.abs(window.innerWidth-shortSide);orient=(lc<sc);}
if(Utils.storeOrient===orient)return;Utils.storeOrient=orient;var ok=(orient==landscape);if(!ok)
{Utils.dispatchEvent("lockscreen");document.getElementById('p2l_container').style.display='block';document.getElementById('screen_background_container').style.display='none';document.getElementById('screen_container').style.display='none';}
else
{Utils.dispatchEvent("unlockscreen");document.getElementById('p2l_container').style.display='none';document.getElementById('screen_background_container').style.display='block';document.getElementById('screen_container').style.display='block';}
if(Utils.checkSpilgamesEnvironment())document.getElementById('p2l_container').style.display='none';setTimeout(Utils.mobileHideAddressBar,1000);setTimeout(Utils.fitLayoutToScreen,1000);},fitLayoutTimer:null,addFitLayoutListeners:function()
{Utils.fitLayoutTimer=setInterval(Utils.fitLayoutToScreen,500);},removeFitLayoutListeners:function()
{clearInterval(Utils.fitLayoutTimer);},fitLayoutLock:false,fitLayoutCorrectHeight:0,fitLayoutToScreen:function(container)
{if(Utils.fitLayoutLock)return;var p,s,width,height;if(typeof container!="object"||!container.width)
{width=window.innerWidth;height=window.innerHeight;if(Utils.checkSpilgamesEnvironment())height-=25;height+=Utils.fitLayoutCorrectHeight;container={width:width,height:height};}
s=document.getElementById("screen_wrapper");if(!s)return;if(!s.initWidth)
{s.initWidth=Utils.initialResolution.width;s.initHeight=Utils.initialResolution.height;}
width=s.initWidth;height=s.initHeight;var scale=1;var scaleX=container.width/width;var scaleY=container.height/height;scale=(scaleX<scaleY?scaleX:scaleY);Utils.globalPixelScale=scale;width=Math.floor(width*scale);height=Math.floor(height*scale);if(s.lastWidth==width&&s.lastHeight==height)return;s.lastWidth=width;s.lastHeight=height;Utils.resizeElement("screen",width,height);Utils.resizeElement("screen_background",width,height);s=document.getElementById("progress");if(s)
{s.style.width=(~~width)+"px";s.style.height=(~~height)+"px";}
s=document.getElementById("screen_wrapper");if(s)
{s.style.width=(~~width)+"px";s.style.height=(~~height)+"px";}
s=document.getElementById("screen_background_wrapper");if(s)
{s.style.width=(~~width)+"px";s.style.height=(~~height)+"px";}
s=document.getElementById("p2l_container");if(s)
{s.style.width=(~~window.innerWidth)+"px";s.style.height="2048px";}
Utils.dispatchEvent("fitlayout");setTimeout(Utils.mobileHideAddressBar,50);},resizeElement:function(id,width,height)
{var s=document.getElementById(id);if(!s)return;s.setAttribute("width",width);s.setAttribute("height",height);},drawIphoneLimiter:function(stage,landscape)
{if(landscape)stage.drawRectangle(240,295,480,54,"#f00",true,0.5,true);else stage.drawRectangle(160,448,320,64,"#f00",true,0.5,true);},drawGrid:function(stage,landscape,col)
{if(typeof landscape=='undefined')landscape=false;var dx=10;var dy=10;if(typeof col=='undefined')col='#FFF';var w=1/Utils.globalScale/Utils.globalPixelScale;var s={w:(landscape?480:320),h:(landscape?320:480)}
for(var x=dx;x<s.w;x+=dx)
{var o=0.1+0.1*(((x-dx)/dx)%10);stage.drawLine(x,0,x,s.h,w,col,o);}
for(var y=dy;y<s.h;y+=dy)
{var o=0.1+0.1*(((y-dy)/dy)%10);stage.drawLine(0,y,s.w,y,w,col,o);}},drawScaleFix:function(stage,landscape)
{if(Utils.globalScale==0.75)
{if(landscape)stage.drawRectangle(507,160,54,320,"#000",true,1,true);else stage.drawRectangle(160,507,320,54,"#000",true,1,true);}
if(Utils.globalScale==1.5)
{if(landscape)stage.drawRectangle(510,160,60,320,"#000",true,1,true);else stage.drawRectangle(160,510,320,60,"#000",true,1,true);}},grad2radian:function(val)
{return val/(180/Math.PI);},radian2grad:function(val)
{return val*(180/Math.PI);},eventsListeners:[],onlockscreen:null,onunlockscreen:null,onfitlayout:null,addEventListener:function(type,callback)
{EventsManager.addEvent(Utils,type,callback);},removeEventListener:function(type,callback)
{EventsManager.removeEvent(Utils,type,callback);},dispatchEvent:function(type,params)
{return EventsManager.dispatchEvent(Utils,type,params);}}
var EventsManager={addEvent:function(obj,type,callback)
{if(!obj.eventsListeners)return;for(var i=0;i<obj.eventsListeners.length;i++)
{if(obj.eventsListeners[i].type===type&&obj.eventsListeners[i].callback===callback)return;}
obj.eventsListeners.push({type:type,callback:callback});},removeEvent:function(obj,type,callback)
{if(!obj.eventsListeners)return;for(var i=0;i<obj.eventsListeners.length;i++)
{if(obj.eventsListeners[i].type===type&&obj.eventsListeners[i].callback===callback)
{obj.eventsListeners=Utils.removeFromArray(obj.eventsListeners,obj.eventsListeners[i]);return;}}},dispatchEvent:function(obj,type,params)
{if(!obj.eventsListeners)return;var ret;if(typeof obj["on"+type]=="function")
{ret=obj["on"+type](params);if(ret===false)return false;}
for(var i=0;i<obj.eventsListeners.length;i++)
{if(obj.eventsListeners[i].type===type)
{ret=obj.eventsListeners[i].callback(params);if(ret===false)return false;}}}}
var ANCHOR_ALIGN_LEFT=-1;var ANCHOR_ALIGN_CENTER=0;var ANCHOR_ALIGN_RIGHT=1;var ANCHOR_VALIGN_TOP=-1;var ANCHOR_VALIGN_MIDDLE=0;var ANCHOR_VALIGN_BOTTOM=1;function Sprite(img,w,h,f,l)
{this.uid=0;this.stage=null;this.x=0;this.y=0;this.width=w;this.height=h;this.offset={left:0,top:0};this.anchor={x:0,y:0};this.scaleX=1;this.scaleY=1;this.rotation=0;this.zIndex=0;this.visible=true;this.opacity=1;this['static']=false;this.ignoreViewport=false;this.animated=true;this.currentFrame=0;this.totalFrames=Math.max(1,~~f);if(this.totalFrames<=1)this.animated=false;this.currentLayer=0;this.totalLayers=Math.max(1,~~l);this.bitmap=img;this.mask=null;this.fillColor=false;this.destroy=false;this.animStep=0;this.animDelay=1;this.drawAlways=false;this.dragged=false;this.dragX=0;this.dragY=0;this.getX=function()
{return Math.round(this.x*Utils.globalScale);};this.getY=function()
{return Math.round(this.y*Utils.globalScale);};this.getWidth=function()
{return this.width*Math.abs(this.scaleX)*Utils.globalScale;};this.getHeight=function()
{return this.height*Math.abs(this.scaleY)*Utils.globalScale;};this.startDrag=function(x,y)
{this.dragged=true;this.dragX=x;this.dragY=y;}
this.stopDrag=function()
{this.dragged=false;this.dragX=0;this.dragY=0;}
this.play=function()
{this.animated=true;};this.stop=function()
{this.animated=false;};this.gotoAndStop=function(frame)
{this.currentFrame=frame;this.stop();};this.gotoAndPlay=function(frame)
{this.currentFrame=frame;this.play();};this.removeTweens=function()
{if(!this.stage)return;this.stage.clearObjectTweens(this);};this.addTween=function(prop,end,duration,ease,onfinish,onchange)
{if(!this.stage)return;var val=this[prop];if(isNaN(val))return;var t=stage.createTween(this,prop,val,end,duration,ease);t.onchange=onchange;t.onfinish=onfinish;return t;};this.moveTo=function(x,y,duration,ease,onfinish,onchange)
{duration=~~duration;if(duration<=0)
{this.setPosition(x,y);}
else
{var t1=this.addTween('x',x,duration,ease,onfinish,onchange);if(t1)t1.play();var t2=this.addTween('y',y,duration,ease,(t1?null:onfinish),(t1?null:onchange));if(t2)t2.play();}
return this;}
this.moveBy=function(x,y,duration,ease,onfinish,onchange)
{return this.moveTo(this.x+x,this.y+y,duration,ease,onfinish,onchange);}
this.fadeTo=function(opacity,duration,ease,onfinish,onchange)
{duration=~~duration;if(duration<=0)
{this.opacity=opacity;}
else
{var t=this.addTween('opacity',opacity,duration,ease,onfinish,onchange);if(t)t.play();}
return this;}
this.fadeBy=function(opacity,duration,ease,onfinish,onchange)
{var val=Math.max(0,Math.min(1,this.opacity+opacity));return this.fadeTo(val,duration,ease,onfinish,onchange);}
this.rotateTo=function(rotation,duration,ease,onfinish,onchange)
{duration=~~duration;if(duration<=0)
{this.rotation=rotation;}
else
{var t=this.addTween('rotation',rotation,duration,ease,onfinish,onchange);if(t)t.play();}
return this;}
this.rotateBy=function(rotation,duration,ease,onfinish,onchange)
{return this.rotateTo(this.rotation+rotation,duration,ease,onfinish,onchange);}
this.scaleTo=function(scale,duration,ease,onfinish,onchange)
{duration=~~duration;if(duration<=0)
{this.scaleX=this.scaleY=scale;}
else
{var t1=this.addTween('scaleX',scale,duration,ease,onfinish,onchange);if(t1)t1.play();var t2=this.addTween('scaleY',scale,duration,ease,(t1?null:onfinish),(t1?null:onchange));if(t2)t2.play();}
return this;}
this.nextFrame=function()
{this.dispatchEvent("enterframe",{target:this});if(!this.animated)return;this.animStep++;if(this.animStep>=this.animDelay)
{this.currentFrame++;this.animStep=0;}
if(this.currentFrame>=this.totalFrames)this.currentFrame=0;};this.eventsWhenInvisible=false;this.onmouseover=null;this.onmouseout=null;this.onmousedown=null;this.onmouseup=null;this.onclick=null;this.oncontextmenu=null;this.onmousemove=null;this.onenterframe=null;this.onprerender=null;this.onrender=null;this.onadd=null;this.onremove=null;this.onbox2dsync=null;this.mouseOn=false;this.getPosition=function()
{return{x:this.x,y:this.y}}
this.setPosition=function(x,y)
{if((typeof y=='undefined')&&(typeof x['x']!='undefined')&&(typeof x['y']!='undefined'))
{return this.setPosition(x.x,x.y);}
this.x=parseFloat(x);this.y=parseFloat(y);}
this.getAnchor=function()
{return this.anchor;}
this.setAnchor=function(x,y)
{if((typeof y=='undefined')&&(typeof x['x']!='undefined')&&(typeof x['y']!='undefined'))
{return this.setAnchor(x.x,x.y);}
this.anchor.x=parseFloat(x);this.anchor.y=parseFloat(y);}
this.alignAnchor=function(h,v)
{h=parseInt(h);if(isNaN(h))h=ANCHOR_ALIGN_CENTER;if(h<0)h=ANCHOR_ALIGN_LEFT;if(h>0)h=ANCHOR_ALIGN_RIGHT;v=parseInt(v);if(isNaN(v))v=ANCHOR_VALIGN_MIDDLE;if(v<0)v=ANCHOR_VALIGN_TOP;if(v>0)v=ANCHOR_VALIGN_BOTTOM;this.anchor.x=this.width*h/2;this.anchor.y=this.height*v/2;return this.getAnchor();}
this.getAbsoluteAnchor=function()
{return this.getPosition();}
this.getRelativeCenter=function()
{var a=this.getAnchor();if(a.x==0&&a.y==0)return a;var c=new Vector(-a.x*this.scaleX,-a.y*this.scaleY);c.rotate(-this.rotation);return c;}
this.getAbsoluteCenter=function()
{var c=this.getRelativeCenter();var v={x:c.x,y:c.y};v.x+=this.x;v.y+=this.y;return v;}
this.getCenter=function()
{return this.getAbsoluteCenter();}
this.getDrawRectangle=function()
{var c=this.getCenter(),r=new Rectangle(0,0,this.width*Math.abs(this.scaleX),this.height*Math.abs(this.scaleY),this.rotation);r.move(c.x,c.y);return r;}
this.getAABBRectangle=function()
{var r=this.getDrawRectangle(),w=r.AABB[1].x-r.AABB[0].x,h=r.AABB[1].y-r.AABB[0].y;return new Rectangle(r.AABB[0].x+(w/2),r.AABB[0].y+(h/2),w,h,0);}
this.localToGlobal=function(x,y)
{var p=((typeof x=='object')&&(typeof x['x']!='undefined')&&(typeof x['y']!='undefined'))?new Vector(x.x+0,x.y+0):new Vector(x,y);p.rotate(this.rotation).add(this.getPosition());return p;}
this.globalToLocal=function(x,y)
{var p=((typeof x=='object')&&(typeof x['x']!='undefined')&&(typeof x['y']!='undefined'))?new Vector(x.x+0,x.y+0):new Vector(x,y);p.subtract(this.getPosition()).rotate(-this.rotation);return p;}
this.allowDebugDrawing=true;this.debugDraw=function()
{if(!this.visible)return;if(!this.allowDebugDrawing)return;var a=this.getPosition(),c=this.getCenter(),r=this.getDrawRectangle(),aabb=this.getAABBRectangle();stage.drawCircle(a.x,a.y,1,1,'rgba(255,0,0,0.9)');stage.drawCircle(c.x,c.y,1,1,'rgba(0,255,0,0.9)');stage.drawLine(a.x,a.y,c.x,c.y,1,'rgba(255,255,255,0.5)');stage.drawPolygon(r.vertices,0.5,'rgba(255,0,255,0.5)',1);stage.drawLine(aabb.vertices[0].x,aabb.vertices[0].y,aabb.vertices[2].x,aabb.vertices[2].y,0.1,'rgba(255,255,255,0.5)');stage.drawLine(aabb.vertices[2].x,aabb.vertices[0].y,aabb.vertices[0].x,aabb.vertices[2].y,0.1,'rgba(255,255,255,0.5)');stage.drawPolygon(aabb.vertices,0.5,'rgba(255,255,255,0.5)');}
this.setZIndex=function(z)
{this.zIndex=~~z;if(!this.stage)return;this.stage.setZIndex(this,~~z);}
this.eventsListeners=[];this.addEventListener=function(type,callback)
{EventsManager.addEvent(this,type,callback);}
this.removeEventListener=function(type,callback)
{EventsManager.removeEvent(this,type,callback);}
this.dispatchEvent=function(type,params)
{return EventsManager.dispatchEvent(this,type,params);}
this.hitTestPoint=function(x,y,checkPixel,checkDragged,debug)
{if(!this.stage)
return false;return this.stage.hitTestPointObject(this,x,y,checkPixel,checkDragged,debug);}}
function Tween(obj,prop,start,end,duration,callback)
{var self=this;if(typeof obj!='object')obj=null;if(obj)
{if(typeof obj[prop]=='undefined')throw new Error('Trying to tween undefined property "'+prop+'"');if(isNaN(obj[prop]))throw new Error('Tweened value can not be '+(typeof obj[prop]));}
else
{if(isNaN(prop))throw new Error('Tweened value can not be '+(typeof prop));}
if(typeof callback!='function')callback=Easing.linear.easeIn;this.obj=obj;this.prop=prop;this.onchange=null;this.onfinish=null;this.start=start;this.end=end;this.duration=~~duration;this.callback=callback;this.playing=false;this._pos=-1;this.play=function()
{self.playing=true;self.tick();}
this.pause=function()
{self.playing=false;}
this.rewind=function()
{self._pos=-1;}
this.forward=function()
{self._pos=this.duration;}
this.stop=function()
{self.pause();self.rewind();}
this.updateValue=function(val)
{if(self.obj)
{self.obj[self.prop]=val;}
else
{self.prop=val;}}
this.tick=function()
{if(!self.playing)return false;self._pos++;if(self._pos<0)return false;if(self._pos>self.duration)return self.finish();var func=self.callback;var val=func(self._pos,self.start,self.end-self.start,self.duration);this.updateValue(val);self.dispatchEvent("change",{target:self,value:val});return false;}
this.finish=function()
{self.stop();self.updateValue(self.end);return self.dispatchEvent("finish",{target:self,value:self.end});}
this.eventsListeners=[];this.addEventListener=function(type,callback)
{EventsManager.addEvent(this,type,callback);}
this.removeEventListener=function(type,callback)
{EventsManager.removeEvent(this,type,callback);}
this.dispatchEvent=function(type,params)
{return EventsManager.dispatchEvent(this,type,params);}}
var Easing={back:{easeIn:function(t,b,c,d)
{var s=1.70158;return c*(t/=d)*t*((s+1)*t-s)+b;},easeOut:function(t,b,c,d)
{var s=1.70158;return c*((t=t/d-1)*t*((s+1)*t+s)+1)+b;},easeInOut:function(t,b,c,d)
{var s=1.70158;if((t/=d/2)<1)return c/2*(t*t*(((s*=(1.525))+1)*t-s))+b;return c/2*((t-=2)*t*(((s*=(1.525))+1)*t+s)+2)+b;}},bounce:{easeIn:function(t,b,c,d)
{return c-Easing.bounce.easeOut(d-t,0,c,d)+b;},easeOut:function(t,b,c,d)
{if((t/=d)<(1/2.75))return c*(7.5625*t*t)+b;else if(t<(2/2.75))return c*(7.5625*(t-=(1.5/2.75))*t+0.75)+b;else if(t<(2.5/2.75))return c*(7.5625*(t-=(2.25/2.75))*t+0.9375)+b;else return c*(7.5625*(t-=(2.625/2.75))*t+0.984375)+b;},easeInOut:function(t,b,c,d)
{if(t<d/2)return Easing.bounce.easeIn(t*2,0,c,d)*0.5+b;else return Easing.bounce.easeOut(t*2-d,0,c,d)*0.5+c*0.5+b;}},circular:{easeIn:function(t,b,c,d)
{return-c*(Math.sqrt(1-(t/=d)*t)-1)+b;},easeOut:function(t,b,c,d)
{return c*Math.sqrt(1-(t=t/d-1)*t)+b;},easeInOut:function(t,b,c,d)
{if((t/=d/2)<1)return-c/2*(Math.sqrt(1-t*t)-1)+b;return c/2*(Math.sqrt(1-(t-=2)*t)+1)+b;}},cubic:{easeIn:function(t,b,c,d)
{return c*(t/=d)*t*t+b;},easeOut:function(t,b,c,d)
{return c*((t=t/d-1)*t*t+1)+b;},easeInOut:function(t,b,c,d)
{if((t/=d/2)<1)return c/2*t*t*t+b;return c/2*((t-=2)*t*t+2)+b;}},exponential:{easeIn:function(t,b,c,d)
{return t==0?b:c*Math.pow(2,10*(t/d-1))+b;},easeOut:function(t,b,c,d)
{return t==d?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOut:function(t,b,c,d)
{if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;}},linear:{easeIn:function(t,b,c,d)
{return c*t/d+b;},easeOut:function(t,b,c,d)
{return c*t/d+b;},easeInOut:function(t,b,c,d)
{return c*t/d+b;}},quadratic:{easeIn:function(t,b,c,d)
{return c*(t/=d)*t+b;},easeOut:function(t,b,c,d)
{return-c*(t/=d)*(t-2)+b;},easeInOut:function(t,b,c,d)
{if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;}},quartic:{easeIn:function(t,b,c,d)
{return c*(t/=d)*t*t*t+b;},easeOut:function(t,b,c,d)
{return-c*((t=t/d-1)*t*t*t-1)+b;},easeInOut:function(t,b,c,d)
{if((t/=d/2)<1)return c/2*t*t*t*t+b;return-c/2*((t-=2)*t*t*t-2)+b;}},quintic:{easeIn:function(t,b,c,d)
{return c*(t/=d)*t*t*t*t+b;},easeOut:function(t,b,c,d)
{return c*((t=t/d-1)*t*t*t*t+1)+b;},easeInOut:function(t,b,c,d)
{if((t/=d/2)<1)return c/2*t*t*t*t*t+b;return c/2*((t-=2)*t*t*t*t+2)+b;}},sine:{easeIn:function(t,b,c,d)
{return-c*Math.cos(t/d*(Math.PI/2))+c+b;},easeOut:function(t,b,c,d)
{return c*Math.sin(t/d*(Math.PI/2))+b;},easeInOut:function(t,b,c,d)
{return-c/2*(Math.cos(Math.PI*t/d)-1)+b;}}}
function StageTimer(callback,timeout,repeat)
{this.repeat=repeat;this.initialTimeout=timeout;this.timeout=timeout;this.callback=callback;this.paused=false;this.update=function()
{if(this.paused)return;this.timeout--;if(this.timeout<=0)
{if(typeof this.callback=="function")this.callback();if(typeof this.callback=="string")eval(this.callback);if(this.repeat)this.timeout=this.initialTimeout;else return true;}
return false;};this.resume=function()
{this.paused=false;};this.pause=function()
{this.paused=true;};}
function Stage(cnsId,w,h)
{var self=this;this.canvas=null;if(cnsId)
{this.canvas=document.getElementById(cnsId);this.canvas.ctx=this.canvas.getContext('2d');}
this.backBuffer=null;this.screenWidth=w;this.screenHeight=h;this.viewport={x:0,y:0};this.objects=[];this.objectsCounter=0;try
{this.buffer=document.createElement('canvas');this.buffer.width=w*Utils.globalScale;this.buffer.height=h*Utils.globalScale;this.buffer.ctx=this.buffer.getContext('2d');}
catch(e)
{this.buffer=this.canvas;}
this.delay=40;this.fillColor=false;this.started=false;this.fps=0;this.lastFPS=0;this.showFPS=false;this.pixelClickEvent=false;this.pixelMouseUpEvent=false;this.pixelMouseDownEvent=false;this.pixelMouseMoveEvent=false;this.ceilSizes=false;this.tmMain
this.tmFPS
this.clearLock=false;this.destroy=function()
{clearTimeout(this.tmMain);clearTimeout(this.tmFPS);this.stop();this.clear();this.clearScreen(this.canvas);}
this.clearScreen=function(canvas)
{if(!this.clearLock)canvas.ctx.clearRect(0,0,this.screenWidth*Utils.globalScale*Utils.globalPixelScale,this.screenHeight*Utils.globalScale*Utils.globalPixelScale);}
this.findMaxZIndex=function()
{var max=-1;var ix=false;for(var i=0;i<this.objects.length;i++)
{if(this.objects[i].zIndex>max)
{max=this.objects[i].zIndex;ix=i;}}
return{index:ix,zIndex:max};};this.findMinZIndex=function()
{var min=-1;var ix=false;for(var i=0;i<this.objects.length;i++)
{if(i==0)
{min=this.objects[i].zIndex;ix=0;}
if(this.objects[i].zIndex<min)
{min=this.objects[i].zIndex;ix=i;}}
return{index:ix,zIndex:min};};this.addChild=function(item)
{var f=this.findMaxZIndex();var z=item.zIndex;if(f.index!==false)item.zIndex=f.zIndex+1;else item.zIndex=0;this.objectsCounter++;item.uid=this.objectsCounter;item.stage=this;this.objects.push(item);if(z!=0)
{this.setZIndex(item,~~z);}
item.dispatchEvent("add",{target:item});return item;};this.removeChild=function(item)
{if(item)
{this.clearObjectTweens(item);item.dispatchEvent("remove",{target:item});item.stage=null;this.objects=Utils.removeFromArray(this.objects,item);}};this.setZIndex=function(item,index)
{item.zIndex=index;this.objects=this.objects.sort(function(obj1,obj2)
{return obj1.zIndex==obj2.zIndex?0:(obj1.zIndex>obj2.zIndex?1:-1);});}
this.hitTestPointObject=function(obj,x,y,pixelCheck,includeDragged,debug)
{var cX,cY,cW,cH,mX,mY,r,present,imageData;cW=obj.width*Math.abs(obj.scaleX);cH=obj.height*Math.abs(obj.scaleY);cX=obj.x-cW/2;cY=obj.y-cH/2;mX=x;mY=y;if(!obj.ignoreViewport)
{mX+=this.viewport.x;mY+=this.viewport.y;}
present=false;if(obj.rotation==0)
{if(cX<=mX&&cY<=mY&&cX+cW>=mX&&cY+cH>=mY)present=true;}
else
{r=obj.getDrawRectangle();if(r.hitTestPoint(new Vector(mX,mY)))present=true;}
if(present&&pixelCheck)
{this.buffer.width=this.screenWidth*Utils.globalScale*Utils.globalPixelScale;this.buffer.height=this.screenHeight*Utils.globalScale*Utils.globalPixelScale;this.clearScreen(this.buffer);this.renderObject(this.buffer,obj);var pX=Math.floor(x*Utils.globalScale*Utils.globalPixelScale);var pY=Math.floor(y*Utils.globalScale*Utils.globalPixelScale);imageData=this.buffer.ctx.getImageData(pX,pY,1,1);if(imageData.data[3]==0)present=false;}
if(!present&&includeDragged&&obj.dragged)present=true;return present;}
this.getObjectsStackByCoord=function(x,y,pixelCheck,includeDragged,debug)
{var obj;var tmp=[];for(var i=0;i<this.objects.length;i++)
{if(this.objects[i].visible||this.objects[i].eventsWhenInvisible)
{obj=this.objects[i];if(this.hitTestPointObject(obj,x,y,pixelCheck,includeDragged,debug))
{tmp.push(obj);}}}
return tmp;};this.getMaxZIndexInStack=function(stack)
{var max=-1;var ix=0;for(var i=0;i<stack.length;i++)
{if(stack[i].zIndex>max)
{max=stack[i].zIndex;ix=i;}}
return ix;};this.sortStack=function(stack,revert)
{var bSort=true;var ok;var i,tmp;while(bSort)
{bSort=false;for(i=0;i<stack.length-1;i++)
{ok=false;if(stack[i].zIndex<stack[i+1].zIndex&&!revert)ok=true;if(stack[i].zIndex>stack[i+1].zIndex&&revert)ok=true;if(ok)
{tmp=stack[i];stack[i]=stack[i+1];stack[i+1]=tmp;bSort=true;}}}
return stack;}
this.finalizeMouseCoords=function(obj,m)
{if(!obj)return m;var eX=this.prepareMouseCoord(m.x);var eY=this.prepareMouseCoord(m.y);if(!obj.ignoreViewport)
{eX+=this.viewport.x;eY+=this.viewport.y;}
eX=eX-obj.x;eY=eY-obj.y;return{x:eX,y:eY};}
this.prepareMouseCoord=function(val)
{return val/Utils.globalScale/Utils.globalPixelScale;}
this.checkClick=function(event)
{var m=Utils.getMouseCoord(event,this.inputController);var stack=this.getObjectsStackByCoord(this.prepareMouseCoord(m.x),this.prepareMouseCoord(m.y),this.pixelClickEvent,false,true);var ret,f;if(stack.length>0)
{stack=this.sortStack(stack);for(var i=0;i<stack.length;i++)
{f=this.finalizeMouseCoords(stack[i],m);ret=stack[i].dispatchEvent("click",{target:stack[i],x:f.x,y:f.y});if(ret===false)return;}}};this.checkContextMenu=function(event)
{var m=Utils.getMouseCoord(event,this.inputController);var stack=this.getObjectsStackByCoord(this.prepareMouseCoord(m.x),this.prepareMouseCoord(m.y),this.pixelClickEvent);var ret,f;if(stack.length>0)
{stack=this.sortStack(stack);for(var i=0;i<stack.length;i++)
{f=this.finalizeMouseCoords(stack[i],m);ret=stack[i].dispatchEvent("contextmenu",{target:stack[i],x:f.x,y:f.y});if(ret===false)return;}}};this.checkMouseMove=function(event)
{var m=Utils.getMouseCoord(event,this.inputController);for(i=0;i<this.objects.length;i++)
{if(this.objects[i].dragged)
{var eX=m.x/Utils.globalScale/Utils.globalPixelScale;var eY=m.y/Utils.globalScale/Utils.globalPixelScale;if(!this.objects[i].ignoreViewport)
{eX+=this.viewport.x;eY+=this.viewport.y;}
this.objects[i].x=eX-this.objects[i].dragX;this.objects[i].y=eY-this.objects[i].dragY;}}
var stack=this.getObjectsStackByCoord(this.prepareMouseCoord(m.x),this.prepareMouseCoord(m.y),this.pixelMouseMoveEvent);var i,n,ret,bOk,f;var overStack=[];if(stack.length>0)
{stack=this.sortStack(stack);for(i=0;i<stack.length;i++)
{overStack.push(stack[i]);f=this.finalizeMouseCoords(stack[i],m);if(!stack[i].mouseOn)ret=stack[i].dispatchEvent("mouseover",{target:stack[i],x:f.x,y:f.y});stack[i].mouseOn=true;if(ret===false)break;}
for(i=0;i<stack.length;i++)
{f=this.finalizeMouseCoords(stack[i],m);ret=stack[i].dispatchEvent("mousemove",{target:stack[i],x:f.x,y:f.y});if(ret===false)break;}}
for(i=0;i<this.objects.length;i++)
{if(this.objects[i].mouseOn)
{bOk=false;for(n=0;n<overStack.length;n++)
{if(overStack[n]==this.objects[i])bOk=true;}
if(!bOk)
{this.objects[i].mouseOn=false;f=this.finalizeMouseCoords(stack[i],m);ret=this.objects[i].dispatchEvent("mouseout",{target:this.objects[i],x:f.x,y:f.y});if(ret===false)break;}}}};this.checkMouseDown=function(event)
{var m=Utils.getMouseCoord(event,this.inputController);var stack=this.getObjectsStackByCoord(this.prepareMouseCoord(m.x),this.prepareMouseCoord(m.y),this.pixelMouseDownEvent);var ret,f;if(stack.length>0)
{stack=this.sortStack(stack);for(var i=0;i<stack.length;i++)
{f=this.finalizeMouseCoords(stack[i],m);ret=stack[i].dispatchEvent("mousedown",{target:stack[i],x:f.x,y:f.y});if(ret===false)return;}}};this.checkMouseUp=function(event)
{var m=Utils.getMouseCoord(event,this.inputController);var stack=this.getObjectsStackByCoord(this.prepareMouseCoord(m.x),this.prepareMouseCoord(m.y),this.pixelMouseUpEvent,true);var ret,f;if(stack.length>0)
{stack=this.sortStack(stack);for(var i=0;i<stack.length;i++)
{f=this.finalizeMouseCoords(stack[i],m);ret=stack[i].dispatchEvent("mouseup",{target:stack[i],x:f.x,y:f.y});if(ret===false)return;}}};this.clear=function()
{for(var i=0;i<this.objects.length;i++)
{this.objects[i].dispatchEvent("remove",{target:this.objects[i]});}
this.objects=[];this.tweens=[];this.timers=[];this.eventsListeners=[];this.objectsCounter=0;};this.hitTest=function(obj1,obj2)
{if(obj1.rotation==0&&obj2.rotation==0)
{var cX1=obj1.getX()-obj1.getWidth()/2;var cY1=obj1.getY()-obj1.getHeight()/2;var cX2=obj2.getX()-obj2.getWidth()/2;var cY2=obj2.getY()-obj2.getHeight()/2;var top=Math.max(cY1,cY2);var left=Math.max(cX1,cX2);var right=Math.min(cX1+obj1.getWidth(),cX2+obj2.getWidth());var bottom=Math.min(cY1+obj1.getHeight(),cY2+obj2.getHeight());var width=right-left;var height=bottom-top;if(width>0&&height>0)return true;else return false;}
else
{var r1=obj1.getDrawRectangle(),r2=obj2.getDrawRectangle();return r1.hitTestRectangle(r2);}};this.drawRectangle=function(x,y,width,height,color,fill,opacity,ignoreViewport)
{var cns=this.canvas;if(typeof opacity!='undefined')cns.ctx.globalAlpha=opacity;else cns.ctx.globalAlpha=1;cns.ctx.fillStyle=color;cns.ctx.strokeStyle=color;if(!ignoreViewport)
{x-=this.viewport.x;y-=this.viewport.y;}
x=x*Utils.globalScale*Utils.globalPixelScale;y=y*Utils.globalScale*Utils.globalPixelScale;width=width*Utils.globalScale*Utils.globalPixelScale;height=height*Utils.globalScale*Utils.globalPixelScale;if(fill)cns.ctx.fillRect(x-width/2,y-height/2,width,height);else cns.ctx.strokeRect(x-width/2,y-height/2,width,height);};this.drawCircle=function(x,y,radius,width,color,opacity,ignoreViewport)
{this.drawArc(x,y,radius,0,Math.PI*2,false,width,color,opacity,ignoreViewport);};this.drawArc=function(x,y,radius,startAngle,endAngle,anticlockwise,width,color,opacity,ignoreViewport)
{var cns=this.canvas;var oldLW=cns.ctx.lineWidth;if(typeof color=="undefined")color="#000"
cns.ctx.strokeStyle=color;if(typeof width=="undefined")width=1;cns.ctx.lineWidth=width*Utils.globalScale*Utils.globalPixelScale;if(typeof opacity=="undefined")opacity=1;cns.ctx.globalAlpha=opacity;if(!ignoreViewport)
{x-=this.viewport.x;y-=this.viewport.y;}
x=x*Utils.globalScale*Utils.globalPixelScale;y=y*Utils.globalScale*Utils.globalPixelScale;radius=radius*Utils.globalScale*Utils.globalPixelScale;cns.ctx.beginPath();cns.ctx.arc(x,y,radius,startAngle,endAngle,anticlockwise);cns.ctx.stroke();cns.ctx.lineWidth=oldLW;};this.drawPolygon=function(points,width,color,opacity,ignoreViewport)
{if((typeof points!="object")||!(points instanceof Array)||points.length<2)return;for(var i=0;i<points.length-1;i++)
{this.drawLine(points[i].x,points[i].y,points[i+1].x,points[i+1].y,width,color,opacity,ignoreViewport);}
this.drawLine(points[i].x,points[i].y,points[0].x,points[0].y,width,color,opacity,ignoreViewport);}
this.drawLine=function(x1,y1,x2,y2,width,color,opacity,ignoreViewport)
{var cns=this.canvas;var oldLW=cns.ctx.lineWidth;if(color)cns.ctx.strokeStyle=color;else cns.ctx.strokeStyle='#000';if(width)cns.ctx.lineWidth=width*Utils.globalScale*Utils.globalPixelScale;else cns.ctx.lineWidth=1*Utils.globalScale*Utils.globalPixelScale;if(opacity)cns.ctx.globalAlpha=opacity;else cns.ctx.globalAlpha=1;if(!ignoreViewport)
{x1-=this.viewport.x;y1-=this.viewport.y;x2-=this.viewport.x;y2-=this.viewport.y;}
x1=x1*Utils.globalScale*Utils.globalPixelScale;y1=y1*Utils.globalScale*Utils.globalPixelScale;x2=x2*Utils.globalScale*Utils.globalPixelScale;y2=y2*Utils.globalScale*Utils.globalPixelScale;cns.ctx.beginPath();cns.ctx.moveTo(x1,y1);cns.ctx.lineTo(x2,y2);cns.ctx.stroke();cns.ctx.lineWidth=oldLW;};this.start=function()
{if(this.started)return;this.started=true;clearFPS();render();}
this.forceRender=function()
{if(this.started)render();}
this.stop=function()
{this.started=false;}
function clearFPS()
{self.lastFPS=self.fps;self.fps=0;if(self.started)self.tmFPS=setTimeout(clearFPS,1000);}
this.setTextStyle=function(font,size,style,color,borderColor,canvas)
{var cns=(canvas?canvas:this.canvas);cns.ctx.fillStyle=color;cns.ctx.strokeStyle=borderColor;var s="";if(style)s+=style+" ";if(size)s+=Math.floor(size*Utils.globalScale*Utils.globalPixelScale)+"px ";if(font)s+=font;cns.ctx.font=s;}
this.drawText=function(text,x,y,opacity,ignoreViewport,alignCenter,canvas)
{var cns=(canvas?canvas:this.canvas);if(typeof opacity=="undefined")cns.ctx.globalAlpha=1;else cns.ctx.globalAlpha=opacity;if(!ignoreViewport)
{x-=this.viewport.x;y-=this.viewport.y;}
x=x*Utils.globalScale*Utils.globalPixelScale;y=y*Utils.globalScale*Utils.globalPixelScale;if(alignCenter)x=x-this.getTextWidth(text)/2;cns.ctx.fillText(text,x,y);}
this.strokeText=function(text,x,y,opacity,ignoreViewport,alignCenter,canvas)
{var cns=(canvas?canvas:this.canvas);if(typeof opacity=="undefined")cns.ctx.globalAlpha=1;else cns.ctx.globalAlpha=opacity;if(!ignoreViewport)
{x-=this.viewport.x;y-=this.viewport.y;}
x=x*Utils.globalScale*Utils.globalPixelScale;y=y*Utils.globalScale*Utils.globalPixelScale;if(alignCenter)x=x-this.getTextWidth(text)/2;cns.ctx.strokeText(text,x,y);}
this.getTextWidth=function(str,canvas)
{var cns=(canvas?canvas:this.canvas);return cns.ctx.measureText(str).width;}
this.allowDebugDrawing=false;this.allowStaticDebugDrawing=false;this.renderObject=function(cns,obj)
{if(obj.dispatchEvent("prerender",{target:obj,canvas:cns})===false)return;var
center=obj.getAbsoluteCenter();ow=obj.width*Utils.globalScale,oh=obj.height*Utils.globalScale,ox=center.x*Utils.globalPixelScale*Utils.globalScale-Math.floor(ow/2),oy=center.y*Utils.globalPixelScale*Utils.globalScale-Math.floor(oh/2),or=obj.rotation,scX=obj.scaleX*Utils.globalPixelScale,scY=obj.scaleY*Utils.globalPixelScale,canvasMod=Boolean(or!=0||scX!=1||scY!=1);if(!obj.ignoreViewport)
{ox-=this.viewport.x*Utils.globalPixelScale*Utils.globalScale;oy-=this.viewport.y*Utils.globalPixelScale*Utils.globalScale;}
if(canvasMod)
{cns.ctx.save();cns.ctx.translate(ox+Math.floor(ow/2),oy+Math.floor(oh/2));cns.ctx.rotate(or);cns.ctx.scale(scX,scY);ox=-Math.floor(ow/2);oy=-Math.floor(oh/2);}
cns.ctx.globalAlpha=obj.opacity;if(this.ceilSizes)
{ow=Math.ceil(ow);oh=Math.ceil(oh);}
if(obj.fillColor)
{cns.ctx.fillStyle=obj.fillColor;cns.ctx.strokeStyle=obj.fillColor;cns.ctx.fillRect(ox,oy,ow,oh);}
if(obj.bitmap)
{var iw=obj.bitmap.width,ih=obj.bitmap.height;var fx=obj.currentLayer*ow+obj.offset.left*Utils.globalScale,fy=obj.currentFrame*oh+obj.offset.top*Utils.globalScale;if(fx<iw&&fy<ih)
{var fw=ow,fh=oh,masked=false;if(fx+fw>iw)fw=iw-fx;if(fy+fh>ih)fh=ih-fy;if(obj.mask)
{this.buffer.ctx.save();this.buffer.ctx.clearRect(0,0,fw,fh);this.buffer.ctx.drawImage(obj.bitmap,fx,fy,fw,fh,0,0,fw,fh);this.buffer.ctx.globalCompositeOperation="destination-in";this.buffer.ctx.drawImage(obj.mask,0,0);fx=0;fy=0;masked=true;}
try
{cns.ctx.drawImage((masked?this.buffer:obj.bitmap),~~fx,~~fy,~~fw,~~fh,~~ox,~~oy,~~ow,~~oh);}
catch(e)
{}
if(masked)this.buffer.ctx.restore();}}
if(canvasMod)cns.ctx.restore();if(this.allowDebugDrawing&&obj.allowDebugDrawing)
{if(this.allowStaticDebugDrawing||!obj.static)
{obj.debugDraw();}}
obj.dispatchEvent("render",{target:obj,canvas:cns});}
this.drawBackAlways=Utils.mobileCheckBrokenGalaxyPhones();this.drawBackBuffer=function(cns,drawStatic)
{if(!drawStatic&&this.backBuffer&&this.drawBackAlways)cns.ctx.drawImage(this.backBuffer,0,0,cns.width,cns.height);}
this.drawScene=function(cns,drawStatic)
{var obj,ok;if(cns&&!cns.ctx)cns.ctx=cns.getContext("2d");if(!this.fillColor)
{if(!this.clearLock)
{this.clearScreen(cns);this.drawBackBuffer(cns,drawStatic);}}
else
{cns.ctx.fillStyle=this.fillColor;cns.ctx.fillRect(0,0,this.screenWidth*Utils.globalScale*Utils.globalPixelScale,this.screenHeight*Utils.globalScale*Utils.globalPixelScale);this.drawBackBuffer(cns,drawStatic);}
for(var i=0;i<this.objects.length;i++)
{obj=this.objects[i];ok=false;if(!drawStatic&&!obj['static'])ok=true;if(drawStatic&&obj['static'])ok=true;if(ok)
{if(obj.destroy)
{this.removeChild(obj);i--;}
else
{obj.nextFrame();if(obj.visible)this.renderObject(cns,obj);}}}
if(drawStatic)
{this.backBuffer=cns;}};this.tweens=[];this.createTween=function(obj,prop,start,end,duration,ease)
{var t=new Tween(obj,prop,start,end,duration,ease);self.tweens.push(t);return t;}
this.removeTween=function(t)
{var id=null;if(isNaN(t))
{for(var i=0;i<self.tweens.length;i++)
{if(self.tweens[i]===t)
{id=i;break;}}}
else id=t;self.tweens[id].pause();self.tweens.splice(id,1);return id;}
this.clearObjectTweens=function(obj)
{for(var i=0;i<self.tweens.length;i++)
{if(self.tweens[i].obj===obj)
{i=self.removeTween(i);i--;}}}
this.updateTweens=function()
{for(var i=0;i<self.tweens.length;i++)
{if(self.tweens[i].tick())
{i=self.removeTween(i);}}}
this.timers=[];this.setTimeout=function(callback,timeout)
{var t=new StageTimer(callback,timeout);this.timers.push(t);return t;};this.clearTimeout=function(t)
{this.timers=Utils.removeFromArray(this.timers,t);};this.setInterval=function(callback,timeout)
{var t=new StageTimer(callback,timeout,true);this.timers.push(t);return t;};this.clearInterval=function(t)
{this.clearTimeout(t);};this.updateTimers=function()
{for(var i=0;i<this.timers.length;i++)
{if(this.timers[i].update())
{this.clearTimeout(this.timers[i]);i--;}}};function render()
{clearTimeout(self.tmMain);var tm_start=new Date().getTime();self.updateTweens();self.updateTimers();self.dispatchEvent("pretick");self.drawScene(self.canvas,false);if(self.showFPS)
{self.setTextStyle("sans-serif",10,"bold","#fff","#000");self.drawText("FPS: "+self.lastFPS,2,10,1,true);}
self.dispatchEvent("posttick");var d=new Date().getTime()-tm_start;d=self.delay-d-1;if(d<1)d=1;self.fps++;if(self.started)self.tmMain=setTimeout(render,d);};this.box2dSync=function(world)
{var p;for(b=world.m_bodyList;b;b=b.m_next)
{if(b.sprite)
{b.sprite.rotation=b.GetRotation();p=b.GetPosition();b.sprite.x=p.x;b.sprite.y=p.y;b.sprite.dispatchEvent("box2dsync",{target:b.sprite});}}}
this.processTouchEvent=function(touches,controller)
{for(var i=0;i<touches.length;i++)
{var e={clientX:touches[i].clientX,clientY:touches[i].clientY};self[controller](e);}}
this.inputController=null;this.addInputListeners=function(obj)
{var ffOS=(navigator.userAgent.toLowerCase().indexOf("firefox")!=-1&&navigator.userAgent.toLowerCase().indexOf("mobile")!=-1);ffOS=false;this.inputController=obj;if(("ontouchstart"in obj)&&!ffOS)
{obj.ontouchstart=function(event)
{self.processTouchEvent(event.touches,"checkMouseDown");self.processTouchEvent(event.touches,"checkClick");};obj.ontouchmove=function(event)
{self.processTouchEvent(event.touches,"checkMouseMove");};obj.ontouchend=function(event)
{self.processTouchEvent(event.changedTouches,"checkMouseUp");};}
else
{obj.onclick=function(event)
{self.checkClick(event);};obj.onmousemove=function(event)
{self.checkMouseMove(event);};obj.onmousedown=function(event)
{if(event.button==0)self.checkMouseDown(event);};obj.onmouseup=function(event)
{if(event.button==0)self.checkMouseUp(event);};obj.oncontextmenu=function(event)
{self.checkContextMenu(event);};}}
if(this.canvas)this.addInputListeners(this.canvas);this.onpretick=null;this.onposttick=null;this.eventsListeners=[];this.addEventListener=function(type,callback)
{EventsManager.addEvent(this,type,callback);}
this.removeEventListener=function(type,callback)
{EventsManager.removeEvent(this,type,callback);}
this.dispatchEvent=function(type,params)
{return EventsManager.dispatchEvent(this,type,params);}}
function Vector(x,y)
{if(typeof(x)=='undefined')x=0;this.x=x;if(typeof(y)=='undefined')y=0;this.y=y;this.isZero=function()
{return this.x==0&&this.y==0;}
this.clone=function()
{return new Vector(this.x,this.y);}
this.add=function(p)
{this.x+=p.x;this.y+=p.y;return this;}
this.subtract=function(p)
{this.x-=p.x;this.y-=p.y;return this;}
this.mult=function(n)
{this.x*=n;this.y*=n;return this;}
this.invert=function()
{this.mult(-1);return this;}
this.rotate=function(angle,offset)
{if(typeof(offset)=='undefined')offset=new Vector(0,0);var r=this.clone();r.subtract(offset);r.x=this.x*Math.cos(angle)+this.y*Math.sin(angle);r.y=this.x*-Math.sin(angle)+this.y*Math.cos(angle);r.add(offset);this.x=r.x;this.y=r.y;return this;}
this.normalize=function(angle,offset)
{if(typeof(offset)=='undefined')offset=new Vector(0,0);this.subtract(offset);this.rotate(-angle);return this;}
this.getLength=function()
{return Math.sqrt(this.x*this.x+this.y*this.y);}
this.distanceTo=function(p)
{p2=this.clone();p2.subtract(p);return p2.getLength();}}
var Rectangle=function(x,y,w,h,angle)
{this.center=new Vector(x,y);this.width=w;this.height=h;this.angle=angle;this.vertices=[];this.AABB=[];this.clone=function()
{return new Rectangle(this.center.x,this.center.y,this.width,this.height,this.angle);}
this.refreshVertices=function()
{var w=this.width/2;var h=this.height/2;this.vertices=[];this.vertices.push(new Vector(-w,h));this.vertices.push(new Vector(w,h));this.vertices.push(new Vector(w,-h));this.vertices.push(new Vector(-w,-h));this.AABB=[this.center.clone(),this.center.clone()];for(var i=0;i<4;i++)
{this.vertices[i].rotate(-this.angle,this.center);if(this.vertices[i].x<this.AABB[0].x)this.AABB[0].x=this.vertices[i].x;if(this.vertices[i].x>this.AABB[1].x)this.AABB[1].x=this.vertices[i].x;if(this.vertices[i].y<this.AABB[0].y)this.AABB[0].y=this.vertices[i].y;if(this.vertices[i].y>this.AABB[1].y)this.AABB[1].y=this.vertices[i].y;}}
this.move=function(x,y)
{this.center.add(new Vector(x,y));this.refreshVertices();}
this.rotate=function(angle)
{this.angle+=angle;this.refreshVertices();}
this.hitTestPoint=function(point)
{var p=point.clone();p.normalize(-this.angle,this.center);return((Math.abs(p.x)<=(this.width/2))&&(Math.abs(p.y)<=(this.height/2)));}
this.hitTestRectangle=function(rect)
{var r1=this.clone();var r2=rect.clone();var len,len1,len2;r1.move(-this.center.x,-this.center.y);r2.move(-this.center.x,-this.center.y);r2.center.rotate(this.angle);r1.rotate(-this.angle);r2.rotate(-this.angle);len=Math.max(r1.AABB[0].x,r1.AABB[1].x,r2.AABB[0].x,r2.AABB[1].x)-Math.min(r1.AABB[0].x,r1.AABB[1].x,r2.AABB[0].x,r2.AABB[1].x);len1=r1.AABB[1].x-r1.AABB[0].x;len2=r2.AABB[1].x-r2.AABB[0].x;if(len>len1+len2)return false;len=Math.max(r1.AABB[0].y,r1.AABB[1].y,r2.AABB[0].y,r2.AABB[1].y)-Math.min(r1.AABB[0].y,r1.AABB[1].y,r2.AABB[0].y,r2.AABB[1].y);len1=r1.AABB[1].y-r1.AABB[0].y;len2=r2.AABB[1].y-r2.AABB[0].y;if(len>len1+len2)return false;r1.move(-r2.center.x,-r2.center.y);r2.move(-r2.center.x,-r2.center.y);r1.center.rotate(r2.angle);r1.refreshVertices();r1.rotate(-r2.angle);r2.rotate(-r2.angle);len=Math.max(r1.AABB[0].x,r1.AABB[1].x,r2.AABB[0].x,r2.AABB[1].x)-Math.min(r1.AABB[0].x,r1.AABB[1].x,r2.AABB[0].x,r2.AABB[1].x);len1=r1.AABB[1].x-r1.AABB[0].x;len2=r2.AABB[1].x-r2.AABB[0].x;if(len>len1+len2)return false;len=Math.max(r1.AABB[0].y,r1.AABB[1].y,r2.AABB[0].y,r2.AABB[1].y)-Math.min(r1.AABB[0].y,r1.AABB[1].y,r2.AABB[0].y,r2.AABB[1].y);len1=r1.AABB[1].y-r1.AABB[0].y;len2=r2.AABB[1].y-r2.AABB[0].y;if(len>len1+len2)return false;return true;}
this.refreshVertices();}
var Asset=function(name,src,w,h,f,l)
{this.name=name+'';this.src=src+'';this.width=w;this.height=h;this.frames=f;this.layers=l;this.bitmap=null;this.object=null;this.ready=(this.width&&this.height);this.detectSize=function()
{if(!this.bitmap)return false;try
{if(isNaN(this.width))
{this.width=this.bitmap.width?parseInt(this.bitmap.width):0;}
if(isNaN(this.height))
{this.height=this.bitmap.height?parseInt(this.bitmap.height):0;}}
catch(e)
{if(CRENDER_DEBUG)console.log(e);}
return(!isNaN(this.width)&&!isNaN(this.height));}
this.normalize=function(scale)
{if(this.ready)return;if(!this.detectSize())return;if(isNaN(this.frames)||this.frames<1)this.frames=1;if(isNaN(this.layers)||this.layers<1)this.layers=1;this.width=Math.ceil((this.width/this.layers)/scale);this.height=Math.ceil((this.height/this.frames)/scale);this.ready=true;}}
var AssetsLibrary=function(path,scale,assets)
{var self=this;this.path='images';this.scale=1;this.items={};this.bitmaps={};this.loaded=false;this.onload=null;this.onloadprogress=null;this.spriteClass=Sprite;this.init=function(path,scale)
{if(typeof path!='undefined')
{this.path=path+'';}
if(typeof scale!='undefined')
{this.scale=parseFloat(scale);if(isNaN(this.scale))this.scale=1;}}
this.addAssets=function(data)
{if(typeof data=='undefined')return;if(typeof data!='object')return;for(var i=0;i<data.length;i++)
{var item=data[i];item.noscale=(typeof item.noscale=='undefined')?false:item.noscale;if(!item.noscale)item.src='%SCALE%/'+item.src;this.addAsset(item.src,item.name,item.width,item.height,item.frames,item.layers);}}
this.addAsset=function(src,name,w,h,f,l)
{function src2name(src)
{var name=src.split('/');name=name.pop();name=name.split('.');name=name.shift()+'';return name;}
src=src.replace('%SCALE%','%PATH%/'+this.scale);src=src.replace('%PATH%',this.path);if(typeof name=='undefined')name=src2name(src);var asset=new Asset(name,src,w,h,f,l);this.items[name]=asset;return asset;}
this.addObject=function(obj)
{var asset=this.addAsset('%SCALE%/'+obj.image,obj.name,obj.width*this.scale,obj.height*this.scale,obj.frames,obj.layers);if(asset)asset.object=obj;return asset;}
this.load=function(onload,onloadprogress)
{this.onload=onload;this.onloadprogress=onloadprogress;var preloader=new ImagesPreloader();var data=[];for(var n in this.items)
data.push(this.items[n]);preloader.load(data,self.onLoadHandler,self.onLoadProgressHandler);}
this.onLoadProgressHandler=function(val)
{if(typeof self.onloadprogress=='function')
{self.onloadprogress(val);}}
this.onLoadHandler=function(data)
{self.loaded=true;for(var n in data)
{var bmp=data[n];var asset=self.items[n];asset.bitmap=bmp;asset.normalize(self.scale);}
if(typeof self.onload=='function')
{self.onload(self.items);}}
this.getAsset=function(name,checkLoad)
{var asset=null;if((typeof this.items[name]!='undefined')&&(this.items[name].bitmap))
{checkLoad=(typeof checkLoad=='undefined')?true:checkLoad;asset=(!checkLoad||this.items[name].ready)?this.items[name]:null;}
if(!asset)
{throw new Error('Trying to get undefined asset "'+name+'"');}
return asset;}
this.getSprite=function(name,params)
{var mc=null;try
{var asset=this.getAsset(name,true);mc=new this.spriteClass(asset.bitmap,asset.width,asset.height,asset.frames,asset.layers);}
catch(e)
{mc=new this.spriteClass(null,1,1,1,1);}
if(typeof params=='object')
{for(var prop in params)mc[prop]=params[prop];}
return mc;}
this.getBitmap=function(name)
{try
{var asset=this.getAsset(name,true);return asset.bitmap;}
catch(e)
{return null;}}
this.init(path,scale);this.addAssets(assets);}
if(typeof console=='undefined')
{console={log:function(){}}};function SpritesGroup(stage)
{var self=this;this.stage=stage;this.x=0;this.y=0;this.rotation=0;this.scaleX=1;this.scaleY=1;this.opacity=1;this.sprites=[];this.addChild=function(obj,add)
{if(typeof obj.gscaleX=="undefined")obj.gscaleX=1;if(typeof obj.gscaleY=="undefined")obj.gscaleY=1;if(typeof obj.grotation=="undefined")obj.grotation=0;if(typeof obj.gopacity=="undefined")obj.gopacity=1;this.sprites.push(obj);if(add)this.stage.addChild(obj);this.update();}
this.removeChild=function(obj,destroy)
{this.sprites=Utils.removeFromArray(this.sprites,obj);if(destroy)obj.destroy=true;}
this.remove=function()
{for(var i=0;i<this.sprites.length;i++)
{this.sprites[i].destroy=true;}
this.sprites=[];}
this.update=function()
{var obj;for(var i=0;i<self.sprites.length;i++)
{obj=self.sprites[i];var x=obj.gx;var y=obj.gy;var p=new Vector(x,y);p.rotate(-self.rotation);x+=p.x;y+=p.y;x*=self.scaleX;y*=self.scaleY;x+=self.x;y+=self.y;obj.x=x;obj.y=y;obj.scaleX=obj.gscaleX*self.scaleX;obj.scaleY=obj.gscaleY*self.scaleY;obj.rotation=obj.grotation+self.rotation;obj.opacity=obj.gopacity*self.opacity;}}
stage.addEventListener("pretick",this.update);};function SimpleText(font,width,height)
{this.ALIGN_LEFT=0;this.ALIGN_RIGHT=1;this.ALIGN_CENTER=2;this.font=font;this.x=0;this.y=0;this.width=width;this.height=height;this.align=this.ALIGN_LEFT;this.rotation=0;this.charSpacing=0;this.scale=1;this.static=false;this.charMap=['0','1','2','3','4','5','6','7','8','9'];this.charWidth=[];this.sprites=[];this.text="";this.manageSprites=function(text)
{var i,char;var len=text.length;var sp_len=this.sprites.length;if(sp_len<len)
{for(i=0;i<len-sp_len;i++)
{char=new Sprite(this.font,this.width,this.height,this.charMap.length);this.sprites.push(char);stage.addChild(char);}}
if(sp_len>len)
{for(i=0;i<sp_len-len;i++)stage.removeChild(this.sprites[i]);this.sprites.splice(0,sp_len-len);}}
this.getCharIx=function(char)
{for(var i=0;i<this.charMap.length;i++)
{if(this.charMap[i]==char)return i;}
return-1;}
this.getCharWidth=function(char)
{var i=this.getCharIx(char);if(i>=0)return this.charWidth[i]?this.charWidth[i]:this.width;else return this.width;}
this.getWidth=function()
{var w=0;for(var i=0;i<this.text.length;i++)
{w+=this.getCharWidth(this.text.substr(i,1))+this.charSpacing;}
return w;}
this.write=function(text)
{var curX,curY,p,p2,n;text=text+"";this.text=text;this.manageSprites(text);curX=this.x;curY=this.y;if(this.align==this.ALIGN_CENTER)curX=this.x-this.getWidth()/2*this.scale+(this.getCharWidth(this.text.substr(0,1))/2);if(this.align==this.ALIGN_RIGHT)curX=this.x-this.getWidth()*this.scale;p=new Vector(curX-this.x,0);p.rotate(-this.rotation);curX=p.x+this.x;curY=p.y+this.y;p=new Vector(0,0);for(var i=0;i<text.length;i++)
{this.sprites[i].visible=true;n=this.charMap.indexOf(text.substr(i,1));if(n<0)this.sprites[i].visible=false;else
{var chw=this.getCharWidth(this.text.substr(i,1));this.sprites[i].scaleX=this.sprites[i].scaleY=this.scale;this.sprites[i].gotoAndStop(n);p2=p.clone();p2.x*=this.scale;p2.rotate(-this.rotation);this.sprites[i].x=p2.x+(this.text.substr(i,1)==','?curX-(chw/2):curX);this.sprites[i].y=p2.y+curY;this.sprites[i].rotation=this.rotation;this.sprites[i].static=this.static;p.x+=chw+this.charSpacing;}}}
this.refresh=function()
{this.write(this.text);}
this.addToGroup=function(group)
{for(var i=0;i<this.sprites.length;i++)
{this.sprites[i].gx=this.sprites[i].x/2;this.sprites[i].gy=this.sprites[i].y;group.addChild(this.sprites[i],false);}}};function AudioPlayer()
{var self=this;this.disabled=false;this.basePath="";this.mp3Support=true;this.webAudioSupport=false;this.delayPlay=false;this.audioWrapper=null;this.locked=false;this.busy=false;this.startPlayTime=0;this.onend=null;this.createNewAudio=function()
{if(this.webAudioSupport)
{var sound=AudioMixer.waContext.createBufferSource();sound.connect(AudioMixer.waContext.destination);return sound;}
else
{return document.createElement('audio');}};this.init=function(path,webAudioSupport)
{this.webAudioSupport=webAudioSupport;this.basePath=path?path:"";this.delayPlay=("ontouchstart"in window);this.audioWrapper=this.createNewAudio();var test=document.createElement('audio');if(test.canPlayType)this.mp3Support=test.canPlayType('audio/mpeg')!="";else this.disabled=true;return!this.disabled;};this.play=function(file,loop)
{if(this.disabled)return false;var url=this.basePath+"/"+file+(this.mp3Support?".mp3":".ogg");this.stop();this.audioWrapper=this.createNewAudio();this.audioWrapper.doLoop=(loop?true:false);if(this.webAudioSupport)
{var self=this;this.loadSound(url,function(buffer)
{self.audioWrapper.buffer=buffer;self.audioWrapper.noteOn(0);self.startPlayTime=new Date().getTime();self.audioWrapper.loop=loop;self.waCheckInterval=setInterval(function()
{if(!self.audioWrapper)
{clearInterval(self.waCheckInterval);return;}
if(self.audioWrapper.playbackState==self.audioWrapper.FINISHED_STATE)
{self.controlPlay();}},100);});}
else
{this.audioWrapper.src=url;this.audioWrapper.type=(this.mp3Support?"audio/mpeg":"audio/ogg");this.audioWrapper.loop=false;this.audioWrapper.preload="auto";this.audioWrapper.load();if(this.delayPlay)this.audioWrapper.addEventListener("canplay",this.readyToPlay);else this.audioWrapper.play();this.audioWrapper.addEventListener("ended",this.controlPlay,false);}
this.busy=true;this.startPlayTime=new Date().getTime();};this.loadSound=function(url,callback)
{if(AudioMixer.buffer[url])
{if(callback)callback(AudioMixer.buffer[url]);return;}
var request=new XMLHttpRequest();request.open('GET',url,true);request.responseType='arraybuffer';request.onload=function()
{AudioMixer.waContext.decodeAudioData(this.response,function(buffer)
{AudioMixer.buffer[url]=buffer;if(callback)callback(buffer);});}
request.send();}
this.readyToPlay=function(e)
{e.currentTarget.play();}
this.stop=function()
{this.busy=false;try
{if(this.webAudioSupport)
{this.audioWrapper.noteOff(0);this.audioWrapper=null;}
else
{this.audioWrapper.removeEventListener("canplay",this.readyToPlay);this.audioWrapper.pause();this.audioWrapper.currentTime=0.0;this.audioWrapper=null;}}
catch(e){};};this.pause=function()
{if(this.webAudioSupport)
{if(self.audioWrapper)self.audioWrapper.disconnect();}
else
{this.audioWrapper.pause();}}
this.resume=function()
{if(this.webAudioSupport)
{if(self.audioWrapper)self.audioWrapper.connect(AudioMixer.waContext.destination);}
else
{this.audioWrapper.play();}}
this.controlPlay=function()
{if(self.audioWrapper.doLoop)
{if(!this.webAudioSupport)
{self.audioWrapper.pause();self.audioWrapper.currentTime=0.0;self.audioWrapper.play();}}
else
{self.busy=false;if(typeof self.onend=="function")self.onend();if(this.waCheckInterval)
{clearInterval(this.waCheckInterval);}}}
this.getPosition=function()
{if(this.webAudioSupport)
{if(!this.startPlayTime)return 0;var duration=this.getDuration();if(!duration)return 0;var position=((new Date().getTime())-this.startPlayTime)/1000;if(position<=duration)return position;if(!this.audioWrapper.doLoop)return duration;return position-Math.floor(position/duration)*duration;}
else
{return this.audioWrapper.currentTime?this.audioWrapper.currentTime:0;}}
this.getDuration=function()
{if(this.webAudioSupport)
{return this.audioWrapper.buffer?this.audioWrapper.buffer.duration:0;}
else
{return this.audioWrapper.duration?this.audioWrapper.duration:0;}}}
function AudioMixer(path,channelsCount)
{this.webAudioSupport=false;this.singleChannelMode=false;this.channels=[];this.init=function(path,channelsCount)
{this.webAudioSupport=("webkitAudioContext"in window);if(this.webAudioSupport)
{AudioMixer.waContext=new webkitAudioContext();var buffer=AudioMixer.waContext.createBuffer(1,1,22050);sound=AudioMixer.waContext.createBufferSource();sound.buffer=buffer;sound.connect(AudioMixer.waContext.destination);sound.noteOn(0);}
if(!this.webAudioSupport&&navigator.userAgent.toLowerCase().indexOf("mac")!=-1)
{this.singleChannelMode=true;channelsCount=1;}
this.path=path;this.channels=[];for(var i=0;i<channelsCount;i++)
{this.channels[i]=new AudioPlayer();this.channels[i].init(path,this.webAudioSupport);}
var hidden,visibilityChange;if(typeof document.hidden!=="undefined")
{hidden="hidden";visibilityChange="visibilitychange";}
else if(typeof document.mozHidden!=="undefined")
{hidden="mozHidden";visibilityChange="mozvisibilitychange";}
else if(typeof document.msHidden!=="undefined")
{hidden="msHidden";visibilityChange="msvisibilitychange";}
else if(typeof document.webkitHidden!=="undefined")
{hidden="webkitHidden";visibilityChange="webkitvisibilitychange";}
var self=this;function handleVisibilityChange()
{if(document[hidden])
{for(var i=0;i<self.channels.length;i++)
{self.channels[i].pause();}}
else
{for(var i=0;i<self.channels.length;i++)
{self.channels[i].resume();}}}
document.addEventListener(visibilityChange,handleVisibilityChange,false);};this.play=function(file,loop,soft,channelID)
{var cID=-1;if(typeof channelID=="number")cID=channelID;else cID=this.getFreeChannel(soft);if(cID>=0&&cID<this.channels.length)
{this.channels[cID].stop();this.channels[cID].play(file,loop);}
return this.channels[cID];};this.stop=function(cID)
{if(cID>=0&&cID<this.channels.length)this.channels[cID].stop();};this.getFreeChannel=function(soft)
{var cID=-1;var freeChannels=[];var maxID=-1;var max=-1;var t=0;for(var i=0;i<this.channels.length;i++)
{if(!this.channels[i].locked)
{if(!this.channels[i].busy)freeChannels.push(i);else
{t=new Date().getTime();t-=this.channels[i].startPlayTime;if(t>max)
{max=t;maxID=i;}}}}
if(freeChannels.length==0)
{if(!soft&&max>=0)cID=max;}
else cID=freeChannels[0];return cID;};this.init(path,channelsCount);}
AudioMixer.buffer={};AudioMixer.waContext=null;;var showDebugDraw=false;var isAndroid=false;var stage;var world;var sound;var mc;var fps=32;var screenWidthCoef;var screenHeightCoef;var graphicsPack=null;var LANDSCAPE_MODE=true;var STATE_LOAD=0;var STATE_SPLASH=1;var STATE_COVER=2;var STATE_MENU=4;var STATE_INSTRUCTION_ONE=5;var STATE_INSTRUCTION_TWO=6;var STATE_GAME_OVER=9;var STATE_BEST_SCORE=10;var STATE_ABOUT=11;var STATE_PAUSE=12;var STATE_SETTINGS=13;var STATE_GAME=7;var STATE_GAME_START=14;var STATE_GAME_PRE_BET=15;var STATE_GAME_BET=16;var STATE_GAME_SPIN1=17;var STATE_GAME_HOLD=18;var STATE_GAME_SPIN2=19;var STATE_GAME_RESULT=20;var STATE_GAME_LOSE=21;var PROCESS_START=1;var PROCESS_GAME=0;var gameState=STATE_LOAD;var processState=PROCESS_START;var charMap=['0','1','2','3','4','5','6','7','8','9','x'];var charWidth=[18,18,18,18,18,18,18,18,18,18,18];var charMapPercent=['0','1','2','3','4','5','6','7','8','9','%','x'];var charMapLineNumber=['0','1','2','3','4','5','6','7','8','9'];var charMapNumber=['0','1','2','3','4','5','6','7','8','9',"+"];var charMapOnlyNumber=['0','1','2','3','4','5','6','7','8','9'];var lineMask=[[[0,-1],[1,-1],[2,-1],[3,-1],[4,-1]],[[0,0],[1,0],[2,0],[3,0],[4,0]],[[0,1],[1,1],[2,1],[3,1],[4,1]],[[0,-1],[1,-1],[2,-1],[3,-1]],[[0,0],[1,0],[2,0],[3,0]],[[0,1],[1,1],[2,1],[3,1]],[[1,-1],[2,-1],[3,-1],[4,-1]],[[1,0],[2,0],[3,0],[4,0]],[[1,1],[2,1],[3,1],[4,1]],[[0,-1],[1,-1],[2,-1]],[[1,-1],[2,-1],[3,-1]],[[2,-1],[3,-1],[4,-1]],[[0,0],[1,0],[2,0]],[[1,0],[2,0],[3,0]],[[2,0],[3,0],[4,0]],[[0,1],[1,1],[2,1]],[[1,1],[2,1],[3,1]],[[2,1],[3,1],[4,1]],[[0,-1],[1,0],[2,1],[3,0],[4,-1]],[[0,-1],[1,0],[2,1],[3,0]],[[1,0],[2,1],[3,0],[4,-1]],[[1,0],[2,1],[3,0]],[[0,-1],[1,0],[2,1]],[[2,1],[3,0],[4,-1]],[[0,1],[1,0],[2,-1],[3,0],[4,1]],[[0,1],[1,0],[2,-1],[3,0]],[[1,0],[2,-1],[3,0],[4,1]],[[1,0],[2,-1],[3,0]],[[0,1],[1,0],[2,-1]],[[2,-1],[3,0],[4,1]]];var winDiagonalMaskBet4=[[[0,-1],[1,0],[2,1],[3,0],[4,-1]],[[0,-1],[1,0],[2,1],[3,0]],[[1,0],[2,1],[3,0],[4,-1]],[[1,0],[2,1],[3,0]],[[0,-1],[1,0],[2,1]],[[2,1],[3,0],[4,-1]]];var winDiagonalMaskBet5=[[[0,1],[1,0],[2,-1],[3,0],[4,1]],[[0,1],[1,0],[2,-1],[3,0]],[[1,0],[2,-1],[3,0],[4,1]],[[1,0],[2,-1],[3,0]],[[0,1],[1,0],[2,-1]],[[2,-1],[3,0],[4,1]]];var description_flag=false;var autoplay_flag=false;var freespin_flag=false;var wheel_flag=false;var animation_flag=false;var close_flag=false;var facebook_flag=false;var treasure_flag=false;var treasure_spin_flag=false;var explosion_flag=false;var bonus_spin_flag=false;var settings_flag=false;var rotate_flag=false;var spin_flag=false;var win_flag=true;var hold_flag=false;var nohold_flag=false;var countFreeTreasure=0;var startLetterPosition={x:-75,y:-158,x_step:42,y_step:42};var startPositionBar={x1:-121,x2:5};var startPositionTreasureGame={x:-185,y:-80,x_step:93,y_step:74};var treasureSprites=[13,2,6,1,9,3,7,12,5,4,8,10,14,11];var greenBar=[];var bonusIcon=[];var allCountBonus=[0,0];var greenBarWidth=0;var countFreeSpinText=null;var wheelPercentText=null;var treasurePercentText=null;var balanceText=null;var linesText=null;var betText=null;var txtCongratulation=null;var reelsSpinPositions=[];var holdButtons=[];var holdFrames=[];var spinSteps=[];var countSlots=5;var countSprite=15;var countSpin=0;var spinButton=null;var autoPlayButton=null;var creditsText;var winnerPlayedText;var coinsPlayedText;var wheelPercent=0;var treasurePercent=0;var countFreeSpin=0;var reelsSprites;var reelsSpinPositions;var holdButtons;var holdFrames;var lockScreen;var reels=[];var reelsValues=[];var holded=[];var spinSteps=[];var winText;var winLock;var winMarks=[];var popup=[];var wheelTurned=false;var wheelFront;var wheelStars;var countRotate=0;var countBetLines=1;var countBets=1;var balance=0;var credits=0;var winnerPlayed=0;var coinsPlayed=0;var startPositionPlayerLines=[{x:0,y:-13},{x:0,y:-80},{x:0,y:57},{x:0,y:-13},{x:0,y:-13}];var startPositionPlayerLinesSecond=[{x:-92,y:-13},{x:92,y:-13}];var maxLevel=0;var totalPoints=0;var totalWords=0;var maxLengthWord=0;var totalCombos=0;var countGames=0;var levelTimeBonus=0;var currentLevel=1;var currentLevelScore=0;var currentTotalScore=0;var tmpTotalScore=0;var currentCreateWords=0;var currentMaxLengthWords=0;var currentCombos=0;var countIteration=0;;window.onload=function()
{GET=Utils.parseGet();Utils.addMobileListeners(LANDSCAPE_MODE);Utils.mobileCorrectPixelRatio();Utils.addFitLayoutListeners();if(window.navigator.userAgent.toLowerCase().indexOf("android")>-1||window.navigator.userAgent.toLowerCase().indexOf("linux")>-1){isAndroid=true;}
setTimeout(startLoad,600);};function startLoad()
{var resolution=Utils.getMobileScreenResolution(LANDSCAPE_MODE);if(GET["debug"]==1){resolution=Utils.getScaleScreenResolution(1,LANDSCAPE_MODE);}
Utils.globalScale=resolution.scale;var ratioCoefs=[1.5,1.6,1.66,1.7,1.78,1.52];var ratioWidth=[1,1.0666,1.106,1.133,1.187,1.016];var ratioHeight=[1,1,1,1,1,1];if(window.innerWidth>window.innerHeight){var coef=window.innerWidth/window.innerHeight;}
else{var coef=window.innerHeight/window.innerWidth;}
var min=100000,minPos=-1,diff;for(var i=0;i<ratioCoefs.length-1;i++){diff=Math.abs(coef-ratioCoefs[i]);if(diff<min){min=diff;minPos=i;}}
console.log('пакет графики = '+minPos);if(window.innerHeight==672){minPos=5;}
screenWidthCoef=ratioWidth[minPos];screenHeightCoef=ratioHeight[minPos];screenWidthRatioPos=minPos;resolution.width=Math.round(resolution.width*screenWidthCoef);Utils.createLayout(document.getElementById("main_container"),resolution);Utils.addEventListener("fitlayout",function()
{if(stage)
{buildBackground();}});Utils.addEventListener("lockscreen",function(){if(stage&&stage.started)
{stage.stop();}});Utils.addEventListener("unlockscreen",function(){if(stage&&!stage.started)
{stage.start();}});Utils.fitLayoutToScreen();Utils.mobileHideAddressBar();mixer=new AudioMixer("music",1);if(GET["debug"]!=1){Utils.checkOrientation(LANDSCAPE_MODE);}
var path="ratios/"+minPos+"/";graphicsPack=minPos;var assets=[{"name":"about","src":"about.jpg","width":480,"height":320},{"name":"animation","src":"animation.png","width":126,"height":126,"frames":4},{"name":"arrow","src":"arrow.png","width":49,"height":142},{"name":"bar-blue","src":"bar-blue.png","width":93,"height":17},{"name":"bar-green","src":"bar-green.png","width":90,"height":15},{"name":"btn-ask","src":"btn-ask.png","width":69,"height":69},{"name":"btn-autoplay","src":"btn-autoplay.png","width":66,"height":53},{"name":"btn-back","src":"btn-back.png","width":43,"height":43},{"name":"btn-bet","src":"btn-bet.png","width":66,"height":53},{"name":"btn-down","src":"btn-down.png","width":20,"height":17},{"name":"btn-facebook-active","src":"btn-facebook-active.png","width":57,"height":57},{"name":"btn-free-spin","src":"btn-free-spin.png","width":66,"height":53},{"name":"btn-hold","src":"btn-hold.png","width":40,"height":26,"frames":2},{"name":"btn-info","src":"btn-info.png","width":69,"height":69},{"name":"btn-lines","src":"btn-lines.png","width":66,"height":53},{"name":"btn-menu","src":"btn-menu.png","width":37,"height":37},{"name":"btn-next","src":"btn-next.png","width":43,"height":43},{"name":"btn-payout","src":"btn-payout.png","width":66,"height":53},{"name":"btn-play-cude","src":"btn-play-cude.png","width":66,"height":38},{"name":"btn-play","src":"btn-play.png","width":85,"height":85},{"name":"btn-preference","src":"btn-preference.png","width":36,"height":36},{"name":"btn-reset","src":"btn-reset.png","width":71,"height":58},{"name":"btn-sound-off","src":"btn-sound-off.png","width":69,"height":69},{"name":"btn-sound-on","src":"btn-sound-on.png","width":69,"height":69},{"name":"btn-spin","src":"btn-spin.png","width":66,"height":53},{"name":"btn-stop","src":"btn-stop.png","width":66,"height":53},{"name":"btn-up","src":"btn-up.png","width":20,"height":17},{"name":"cursor-pointer","src":"cursor-pointer.png","width":53,"height":56},{"name":"fishka","src":"fishka.png","width":68,"height":68},{"name":"frame","src":"frame.png","width":94,"height":216},{"name":"i1","src":"icons/i1.png","width":67,"height":60},{"name":"i10","src":"icons/i10.png","width":62,"height":64},{"name":"i11","src":"icons/i11.png","width":59,"height":53},{"name":"i12","src":"icons/i12.png","width":62,"height":64},{"name":"i13","src":"icons/i13.png","width":52,"height":65},{"name":"i14","src":"icons/i14.png","width":59,"height":62},{"name":"i2","src":"icons/i2.png","width":67,"height":58},{"name":"i3","src":"icons/i3.png","width":62,"height":61},{"name":"i4","src":"icons/i4.png","width":65,"height":63},{"name":"i5","src":"icons/i5.png","width":63,"height":61},{"name":"i6","src":"icons/i6.png","width":64,"height":64},{"name":"i7","src":"icons/i7.png","width":62,"height":63},{"name":"i8","src":"icons/i8.png","width":67,"height":48},{"name":"i9","src":"icons/i9.png","width":62,"height":63},{"name":"1","src":"fruits/1.png","width":68,"height":68},{"name":"10","src":"fruits/10.png","width":68,"height":68},{"name":"11","src":"fruits/11.png","width":68,"height":68},{"name":"12","src":"fruits/12.png","width":68,"height":68},{"name":"13","src":"fruits/13.png","width":58,"height":68},{"name":"14","src":"fruits/14.png","width":68,"height":68},{"name":"15","src":"fruits/15.png","width":68,"height":68},{"name":"2","src":"fruits/2.png","width":68,"height":68},{"name":"3","src":"fruits/3.png","width":68,"height":68},{"name":"4","src":"fruits/4.png","width":68,"height":68},{"name":"5","src":"fruits/5.png","width":68,"height":68},{"name":"6","src":"fruits/6.png","width":68,"height":68},{"name":"7","src":"fruits/7.png","width":68,"height":68},{"name":"8","src":"fruits/8.png","width":68,"height":68},{"name":"9","src":"fruits/9.png","width":68,"height":68},{"name":"line1","src":"line1.png","width":360,"height":18},{"name":"line2","src":"line2.png","width":266,"height":18},{"name":"line3","src":"line3.png","width":454,"height":18},{"name":"line4-1","src":"line4-1.png","width":419,"height":169},{"name":"line4-2","src":"line4-2.png","width":419,"height":169},{"name":"line4-3","src":"line4-3.png","width":419,"height":169},{"name":"line4","src":"line4.png","width":419,"height":169},{"name":"line5-1","src":"line5-1.png","width":419,"height":169},{"name":"line5-2","src":"line5-2.png","width":419,"height":169},{"name":"line5-3","src":"line5-3.png","width":419,"height":169},{"name":"line5","src":"line5.png","width":419,"height":169},{"name":"number-big-num","src":"number-big-num.png","width":42,"height":50,"frames":10},{"name":"number-for-lines","src":"number-for-lines.png","width":18,"height":20,"frames":10},{"name":"number-full","src":"number-full.png","width":12,"height":14,"frames":11},{"name":"number-score","src":"number-score.png","width":22,"height":26,"frames":11},{"name":"number","src":"number.png","width":10,"height":12,"frames":11},{"name":"cover","src":path+"cover.png","width":480,"height":320},{"name":"game-over","src":path+"game-over.png","width":480,"height":320},{"name":"instructions-payout","src":path+"instructions-payout.png","width":480,"height":320},{"name":"instructions","src":path+"instructions.png","width":480,"height":320},{"name":"menu","src":path+"menu.png","width":480,"height":320},{"name":"settings","src":path+"settings.png","width":480,"height":320},{"name":"share-fb","src":path+"share-fb.png","width":480,"height":320},{"name":"spin","src":path+"spin.png","width":480,"height":320},{"name":"spin-numbers","src":path+"spin-numbers.png","width":480,"height":320},{"name":"treasure-game","src":path+"treasure-game.png","width":480,"height":320},{"name":"treasure","src":path+"treasure.png","width":480,"height":320},{"name":"treasure-numbers","src":path+"treasure-numbers.png","width":480,"height":320},{"name":"splash","src":"splash.png","width":480,"height":320},{"name":"text","src":"text.png","width":435,"height":38},{"name":"treasure-chest","src":"treasure-chest.png","width":27,"height":28},{"name":"txt-congratulations","src":"txt-congratulations.png","width":547,"height":182},{"name":"txt-10fs","src":"txt-10fs.png","width":388,"height":50},{"name":"txt-20fs","src":"txt-20fs.png","width":397,"height":51},{"name":"txt-3fs","src":"txt-3fs.png","width":359,"height":51},{"name":"txt-5fs","src":"txt-5fs.png","width":359,"height":51},{"name":"wheel","src":"wheel.png","width":25,"height":25},{"name":"white-point","src":"white-point.png","width":114,"height":157}];library=new AssetsLibrary('images',Utils.globalScale,assets);library.load(loadImagesEnd,Utils.showLoadProgress);}
function loadImagesEnd()
{document.getElementById('progress_container').style.display='none';document.getElementById('screen_container').style.display='block';document.getElementById('screen_background_container').style.display='block';if(GET["debug"]!=1)
{prepareGame();}}
function getStageWidth()
{return Math.round(480*screenWidthCoef);}
function getStageHeight()
{return Math.floor(320*screenHeightCoef);}
function getStageWidthCenter()
{return Math.round(getStageWidth()/2);}
function getStageHeightCenter()
{return Math.round(getStageHeight()/2);}
function createStage()
{if(stage)
{stage.destroy();stage.stop();}
stage=new Stage('screen',getStageWidth(),getStageHeight());stage.delay=1000/fps;stage.onpretick=preTick;stage.onposttick=postTick;stage.ceilSizes=true;stage.showFPS=false;}
function createScene()
{console.log('=====createScene');createStage();console.log('gameState = '+gameState);if(gameState==STATE_SPLASH)
{setBackColor('#fee002');showSplash();}
if(gameState==STATE_COVER)
{setBackColor('#23c326');showCover();if(sound){mixer.play('music',true,false,0);}}
if(gameState==STATE_MENU)
{processState=PROCESS_START;setBackColor('#23c326');showMenu();}
if(gameState==STATE_SETTINGS)
{setBackColor('#23c326');showSettings();}
if(gameState==STATE_INSTRUCTION_ONE)
{setBackColor('#23c326');showInstructionOne();}
if(gameState==STATE_INSTRUCTION_TWO)
{setBackColor('#23c326');showInstructionTwo();}
if(gameState==STATE_GAME)
{console.log('===STATE_GAME');setBackColor('#23c326');if(processState==PROCESS_START){processState=PROCESS_GAME;createGameArea();}
else{}}
if(gameState==STATE_GAME_OVER)
{setBackColor('#23c326');showGameOver();}
if(gameState==STATE_BEST_SCORE)
{setBackColor('#23c326');GameBase.getPlayerScore();showBestResult();}
if(gameState==STATE_ABOUT)
{setBackColor('#fee002');showAbout();}
buildBackground();stage.start();}
function showSplash()
{var spr=library.getSprite("splash");spr.x=getStageWidthCenter();spr.y=getStageHeightCenter();spr.static=true;stage.addChild(spr);setTimeout(function()
{setBackColor('#4487d6');gameState=STATE_MENU;createScene();},3000);}
function showCover()
{mc=library.getSprite('cover',{width:getStageWidth(),height:getStageHeight()});mc.x=getStageWidthCenter();mc.y=getStageHeightCenter();mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-play');mc.x=getStageWidthCenter()+160;mc.y=getStageHeightCenter()+11;mc.static=true;mc.zIndex=20;mc.onclick=function()
{gameState=STATE_MENU;createScene();};stage.addChild(mc);}
function showMenu()
{mc=library.getSprite('menu',{width:getStageWidth(),height:getStageHeight()});mc.x=getStageWidthCenter();mc.y=getStageHeightCenter();mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-preference');mc.x=getStageWidthCenter()-165;mc.y=getStageHeightCenter()+136;mc.static=true;mc.zIndex=20;mc.onclick=function()
{gameState=STATE_SETTINGS;createScene();};stage.addChild(mc);mc=library.getSprite('btn-how-to-play');mc.x=getStageWidthCenter()-211;mc.y=getStageHeightCenter()+136;mc.static=true;mc.zIndex=20;mc.onclick=function(e)
{window.open("http://www.tweensoft.com/");};stage.addChild(mc);mc=library.getSprite('btn-play');mc.x=getStageWidthCenter()+17;mc.y=getStageHeightCenter()+69;mc.static=true;mc.zIndex=20;mc.onclick=function()
{gameState=STATE_GAME;if(!Utils.getCookie('fs_instruction')){gameState=STATE_INSTRUCTION_ONE;}
createScene();};stage.addChild(mc);}
function showSettings()
{settings_flag=true;mc=library.getSprite('settings',{width:getStageWidth(),height:getStageHeight()});mc.x=getStageWidthCenter();mc.y=getStageHeightCenter();mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-back');mc.x=getStageWidthCenter()-215;mc.y=getStageHeightCenter()+135;mc.static=true;mc.zIndex=20;mc.onclick=function()
{settings_flag=false;gameState=STATE_MENU;createScene();};stage.addChild(mc);mc=library.getSprite('btn-ask');mc.x=getStageWidthCenter()-108;mc.y=getStageHeightCenter()+12;mc.static=true;mc.zIndex=20;mc.onclick=function(e)
{gameState=STATE_INSTRUCTION_ONE;createScene();};stage.addChild(mc);mc=library.getSprite('btn-info');mc.x=getStageWidthCenter()+108;mc.y=getStageHeightCenter()+12;mc.static=true;mc.zIndex=20;mc.onclick=function()
{gameState=STATE_ABOUT;createScene();};stage.addChild(mc);mc=library.getSprite(sound?'btn-sound-on':'btn-sound-off');mc.x=getStageWidthCenter();mc.y=getStageHeightCenter()+12;mc.static=true;mc.zIndex=20;mc.onclick=function(e)
{if(sound){e.target.bitmap=library.getBitmap('btn-sound-off');mixer.stop(0);Utils.setCookie('sound',2);sound=false;}
else{e.target.bitmap=library.getBitmap('btn-sound-on');mixer.play('music',true,false,0);Utils.setCookie('sound',1);sound=true;}
buildBackground();return false;};stage.addChild(mc);}
function showInstructionOne()
{mc=library.getSprite('instructions',{width:getStageWidth(),height:getStageHeight()});mc.x=getStageWidthCenter();mc.y=getStageHeightCenter();mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-back');mc.x=getStageWidthCenter()-214;mc.y=getStageHeightCenter()+135;mc.animated=false;mc.static=true;mc.onclick=function()
{if(settings_flag){gameState=STATE_SETTINGS;}
else{gameState=STATE_MENU;}
createScene();};stage.addChild(mc);mc=library.getSprite('btn-next');mc.x=getStageWidthCenter()+214;mc.y=getStageHeightCenter()+138;mc.animated=false;mc.static=true;mc.onclick=function()
{gameState=STATE_INSTRUCTION_TWO;createScene();};stage.addChild(mc);}
function showInstructionTwo()
{mc=library.getSprite('instructions-payout',{width:getStageWidth(),height:getStageHeight()});mc.x=getStageWidthCenter();mc.y=getStageHeightCenter();mc.static=true;stage.addChild(mc);mc=library.getSprite('text');mc.x=getStageWidthCenter();mc.y=getStageHeightCenter()-96;mc.animated=false;mc.static=false;stage.addChild(mc);mc=library.getSprite('btn-back');mc.x=getStageWidthCenter()-214;mc.y=getStageHeightCenter()+135;mc.animated=false;mc.static=true;mc.onclick=function()
{gameState=STATE_INSTRUCTION_ONE;createScene();};stage.addChild(mc);if(!settings_flag){mc=library.getSprite('btn-next');mc.x=getStageWidthCenter()+214;mc.y=getStageHeightCenter()+138;mc.animated=false;mc.static=true;mc.onclick=function()
{if(!Utils.getCookie('fs_instruction')){Utils.setCookie('fs_instruction',1);}
gameState=STATE_GAME;createScene();};stage.addChild(mc);}}
function showGameOver()
{console.log('=====showFinished');var bg=library.getSprite('game-over',{width:getStageWidth(),height:getStageHeight()});bg.x=getStageWidthCenter();bg.y=getStageHeightCenter();bg.static=false;bg.onmousedown=function()
{return false;};bg.onmouseup=function()
{return false;};stage.addChild(bg);var bt=library.getSprite('btn-reset');bt.x=getStageWidthCenter();bt.y=getStageHeightCenter()+16;bt.animated=false;bt.static=false;bt.onclick=function()
{bt.visible=false;bt.destroy=false;bg.visible=false;bg.destroy=false;GameBase.resetGameParameters();gameState=STATE_GAME;createScene();};stage.addChild(bt);buildBackground();}
function showFBShare()
{console.log('=====showFBShare');var tmp_autoplay_flag=autoplay_flag;facebook_flag=true;autoplay_flag=false;var bg=library.getSprite('share-fb',{width:getStageWidth(),height:getStageHeight()});bg.x=getStageWidthCenter();bg.y=getStageHeightCenter();bg.static=false;bg.onmousedown=function()
{return false;};bg.onmouseup=function()
{return false;};stage.addChild(bg);var bn=library.getSprite('btn-next');bn.x=getStageWidthCenter()+214;bn.y=getStageHeightCenter()+138;bn.static=false;bn.onclick=function()
{bt.visible=false;bt.destroy=false;bg.visible=false;bg.destroy=false;bn.visible=false;bn.destroy=false;cp.visible=false;cp.destroy=false;facebook_flag=false;autoplay_flag=tmp_autoplay_flag;return;};stage.addChild(bn);var cp=library.getSprite('cursor-pointer');cp.x=getStageWidthCenter()+44;cp.y=getStageHeightCenter()+37;cp.static=false;stage.addChild(cp);var bt=library.getSprite('btn-facebook-active');bt.x=getStageWidthCenter();bt.y=getStageHeightCenter()+16;bt.animated=false;bt.static=false;bt.onmouseup=function()
{FaceBook.init();FaceBook.getUserInfo(FaceBook.postOnWall);bt.visible=false;bt.destroy=false;bg.visible=false;bg.destroy=false;bn.visible=false;bn.destroy=false;cp.visible=false;cp.destroy=false;facebook_flag=false;autoplay_flag=tmp_autoplay_flag;return;};stage.addChild(bt);buildBackground();}
function showWheel()
{setBackColor('#23c326');wheel_flag=true;countRotate=needCountRotateWheel;rotate_flag=false;console.log('=====showWheel');var bg=library.getSprite('spin',{width:getStageWidth(),height:getStageHeight()});bg.x=getStageWidthCenter();bg.y=getStageHeightCenter();bg.static=false;bg.onmousedown=function()
{return false;};bg.onmouseup=function()
{return false;};stage.addChild(bg);var ar=library.getSprite('arrow');ar.x=getStageWidthCenter()-26;ar.y=getStageHeightCenter()+5;ar.static=false;ar.rotation=Math.PI/16;ar.anchor={x:0,y:47};stage.addChild(ar);var nb=library.getSprite('spin-numbers');nb.x=getStageWidthCenter();nb.y=getStageHeightCenter();nb.static=false;stage.addChild(nb);var bt=new SimpleText(library.getBitmap('number-score'),22,26);bt.x=getStageWidthCenter()+180;bt.y=getStageHeightCenter()-130;bt.scale=0.8;bt.charMap=charMap;bt.align=bt.ALIGN_CENTER;bt.write(balance.insertComma());var sb=library.getSprite('btn-spin');sb.x=getStageWidthCenter()+199;sb.y=getStageHeightCenter()+129;sb.static=false;sb.onmouseup=function(e)
{if(!rotate_flag){countRotate--;tx.write(countRotate+'x');if(countRotate==0){tx.write();e.target.visible=false;e.target.destroy=true;bb.visible=true;}
rotateArrow(ar,bt);}};stage.addChild(sb);var tx=new SimpleText(library.getBitmap('number-score'),22,26);tx.x=getStageWidthCenter()+145;tx.y=getStageHeightCenter()+145;tx.charMap=charMap;tx.align=tx.ALIGN_LEFT;tx.write(countRotate+'x');var bb=library.getSprite('btn-back');bb.x=getStageWidthCenter()-214;bb.y=getStageHeightCenter()+135;bb.static=false;bb.visible=false;bb.onclick=function()
{if(rotate_flag)
{return false;}
wheel_flag=false;ar.destroy=true;bg.destroy=true;bb.destroy=true;sb.destroy=true;nb.destroy=true;bt.write();tx.write();setBackColor('#23c326');buildBackground();return;};stage.addChild(bb);}
function rotateArrow(e,ts)
{rotate_flag=true;var element=e;var steps=0;var tween=null;steps=getRandomInt(24,40);tween=stage.createTween(element,"rotation",element.rotation,element.rotation+(2*Math.PI)+steps*(2*Math.PI)/16,(16+steps)*2,Easing.cubic.easeOut);tween.play();tween.onfinish=function(e)
{tween.stop();var r=e.target.obj.rotation-Math.floor(e.target.obj.rotation/(2*Math.PI))*(2*Math.PI);var id=Math.floor(r/((2*Math.PI)/16));var bonus=wheelWinCoef[id];balance+=bonus;moveBonus(bonus,function()
{rotate_flag=false;ts.write(balance);});};}
function showTreasure()
{console.log('=====showTreasure');treasure_flag=true;setBackColor('#23c326');var bg=library.getSprite('treasure',{width:getStageWidth(),height:getStageHeight()});bg.x=getStageWidthCenter();bg.y=getStageHeightCenter();bg.static=false;bg.onmousedown=function()
{return false;};bg.onmouseup=function()
{return false;};bg.onmousemove=function()
{return false;};stage.addChild(bg);var ns=new SimpleText(library.getBitmap('number-score'),22,26);ns.x=getStageWidthCenter()+180;ns.y=getStageHeightCenter()-130;ns.scale=0.8;ns.charMap=charMap;ns.align=ns.ALIGN_CENTER;ns.write(balance.insertComma());var yb=library.getSprite('fishka');yb.x=getStageWidthCenter();yb.y=getStageHeightCenter();yb.animated=false;yb.static=false;yb.visible=false;stage.addChild(yb);var cnt=0;var spr=[];for(var j=0;j<3;j++){for(var i=0;i<5;i++){spr[cnt]=library.getSprite('i'+treasureSprites[cnt]);spr[cnt].x=getStageWidthCenter()+startPositionTreasureGame.x+(i*startPositionTreasureGame.x_step);spr[cnt].y=getStageHeightCenter()+startPositionTreasureGame.y+(j*startPositionTreasureGame.y_step);spr[cnt].static=false;stage.addChild(spr[cnt]);cnt++;}}
countFreeTreasure=needCountFreeTreasure;var nb=library.getSprite('treasure-numbers');nb.x=getStageWidthCenter();nb.y=getStageHeightCenter();nb.animated=false;nb.static=false;stage.addChild(nb);var pb=library.getSprite('btn-play-cude');pb.x=getStageWidthCenter()+204;pb.y=getStageHeightCenter()+138;pb.animated=false;pb.static=false;pb.onclick=function(e)
{if(!treasure_spin_flag){countFreeTreasure--;tx.write(countFreeTreasure+'x');if(countFreeTreasure==0){e.target.destroy=true;tx.write('');bb.visible=true;}
checkRandomFruits(ns,yb);}};stage.addChild(pb);var tx=new SimpleText(library.getBitmap('number-score'),22,26);tx.x=getStageWidthCenter()+145;tx.y=getStageHeightCenter()+145;tx.charMap=charMap;tx.align=tx.ALIGN_LEFT;tx.write(countFreeTreasure+'x');var bb=library.getSprite('btn-back');bb.x=getStageWidthCenter()-214;bb.y=getStageHeightCenter()+135;bb.static=false;bb.visible=false;bb.onclick=function()
{if(treasure_spin_flag)
{return false;}
for(var n=0;n<spr.length;n++){spr[n].destroy=true;}
bg.destroy=true;bb.destroy=true;pb.destroy=true;nb.destroy=true;treasure_flag=false;ns.write('');tx.write('');setBackColor('#23c326');buildBackground();return false;};stage.addChild(bb);}
function checkRandomFruits(ts,fs)
{treasure_spin_flag=true;var pos_x=0;var pos_y=0;var x=0;var y=0;var timeout=10;var s=0;function step()
{timeout+=10;s+=20;if(!explosion_flag){pos_x=getRandomInt(0,4);pos_y=getRandomInt(0,2);while(pos_x==4&&pos_y==2){pos_x=getRandomInt(0,4);pos_y=getRandomInt(0,2);}
x=getStageWidthCenter()+startPositionTreasureGame.x+(pos_x*startPositionTreasureGame.x_step);y=getStageHeightCenter()+startPositionTreasureGame.y+(pos_y*startPositionTreasureGame.y_step);fs.x=x;fs.y=y;if(!fs.visible){fs.visible=true;}
if(s>=350)
{var tr=setTimeout(function()
{clearTimeout(tr);fs.visible=false;showExplosion(x,y);var bonus=treasureWinCoef[pos_y][pos_x];if(!bonus){bonus_spin_flag=true;countFreeSpin+=10;freespin_flag=true;spinButton.bitmap=library.getBitmap('btn-free-spin');showFreeSpinBonus(10,function()
{treasure_spin_flag=false;});}
else{balance+=bonus;moveBonus(bonus,function()
{ts.write(balance);treasure_spin_flag=false;});}},600);}
else
{setTimeout(step,timeout);}}}
step();}
function showDescription()
{setBackColor('#23c326');description_flag=true;var bg=library.getSprite('instructions-payout',{width:getStageWidth(),height:getStageHeight()});bg.x=getStageWidthCenter();bg.y=getStageHeightCenter();bg.static=false;bg.onmousedown=function()
{return false;};bg.onmouseup=function()
{return false;};bg.onmousemove=function()
{return false;};stage.addChild(bg);var tx=library.getSprite('text');tx.x=getStageWidthCenter();tx.y=getStageHeightCenter()-96;tx.animated=false;tx.static=false;stage.addChild(tx);var bt=library.getSprite('btn-back');bt.x=getStageWidthCenter()-214;bt.y=getStageHeightCenter()+135;bt.animated=false;bt.static=false;bt.onmousedown=function()
{bg.destroy=true;bt.destroy=true;tx.destroy=true;description_flag=false;setBackColor('#23c326');buildBackground();return false;};stage.addChild(bt);}
function showAbout()
{var spr=library.getSprite("about",{width:getStageWidth(),height:getStageHeight()});spr.x=getStageWidthCenter();spr.y=getStageHeightCenter();spr.static=true;spr.onclick=function()
{gameState=STATE_SETTINGS;createScene();};stage.addChild(spr);}
function setBackColor(color)
{document.body.style.background=color;}
function createGameArea()
{console.log('====createGameArea');var ga=library.getSprite('treasure-game',{width:getStageWidth(),height:getStageHeight()});ga.static=true;ga.setPosition(getStageWidthCenter(),getStageHeightCenter());ga.onmouseup=function()
{return false;};ga.onmousedown=function()
{return false;};stage.addChild(ga);mc=library.getSprite('btn-menu');mc.x=getStageWidthCenter()-218;mc.y=getStageHeightCenter()-141;mc.static=true;mc.onmousedown=function()
{GameBase.setPlayerScore();resetProgressBars();gameState=STATE_MENU;createScene();};stage.addChild(mc);balanceText=new SimpleText(library.getBitmap('number-score'),22,26);balanceText.x=getStageWidthCenter()+180;balanceText.y=getStageHeightCenter()-133;balanceText.scale=0.8;balanceText.charMap=charMap;balanceText.align=balanceText.ALIGN_CENTER;balanceText.write(balance.insertComma());var blueBar=library.getSprite('bar-blue');blueBar.x=getStageWidthCenter()+startPositionBar.x1;blueBar.y=getStageHeightCenter()-135;blueBar.static=true;blueBar.BAR=true;stage.addChild(blueBar);blueBar=library.getSprite('bar-blue');blueBar.x=getStageWidthCenter()+startPositionBar.x2;blueBar.y=getStageHeightCenter()-135;blueBar.static=true;blueBar.BAR=true;stage.addChild(blueBar);drawProgressBar(0,0);drawProgressBar(1,0);wheelPercentText=new SimpleText(library.getBitmap('number'),10,12);wheelPercentText.x=getStageWidthCenter()+startPositionBar.x1;wheelPercentText.y=getStageHeightCenter()-134;wheelPercentText.charMap=charMapPercent;wheelPercentText.align=wheelPercentText.ALIGN_LEFT;wheelPercentText.write('0%');treasurePercentText=new SimpleText(library.getBitmap('number'),10,12);treasurePercentText.x=getStageWidthCenter()+startPositionBar.x2;treasurePercentText.y=getStageHeightCenter()-134;treasurePercentText.charMap=charMapPercent;treasurePercentText.align=treasurePercentText.ALIGN_LEFT;treasurePercentText.write('0%');for(var i=0;i<5;i++){mc=library.getSprite('btn-hold');mc.x=getStageWidthCenter()-212+(i*93);mc.y=getStageHeightCenter()+87;mc.static=false;mc.slotID=i*1;mc.onmousedown=hold;stage.addChild(mc);holdButtons[i]=mc;}
mc=library.getSprite('btn-payout');mc.x=getStageWidthCenter()-197;mc.y=getStageHeightCenter()+129;mc.static=true;mc.onmousedown=function()
{showDescription();return false;};stage.addChild(mc);mc=library.getSprite('btn-lines');mc.x=getStageWidthCenter()-87;mc.y=getStageHeightCenter()+129;mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-up');mc.x=getStageWidthCenter()-128;mc.y=getStageHeightCenter()+113;mc.static=true;mc.LINE_UP=true;mc.onmousedown=countPlayerLines;stage.addChild(mc);mc=library.getSprite('btn-down');mc.x=getStageWidthCenter()-128;mc.y=getStageHeightCenter()+145;mc.static=true;mc.LINE_DOWN=true;mc.onmousedown=countPlayerLines;stage.addChild(mc);linesText=new SimpleText(library.getBitmap('number-score'),22,26);linesText.x=getStageWidthCenter()-87;linesText.y=getStageHeightCenter()+140;linesText.charMap=charMapLineNumber;linesText.align=linesText.ALIGN_CENTER;linesText.write(countBetLines);mc=library.getSprite('btn-bet');mc.x=getStageWidthCenter()+5;mc.y=getStageHeightCenter()+129;mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-up');mc.x=getStageWidthCenter()-37;mc.y=getStageHeightCenter()+113;mc.BET_UP=true;mc.onmousedown=countPlayerBets;mc.static=true;stage.addChild(mc);mc=library.getSprite('btn-down');mc.x=getStageWidthCenter()-37;mc.y=getStageHeightCenter()+145;mc.BET_DOWN=true;mc.onmousedown=countPlayerBets;mc.static=true;stage.addChild(mc);betText=new SimpleText(library.getBitmap('number-score'),22,26);betText.x=getStageWidthCenter()+5;betText.y=getStageHeightCenter()+140;betText.charMap=charMapLineNumber;betText.align=betText.ALIGN_CENTER;betText.write(countBets);autoPlayButton=library.getSprite('btn-autoplay');autoPlayButton.x=getStageWidthCenter()+95;autoPlayButton.y=getStageHeightCenter()+129;autoPlayButton.static=true;autoPlayButton.onmouseup=function(e)
{if(!autoplay_flag){autoplay_flag=true;e.target.bitmap=library.getBitmap('btn-stop');buildBackground();spinReels();}
else{autoplay_flag=false;e.target.bitmap=library.getBitmap('btn-autoplay');buildBackground();return false;}};stage.addChild(autoPlayButton);spinButton=library.getSprite('btn-spin');spinButton.x=getStageWidthCenter()+199;spinButton.y=getStageHeightCenter()+129;spinButton.SPIN=true;spinButton.static=true;spinButton.onmouseup=function(e)
{if(autoplay_flag||spin_flag){return false;}
spin_flag=true;if(countFreeSpin>0){countFreeSpin--;}
buildBackground();spinReels(e);};stage.addChild(spinButton);countFreeSpinText=new SimpleText(library.getBitmap('number-score'),22,26);countFreeSpinText.x=getStageWidthCenter()+175;countFreeSpinText.y=getStageHeightCenter()+145;countFreeSpinText.scale=0.6;countFreeSpinText.charWidth=charWidth;countFreeSpinText.charMap=charMap;countFreeSpinText.align=countFreeSpinText.ALIGN_RIGHT;countFreeSpinText.write(' ');startNewGame();}
function startNewGame()
{GameBase.getPlayerScore();if(!balance){balance=START_COINS;}
if(!countBetLines){countBetLines=MIN_BET;}
if(!countBets){countBets=MIN_BET;}
holded=[false,false,false,false,false];reels=[0,0,0,0,0];reelsValues=[];for(var i=0;i<5;i++)reelsValues[i]=shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]);createReels();setReelsRandomly();showCurrentReels();startNewMatch();}
function createReels()
{reelsSprites=[];reelsSpinPositions=[];holdFrames=[];var curX=getStageWidthCenter()-186;for(var i=0;i<5;i++){reelsSprites[i]=[];for(var n=0;n<4;n++){mc=new Sprite(null,68,68);mc.x=curX;reelsSprites[i][n]=mc;stage.addChild(mc);}
reelsSpinPositions[i]=0;mc=library.getSprite('frame');mc.x=curX;mc.y=getStageHeightCenter()-12;stage.addChild(mc);mc.visible=false;holdFrames[i]=mc;mc=new Sprite(null,94,216);mc.x=curX;mc.y=getStageHeightCenter()-12;mc.slotID=i*1;mc.onmousedown=hold;stage.addChild(mc);curX+=93;}}
function startNewMatch()
{console.log('startNewMatch-------------------------------------------------');gameState=STATE_GAME_PRE_BET;resetHolded();}
function drawProgressBar(numberBar,countBonus)
{console.log('======drawProgressBar');var posX=startPositionBar.x1;if(numberBar==BONUS_TREASURE){posX=startPositionBar.x2;}
if(!greenBar[numberBar]){greenBar[numberBar]=library.getSprite('bar-green');greenBar[numberBar].x=getStageWidthCenter()+posX;greenBar[numberBar].y=getStageHeightCenter()-135;greenBar[numberBar].static=true;greenBar[numberBar].BAR=true;stage.addChild(greenBar[numberBar]);if(!greenBarWidth){greenBarWidth=greenBar[numberBar].width;}}
if(!bonusIcon[numberBar]){bonusIcon[numberBar]=library.getSprite(numberBar==BONUS_WHEEL?'wheel':'treasure-chest');bonusIcon[numberBar].x=getStageWidthCenter()+posX;bonusIcon[numberBar].y=getStageHeightCenter()-135;bonusIcon[numberBar].static=true;bonusIcon[numberBar].BONUS_ICON=true;stage.addChild(bonusIcon[numberBar]);bonusIcon[numberBar].x-=bonusIcon[numberBar].width*2;}
allCountBonus[numberBar]+=countBonus;var step=greenBarWidth/needCountBonus[numberBar];var show_steps=step*allCountBonus[numberBar];var x=(getStageWidthCenter()+posX-(greenBarWidth/2))+(show_steps/2);greenBar[numberBar].width=show_steps;greenBar[numberBar].x=((greenBar[numberBar].width%2)!=0?x:x+1);greenBar[numberBar].visible=true;for(var i=0;i<bonusIcon.length;i++){if(bonusIcon[i]){bonusIcon[i].setZIndex(stage.objects[stage.getMaxZIndexInStack(stage.objects)].zIndex+1);}}
var p=Math.round((show_steps*100)/greenBarWidth);if(p>=100){allCountBonus[numberBar]=0;greenBar[numberBar].width=0;}
if(numberBar==BONUS_WHEEL){wheelPercent=p;if(wheelPercent>=100){wheelPercent=0;wheel_flag=true;console.log('----- wheel_flag = '+wheel_flag);}}
else{treasurePercent=p;if(treasurePercent>=100){treasurePercent=0;autoplay_flag=false;autoPlayButton.bitmap=library.getBitmap('btn-autoplay');treasure_flag=true;}}
buildBackground();}
function resetProgressBars()
{for(var i=0;i<greenBar.length;i++){if(greenBar[i]){greenBar[i].visible=false;greenBar[i].destroy=true;}}
for(var i=0;i<bonusIcon.length;i++){if(bonusIcon[i]){bonusIcon[i].visible=false;bonusIcon[i].destroy=true;}}
greenBar=[];bonusIcon=[];}
function checkBonusOnReels()
{for(var r=0;r<5;r++){for(var s=-1;s<2;s++){var v=getSlotValue(r,s);if((s==-1&&countBetLines<2)||(s==1&&countBetLines<3))
{continue;}
if(v==14&&!holded[r]){drawProgressBar(1,1);}
if(v==15&&!holded[r]){drawProgressBar(0,1);}}}}
function setReelsRandomly()
{for(var i=0;i<5;i++)
{reels[i]=getRandomInt(1,15);}
console.log('setReelsRandomly) reels = ',reels);}
function showCurrentReels()
{var fh=68;var positions=[getStageHeightCenter()-152,getStageHeightCenter()-83,getStageHeightCenter()-14,getStageHeightCenter()+55];var topLimit=getStageHeightCenter()-117;var bottomLimit=getStageHeightCenter()+90;for(var i=0;i<5;i++)
{var v1=reels[i]-1;if(v1<1)v1=15;var v0=v1-1;if(v0<1)v0=15;var v2=reels[i];var v3=reels[i]+1;if(v3>15)v3=1;reelsSprites[i][0].bitmap=library.getBitmap(reelsValues[i][v0-1]);reelsSprites[i][1].bitmap=library.getBitmap(reelsValues[i][v1-1]);reelsSprites[i][2].bitmap=library.getBitmap(reelsValues[i][v2-1]);reelsSprites[i][3].bitmap=library.getBitmap(reelsValues[i][v3-1]);reelsSprites[i][0].y=positions[0]+reelsSpinPositions[i];reelsSprites[i][1].y=positions[1]+reelsSpinPositions[i];reelsSprites[i][2].y=positions[2]+reelsSpinPositions[i];reelsSprites[i][3].y=positions[3]+reelsSpinPositions[i];for(var n=0;n<4;n++)
{reelsSprites[i][n].offset.top=0;reelsSprites[i][n].height=fh;reelsSprites[i][n].visible=true;if(reelsSprites[i][n].y-fh/2<topLimit)
{reelsSprites[i][n].offset.top=topLimit-(reelsSprites[i][n].y-fh/2);reelsSprites[i][n].height=fh-reelsSprites[i][n].offset.top;reelsSprites[i][n].y=topLimit+reelsSprites[i][n].height/2;}
if(reelsSprites[i][n].y+fh/2>bottomLimit)
{reelsSprites[i][n].height=bottomLimit-(reelsSprites[i][n].y-fh/2);reelsSprites[i][n].y=bottomLimit-reelsSprites[i][n].height/2;}
if(reelsSprites[i][n].height<=0)reelsSprites[i][n].visible=false;}}
setHoldButtonsMaxZIndex();}
function checkReelsStop()
{if(gameState==STATE_GAME_SPIN1||gameState==STATE_GAME_SPIN2)
{var ok=true;for(var i=0;i<5;i++)
{if(spinSteps[i]>0||reelsSpinPositions[i]!=0)ok=false;}
if(ok)
{endSpinReels();}}}
function endSpinReels()
{checkBonusOnReels();if(gameState==STATE_GAME_SPIN1)
{if(getWins().length>0)gameState=STATE_GAME_SPIN2;else gameState=STATE_GAME_HOLD;}
if(gameState==STATE_GAME_SPIN2)
{gameState=STATE_GAME_HOLD;showResult();}
if(countFreeSpin>=0&&freespin_flag)
{if(countFreeSpin<=0){spinButton.bitmap=library.getBitmap('btn-spin');countFreeSpin=0;freespin_flag=false;buildBackground();}}
if(autoplay_flag)
{var ta=setInterval(function()
{clearInterval(ta);ta=null;spinReels();},1500);}
countSpin++;spin_flag=false;nohold_flag=false;console.log('<<< hold_flag = '+hold_flag);if(hold_flag)
{nohold_flag=true;}
var t=setInterval(function()
{if(!animation_flag){clearInterval(t);if(wheel_flag){showWheel();}
if(treasure_flag){showTreasure();}
if(balance<=0){showGameOver();}}},200);GameBase.setPlayerScore();resetHolded(true);}
function checkReelPosible(reel,position,id)
{if(!holded[reel])return true;return getSlotValue(reel,position)===id;}
function doSpinReels()
{console.log('====doSpinReels');var pos=[];for(var i=0;i<5;i++)
{if(!holded[i])
{pos.push({value:getRandomInt(1,13),shift:0});}
else
{pos.push({value:-1,shift:0});}}
if(gameState==STATE_GAME_SPIN1||gameState==STATE_GAME_SPIN2||gameState==STATE_GAME_HOLD)
{var rnd=Math.random();console.log('rnd = '+rnd+' | CWR = '+CWR);if(rnd<=CWR)
{var ok=false;console.log('holded = ',holded);var combos=[];var mask;for(var id=1;id<14;id++)
{for(var li=0;li<lineMask.length;li++)
{var ok=true;mask=lineMask[li];for(i=0;i<mask.length;i++)
{ok&=checkReelPosible(mask[i][0],mask[i][1],id);}
if(ok)combos.push({id:id,mask:li});}}
if(combos.length)
{var combo=combos[getRandomInt(0,combos.length-1)];console.log('combo = ',combo);for(var it=0;it<lineMask[combo.mask].length;it++)
{for(var n=0;n<15;n++)
{if(reelsValues[lineMask[combo.mask][it][0]][n]==combo.id)
{pos[lineMask[combo.mask][it][0]].value=n+1;pos[lineMask[combo.mask][it][0]].shift=lineMask[combo.mask][it][1];}}}}}}
for(var i=0;i<5;i++)
{if(!holded[i])
{spinSteps[i]=(reels[i]-pos[i].value+pos[i].shift)+15+i*15;}}}
function showHolded()
{console.log('-----showHolded');for(var i=0;i<5;i++)
{holdFrames[i].visible=holded[i];holdButtons[i].gotoAndStop(holded[i]?1:0);}}
function resetHolded(reset)
{if(reset)
{hold_flag=false;}
holded=[false,false,false,false,false];showHolded();}
function hold(e)
{console.log('-----hold');if((gameState!=STATE_GAME_HOLD&&win_flag)||nohold_flag||spin_flag)
{return;}
var id=e.target.slotID;hold_flag=!hold_flag;holded[id]=!holded[id];showHolded();hold_flag=false;for(var i=0;i<5;i++)
{if(holded[i])
{hold_flag=true;}}
return false;}
function spinReels()
{console.log('====spinReels');if(!freespin_flag){balance-=countBets*countBetLines;if(balance<0){balance+=countBets*countBetLines;return;}}
else
{if(countFreeSpin>=0&&autoplay_flag){countFreeSpin--;}}
if(autoplay_flag)
{spin_flag=true;}
unMarkCombos();win_flag=false;if(gameState==STATE_GAME_PRE_BET)gameState=STATE_GAME_BET;if(gameState==STATE_GAME_BET)
{credits-=coinsPlayed;if(credits<0)credits=0;gameState=STATE_GAME_SPIN1;doSpinReels();}
if(gameState==STATE_GAME_HOLD)
{gameState=STATE_GAME_SPIN2;doSpinReels();}}
function showResult()
{var wins=getWins();var winned=0;var fs_winned=0;winMarks=[];if(wins.length>0)
{var sum=0;var wins_len=wins.length;win_flag=true;if(wins_len>countBetLines){wins_len=countBetLines;}
for(var i=0;i<wins_len;i++)
{var w=wins[i];if(w.value<14){if(w.type==1)
{if(w.value!=11)
{winned+=winCoef[w.value][2];}
else
{fs_winned+=winCoef[w.value][2];}
sound="win";mc=createWinMark();mc.x=reelsSprites[2][2].x;mc.y=reelsSprites[2][w.y+2].y;winMarks.push(mc);showExplosion(reelsSprites[0][2].x,mc.y);showExplosion(reelsSprites[1][2].x,mc.y);showExplosion(reelsSprites[2][2].x,mc.y);showExplosion(reelsSprites[3][2].x,mc.y);showExplosion(reelsSprites[4][2].x,mc.y);console.log('1|  winCoef['+w.value+'][2] = '+winCoef[w.value][2]);}
if(w.type==2)
{if(w.value!=11)
{winned+=winCoef[w.value][1];}
else
{fs_winned+=winCoef[w.value][1];}
sound="win";mc=createWinMark();mc.x=reelsSprites[2][2].x-(reelsSprites[2][2].x-reelsSprites[1][2].x)/2;mc.y=reelsSprites[2][w.y+2].y;mc.scaleX=0.8;winMarks.push(mc);showExplosion(reelsSprites[0][2].x,mc.y);showExplosion(reelsSprites[1][2].x,mc.y);showExplosion(reelsSprites[2][2].x,mc.y);showExplosion(reelsSprites[3][2].x,mc.y);console.log('2| winCoef['+w.value+'][1] = '+winCoef[w.value][1]);}
if(w.type==3)
{if(w.value!=11)
{winned+=winCoef[w.value][1];}
else
{fs_winned+=winCoef[w.value][1];}
sound="win";mc=createWinMark();mc.x=reelsSprites[2][2].x+(reelsSprites[2][2].x-reelsSprites[1][2].x)/2;mc.y=reelsSprites[2][w.y+2].y;mc.scaleX=0.8;winMarks.push(mc);showExplosion(reelsSprites[1][2].x,mc.y);showExplosion(reelsSprites[2][2].x,mc.y);showExplosion(reelsSprites[3][2].x,mc.y);showExplosion(reelsSprites[4][2].x,mc.y);console.log('3| winCoef['+w.value+'][1] = '+winCoef[w.value][1]);}
if(w.type==4)
{if(w.value!=11)
{winned+=winCoef[w.value][0];}
else
{fs_winned+=winCoef[w.value][0];}
mc=createWinMark();mc.x=reelsSprites[w.x+1][2].x;mc.y=reelsSprites[2][w.y+2].y;mc.scaleX=0.6;winMarks.push(mc);showExplosion(reelsSprites[w.x][2].x,mc.y);showExplosion(reelsSprites[w.x+1][2].x,mc.y);showExplosion(reelsSprites[w.x+2][2].x,mc.y);console.log('4| winCoef['+w.value+'][0] = '+winCoef[w.value][0]);}
if(w.type==5)
{if(w.value!=11)
{winned+=winCoef[w.value][w.count];}
else
{fs_winned+=winCoef[w.value][w.count];}
var name_line=(w.mask>0?(w.mask<4?'4-'+w.mask:null):'4');mc=createWinMark(name_line);if(w.mask<4)
{mc.scaleX=1;mc.scaleY=1;mc.rotation=0;mc.x=reelsSprites[2][2].x;mc.y=reelsSprites[2][2].y;}
else
{mc.scaleX=0.76;mc.x=reelsSprites[w.x-1][2].x;mc.y=reelsSprites[2][2].y;mc.rotation=(w.mask==4?Math.PI/4-0.11:-Math.PI/4+0.11);}
winMarks.push(mc);console.log('5| winCoef['+w.value+']['+(!w.count?0:w.count)+'] = '+winCoef[w.value][(!w.count?0:w.count)]);}
if(w.type==6)
{if(w.value!=11)
{winned+=winCoef[w.value][w.count];}
else
{fs_winned+=winCoef[w.value][w.count];}
var name_line=(w.mask>0?(w.mask<4?'5-'+w.mask:null):'5');mc=createWinMark(name_line);mc.scaleX=1;mc.scaleY=1;mc.rotation=0;if(w.mask<4)
{mc.x=reelsSprites[2][2].x;mc.y=reelsSprites[2][2].y;}
else
{mc.scaleX=0.76;mc.x=reelsSprites[w.x-1][2].x;mc.y=reelsSprites[2][2].y;mc.rotation=(w.mask==4?-Math.PI/4+0.11:Math.PI/4-0.11);}
winMarks.push(mc);console.log('6| winCoef['+w.value+']['+(!w.count?0:w.count)+'] = '+winCoef[w.value][(!w.count?0:w.count)]);}}
console.log('w.type = '+w.type);console.log('w.mark = '+w.mark);}
if(fs_winned>0)
{countFreeSpin+=fs_winned;freespin_flag=true;spinButton.bitmap=library.getBitmap('btn-free-spin');showFreeSpinBonus(fs_winned);}
if(winned>0)
{console.log(sum+' += '+(winned*countBets));sum+=winned*countBets;console.log('sum = '+sum);balance+=sum;var tb=setInterval(function()
{if(!animation_flag)
{clearInterval(tb);moveBonus(sum,unMarkCombos);}},15);}
doClearField();}
else doClearField();}
function getWins()
{var wins=[];var ok,e;for(var y=-1;y<2;y++)
{if((y==-1&&countBetLines<2)||(y==1&&countBetLines<3))
{continue;}
ok=true;e=getSlotValue(0,y);for(var i=1;i<5;i++)
{if(getSlotValue(i,y)!=e)
ok=false;}
if(ok)
{wins.push({"type":1,"value":e,"y":y});}
else
{var ok2=false;ok=true;e=getSlotValue(0,y);for(var i=1;i<4;i++)
{if(getSlotValue(i,y)!=e)
ok=false;}
if(ok)
{wins.push({"type":2,"value":e,"y":y});ok2=true;}
ok=true;e=getSlotValue(1,y);for(var i=2;i<5;i++)
{if(getSlotValue(i,y)!=e)
ok=false;}
if(ok)
{wins.push({"type":3,"value":e,"y":y});ok2=true;}
if(!ok2)
{for(var x=0;x<3;x++)
{ok=true;e=getSlotValue(x,y);for(var i=1;i<3;i++)
{if(getSlotValue(x+i,y)!=e)
ok=false;}
if(ok)
wins.push({"type":4,"value":e,"x":x,"y":y});}}}}
if(countBetLines>3)
{var x=0;var type=0;for(var l=0;l<winDiagonalMaskBet4.length;l++)
{var mask=winDiagonalMaskBet4[l];ok=true;e=getSlotValue(mask[0][0],mask[0][1]);for(var p=0;p<mask.length;p++)
{x=mask[p][0];if(getSlotValue(mask[p][0],mask[p][1])!=e)
{ok=false;}}
if(ok)
{wins.push({"type":5,"value":e,"x":x,"mask":l,"count":(mask.length-3)});break;}}}
if(countBetLines>4)
{var x=0;var type=0;for(var l=0;l<winDiagonalMaskBet5.length;l++)
{var mask=winDiagonalMaskBet5[l];ok=true;e=getSlotValue(mask[0][0],mask[0][1]);for(var p=0;p<mask.length;p++)
{x=mask[p][0];if(getSlotValue(mask[p][0],mask[p][1])!=e)
{ok=false;}}
if(ok)
{wins.push({"type":6,"value":e,"x":x,"mask":l,"count":(mask.length-3)});break;}}}
console.log('(--) wins = ',wins);return wins;}
function getSlotValue(reel,position)
{var p=reels[reel]+position;if(p>15)p=1;if(p<1)p=15;return reelsValues[reel][p-1];}
function createWinMark(name)
{var line=library.getSprite(!name?'line3':'line'+name);console.log('---------------------------------------------- line name = '+(!name?'line3':'line'+name));line.animDelay=4;line.blinkCnt=0;line.onrender=function(e)
{if(e.target.currentFrame==0&&e.target.blinkCnt<14)e.target.blinkCnt++;if(e.target.blinkCnt>=14)e.target.gotoAndStop(0);};stage.addChild(line);return line;}
function doClearField()
{restartMatch();startNewMatch();}
function unMarkCombos()
{for(var i=0;i<winMarks.length;i++)stage.removeChild(winMarks[i]);}
function setHoldButtonsMaxZIndex()
{for(var i=0;i<holdButtons.length;i++){if(holdButtons[i]){holdButtons[i].setZIndex(stage.objects[stage.getMaxZIndexInStack(stage.objects)].zIndex+1);}}}
function countPlayerLines(e)
{console.log('======countPlayerLines');if(freespin_flag||spin_flag){return;}
function _Blink(e)
{var t=setTimeout(function()
{clearTimeout(t);for(var i=0;i<line.length;i++){e.target.destroy=true;e.target.visible=false;}},2000);}
var line=[];if(e.target.LINE_UP){countBetLines++;if(countBetLines>MAX_BET_LINES){countBetLines=MAX_BET_LINES;}}
if(e.target.LINE_DOWN){countBetLines--;if(countBetLines<MIN_BET){countBetLines=MIN_BET;}}
console.log('countBetLines = '+countBetLines);if(countBetLines==1){line[0]=library.getSprite('line3');line[0].static=false;line[0].onrender=_Blink;line[0].x=getStageWidthCenter()+startPositionPlayerLines[0].x;line[0].y=getStageHeightCenter()+startPositionPlayerLines[0].y;stage.addChild(line[0]);}
if(countBetLines==2){for(var i=0;i<2;i++){line[i]=library.getSprite('line3');line[i].static=false;line[i].onrender=_Blink;line[i].x=getStageWidthCenter()+startPositionPlayerLines[i].x;line[i].y=getStageHeightCenter()+startPositionPlayerLines[i].y;stage.addChild(line[i]);}}
if(countBetLines==3){for(var i=0;i<3;i++){line[i]=library.getSprite('line3');line[i].animDelay=4;line[i].blinkCnt=0;line[i].onrender=_Blink;line[i].x=getStageWidthCenter()+startPositionPlayerLines[i].x;line[i].y=getStageHeightCenter()+startPositionPlayerLines[i].y;stage.addChild(line[i]);}}
if(countBetLines==4){for(var i=0;i<4;i++){line[i]=library.getSprite('line'+(i<3?3:(i+1)));line[i].animDelay=4;line[i].blinkCnt=0;line[i].onrender=_Blink;line[i].x=getStageWidthCenter()+startPositionPlayerLines[i].x;line[i].y=getStageHeightCenter()+startPositionPlayerLines[i].y;stage.addChild(line[i]);}}
if(countBetLines==5){for(var i=0;i<5;i++){line[i]=library.getSprite('line'+(i<3?3:(i+1)));line[i].animDelay=4;line[i].blinkCnt=0;line[i].onrender=_Blink;line[i].x=getStageWidthCenter()+startPositionPlayerLines[i].x;line[i].y=getStageHeightCenter()+startPositionPlayerLines[i].y;stage.addChild(line[i]);}}}
function countPlayerBets(e)
{console.log('======countPlayerBets');if(freespin_flag||spin_flag){return;}
if(e.target.BET_UP){countBets++;if(countBets>MAX_BET){countBets=MAX_BET;}}
if(e.target.BET_DOWN){countBets--;if(countBets<MIN_BET){countBets=MIN_BET;}}}
function restartMatch()
{if(winnerPlayed>0)
{credits+=winnerPlayed;winnerPlayed=0;}
if(coinsPlayed>credits)
{coinsPlayed=credits;}}
function prepareGame()
{if((parseInt(Utils.getCookie("sound"))==2)||(parseInt(Utils.getCookie("sound"))==1)){}
else{Utils.setCookie("sound",1);}
if(parseInt(Utils.getCookie("sound"))==1){sound=true;}
else if(parseInt(Utils.getCookie("sound"))==2){sound=false;}
GameBase.getPlayerScore();gameState=STATE_SPLASH;createScene();}
function buildBackground()
{stage.drawScene(document.getElementById("screen_background"),true);}
function preTick()
{if(processState==PROCESS_GAME&&(gameState==STATE_GAME_SPIN1||gameState==STATE_GAME_SPIN2)&&!wheel_flag&&!facebook_flag&&!description_flag&&!treasure_flag)
{var ok=false;var step=32;for(var i=0;i<5;i++)
{if(spinSteps[i]>0)
{ok=true;reelsSpinPositions[i]+=step;if(reelsSpinPositions[i]>=56)
{reels[i]--;if(reels[i]<1)reels[i]=15;reelsSpinPositions[i]=0;spinSteps[i]--;}}
else
{if(reelsSpinPositions[i]<0)
{ok=true;reelsSpinPositions[i]+=step;if(reelsSpinPositions[i]>0)reelsSpinPositions[i]=0;}}}
if(ok)showCurrentReels();else checkReelsStop();}}
function postTick()
{if(processState==PROCESS_GAME&&!description_flag&&!wheel_flag&&!facebook_flag&&!treasure_flag){balanceText.write(balance.insertComma());linesText.write(countBetLines);betText.write(countBets);wheelPercentText.write(wheelPercent+'%');treasurePercentText.write(treasurePercent+'%');countFreeSpinText.write(countFreeSpin>0?countFreeSpin+'x':' ');}}
function moveTextHitScore(text,x_start,y_start,y_end)
{t=new SimpleText(library.getBitmap('point_number'),14,14);t.x=x_start;t.y=y_start;t.charMap=charMapNumber;t.align=t.ALIGN_CENTER;t.write(text);var tween=stage.createTween(t,"y",y_start,y_end,fps/2,Easing.linear.easeIn);tween.onchange=function(e)
{e.target.obj.write(text);};tween.onfinish=function(e)
{e.target.obj.write('');delete e.target.obj;};tween.play();}
function moveBonus(text,callback)
{animation_flag=true;var x_start=getStageWidthCenter();var y_start=getStageHeightCenter();var x_end=getStageWidthCenter()+170;var y_end=getStageHeightCenter()-133;var scale_start=1;var scale_end=0.5;t=new SimpleText(library.getBitmap('number-big-num'),42,50);t.x=getStageWidthCenter();t.y=getStageHeightCenter();t.charMap=charMapOnlyNumber;t.align=t.ALIGN_CENTER;t.write(text);var step_x=0;var step_y=0;var count_step=0;var step_scale=0;var tween=stage.createTween(t,"x",getStageWidthCenter(),getStageWidthCenter()+170,fps/2,Easing.linear.easeIn);var t=setTimeout(function()
{clearTimeout(t);tween.play();tween.onchange=function(e)
{if(!step_x){step_x=e.target.obj.x-x_start;}
if(!count_step){count_step=(x_end-x_start)/step_x;}
if(!step_y){step_y=(y_end-y_start)/count_step;}
if(!step_scale){step_scale=(scale_start-scale_end)/count_step;}
e.target.obj.y+=Math.ceil(step_y);e.target.obj.scale-=step_scale;e.target.obj.write(text);};tween.onfinish=function(e)
{e.target.obj.write('');delete e.target.obj;animation_flag=false;if(typeof callback==='function'){callback();}};},1000);}
function showExplosion(x,y)
{explosion_flag=true;var ex=library.getSprite('animation');ex.x=x;ex.y=y;ex.animation=true;ex.animDelay=4;ex.static=false;ex.onrender=function(e)
{if(e.target.currentFrame==e.target.totalFrames-1){e.target.destroy=true;explosion_flag=false;}};stage.addChild(ex);buildBackground();}
function showFreeSpinBonus(bonus,callback)
{animation_flag=true;var bt=library.getSprite('txt-'+bonus+'fs');bt.x=getStageWidthCenter();bt.y=getStageHeightCenter();bt.static=false;stage.addChild(bt);var t=setTimeout(function()
{clearTimeout(t);buildBackground();bt.destroy=true;animation_flag=false;if(typeof callback==='function'){callback();}},1500);};var GameArea={};var Reels={};var GameBase={getPlayerScore:function()
{balance=Utils.getCookie("fs_balance")==null?0:parseInt(Utils.getCookie("fs_balance"));allCountBonus[0]=Utils.getCookie("fs_treasure_percent")==null?0:parseInt(Utils.getCookie("fs_treasure_percent"));allCountBonus[1]=Utils.getCookie("fs_wheel_percent")==null?0:parseInt(Utils.getCookie("fs_wheel_percent"));countBets=Utils.getCookie("fs_count_bets")==null?0:parseInt(Utils.getCookie("fs_count_bets"));countBetLines=Utils.getCookie("fs_count_bet_lines")==null?0:parseInt(Utils.getCookie("fs_count_bet_lines"));},setPlayerScore:function()
{Utils.setCookie("fs_treasure_percent",allCountBonus[0]);Utils.setCookie("fs_wheel_percent",allCountBonus[1]);Utils.setCookie("fs_count_bets",countBets);Utils.setCookie("fs_count_bet_lines",countBetLines);Utils.setCookie("fs_balance",balance);},resetGameParameters:function()
{pause_flag=false;description_flag=false;popup_flag=false;menu_flag=false;autoplay_flag=false;freespin_flag=false;facebook_flag=false;wait_iteration=0;move_counter=0;greenBar=[];bonusIcon=[];allCountBonus=[0,0];greenBarWidth=0;wheelPercent=0;treasurePercent=0;countFreeSpin=0;countBetLines=MIN_BET;countBets=MIN_BET;processState=PROCESS_START;}};;function shuffle(arr)
{var len=arr.length;var i=len;while(i--){var p=parseInt(Math.random()*len);var t=arr[i];arr[i]=arr[p];arr[p]=t;}
return arr;}
function getRandomInt(min,max)
{return Math.floor(Math.random()*(max-min+1))+min;}
function toFormattedTime(input)
{var minutesString='00';var secondsString='00';var minutes=0;var seconds=0;input=input%(60*60);minutes=Math.floor(input/60);input=input%60;seconds=input;minutesString=(minutes>=10)?minutes.toString():'0'+minutes.toString();secondsString=(seconds>=10)?seconds.toString():'0'+seconds.toString();return minutesString+':'+secondsString;}
Number.prototype.insertComma=function(){var s=parseInt(this).toString().split('').reverse().join('');var r='';for(var i=0;i<s.length;i++){r+=((i>0&&i%3==0)?',':'')+s.charAt(i);}
return r.split('').reverse().join('');};Array.prototype.deleteElement=function(value){for(var i=0;i<this.length;i++){if(this[i]==value){this.splice(i,1);}}};;var BONUS_WHEEL=0;var BONUS_TREASURE=1;var needCountBonus=[40,40];var needSpinForFB=30;var START_COINS=100;var CWR=0.35;var MIN_BET=1;var MAX_BET=10;var MAX_BET_LINES=5;var countElementOnFortuneWheel=16;var needCountRotateWheel=3;var needCountFreeSpin=3;var needCountBonusFreeSpin=10;var needCountFreeTreasure=3;var wheelWinCoef=[20,20,25,200,5,15,20,175,75,10,20,150,30,100,50,300];var treasureWinCoef=[[100,150,50,250,65],[100,5,15,75,35],[125,10,50,0]];var winCoef=[[0,0,0],[300,400,500],[200,300,400],[175,250,300],[150,200,250],[100,150,200],[75,100,150],[50,75,100],[30,40,50],[25,30,35],[20,25,30],[5,10,20],[15,20,25],[5,10,15],[10,15,20]];;var app_id="1417586768472591";var app_link='http://true-token.com/casuals/public/pirate_slots/';var app_picture='http://true-token.com/casuals/public/pirate_slots/cover.png';var fb_message={method:'feed',name:'',caption:'',description:'',picture:app_picture,link:app_link};;var FaceBook={init:function()
{fb_message.description='Credits = '+balance;},getUserInfo:function(callback)
{FB.getLoginStatus(function(response)
{if(response.status==='connected'){flag_fb=1;if(typeof callback==='function'){callback();}}
else{FB.login(function(response)
{if(response.authResponse){flag_fb=1;if(typeof callback==='function'){callback();}}
else{flag_fb=0;return false;}},{scope:'publish_actions'});}});},postOnWall:function()
{FB.ui(fb_message,function(response)
{if(response==null||response.post_id==undefined){alert('Not posted on Facebook wall.');}
else{alert('Facebook wall posted.');}});},doLike:function()
{FB.api('/me/likes/'+app_id,function(resp){console.log('resp = ',resp);});}};;