!function(){Cocoon=window.Cocoon?window.Cocoon:{},Cocoon.version="3.0.5",Cocoon.nativeAvailable=!!window.ext,Cocoon.extend=function(subc,superc){var subcp=subc.prototype,CocoonJSExtendHierarchyChainClass=function(){};CocoonJSExtendHierarchyChainClass.prototype=superc.prototype,subc.prototype=new CocoonJSExtendHierarchyChainClass,subc.superclass=superc.prototype,subc.prototype.constructor=subc,superc.prototype.constructor===Object.prototype.constructor&&(superc.prototype.constructor=superc);for(var method in subcp)subcp.hasOwnProperty(method)&&(subc.prototype[method]=subcp[method])},Cocoon.clone=function(obj,copy){if(null==obj||"object"!=typeof obj)return obj;var arr=[];for(var attr in obj)arr.push(copy.hasOwnProperty(attr)?copy[attr]:obj[attr]);return arr},Cocoon.callNative=function(nativeExtensionObjectName,nativeFunctionName,args,async){if(Cocoon.nativeAvailable){var argumentsArray=Array.prototype.slice.call(args);argumentsArray.unshift(nativeFunctionName);var nativeExtensionObject=ext[nativeExtensionObjectName],makeCallFunction=async?nativeExtensionObject.makeCallAsync:nativeExtensionObject.makeCall,ret=makeCallFunction.apply(nativeExtensionObject,argumentsArray),finalRet=ret;if("string"==typeof ret)try{finalRet=JSON.parse(ret)}catch(error){console.log(error)}return finalRet}},Cocoon.getObjectFromPath=function(baseObject,objectPath){for(var parts=objectPath.split("."),obj=baseObject,i=0,len=parts.length;len>i;++i)obj[parts[i]]=obj[parts[i]]||void 0,obj=obj[parts[i]];return obj},Cocoon.EventHandler=function(nativeExtensionObjectName,CocoonExtensionObjectName,nativeEventName,chainFunction){return this.listeners=[],this.listenersOnce=[],this.chainFunction=chainFunction,this.addEventListener=function(listener){if(chainFunction){var f=function(){chainFunction.call(this,arguments.callee.sourceListener,Array.prototype.slice.call(arguments))};listener.CocoonEventHandlerChainFunction=f,f.sourceListener=listener,listener=f}var CocoonExtensionObject=Cocoon.getObjectFromPath(Cocoon,CocoonExtensionObjectName);if(CocoonExtensionObject&&CocoonExtensionObject.nativeAvailable)ext[nativeExtensionObjectName].addEventListener(nativeEventName,listener);else{var indexOfListener=this.listeners.indexOf(listener);0>indexOfListener&&this.listeners.push(listener)}},this.addEventListenerOnce=function(listener){if(chainFunction){var f=function(){chainFunction(arguments.callee.sourceListener,Array.prototype.slice.call(arguments))};f.sourceListener=listener,listener=f}var CocoonExtensionObject=Cocoon.getObjectFromPath(Cocoon,CocoonExtensionObjectName);if(CocoonExtensionObject.nativeAvailable)ext[nativeExtensionObjectName].addEventListenerOnce(nativeEventName,listener);else{var indexOfListener=this.listeners.indexOf(listener);0>indexOfListener&&this.listenersOnce.push(listener)}},this.removeEventListener=function(listener){chainFunction&&(listener=listener.CocoonEventHandlerChainFunction,delete listener.CocoonEventHandlerChainFunction);var CocoonExtensionObject=Cocoon.getObjectFromPath(Cocoon,CocoonExtensionObjectName);if(CocoonExtensionObject.nativeAvailable)ext[nativeExtensionObjectName].removeEventListener(nativeEventName,listener);else{var indexOfListener=this.listeners.indexOf(listener);indexOfListener>=0&&this.listeners.splice(indexOfListener,1)}},this.removeEventListenerOnce=function(listener){chainFunction&&(listener=listener.CocoonEventHandlerChainFunction,delete listener.CocoonEventHandlerChainFunction);var CocoonExtensionObject=Cocoon.getObjectFromPath(Cocoon,CocoonExtensionObjectName);if(CocoonExtensionObject.nativeAvailable)ext[nativeExtensionObjectName].removeEventListenerOnce(nativeEventName,listener);else{var indexOfListener=this.listenersOnce.indexOf(listener);indexOfListener>=0&&this.listenersOnce.splice(indexOfListener,1)}},this.notifyEventListeners=function(){var CocoonExtensionObject=Cocoon.getObjectFromPath(Cocoon,CocoonExtensionObjectName);if(CocoonExtensionObject&&CocoonExtensionObject.nativeAvailable)ext[nativeExtensionObjectName].notifyEventListeners(nativeEventName);else{var argumentsArray=Array.prototype.slice.call(arguments),listeners=Array.prototype.slice.call(this.listeners),listenersOnce=Array.prototype.slice.call(this.listenersOnce),_this=this;setTimeout(function(){for(var i=0;i<listeners.length;i++)listeners[i].apply(_this,argumentsArray);for(var i=0;i<listenersOnce.length;i++)listenersOnce[i].apply(_this,argumentsArray)},0),_this.listenersOnce=[]}},this},Cocoon.define=function(extName,ext){for(var namespace="Cocoon."==extName.substring(0,7)?extName.substr(7):extName,base=window.Cocoon,parts=namespace.split("."),object=base,i=0;i<parts.length;i++){var part=parts[i];if(console.log(object[part]?"Updated namespace: - "+extName:"Created namespace: "+extName),object=object[part]=i==parts.length-1?ext(object[part]||{}):{},!object)throw"Unable to create class "+extName}return!0},console.log("Created namespace: Cocoon")}(),Cocoon.define("Cocoon.Signal",function(extension){"use strict";return extension.createSignal=function(){this.handle=null,this.signals={},this.register=function(namespace,handle){if(!namespace&&!handle)throw new Error("Can't create signal "+(namespace||""));if(handle.addEventListener)return this.signals[namespace]=handle,!0;if(!handle.addEventListener){this.signals[namespace]={};for(var prop in handle)handle.hasOwnProperty(prop)&&(this.signals[namespace][prop]=handle[prop]);return!0}throw new Error("Can't create handler for "+namespace+" signal.")},this.expose=function(){return function(signal,callback,params){var once=!1;if(1===arguments.length){var that=this,fnc=function(signal){this.signal=signal};return fnc.prototype.remove=function(functionListener){var handle=that.signals[this.signal];handle&&handle.removeEventListener&&(handle.removeEventListener.apply(that,[functionListener]),that.signals[this.signal]=void 0)},new fnc(signal)}if(params&&params.once&&(once=!0),!this.signals[signal])throw new Error("The signal "+signal+" does not exists.");var handle=this.signals[signal];if(handle.addEventListener&&(once?handle.addEventListenerOnce(function(){callback.apply(this||window,arguments)}):handle.addEventListener(function(){callback.apply(this||window,arguments)})),!this.signals[signal].addEventListener)for(var prop in this.signals[signal])if(this.signals[signal].hasOwnProperty(prop)){var handle=this.signals[signal][prop];once?handle.addEventListenerOnce(function(){this.clbk[this.name].apply(this||window,arguments)}.bind({name:prop,clbk:callback})):handle.addEventListener(function(){this.clbk[this.name].apply(this||window,arguments)}.bind({name:prop,clbk:callback}))}}.bind(this)}},extension}),Cocoon.define("Cocoon.App",function(extension){extension.nativeAvailable=!!window.ext&&!!window.ext.IDTK_APP,extension.isBridgeAvailable=function(){if("boolean"===Cocoon.App.forward.nativeAvailable)return Cocoon.App.forward.nativeAvailable;var available=Cocoon.callNative("IDTK_APP","forwardAvailable",arguments);return available=!!available,Cocoon.App.forward.nativeAvailable=available,available},extension.forward=function(javaScriptCode){return Cocoon.App.nativeAvailable&&Cocoon.App.isBridgeAvailable()?Cocoon.callNative("IDTK_APP","forward",arguments):navigator.isCocoonJS?void 0:"CocoonJS_App_ForCocoonJS_WebViewIFrame"==window.name?window.parent.eval(javaScriptCode):window.frames.CocoonJS_App_ForCocoonJS_WebViewIFrame.window.eval(javaScriptCode)},extension.forwardAsync=function(javaScriptCode,returnCallback){return Cocoon.App.nativeAvailable&&Cocoon.App.isBridgeAvailable()?"undefined"!=typeof returnCallback?ext.IDTK_APP.makeCallAsync("forward",javaScriptCode,returnCallback):ext.IDTK_APP.makeCallAsync("forward",javaScriptCode):void setTimeout(function(){var res;"CocoonJS_App_ForCocoonJS_WebViewIFrame"==window.name?(res=window.parent.eval(javaScriptCode),"function"==typeof returnCallback&&returnCallback(res)):(res=window.parent.frames.CocoonJS_App_ForCocoonJS_WebViewIFrame.window.eval(javaScriptCode),"function"==typeof returnCallback&&returnCallback(res))},1)},extension.load=function(path){if(Cocoon.App.nativeAvailable)return Cocoon.callNative("IDTK_APP","loadPath",arguments);if(!navigator.isCocoonJS){var xhr=new XMLHttpRequest;xhr.onreadystatechange=function(){if(4===xhr.readyState)if(200===xhr.status){var jsCode;jsCode=Cocoon.App.EmulatedWebViewIFrame?"window.Cocoon && window.Cocoon.App.onLoadInCocoonJSSucceed.notifyEventListeners('"+path+"');":"window.Cocoon && window.Cocoon.App.onLoadInTheWebViewSucceed.notifyEventListeners('"+path+"');",Cocoon.App.forwardAsync(jsCode),window.location.href=path}else if(404===xhr.status){this.onreadystatechange=null;var jsCode;jsCode=Cocoon.App.EmulatedWebViewIFrame?"Cocoon && Cocoon.App.onLoadInCocoonJSFailed.notifyEventListeners('"+path+"');":"Cocoon && Cocoon.App.onLoadInTheWebViewFailed.notifyEventListeners('"+path+"');",Cocoon.App.forwardAsync(jsCode)}},xhr.open("GET",path,!0),xhr.send()}},extension.reload=function(){return Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","reload",arguments):navigator.isCocoonJS?void 0:"CocoonJS_App_ForCocoonJS_WebViewIFrame"==window.name?window.parent.location.reload():window.parent.frames.CocoonJS_App_ForCocoonJS_WebViewIFrame.window.location.reload()},extension.openURL=function(url){return Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","openURL",arguments,!0):void(navigator.isCocoonJS||window.open(url,"_blank"))},extension.exit=function(){return Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","forceToFinish",arguments):void(navigator.isCocoonJS||window.close())},extension.StorageType={APP_STORAGE:"APP_STORAGE",INTERNAL_STORAGE:"INTERNAL_STORAGE",EXTERNAL_STORAGE:"EXTERNAL_STORAGE",TEMPORARY_STORAGE:"TEMPORARY_STORAGE"},extension.onSuspended=new Cocoon.EventHandler("IDTK_APP","App","onsuspended"),extension.onActivated=new Cocoon.EventHandler("IDTK_APP","App","onactivated"),extension.onSuspending=new Cocoon.EventHandler("IDTK_APP","App","onsuspending"),extension.onMemoryWarning=new Cocoon.EventHandler("IDTK_APP","App","onmemorywarning"),extension.onHeadphonesPluggedIn=new Cocoon.EventHandler("IDTK_APP","App","onheadphonespluggedin"),extension.onHeadphonesUnplugged=new Cocoon.EventHandler("IDTK_APP","App","onheadphonesunplugged");var signal=new Cocoon.Signal.createSignal;return signal.register("suspended",extension.onSuspended),signal.register("activated",extension.onActivated),signal.register("suspending",extension.onSuspending),signal.register("memorywarning",extension.onMemoryWarning),signal.register("headphonespluggedin",extension.onHeadphonesPluggedIn),signal.register("headphonesunplugged",extension.onHeadphonesUnplugged),extension.on=signal.expose(),extension}),Cocoon.define("Cocoon.App",function(extension){function checkEmulatedWebViewReady(){var emulatedWB=Cocoon.App.EmulatedWebView;if(!emulatedWB){emulatedWB=document.createElement("div"),emulatedWB.setAttribute("id","CocoonJS_App_ForCocoonJS_WebViewDiv"),emulatedWB.style.width=0,emulatedWB.style.height=0,emulatedWB.style.position="absolute",emulatedWB.style.left=0,emulatedWB.style.top=0,emulatedWB.style.backgroundColor="transparent",emulatedWB.style.border="0px solid #000";var frame=document.createElement("IFRAME");frame.setAttribute("id","CocoonJS_App_ForCocoonJS_WebViewIFrame"),frame.setAttribute("name","CocoonJS_App_ForCocoonJS_WebViewIFrame"),frame.style.width=0,frame.style.height=0,frame.frameBorder=0,frame.allowtransparency=!0,emulatedWB.appendChild(frame),Cocoon.App.EmulatedWebView=emulatedWB,Cocoon.App.EmulatedWebViewIFrame=frame,document.body||(document.body=document.createElement("body")),document.body.appendChild(Cocoon.App.EmulatedWebView)}}extension.pause=function(){return Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","pause",arguments):void 0},extension.resume=function(){return Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","resume",arguments):void 0},extension.loadInTheWebView=function(path){if(navigator.isCocoonJS&&Cocoon.App.nativeAvailable)Cocoon.callNative("IDTK_APP","loadInTheWebView",arguments);else{var xhr=new XMLHttpRequest;xhr.onreadystatechange=function(){if(4===xhr.readyState)if(xhr.status>=200&&xhr.status<=299||0===xhr.status){checkEmulatedWebViewReady();var callback=function(){Cocoon.App.onLoadInTheWebViewSucceed.notifyEventListeners(path),Cocoon.App.EmulatedWebViewIFrame.removeEventListener("load",callback)};Cocoon.App.EmulatedWebViewIFrame.addEventListener("load",callback),Cocoon.App.EmulatedWebViewIFrame.contentWindow.location.href=path}else this.onreadystatechange=null,Cocoon.App.onLoadInTheWebViewFailed.notifyEventListeners(path)},xhr.open("GET",path,!0),xhr.send()}},extension.reloadWebView=function(){Cocoon.App.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_APP","reloadWebView",arguments):(checkEmulatedWebViewReady(),Cocoon.App.EmulatedWebViewIFrame.contentWindow.location.reload())},extension.showTheWebView=function(x,y,width,height){Cocoon.App.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_APP","showTheWebView",arguments):(checkEmulatedWebViewReady(),Cocoon.App.EmulatedWebViewIFrame.style.width=(width?width/window.devicePixelRatio:window.innerWidth)+"px",Cocoon.App.EmulatedWebViewIFrame.style.height=(height?height/window.devicePixelRatio:window.innerHeight)+"px",Cocoon.App.EmulatedWebView.style.left=(x?x:0)+"px",Cocoon.App.EmulatedWebView.style.top=(y?y:0)+"px",Cocoon.App.EmulatedWebView.style.width=(width?width/window.devicePixelRatio:window.innerWidth)+"px",Cocoon.App.EmulatedWebView.style.height=(height?height/window.devicePixelRatio:window.innerHeight)+"px",Cocoon.App.EmulatedWebView.style.display="block")},extension.hideTheWebView=function(){if(Cocoon.App.nativeAvailable&&navigator.isCocoonJS){var javaScriptCodeToForward="ext.IDTK_APP.makeCall('hide');";return Cocoon.App.forwardAsync(javaScriptCodeToForward)}checkEmulatedWebViewReady(),Cocoon.App.EmulatedWebView.style.display="none"},extension.exitCallback=function(appShouldFinishCallback){navigator.isCocoonJS&&Cocoon.App.nativeAvailable&&(window.onidtkappfinish=appShouldFinishCallback)},extension.forwardedEventFromTheWebView=function(eventName,eventDataString){var eventData=JSON.parse(eventDataString);eventData.target=window;var event=new Event(eventName);for(var att in eventData)event[att]=eventData[att];event.target=window,window.dispatchEvent(event);for(var canvases=document.getElementsByTagName("canvas"),i=0;i<canvases.length;i++)event.target=canvases[i],canvases[i].dispatchEvent(event)},extension.onLoadInTheWebViewSucceed=new Cocoon.EventHandler("IDTK_APP","App","forwardpageload"),extension.onLoadInTheWebViewFailed=new Cocoon.EventHandler("IDTK_APP","App","forwardpagefail");var signal=new Cocoon.Signal.createSignal;return signal.register("load",{success:extension.onLoadInTheWebViewSucceed,error:extension.onLoadInTheWebViewFailed}),extension.WebView=Cocoon.WebView||{},extension.WebView.on=signal.expose(),extension}),Cocoon.define("Cocoon.Utils",function(extension){"use strict";return extension.logMemoryInfo=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_APP","logMemoryInfo",arguments):void 0},extension.textureReduction=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_APP","setDefaultTextureReducerThreshold",arguments):void 0},extension.markAsMusic=function(){return Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","addForceMusic",arguments):void 0},extension.captureScreen=function(){return Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","captureScreen",arguments):void 0},extension.captureScreenAsync=function(){Cocoon.nativeAvailable&&Cocoon.callNative("IDTK_APP","captureScreen",arguments,!0)},extension.setAntialias=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_APP","setDefaultAntialias",arguments):void 0},extension.setWebGLEnabled=function(){return Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","setDefaultAntialias",arguments):void 0},extension.setNPOTEnabled=function(enabled){return Cocoon.nativeAvailable&&navigator.isCocoonJS?window.ext.IDTK_APP.makeCall("setNPOTEnabled",enabled):void 0},extension.setMaxMemory=function(memoryInMBs){return Cocoon.nativeAvailable&&navigator.isCocoonJS?window.ext.IDTK_APP.makeCall("setMaxMemory",memoryInMBs):void 0},extension.CaptureType={EVERYTHING:0,COCOONJS_GL_SURFACE:1,JUST_SYSTEM_VIEWS:2},extension.existsPath=function(){return Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","existsPath",arguments):!1},extension.setTextCacheSize=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_APP","setTextCacheSize",arguments):void 0},extension}),Cocoon.define("Cocoon.Dialog",function(extension){"use strict";return extension.keyboardType={TEXT:"text",NUMBER:"num",PHONE:"phone",EMAIL:"email",URL:"url"},extension.prompt=function(params,callbacks){if(!callbacks)throw"Callback missing for Cocoon.Dialog.prompt();";var defaultKeyboard=Cocoon.Dialog.keyboardType.TEXT;switch(params.type){case Cocoon.Dialog.keyboardType.TEXT:defaultKeyboard=Cocoon.Dialog.keyboardType.TEXT;break;case Cocoon.Dialog.keyboardType.NUMBER:defaultKeyboard=Cocoon.Dialog.keyboardType.NUMBER;break;case Cocoon.Dialog.keyboardType.PHONE:defaultKeyboard=Cocoon.Dialog.keyboardType.PHONE;break;case Cocoon.Dialog.keyboardType.EMAIL:defaultKeyboard=Cocoon.Dialog.keyboardType.EMAIL;break;case Cocoon.Dialog.keyboardType.URL:defaultKeyboard=Cocoon.Dialog.keyboardType.URL}var properties={title:"",message:"",text:"",type:defaultKeyboard,cancelText:"Cancel",confirmText:"Ok",secureText:!1},args=Cocoon.clone(properties,params),succedListener=function(){Cocoon.Dialog.onTextDialogCancelled.removeEventListener(errorListener),Cocoon.Dialog.onTextDialogFinished.removeEventListener(succedListener),callbacks.success.apply(window,Array.prototype.slice.call(arguments))},errorListener=function(){Cocoon.Dialog.onTextDialogCancelled.removeEventListener(errorListener),Cocoon.Dialog.onTextDialogFinished.removeEventListener(succedListener),callbacks.cancel.apply(window,Array.prototype.slice.call(arguments))};return Cocoon.Dialog.onTextDialogCancelled.addEventListener(errorListener),Cocoon.Dialog.onTextDialogFinished.addEventListener(succedListener),Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","showTextDialog",args,!0):void setTimeout(function(){var result=prompt(properties.message,properties.text),eventObject=result?Cocoon.Dialog.onTextDialogFinished:Cocoon.Dialog.onTextDialogCancelled;eventObject.notifyEventListeners(result)},0)},extension.confirm=function(params,callback){if(!callback)throw"Callback missing for Cocoon.Dialog.confirm();";var properties={title:"",message:"",cancelText:"Cancel",confirmText:"Ok"},args=Cocoon.clone(properties,params),succedListener=function(){Cocoon.Dialog.onMessageBoxDenied.removeEventListenerOnce(errorListener),callback(!0)},errorListener=function(){Cocoon.Dialog.onMessageBoxConfirmed.removeEventListenerOnce(succedListener),callback(!1)};return Cocoon.Dialog.onMessageBoxDenied.addEventListenerOnce(errorListener),Cocoon.Dialog.onMessageBoxConfirmed.addEventListenerOnce(succedListener),Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","showMessageBox",args,!0):void setTimeout(function(){var result=confirm(properties.message),eventObject=result?Cocoon.Dialog.onMessageBoxConfirmed:Cocoon.Dialog.onMessageBoxDenied;eventObject.notifyEventListeners()},0)},extension.showKeyboard=function(params,callbacks){params=params||{},params.type=params.type||Cocoon.Dialog.keyboardType.TEXT;var insertCallback=callbacks&&callbacks.insertText,deleteCallback=callbacks&&callbacks.deleteBackward,doneCallback=callbacks&&callbacks.done,cancelCallback=callbacks&&callbacks.cancel;Cocoon.nativeAvailable&&Cocoon.callNative("IDTK_APP","showKeyboard",[params,insertCallback,deleteCallback,doneCallback,cancelCallback],!0)},extension.dismissKeyboard=function(){Cocoon.nativeAvailable&&Cocoon.callNative("IDTK_APP","dismissKeyboard",[],!0)},extension.onTextDialogFinished=new Cocoon.EventHandler("IDTK_APP","App","ontextdialogfinish"),extension.onTextDialogCancelled=new Cocoon.EventHandler("IDTK_APP","App","ontextdialogcancel"),extension.onMessageBoxConfirmed=new Cocoon.EventHandler("IDTK_APP","App","onmessageboxconfirmed"),extension.onMessageBoxDenied=new Cocoon.EventHandler("IDTK_APP","App","onmessageboxdenied"),extension}),Cocoon.define("Cocoon.WebView",function(extension){return"undefined"==typeof Cocoon||null===Cocoon?extension:"undefined"==typeof Cocoon.App||null===Cocoon.App?extension:navigator.isCocoonJS?extension:(extension.show=function(x,y,width,height){if(Cocoon.App.nativeAvailable)return Cocoon.callNative("IDTK_APP","show",arguments);var div=window.parent.document.getElementById("CocoonJS_App_ForCocoonJS_WebViewDiv");div.style.left=(x?x:div.style.left)+"px",div.style.top=(y?y:div.style.top)+"px",div.style.width=(width?width/window.devicePixelRatio:window.parent.innerWidth)+"px",div.style.height=(height?height/window.devicePixelRatio:window.parent.innerHeight)+"px",div.style.display="block";var iframe=window.parent.document.getElementById("CocoonJS_App_ForCocoonJS_WebViewIFrame");iframe.style.width=(width?width/window.devicePixelRatio:window.parent.innerWidth)+"px",iframe.style.height=(height?height/window.devicePixelRatio:window.parent.innerHeight)+"px"},extension.hide=function(){return Cocoon.App.nativeAvailable?Cocoon.callNative("IDTK_APP","hide",arguments):void(window.parent.document.getElementById("CocoonJS_App_ForCocoonJS_WebViewDiv").style.display="none")},extension.loadInCocoon=function(path,callbacks,storageType){if(Cocoon.App.nativeAvailable){var javaScriptCodeToForward="ext.IDTK_APP.makeCall('loadPath'";return"undefined"!=typeof path&&(javaScriptCodeToForward+=", '"+path+"'","undefined"!=typeof storageType&&(javaScriptCodeToForward+=", '"+storageType+"'")),javaScriptCodeToForward+=");",Cocoon.App.forwardAsync(javaScriptCodeToForward)}Cocoon.App.forwardAsync("Cocoon.App.load('"+path+"');")},extension.reloadCocoonJS=function(){return Cocoon.App.nativeAvailable?Cocoon.App.forwardAsync("ext.IDTK_APP.makeCall('reload');"):void(navigator.isCocoonJS||window.parent.location.reload())},window.addEventListener("load",function(){function forwardEventToCocoonJS(eventName,event){var att,i,eventData={};for(var att in event)i=EVENT_ATTRIBUTES.indexOf(att),i>=0&&(eventData[att]=event[att]);var jsCode="Cocoon && Cocoon.App && Cocoon.App.forwardedEventFromTheWebView && Cocoon.App.forwardedEventFromTheWebView("+JSON.stringify(eventName)+", '"+JSON.stringify(eventData)+"');";Cocoon.App.forward(jsCode)}if(!Cocoon.App.nativeAvailable&&"CocoonJS_App_ForCocoonJS_WebViewIFrame"==window.name){Cocoon.App.forwardEventsToCocoonJSEnabled=!1;var EVENT_ATTRIBUTES=["timeStamp","button","type","x","y","pageX","pageY","clientX","clientY","offsetX","offsetY"],EVENTS=["dblclick","touchmove","mousemove","touchend","touchcancel","mouseup","touchstart","mousedown","release","dragleft","dragright","swipeleft","swiperight"];for(i=0;i<EVENTS.length;i++)window.addEventListener(EVENTS[i],function(eventName){return function(event){Cocoon.App.forwardEventsToCocoonJSEnabled&&forwardEventToCocoonJS(eventName,event)}}(EVENTS[i]))}}),extension.onLoadInCocoonJSSucceed=new Cocoon.EventHandler("IDTK_APP","App","forwardpageload"),extension.onLoadInCocoonJSFailed=new Cocoon.EventHandler("IDTK_APP","App","forwardpagefail"),extension)}),Cocoon.define("Cocoon.Proxify",function(extension){"use strict";return extension.getKeyForValueInDictionary=function(dictionary,value){var finalKey=null;for(var key in dictionary)if(dictionary[key]===value){finalKey=key;break}return finalKey},extension.setupOriginProxyType=function(typeName,attributeNames,functionNames,eventHandlerNames){if(Cocoon.nativeAvailable){if(!typeName)throw"The given typeName must be valid.";if(!attributeNames&&!functionNames&&!eventHandlerNames)throw"There is no point on setting up a proxy for no attributes, functions nor eventHandlers.";attributeNames=attributeNames?attributeNames:[],functionNames=functionNames?functionNames:[],eventHandlerNames=eventHandlerNames?eventHandlerNames:[];var parentObject=window,jsCode="Cocoon.Proxify.setupDestinationProxyType("+JSON.stringify(typeName)+", "+JSON.stringify(eventHandlerNames)+");";Cocoon.App.forward(jsCode);var originalType=parentObject[typeName];parentObject[typeName]=function(){var _this=this;this._cocoonjs_proxy_object_data={};var jsCode="Cocoon.Proxify.newDestinationProxyObject("+JSON.stringify(typeName)+");";this._cocoonjs_proxy_object_data.id=Cocoon.App.forward(jsCode),this._cocoonjs_proxy_object_data.eventHandlers={},this._cocoonjs_proxy_object_data.typeName=typeName,this._cocoonjs_proxy_object_data.eventListeners={},parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[this._cocoonjs_proxy_object_data.id]=this;for(var i=0;i<attributeNames.length;i++)!function(attributeName){_this.__defineSetter__(attributeName,function(value){var jsCode="Cocoon.Proxify.setDestinationProxyObjectAttribute("+JSON.stringify(typeName)+", "+_this._cocoonjs_proxy_object_data.id+", "+JSON.stringify(attributeName)+", "+JSON.stringify(value)+");";return Cocoon.App.forward(jsCode)}),_this.__defineGetter__(attributeName,function(){var jsCode="Cocoon.Proxify.getDestinationProxyObjectAttribute("+JSON.stringify(typeName)+", "+_this._cocoonjs_proxy_object_data.id+", "+JSON.stringify(attributeName)+");";return Cocoon.App.forward(jsCode)})}(attributeNames[i]);for(var i=0;i<functionNames.length;i++)!function(functionName){_this[functionName]=function(){var argumentsArray=Array.prototype.slice.call(arguments);argumentsArray.unshift(functionName),argumentsArray.unshift(this._cocoonjs_proxy_object_data.id),argumentsArray.unshift(typeName);for(var jsCode="Cocoon.Proxify.callDestinationProxyObjectFunction(",i=0;i<argumentsArray.length;i++)jsCode+=(1!==i?JSON.stringify(argumentsArray[i]):argumentsArray[i])+(i<argumentsArray.length-1?", ":"");jsCode+=");";var ret=Cocoon.App.forwardAsync(jsCode);return ret}}(functionNames[i]);for(var i=0;i<eventHandlerNames.length;i++)!function(eventHandlerName){_this.__defineSetter__(eventHandlerName,function(value){_this._cocoonjs_proxy_object_data.eventHandlers[eventHandlerName]=value}),_this.__defineGetter__(eventHandlerName,function(){return _this._cocoonjs_proxy_object_data.eventHandlers[eventHandlerName]})}(eventHandlerNames[i]);return _this.addEventListener=function(eventTypeName,eventCallback){var addEventCallback=!0,eventListeners=_this._cocoonjs_proxy_object_data.eventListeners[eventTypeName];if(eventListeners)addEventCallback=eventListeners.indexOf(eventCallback)<0;else{eventListeners=[],_this._cocoonjs_proxy_object_data.eventListeners[eventTypeName]=eventListeners;var jsCode="Cocoon.Proxify.addDestinationProxyObjectEventListener("+JSON.stringify(_this._cocoonjs_proxy_object_data.typeName)+", "+_this._cocoonjs_proxy_object_data.id+", "+JSON.stringify(eventTypeName)+");";Cocoon.App.forwardAsync(jsCode)}addEventCallback&&eventListeners.push(eventCallback)},_this.removeEventListener=function(eventTypeName,eventCallback){var eventListeners=_this._cocoonjs_proxy_object_data.eventListeners[eventTypeName];if(eventListeners){var eventCallbackIndex=eventListeners.indexOf(eventCallback);eventCallbackIndex>=0&&eventListeners.splice(eventCallbackIndex,1)}},this},parentObject[typeName]._cocoonjs_proxy_type_data={originalType:originalType,proxyObjects:[]},parentObject[typeName]._cocoonjs_proxy_type_data.deleteProxyObject=function(object){var proxyObjectKey=extension.getKeyForValueInDictionary(this.proxyObjects,object);if(proxyObjectKey){var jsCode="Cocoon.Proxify.deleteDestinationProxyObject("+JSON.stringify(typeName)+", "+object._cocoonjs_proxy_object_data.id+");";Cocoon.App.forwardAsync(jsCode),object._cocoonjs_proxy_object_data=null,delete this.proxyObjects[proxyObjectKey]}},parentObject[typeName]._cocoonjs_proxy_type_data.callProxyObjectEventHandler=function(id,eventHandlerName){var object=this.proxyObjects[id],eventHandler=object._cocoonjs_proxy_object_data.eventHandlers[eventHandlerName];eventHandler&&eventHandler({target:object})},parentObject[typeName]._cocoonjs_proxy_type_data.callProxyObjectEventListeners=function(id,eventTypeName){for(var object=this.proxyObjects[id],eventListeners=object._cocoonjs_proxy_object_data.eventListeners[eventTypeName].slice(),i=0;i<eventListeners.length;i++)eventListeners[i]({target:object})}}},extension.takedownOriginProxyType=function(typeName){if(Cocoon.App.nativeAvailable){var parentObject=window;parentObject[typeName]&&parentObject[typeName]._cocoonjs_proxy_type_data&&(parentObject[typeName]=parentObject[typeName]._cocoonjs_proxy_type_data.originalType)}},extension.deleteOriginProxyObject=function(object){if(Cocoon.App.nativeAvailable){var parentObject=window;object&&object._cocoonjs_proxy_object_data&&parentObject[object._cocoonjs_proxy_object_data.typeName]._cocoonjs_proxy_type_data.deleteProxyObject(object)}},extension.callOriginProxyObjectEventHandler=function(typeName,id,eventHandlerName){if(Cocoon.App.nativeAvailable){var parentObject=window;parentObject[typeName]._cocoonjs_proxy_type_data.callProxyObjectEventHandler(id,eventHandlerName)}},extension.callOriginProxyObjectEventListeners=function(typeName,id,eventTypeName){if(Cocoon.App.nativeAvailable){var parentObject=window;parentObject[typeName]._cocoonjs_proxy_type_data.callProxyObjectEventListeners(id,eventTypeName)}},extension.setupDestinationProxyType=function(typeName,eventHandlerNames){if(Cocoon.App.nativeAvailable){var parentObject=window;parentObject[typeName]._cocoonjs_proxy_type_data={nextId:0,proxyObjects:{},eventHandlerNames:eventHandlerNames}}},extension.takedownDestinationProxyType=function(typeName){if(Cocoon.App.nativeAvailable){var parentObject=window;parent[typeName]&&parentObject[typeName]._cocoonjs_proxy_type_data&&delete parentObject[typeName]._cocoonjs_proxy_type_data}},extension.newDestinationProxyObject=function(typeName){if(Cocoon.App.nativeAvailable){var parentObject=window,proxyObject=new parentObject[typeName];proxyObject._cocoonjs_proxy_object_data={},proxyObject._cocoonjs_proxy_object_data.typeName=typeName;var proxyObjectId=parentObject[typeName]._cocoonjs_proxy_type_data.nextId;parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[proxyObjectId]=proxyObject,proxyObject._cocoonjs_proxy_object_data.id=proxyObjectId,parentObject[typeName]._cocoonjs_proxy_type_data.nextId++;for(var i=0;i<parentObject[typeName]._cocoonjs_proxy_type_data.eventHandlerNames.length;i++)!function(eventHandlerName){proxyObject[eventHandlerName]=function(){var proxyObject=this,jsCode="Cocoon.App.callOriginProxyObjectEventHandler("+JSON.stringify(proxyObject._cocoonjs_proxy_object_data.typeName)+", "+proxyObject._cocoonjs_proxy_object_data.id+", "+JSON.stringify(eventHandlerName)+");";Cocoon.App.forwardAsync(jsCode)}}(parentObject[typeName]._cocoonjs_proxy_type_data.eventHandlerNames[i]);return proxyObject._cocoonjs_proxy_object_data.eventListeners={},proxyObjectId}},extension.callDestinationProxyObjectFunction=function(typeName,id,functionName){if(Cocoon.App.nativeAvailable){var parentObject=window,argumentsArray=Array.prototype.slice.call(arguments);argumentsArray.splice(0,3);var proxyObject=parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[id],result=proxyObject[functionName].apply(proxyObject,argumentsArray);return result}},extension.setDestinationProxyObjectAttribute=function(typeName,id,attributeName,attributeValue){if(Cocoon.App.nativeAvailable){var parentObject=window,proxyObject=parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[id];proxyObject[attributeName]=attributeValue}},extension.getDestinationProxyObjectAttribute=function(typeName,id,attributeName){if(Cocoon.App.nativeAvailable){var parentObject=window,proxyObject=parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[id];return proxyObject[attributeName]}},extension.deleteDestinationProxyObject=function(typeName,id){if(Cocoon.App.nativeAvailable){var parentObject=window;delete parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[id]
}},extension.addDestinationProxyObjectEventListener=function(typeName,id,eventTypeName){if(Cocoon.App.nativeAvailable){var parentObject=window,proxyObject=parentObject[typeName]._cocoonjs_proxy_type_data.proxyObjects[id],callback=function(){var proxyObject=this,jsCode="Cocoon.Proxify.callOriginProxyObjectEventListeners("+JSON.stringify(proxyObject._cocoonjs_proxy_object_data.typeName)+", "+proxyObject._cocoonjs_proxy_object_data.id+", "+JSON.stringify(eventTypeName)+");";Cocoon.App.forwardAsync(jsCode)};proxyObject._cocoonjs_proxy_object_data.eventListeners[eventTypeName]=callback,proxyObject.addEventListener(eventTypeName,callback)}},extension.xhr=function(){var ATTRIBUTE_NAMES=["timeout","withCredentials","upload","status","statusText","responseType","response","responseText","responseXML","readyState"],FUNCTION_NAMES=["open","setRequestHeader","send","abort","getResponseHeader","getAllResponseHeaders","overrideMimeType"],EVENT_HANDLER_NAMES=["onloadstart","onprogress","onabort","onerror","onload","ontimeout","onloadend","onreadystatechange"];Cocoon.Proxify.setupOriginProxyType("XMLHttpRequest",ATTRIBUTE_NAMES,FUNCTION_NAMES,EVENT_HANDLER_NAMES)},extension.audio=function(){var ATTRIBUTE_NAMES=["src","loop","volume","preload"],FUNCTION_NAMES=["play","pause","load","canPlayType"],EVENT_HANDLER_NAMES=["onended","oncanplay","oncanplaythrough","onerror"];Cocoon.Proxify.setupOriginProxyType("Audio",ATTRIBUTE_NAMES,FUNCTION_NAMES,EVENT_HANDLER_NAMES)},extension.console=function(){if(Cocoon.nativeAvailable){"undefined"==typeof Cocoon.originalConsole&&(Cocoon.originalConsole=window.console);for(var functions=["log","error","info","debug","warn"],newConsole={},i=0;i<functions.length;i++)newConsole[functions[i]]=function(){return function(message){try{var jsCode="Proxified log: "+JSON.stringify(message);Cocoon.originalConsole.log(jsCode),ext.IDTK_APP.makeCallAsync("forward",jsCode)}catch(e){console.log("Proxified log: "+e)}}}(functions[i]);newConsole.assert||(newConsole.assert=function(){if(arguments.length>0&&!arguments[0]){var str="Assertion failed: "+(arguments.length>1?arguments[1]:"");newConsole.error(str)}}),window.console=newConsole}},extension.deproxifyConsole=function(){!window.navigator.isCocoonJS&&Cocoon.nativeAvailable&&"undefined"!=typeof Cocoon.originalConsole&&(window.console=Cocoon.originalConsole,Cocoon.originalConsole=void 0)},extension}),Cocoon.define("Cocoon.Device",function(extension){"use strict";return extension.DeviceInfo={os:null,version:null,dpi:null,brand:null,model:null,imei:null,platformId:null,odin:null,openudid:null},extension.getDeviceId=function(){return Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("getDeviceId"):void 0},extension.getDeviceInfo=function(){return Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("getDeviceInfo"):void 0},extension.getOrientation=function(){return Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("getPreferredOrientation"):0},extension.setOrientation=function(preferredOrientation){Cocoon.nativeAvailable&&window.ext.IDTK_APP.makeCall("setPreferredOrientation",preferredOrientation)},extension.Orientations={PORTRAIT:1,PORTRAIT_UPSIDE_DOWN:2,LANDSCAPE_LEFT:4,LANDSCAPE_RIGHT:8,LANDSCAPE:12,BOTH:15},extension.autoLock=function(){return Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","setAutoLockEnabled",arguments):void 0},extension}),Cocoon.define("Cocoon.Motion",function(extension){"use strict";return extension.nativeAvailable=Cocoon.nativeAvailable,extension.setAccelerometerInterval=function(updateIntervalInSeconds){return Cocoon.Motion.nativeAvailable?window.ext.IDTK_APP.makeCall("setAccelerometerUpdateIntervalInSeconds",updateIntervalInSeconds):void 0},extension.getAccelerometerInterval=function(){return Cocoon.Motion.nativeAvailable?window.ext.IDTK_APP.makeCall("getAccelerometerUpdateIntervalInSeconds"):void 0},extension.setGyroscopeInterval=function(updateIntervalInSeconds){return Cocoon.Motion.nativeAvailable?window.ext.IDTK_APP.makeCall("setGyroscopeUpdateIntervalInSeconds",updateIntervalInSeconds):void 0},extension.getGyroscopeInterval=function(){Cocoon.Motion.nativeAvailable&&window.ext.IDTK_APP.makeCall("getGyroscopeUpdateIntervalInSeconds")},extension}),Cocoon.define("Cocoon.Touch",function(extension){return extension.addADivToDisableInput=function(){var div=document.createElement("div");div.id="CocoonJSInputBlockingDiv",div.style.left=0,div.style.top=0,div.style.width="100%",div.style.height="100%",div.style.position="absolute",div.style.backgroundColor="transparent",div.style.border="0px solid #000",div.style.zIndex=999999999,document.body.appendChild(div)},extension.removeTheDivToEnableInput=function(){var div=document.getElementById("CocoonJSInputBlockingDiv");div&&document.body.removeChild(div)},extension.disable=function(){Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("disableTouchLayer","CocoonJSView"):navigator.isCocoonJS||Cocoon.App.EmulatedWebViewIFrame||(Cocoon.App.forwardEventsToCocoonJSEnabled=!1,Cocoon.App.forwardAsync("Cocoon && Cocoon.Touch && Cocoon.Touch.disable();"))},extension.enable=function(){Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("enableTouchLayer","CocoonJSView"):navigator.isCocoonJS||Cocoon.App.EmulatedWebViewIFrame||(Cocoon.App.forwardEventsToCocoonJSEnabled=!0,Cocoon.App.forwardAsync("Cocoon && Cocoon.Touch && Cocoon.Touch.enable();"))},extension.disableInWebView=function(){Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("disableTouchLayer","WebView"):navigator.isCocoonJS||(Cocoon.App.EmulatedWebViewIFrame?Cocoon.App.forwardAsync("Cocoon && Cocoon.Touch && Cocoon.Touch.disableInWebView();"):Cocoon.Touch.addADivToDisableInput())},extension.enableInWebView=function(){Cocoon.nativeAvailable?window.ext.IDTK_APP.makeCall("enableTouchLayer","WebView"):navigator.isCocoonJS||(Cocoon.App.EmulatedWebViewIFrame?Cocoon.Touch.forwardAsync("Cocoon && Cocoon.Touch && Cocoon.Touch.enableInWebView();"):Cocoon.Touch.removeTheDivToEnableInput())},extension}),Cocoon.define("Cocoon.Widget",function(extension){"use strict";return extension.WebDialog=function(){if(Cocoon.App.nativeAvailable)this.webDialogID=window.ext.IDTK_APP.makeCall("createWebDialog");else{var iframe=document.createElement("iframe");iframe.id="CocoonJSWebDialogIFrame",iframe.name="CocoonJSWebDialogIFrame",iframe.style.cssText="position:fixed;left:0;top:0;bottom:0;right:0; width:100%; height:100%;margin:0;padding:0;";var me=this;iframe.onload=function(){me.iframeloaded=!0;var js="Cocoon = {}; Cocoon.Widget = {}; Cocoon.Widget.WebDialog = {}; Cocoon.Widget.WebDialog.close = function(){   window.parent.CocoonJSCloseWebDialog();};";me.evalIframe(js);for(var i=0;i<me.pendingEvals.length;++i)me.evalIframe(me.pendingEvals[i]);me.pendingEvals=[]},iframe.onerror=function(){me.close()},this.iframe=iframe,this.pendingEvals=[],window.CocoonJSCloseWebDialog=function(){me.close()}}},extension.WebDialog.prototype={show:function(url,callback){return this.closeCallback=function(){Cocoon.Touch.enable(),callback&&callback()},Cocoon.App.nativeAvailable?(Cocoon.Touch.disable(),window.ext.IDTK_APP.makeCallAsync("showWebDialog",this.webDialogID,url,this.closeCallback)):(this.iframe.src=url,void document.body.appendChild(this.iframe))},close:function(){return Cocoon.App.nativeAvailable?window.ext.IDTK_APP.makeCallAsync("closeWebDialog",this.webDialogID):(this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),void(this.closeCallback&&this.closeCallback()))},evalIframe:function(js){window.frames.CocoonJSWebDialogIFrame.eval(js)},eval:function(js){return Cocoon.App.nativeAvailable?window.ext.IDTK_APP.makeCallAsync("evalWebDialog",this.webDialogID,js):void(this.iframeloaded?this.evalIframe(js):this.pendingEvals.push(js))}},extension}),Cocoon.define("Cocoon.Camera",function(extension){return navigator.getUserMedia_=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,extension.CameraType={FRONT:"FRONT",BACK:"BACK"},extension.CaptureFormatType={JPEG:"JPEG",RGB_565:"RGB_565",NV21:"NV21",NV16:"NV16",YUY2:"YUY2",YV12:"YV12",BGRA32:"32BGRA"},extension.CameraInfo={cameraIndex:0,cameraType:extension.CameraType.BACK,supportedVideoSizes:[],supportedVideoFrameRates:[],supportedVideoCaptureImageFormats:[]},extension.getNumberOfCameras=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_SRV_CAMERA","getNumberOfCameras",arguments):navigator.getUserMedia_?1:0},extension.getAllCamerasInfo=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_SRV_CAMERA","getAllCamerasInfo",arguments):void 0},extension.getCameraInfoByIndex=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_SRV_CAMERA","getCameraInfoByIndex",arguments):void 0},extension.getCameraInfoByType=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_SRV_CAMERA","getCameraInfoByType",arguments):void 0},extension.start=function(params){if(!Boolean(params.success)||!Boolean(params.error))throw new Error("Missing callbacks for Cocoon.Camera.start();");if(Cocoon.nativeAvailable){var properties={cameraIndex:0,width:50,height:50,frameRate:25},args=Cocoon.clone(properties,params),img=Cocoon.callNative("IDTK_SRV_CAMERA","startCapturing",args);Boolean(img)?params.success(img):params.error(!1)}else navigator.getUserMedia_({video:!0,audio:!1},function(stream){params.success(stream)},function(error){params.error(error)})},extension.stop=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_SRV_CAMERA","stopCapturing",arguments):void 0},extension.isCapturing=function(){return Cocoon.nativeAvailable&&navigator.isCocoonJS?Cocoon.callNative("IDTK_SRV_CAMERA","isCapturing",arguments):void 0},extension}),Cocoon.define("Cocoon.Ad",function(extension){"use strict";extension.nativeAvailable=!!Cocoon.nativeAvailable&&!!window.ext.IDTK_SRV_AD,extension.BannerLayout={TOP_CENTER:"TOP_CENTER",BOTTOM_CENTER:"BOTTOM_CENTER"},extension.Rectangle=function(x,y,width,height){this.x=x,this.y=y,this.width=width,this.height=height},extension.Banner=function(id){if("number"!=typeof id)throw"The given ad ID is not a number.";this.id=id;var me=this;this.onBannerShown=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onbannershow",function(sourceListener,args){me.id===args[0]&&sourceListener()}),this.onBannerHidden=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onbannerhide",function(sourceListener,args){me.id===args[0]&&sourceListener()}),this.onBannerReady=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onbannerready",function(sourceListener,args){me.id===args[0]&&sourceListener(args[1],args[2])});var signal=new Cocoon.Signal.createSignal;signal.register("ready",this.onBannerReady),signal.register("shown",this.onBannerShown),signal.register("hidden",this.onBannerHidden),this.on=signal.expose()},extension.Banner.prototype={showBanner:function(){Cocoon.Ad.nativeAvailable&&Cocoon.callNative("IDTK_SRV_AD","showBanner",[this.id],!0)},hideBanner:function(){Cocoon.Ad.nativeAvailable&&Cocoon.callNative("IDTK_SRV_AD","hideBanner",[this.id],!0)},load:function(){Cocoon.Ad.nativeAvailable&&Cocoon.callNative("IDTK_SRV_AD","refreshBanner",[this.id],!0)},getRectangle:function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","getRectangle",[this.id]):void 0},setRectangle:function(rect){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","setRectangle",[this.id,rect]):void 0},setBannerLayout:function(bannerLayout){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","setBannerLayout",[this.id,bannerLayout]):void 0}},extension.Interstitial=function(id){if("number"!=typeof id)throw"The given ad ID is not a number.";this.id=id;var me=this;this.onFullScreenShown=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onfullscreenshow",function(sourceListener,args){me.id===args[0]&&sourceListener()}),this.onFullScreenHidden=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onfullscreenhide",function(sourceListener,args){me.id===args[0]&&sourceListener()}),this.onFullScreenReady=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onfullscreenready",function(sourceListener,args){me.id===args[0]&&sourceListener()});var signal=new Cocoon.Signal.createSignal;signal.register("ready",this.onFullScreenReady),signal.register("shown",this.onFullScreenShown),signal.register("hidden",this.onFullScreenHidden),this.on=signal.expose()},extension.Interstitial.prototype={showInterstitial:function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","showFullScreen",[this.id],!0):void 0},refreshInterstitial:function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","refreshFullScreen",[this.id],!0):void 0}},extension.configure=function(parameters){return"undefined"==typeof parameters&&(parameters={}),Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","requestInitialization",arguments,!0):void 0},extension.createBanner=function(parameters){if("undefined"==typeof parameters&&(parameters={}),Cocoon.Ad.nativeAvailable){var adId=Cocoon.callNative("IDTK_SRV_AD","createBanner",[parameters]),banner=new extension.Banner(adId);return banner}},extension.releaseBanner=function(banner){if("undefined"==typeof banner)throw"The banner ad object to be released is undefined";Cocoon.Ad.nativeAvailable&&Cocoon.callNative("IDTK_SRV_AD","releaseBanner",[banner.id])},extension.createInterstitial=function(parameters){if("undefined"==typeof parameters&&(parameters={}),Cocoon.Ad.nativeAvailable){var adId=Cocoon.callNative("IDTK_SRV_AD","createFullscreen",[parameters]),fullscreen=new Cocoon.Ad.Interstitial(adId);return fullscreen}},extension.releaseInterstitial=function(fullscreen){if(!fullscreen)throw"The fullscreen ad object to be released is undefined";Cocoon.Ad.nativeAvailable&&Cocoon.callNative("IDTK_SRV_AD","releaseFullscreen",[fullscreen.id])},extension.showBanner=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","showBanner",arguments,!0):void 0},extension.hideBanner=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","hideBanner",arguments,!0):void 0},extension.refreshBanner=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","refreshBanner",arguments,!0):void 0},extension.showInterstitial=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","showFullScreen",arguments,!0):void 0},extension.refreshInterstitial=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","refreshFullScreen",arguments,!0):void 0},extension.preloadedBanner=!1,extension.loadBanner=function(){return Cocoon.Ad.nativeAvailable?Cocoon.Ad.preloadedBanner?Cocoon.Ad.refreshBanner():(Cocoon.Ad.preloadedBanner=!0,Cocoon.callNative("IDTK_SRV_AD","preloadBanner",arguments,!0)):void 0},extension.preloadedInterstitial=!1,extension.loadInterstitial=function(){return Cocoon.Ad.nativeAvailable?Cocoon.Ad.preloadedInterstitial?Cocoon.Ad.refreshInterstitial():(Cocoon.Ad.preloadedInterstitial=!0,Cocoon.callNative("IDTK_SRV_AD","preloadFullScreen",arguments,!0)):void 0},extension.setRectangle=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","setRectangle",arguments):void 0},extension.getRectangle=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","getRectangle",arguments):void 0},extension.setBannerLayout=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","setBannerLayout",arguments):void 0},extension.getIDFA=function(){return Cocoon.Ad.nativeAvailable?Cocoon.callNative("IDTK_SRV_AD","getIDFA",arguments):void 0},extension.onBannerShown=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onbannershow"),extension.onBannerHidden=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onbannerhide"),extension.onBannerReady=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onbannerready"),extension.onFullScreenShown=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onfullscreenshow"),extension.onFullScreenHidden=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onfullscreenhide"),extension.onFullScreenReady=new Cocoon.EventHandler("IDTK_SRV_AD","Ad","onfullscreenready");var signal=new Cocoon.Signal.createSignal;signal.register("ready",extension.onBannerReady),signal.register("shown",extension.onBannerShown),signal.register("hidden",extension.onBannerHidden),extension.banner={},extension.banner.on=signal.expose();var signal=new Cocoon.Signal.createSignal;return signal.register("ready",extension.onFullScreenReady),signal.register("shown",extension.onFullScreenShown),signal.register("hidden",extension.onFullScreenHidden),extension.interstitial={},extension.interstitial.on=signal.expose(),extension}),Cocoon.define("Cocoon.Store",function(extension){"use strict";extension.nativeAvailable=!!Cocoon.nativeAvailable&&!!window.ext.IDTK_SRV_STORE,extension.ProductInfo={productId:"productId",productAlias:"productAlias",productType:"productType",title:"title",description:"description",price:"price",localizedPrice:"localizedPrice",downloadURL:"downloadURL"},extension.ProductType={CONSUMABLE:0,NON_CONSUMABLE:1,AUTO_RENEWABLE_SUBSCRIPTION:2,FREE_SUBSCRIPTION:3,NON_RENEWABLE_SUBSCRIPTION:4},extension.StoreType={APP_STORE:0,PLAY_STORE:1,MOCK_STORE:2,CHROME_STORE:3,AMAZON_STORE:4,NOOK_STORE:5},extension.PurchaseInfo=function(transactionId,purchaseTime,purchaseState,productId,quantity){return this.transactionId=transactionId,this.purchaseTime=purchaseTime,this.purchaseState=purchaseState,this.productId=productId,this.quantity=quantity,this},extension.PurchaseState={PURCHASED:0,CANCELED:1,REFUNDED:2,EXPIRED:3},extension.getStoreType=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","getStoreType",arguments):!1},extension.initialize=function(params){params=params||{},Cocoon.Store.requestInitialization(params),Cocoon.Store.start()},extension.requestInitialization=function(parameters){return"undefined"==typeof parameters?parameters={}:(void 0!==parameters.managed&&(parameters.remote=parameters.managed),void 0!==parameters.sandbox&&(parameters.debug=parameters.sandbox)),Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","requestInitialization",arguments,!0):void 0},extension.start=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","start",arguments):void 0},extension.canPurchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","canPurchase",arguments):!1},extension.fetchProductsFromServer=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","fetchProductsFromServer",arguments,!0):void 0},extension.loadProducts=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","fetchProductsFromStore",arguments,!0):void 0},extension.finish=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","finishPurchase",arguments,!0):void 0},extension.consume=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","consumePurchase",arguments,!0):void 0},extension.purchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","purchaseFeature",arguments,!0):void 0},extension.puchaseProductModal=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","purchaseFeatureModal",arguments,!0):void 0},extension.purchaseProductModalWithPreview=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","purchaseFeatureModalWithPreview",arguments,!0):void 0},extension.isProductPurchased=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","isFeaturePurchased",arguments):void 0},extension.restore=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","restorePurchases",arguments,!0):void 0},extension.restorePurchasesModal=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","restorePurchasesModal",arguments,!0):void 0},extension.getProducts=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","getProducts",arguments):void 0},extension.addProduct=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","addProduct",arguments):void 0},extension.removeProduct=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","removeProduct",arguments):void 0},extension.getPurchases=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","getPurchases",arguments):void 0},extension.addPurchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","addPurchase",arguments):void 0},extension.removePurchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","removePurchase",arguments):void 0},extension.cancelPurchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","cancelPurchase",arguments):void 0},extension.refundPurchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","refundPurchase",arguments):void 0},extension.expirePurchase=function(){return Cocoon.Store.nativeAvailable?Cocoon.callNative("IDTK_SRV_STORE","expirePurchase",arguments):void 0},extension.onProductsFetchStarted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductsFetchStarted"),extension.onProductsFetchCompleted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductsFetchCompleted"),extension.onProductsFetchFailed=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductsFetchFailed"),extension.onProductPurchaseStarted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductPurchaseStarted"),extension.onProductPurchaseVerificationRequestReceived=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductPurchaseVerificationRequestReceived"),extension.onProductPurchaseCompleted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductPurchaseCompleted"),extension.onProductPurchaseFailed=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onProductPurchaseFailed"),extension.onRestorePurchasesStarted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onRestorePurchasesStarted"),extension.onRestorePurchasesCompleted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onRestorePurchasesCompleted"),extension.onRestorePurchasesFailed=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onRestorePurchasesFailed"),extension.onConsumePurchaseStarted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onConsumePurchaseStarted"),extension.onConsumePurchaseCompleted=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onConsumePurchaseCompleted"),extension.onConsumePurchaseFailed=new Cocoon.EventHandler("IDTK_SRV_STORE","Store","onConsumePurchaseFailed");var signal=new Cocoon.Signal.createSignal;return signal.register("load",{started:extension.onProductsFetchStarted,success:extension.onProductsFetchCompleted,error:extension.onProductsFetchFailed}),signal.register("purchase",{started:extension.onProductPurchaseStarted,success:extension.onProductPurchaseCompleted,verification:extension.onProductPurchaseVerificationRequestReceived,error:extension.onProductPurchaseFailed}),signal.register("consume",{started:extension.onConsumePurchaseStarted,success:extension.onConsumePurchaseCompleted,error:extension.onConsumePurchaseFailed}),signal.register("restore",{started:extension.onRestorePurchasesStarted,success:extension.onRestorePurchasesCompleted,error:extension.onRestorePurchasesFailed}),extension.on=signal.expose(),extension}),Cocoon.define("Cocoon.Notification",function(extension){extension.nativeAvailable=!!window.ext&&!!window.ext.IDTK_SRV_NOTIFICATION,extension.Local={},extension.Push={},extension.Local.create=function(params){var properties={message:"",soundEnabled:!0,badgeNumber:0,userData:{},contentBody:"",contentTitle:"",date:(new Date).valueOf()+1e3},args=Cocoon.clone(properties,params);return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","createLocalNotification",args):void 0},extension.Push.create=function(params){var properties={message:"",soundEnabled:!0,badgeNumber:0,userData:{},channels:[],expirationTime:0,expirationTimeInterval:0};for(var prop in properties)params[prop]||(params[prop]=properties[prop]);return params},extension.start=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","start",arguments):void 0},extension.Push.register=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","registerForPushNotifications",arguments,!0):void 0},extension.Push.unregister=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","unregisterForPushNotifications",arguments,!0):void 0},extension.Local.cancel=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","cancelLocalNotification",arguments):void 0},extension.Local.cancelLast=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","cancelLocalNotification",arguments,!0):void 0},extension.Local.cancelAllNotifications=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","cancelAllLocalNotifications",arguments):void 0},extension.Local.send=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","sendLocalNotification",arguments,!0):void 0},extension.subscribe=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","subscribe",arguments,!0):void 0},extension.unsubscribe=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","unsubscribe",arguments,!0):void 0},extension.Push.send=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","sendPushNotification",arguments,!0):void 0},extension.setBadgeNumber=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","setBadgeNumber",arguments):void 0},extension.getBadgeNumber=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","getBadgeNumber",arguments):void 0},extension.Local.getLastNotificationData=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","getLastReceivedLocalNotificationData",arguments):void 0},extension.Push.getLastNotificationData=function(){return Cocoon.Notification.nativeAvailable?Cocoon.callNative("IDTK_SRV_NOTIFICATION","getLastReceivedPushNotificationData",arguments):void 0},extension.onRegisterForPushNotificationsSucceed=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","pushNotificationServiceRegistered"),extension.onUnregisterForPushNotificationsSucceed=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","pushNotificationServiceUnregistered"),extension.onRegisterForPushNotificationsFailed=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","pushNotificationServiceFailedToRegister"),extension.onPushNotificationReceived=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","pushNotificationReceived"),extension.onLocalNotificationReceived=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","localNotificationReceived"),extension.onPushNotificationDeliverySucceed=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","pushNotificationSuccessfullyDelivered"),extension.onPushNotificationDeliveryFailed=new Cocoon.EventHandler("IDTK_SRV_NOTIFICATION","Notification","pushNotificationDeliveryError");var signal=new Cocoon.Signal.createSignal;signal.register("notification",{received:extension.onLocalNotificationReceived}),extension.Local.on=signal.expose();var signal=new Cocoon.Signal.createSignal;return signal.register("register",{success:extension.onRegisterForPushNotificationsSucceed,unregister:extension.onUnregisterForPushNotificationsSucceed,error:extension.onRegisterForPushNotificationsFailed}),signal.register("notification",{received:extension.onPushNotificationReceived}),signal.register("deliver",{success:extension.onPushNotificationDeliverySucceed,error:extension.onPushNotificationDeliveryFailed}),extension.Push.on=signal.expose(),extension}),Cocoon.define("Cocoon.Social",function(extension){return extension.Interface=function(){this.onLoginStatusChanged=new Cocoon.EventHandler("","dummy","onLoginStatusChanged");var signal=new Cocoon.Signal.createSignal;return signal.register("loginStatusChanged",this.onLoginStatusChanged),this.on=signal.expose(),this},extension.Interface.prototype={isLoggedIn:function(){return!1},login:function(callback){callback&&callback(!1,{message:"Not implemented!"})},logout:function(callback){callback&&callback({message:"Not implemented!"})},getLoggedInUser:function(){return null},hasPublishPermissions:function(callback){callback(!0)},requestPublishPermissions:function(callback){callback&&callback(!0,null)},requestUser:function(callback){callback(null,{message:"Not implemented!"})},requestUserImage:function(callback){callback("",{message:"Not implemented!"})},requestFriends:function(callback){callback([],{message:"Not implemented!"})},publishMessage:function(message,callback){callback({message:"Not implemented!"})},publishMessageWithDialog:function(message,callback){callback({message:"Not implemented!"})}},extension.SocialGamingService=function(){return Cocoon.Social.SocialGamingService.superclass.constructor.call(this),this},extension.SocialGamingService.prototype={_cachedAchievements:null,_achievementsMap:null,_leaderboardsTemplate:null,_achievementsTemplate:null,requestScore:function(callback){callback(null,{message:"Not implemented!"})},submitScore:function(score,callback){callback&&callback({message:"Not implemented!"})},showLeaderboard:function(callback){callback&&callback({message:"Not implemented!"})},requestAllAchievements:function(callback){callback([],{message:"Not implemented!"})},requestAchievements:function(callback){callback([],{message:"Not implemented!"})},submitAchievement:function(achievementID,callback){callback&&callback({message:"Not implemented!"})},resetAchievements:function(callback){callback&&callback([],{message:"Not implemented!"})},showAchievements:function(callback){if(!this._achievementsTemplate)throw"Please, provide a html template for achievements with the setTemplates method";var dialog=new Cocoon.Widget.WebDialog,callbackSent=!1;dialog.show(this._achievementsTemplate,function(error){dialog.closed=!0,!callbackSent&&callback&&callback(error)});var me=this;this.requestAchievements(function(achievements,error){if(!dialog.closed){if(error)return callbackSent=!0,void(callback&&callback(error));var achs=[];if(me._cachedAchievements)for(var i=0;i<me._cachedAchievements.length;++i){var ach=me._cachedAchievements[i];if(achs.push(ach),achievements&&achievements.length)for(var j=0;j<achievements.length;++j)if(achievements[j].achievementID===ach.achievementID){ach.achieved=!0;break}}var js="addAchievements("+JSON.stringify(achs)+");";dialog.eval(js)}})},setAchievementsMap:function(map){this._achievementsMap=map,this._cachedAchievements&&this.syncAchievementsMap(this._cachedAchievements)},setTemplates:function(leaderboardsTemplate,achievementsTemplate){this._leaderboardsTemplate=leaderboardsTemplate,this._achievementsTemplate=achievementsTemplate},setCachedAchievements:function(achievements){this._cachedAchievements=achievements,achievements&&this._achievementsMap&&this.syncAchievementsMap(this._cachedAchievements)},findAchievement:function(id){if(!this._cachedAchievements)return null;for(var i=0;i<this._cachedAchievements.length;++i)if(id===this._cachedAchievements[i].achievementID)return this._cachedAchievements[i];return null},translateAchievementID:function(id){if(this._achievementsMap)for(var customID in this._achievementsMap)if(customID==id)return this._achievementsMap[customID];return id},syncAchievementsMap:function(achievements){if(this._achievementsMap)for(var i=0;i<achievements.length;++i)for(var customID in this._achievementsMap)this._achievementsMap[customID]===achievements[i].achievementID&&(achievements[i].customID=customID)
}},Cocoon.extend(extension.SocialGamingService,extension.Interface),extension.ImageSize={THUMB:"thumb",SMALL:"small",MEDIUM:"medium",LARGE:"large"},extension.User=function(userID,userName,userImage){return this.userID=userID,this.userName=userName,this.userImage=userImage,this},extension.Message=function(message,mediaURL,linkURL,linkText,linkCaption){return this.message=message,this.mediaURL=mediaURL,this.linkURL=linkURL,this.linkText=linkText,this.linkCaption=linkCaption,this},extension.Score=function(userID,score,userName,imageURL,leaderboardID){return this.userID=userID,this.score=score||0,this.userName=userName,this.imageURL=imageURL,this.leaderboardID=leaderboardID,this},extension.ScoreParams=function(userID,leaderboardID,friends,timeScope){this.userID=userID,this.leaderboardID=leaderboardID,this.friends=!!friends,this.timeScope=timeScope||2},extension.TimeScope={ALL_TIME:0,WEEK:1,TODAY:2},extension.Achievement=function(achievementID,title,description,imageURL,points){return this.achievementID=achievementID,this.customID=achievementID,this.title=title,this.description=description,this.imageURL=imageURL,this.points=points||0,this},extension.share=function(){return Cocoon.nativeAvailable?Cocoon.callNative("IDTK_APP","share",arguments,!0):void 0},extension}),Cocoon.define("Cocoon.Social",function(extension){return extension.ManagerService=function(){this.services=[]},extension.ManagerService.prototype={services:null,registerSocialService:function(service){this.services.push(service)},submitAchievement:function(achievementID){for(var i=0;i<this.services.length;++i){var service=this.services[i];!service.readOnlyHint&&service.isLoggedIn()&&service.submitAchievement(achievementID,function(error){error&&console.error("Error submitting achievement: "+error.message)})}},submitScore:function(score,params){for(var i=0;i<this.services.length;++i){var service=this.services[i];!service.readOnlyHint&&service.isLoggedIn()&&service.submitScore(score,function(error){error&&console.error("Error submitting score: "+error.message)},params)}},getLoggedInServices:function(){for(var result=[],i=0;i<this.services.length;++i){var service=this.services[i];!service.fakeSocialService&&service.isLoggedIn()&&result.push(service)}return result},isLoggedInAnySocialService:function(){return this.getLoggedInServices().length>0}},extension.Manager=new extension.ManagerService,extension}),Cocoon.define("Cocoon.Social",function(extension){return extension.LocalStorageService=function(){Cocoon.Social.LocalStorageService.superclass.constructor.call(this),this.fakeSocialService=!0},extension.LocalStorageService.prototype={loggedIn:!1,keys:{score:"Cocoon.Social.LocalStorageService.score",earnedAchievements:"Cocoon.Social.LocalStorageService.earned"},isLoggedIn:function(){return this.loggedIn},login:function(callback){this.loggedIn||this.onLoginStatusChanged.notifyEventListeners(!0),this.loggedIn=!0,callback&&setTimeout(function(){callback(!0)},0)},logout:function(callback){this.loggedIn&&this.onLoginStatusChanged.notifyEventListeners(!0),this.loggedIn=!1,callback&&setTimeout(function(){callback()},0)},getLoggedInUser:function(){return new Cocoon.Social.User("me","LocalStorage")},requestUser:function(callback,userID){var user=new Cocoon.Social.User(userID||"me","LocalStorage");callback&&setTimeout(function(){callback(user)},0)},requestScore:function(callback){var scoreItem=localStorage.getItem(this.keys.score),score=parseInt(scoreItem)||0;setTimeout(function(){callback(new Cocoon.Social.Score("me",score))},0)},submitScore:function(score,callback){var scoreItem=localStorage.getItem(this.keys.score),topScore=parseInt(scoreItem)||0;score>topScore&&localStorage.setItem(this.keys.score,score),callback&&setTimeout(function(){callback()},0)},getLocalStorageEarnedAchievements:function(){var achievementsItem=localStorage.getItem(this.keys.earnedAchievements),earned=[];if(achievementsItem){var array=JSON.stringify(achievementsItem);array&&array.length&&(earned=array)}return earned},requestAchievements:function(callback){var earned=this.getLocalStorageEarnedAchievements();setTimeout(function(){callback(earned)},0)},submitAchievement:function(achievementID,callback){if(null===achievementID||"undefined"==typeof achievementID)throw"No achievementID specified";for(var earned=this.getLocalStorageEarnedAchievements(),exists=!1,i=0;i<earned.length;++i)if(earned[i]===achievementID){exists=!0;break}exists||(earned.push(achievementID),localStorage.setItem(this.keys.earnedAchievements,JSON.stringify(earned))),callback&&setTimeout(function(){callback()},0)},resetAchievements:function(callback){localStorage.removeItem(this.keys.earnedAchievements),callback&&setTimeout(function(){callback()},0)}},Cocoon.extend(extension.LocalStorageService,extension.SocialGamingService),extension.LocalStorage=new extension.LocalStorageService,extension}),Cocoon.define("Cocoon.Social",function(extension){function fromSessionToAuthTokenObject(response,error){return{access_token:response.access_token,state:response.state,error:error,expires_in:response.expirationDate?response.expirationDate-Date.now():0,player_id:response.playerId}}function fromGPPlayerToCocoonUser(gpPlayer){return new Cocoon.Social.User(gpPlayer.playerId,gpPlayer.displayName,gpPlayer.avatarImageUrl)}function fromGPPersonToCocoonUser(gpUser){var avatar=gpUser.image?gpUser.image.url:"";return avatar=avatar.replace(/sz=\d+/g,"sz=100"),new Cocoon.Social.User(gpUser.id,gpUser.displayName,avatar)}function fromImageSizeToGPSize(imageSize){return imageSize===Cocoon.Social.ImageSize.THUMB?100:imageSize===Cocoon.Social.ImageSize.MEDIUM?200:imageSize===Cocoon.Social.ImageSize.LARGE?512:void 0}function fromGPAchievementToCocoonAchievement(gpItem){var result=new Cocoon.Social.Achievement(gpItem.id,gpItem.name,gpItem.description,gpItem.revealedIconUrl,0);return result.gpAchievementData=gpItem,result}function fromGPScoreToCocoonScore(gpItem,leaderboardID){return new Cocoon.Social.Score(gpItem.player.playerId,gpItem.scoreValue,gpItem.player.displayName,gpItem.player.avatarImageUrl,leaderboardID)}return extension.GooglePlayGamesExtension=function(){this.nativeExtensionName="IDTK_SRV_GOOGLE_PLAY_GAMES",this.extensionName="Social.GooglePlayGames",this.nativeAvailable=Cocoon.nativeAvailable&&"undefined"!=typeof window.ext[this.nativeExtensionName],this.auth=new Cocoon.Social.GooglePlayGamesAuthExtension(this),this.client=new Cocoon.Social.GooglePlayGamesClientExtension(this),this.defaultScopes=["https://www.googleapis.com/auth/games","https://www.googleapis.com/auth/plus.login"],this.gamesAPI="/games/v1",this.plusAPI="/plus/v1",this.onSessionChanged=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onSessionChanged"),Cocoon.Social.GooglePlayGames=this;var me=this;return this.onSessionChanged.addEventListener(function(session,error){me.token=fromSessionToAuthTokenObject(session,error),session&&session.access_token&&me.client.request({path:me.gamesAPI+"/players/me",callback:function(response){me.currentPlayer=response}})}),this},extension.GooglePlayGamesExtension.prototype={token:null,settings:{},socialService:null,currentPlayer:null,initialized:!1,auth:null,client:null,init:function(params){if(!params||"object"!=typeof params)throw"Invalid params argument";if(this.settings=params,this.initialized=!0,this.nativeAvailable)Cocoon.callNative(this.nativeExtensionName,"init",[this.settings.clientId],!0);else{var me=this,initWebAPi=function(){gapi.auth.authorize({immediate:!0,scope:me.defaultScopes,client_id:me.settings.clientId},function(response){me.token=response,response&&response.access_token&&me.onSessionChanged.notifyEventListeners(response)})};if(window.gapi)initWebAPi();else{window.onGapiLoadCallback=function(){window.setTimeout(initWebAPi,1)};var script=document.createElement("script");script.src="https://apis.google.com/js/client.js?onload=onGapiLoadCallback",document.getElementsByTagName("head")[0].appendChild(script)}}},getSocialInterface:function(){if(!this.initialized)throw"You must call init() before getting the Social Interface";return this.socialService||(this.socialService=new Cocoon.Social.SocialGamingServiceGooglePlayGames(this)),this.socialService},getMultiplayerInterface:function(){return Cocoon.Multiplayer.GooglePlayGames},share:function(){return window.open(this.href,"","menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600"),!1}},extension.GooglePlayGamesAuthExtension=function(extension){return this.extension=extension,this},extension.GooglePlayGamesAuthExtension.prototype={authorize:function(params,callback){var me=this;this.extension.nativeAvailable?Cocoon.callNative(this.extension.nativeExtensionName,"authorize",[params,function(response,error){me.extension.token=fromSessionToAuthTokenObject(response,error),callback&&callback(me.extension.token)}],!0):gapi.auth.authorize(params,function(response){me.extension.token=response,me.extension.onSessionChanged.notifyEventListeners(response,response?response.error:null),callback&&callback(response)})},disconnect:function(callback){this.extension.nativeAvailable?Cocoon.callNative(this.extension.nativeExtensionName,"disconnect",[callback],!0):callback&&callback({error:"Not implemented yet"})},init:function(callback){this.extension.nativeAvailable?callback():gapi.auth.init(callback)},getToken:function(){return this.extension.nativeAvailable?this.extension.token:gapi.auth.getToken()},setToken:function(token){this.extension.nativeAvailable?this.extension.token=token:gapi.auth.setToken(token)}},extension.GooglePlayGamesClientExtension=function(extension){return this.extension=extension,this},extension.GooglePlayGamesClientExtension.prototype={setApiKey:function(apiKey){this.extension.nativeAvailable?Cocoon.callNative(this.extension.nativeExtensionName,"setApiKey",[apiKey],!0):gapi.client.setApiKey(apiKey)},request:function(args){if(this.extension.nativeAvailable){if(args.callback)return Cocoon.callNative(this.extension.nativeExtensionName,"request",[args,function(response,error){var result=response;error&&(result=response||{},result.error=error),args.callback(result)}],!0),null;var me=this,httpRequest={execute:function(callback){Cocoon.callNative(me.extension.nativeExtensionName,"request",[args,function(response,error){var result=response;error&&(result=response||{},result.error=error),callback(result)}],!0)}};return httpRequest}return gapi.client.request(args)}},extension.GooglePlayGames=new Cocoon.Social.GooglePlayGamesExtension,extension.SocialGamingServiceGooglePlayGames=function(apiObject){Cocoon.Social.SocialGamingServiceGooglePlayGames.superclass.constructor.call(this),this.gapi=apiObject;var me=this;return this.gapi.onSessionChanged.addEventListener(function(session){var obj=session||{};me.onLoginStatusChanged.notifyEventListeners(!!obj.access_token,obj.error)}),this},extension.SocialGamingServiceGooglePlayGames.prototype={isLoggedIn:function(){return this.gapi.token&&this.gapi.token.access_token?!0:!1},login:function(callback){var me=this;this.gapi.auth.authorize({client_id:this.gapi.settings.clientId,scope:this.gapi.defaultScopes},function(response){callback&&callback(me.isLoggedIn(),response.error)})},logout:function(callback){this.gapi.auth.disconnect(callback)},getLoggedInUser:function(){return this.gapi.currentPlayer?fromGPUserToCocoonUser(this.gapi.currentPlayer):null},requestUser:function(callback,userId){var playerId=userId||"me";this.gapi.client.request({path:this.gapi.gamesAPI+"/players/"+playerId,callback:function(response){var user=response&&!response.error?fromGPPlayerToCocoonUser(response):null;callback(user,response.error)}})},requestUserImage:function(callback,userID,imageSize){this.requestUser(function(user,error){if(user&&user.userImage){var pixelSize=fromImageSizeToGPSize(imageSize||Cocoon.Social.ImageSize.MEDIUM);-1===user.userImage.indexOf("sz=")?user.userImage+="?sz="+pixelSize:user.userImage=user.userImage.replace(/sz=\d+/g,"sz="+pixelSize)}callback(user?user.userImage:null,error)},userID)},requestFriends:function(callback,userId){var params={orderBy:"best"},playerId=userId||"me";this.gapi.client.request({path:this.gapi.plusAPI+"/people/"+playerId+"/people/visible",params:params,callback:function(response){if(response&&!response.error){for(var friends=[],i=0;i<response.items.length;++i)friends.push(fromGPPersonToCocoonUser(response.items[i]));callback(friends)}else callback([],response?response.error:null)}})},publishMessage:function(message,callback){callback&&callback("Not supported... use publishMessageWithDialog method instead")},publishMessageWithDialog:function(message,callback){if(this.gapi.nativeAvailable){var params={prefilledText:message.message,mediaUrl:message.mediaURL,mediaTitle:message.linkCaption,mediaDescription:message.linkText,url:message.linkURL};Cocoon.callNative(this.gapi.nativeExtensionName,"shareMessage",[params,callback],!0)}else{var me=this,share=function(){var options={contenturl:"https://plus.google.com/pages/",contentdeeplinkid:"/pages",clientid:me.gapi.settings.clientId,cookiepolicy:"single_host_origin",prefilltext:message.message,calltoactionlabel:"CREATE",calltoactionurl:"http://plus.google.com/pages/create",calltoactiondeeplinkid:"/pages/create"};gapi.interactivepost.render("sharePost",options)};if(gapi.interactivepost)share();else{var script=document.createElement("script");script.type="text/javascript",script.async=!0,script.src="https://apis.google.com/js/plusone.js",script.onload=function(){share()},document.getElementsByTagName("head")[0].appendChild(script)}}},requestScore:function(callback,params){params=params||{};var playerId=params.userID||"me",leaderboardID=params.leaderboardID||this.gapi.settings.defaultLeaderboard;if(!leaderboardID)throw"leaderboardID not provided in the params. You can also set the default leaderboard in the init method";this.gapi.client.request({path:this.gapi.gamesAPI+"/players/"+playerId+"/leaderboards/"+leaderboardID+"/scores/ALL_TIME",callback:function(response){if(response&&response.error)callback(null,response.error);else if(response&&response.items&&response.items.length>0){var item=response.items[0],data=new Cocoon.Social.Score(playerId,item.scoreValue,"","",item.leaderboard_id);callback(data,null)}else callback(null,null)}})},submitScore:function(score,callback,params){params=params||{};var leaderboardID=params.leaderboardID||this.gapi.settings.defaultLeaderboard;if(!leaderboardID)throw"leaderboardID not provided in the params. You can also set the default leaderboard in the init method";this.gapi.client.request({path:this.gapi.gamesAPI+"/leaderboards/"+leaderboardID+"/scores",method:"POST",params:{score:score},callback:function(response){callback&&callback(response?response.error:null)}})},showLeaderboard:function(callback,params){params=params||{};var leaderboardID=params.leaderboardID||this.gapi.settings.defaultLeaderboard;if(!leaderboardID)throw"leaderboardID not provided in the params. You can also set the default leaderboard in the init method";var ios=/(iPad|iPhone|iPod)/gi.test(navigator.userAgent);if(!ios&&this.gapi.nativeAvailable){var timeScope=params.timeScope||0;Cocoon.callNative(this.gapi.nativeExtensionName,"showLeaderboard",[leaderboardID,timeScope,callback],!0)}else{if(!this._leaderboardsTemplate)throw"Please, provide a html template for leaderboards with the setTemplates method";var dialog=new Cocoon.Widget.WebDialog,callbackSent=!1;dialog.show(this._leaderboardsTemplate,function(error){dialog.closed=!0,!callbackSent&&callback&&callback(error)});var collection=params.friends?"SOCIAL":"PUBLIC",timeSpan="ALL_TIME";params.timeScope===Cocoon.Social.TimeScope.WEEK?timeSpan="WEEKLY":params.timeScope===Cocoon.Social.TimeScope.TODAY&&(timeSpan="DAILY"),this.gapi.client.request({path:this.gapi.gamesAPI+"/leaderboards/"+leaderboardID+"/window/"+collection,method:"GET",params:{timeSpan:timeSpan},callback:function(response){if(!dialog.closed){if(response.error)return void(callback&&(callbackSent=!0,callback(response.error),dialog.close()));var scores=[],items=[];response&&response.items&&(items=response.items.slice(0)),response&&response.playerScore&&items.push(response.playerScore);for(var i=0;i<items.length;++i){var item=items[i],score=fromGPScoreToCocoonScore(item,leaderboardID);score.imageURL+="?sz=50",score.position=item.scoreRank||i+1,score.me=!1,scores.push(score)}var js="addScores("+JSON.stringify(scores)+")";dialog.eval(js)}}})}},prepareAchievements:function(reload,callback){if(!this._cachedAchievements||reload){var me=this;this.gapi.client.request({path:this.gapi.gamesAPI+"/achievements",callback:function(response){if(response&&!response.error){var achievements=[];if(response&&response.items)for(var i=0;i<response.items.length;i++)achievements.push(fromGPAchievementToCocoonAchievement(response.items[i]));me.setCachedAchievements(achievements),callback(achievements,null)}else callback([],response?response.error:null)}})}else callback(this._cachedAchievements,null)},requestAllAchievements:function(callback){this.prepareAchievements(!0,callback)},requestAchievements:function(callback,userID){var me=this;this.prepareAchievements(!1,function(allAchievements,error){if(error)return void callback([],error);var playerID=userID||"me";me.gapi.client.request({path:me.gapi.gamesAPI+"/players/"+playerID+"/achievements",params:{state:"UNLOCKED"},callback:function(response){if(response&&!response.error){var achievements=[];if(response.items)for(var i=0;i<response.items.length;i++){var ach=me.findAchievement(response.items[i].id);ach&&achievements.push(ach)}callback(achievements,null)}else callback([],response?response.error:null)}})})},submitAchievement:function(achievementID,callback){if(null===achievementID||"undefined"==typeof achievementID)throw"No achievementID specified";var achID=this.translateAchievementID(achievementID);if(this.gapi.nativeAvailable){var showNotification=!!this.gapi.settings.showAchievementNotifications;Cocoon.callNative(this.gapi.nativeExtensionName,"unlockAchievement",[achID,showNotification,callback],!0)}else this.gapi.client.request({path:this.gapi.gamesAPI+"/achievements/"+achID+"/unlock",method:"POST",callback:function(response){callback&&callback(response?response.error:null)}})},resetAchievements:function(callback){this.gapi.client.request({path:"/games/v1management/achievements/reset",method:"POST",callback:function(response){callback&&callback(response?response.error:null)}})},showAchievements:function(callback){var ios=/(iPad|iPhone|iPod)/gi.test(navigator.userAgent);!ios&&this.gapi.nativeAvailable?Cocoon.callNative(this.gapi.nativeExtensionName,"showAchievements",[callback],!0):Cocoon.Social.SocialGamingServiceGooglePlayGames.superclass.showAchievements.call(this)}},Cocoon.extend(Cocoon.Social.SocialGamingServiceGooglePlayGames,Cocoon.Social.SocialGamingService),extension}),Cocoon.define("Cocoon.Social",function(extension){function fromGCPLayerToCocoonUser(player){return new Cocoon.Social.User(player.playerID,player.alias)}function fromGCAchievementDescriptionToCocoonAchievement(ach){return new Cocoon.Social.GameCenter.Achievement(ach.identifier,ach.title,ach.achievedDescription,"",ach.maximumPoints)}return extension.GameCenterExtension=function(){this.nativeExtensionName="IDTK_SRV_GAMECENTER",this.extensionName="Social.GameCenter",this.nativeAvailable=!!window.ext&&!!window.ext[this.nativeExtensionName];var me=this;return this.nativeAvailable&&(this.onGameCenterLoginStateChanged=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onGameCenterLoginStateChanged"),this.onGameCenterLoginStateChanged.addEventListener(function(localPlayer){me._currentPlayer=localPlayer})),this},extension.GameCenterExtension.prototype={_currentPlayer:null,getSocialInterface:function(){return this._socialService||(this._socialService=new Cocoon.Social.SocialGamingServiceGameCenter(this)),this._socialService},getMultiplayerInterface:function(){return Cocoon.Multiplayer.GameCenter},isLoggedIn:function(){return this._currentPlayer&&this._currentPlayer.isAuthenticated},login:function(callback){var me=this;if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"login",[function(response,error){me._currentPlayer=response,callback&&callback(response,error)}],!0)},getLocalPlayer:function(){if(this._currentPlayer)return this._currentPlayer;if(this.nativeAvailable)return this._currentPlayer=Cocoon.callNative(this.nativeExtensionName,"getLocalPlayer",[]),this._currentPlayer;throw"Game Center not available"},loadPlayers:function(playerIDs,callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"loadPlayers",[playerIDs,callback],!0)},loadFriends:function(callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"loadFriends",[callback],!0)},loadAchievements:function(callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"loadAchievements",[callback],!0)},loadAchievementDescriptions:function(callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"loadAchievementDescriptions",[callback],!0)},loadScores:function(callback,query){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"loadScores",[query,callback],!0)},submitScore:function(score,callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"submitScore",[score,callback],!0)},submitAchievements:function(achievements,callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"submitAchievements",[achievements,callback],!0)},resetAchievements:function(callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"resetAchievements",[callback],!0)},showAchievements:function(callback){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"showAchievements",[callback],!0)},showLeaderboards:function(callback,query){if(!this.nativeAvailable)throw"Game Center not available";Cocoon.callNative(this.nativeExtensionName,"showLeaderboards",[query,callback],!0)}},extension.GameCenter=new extension.GameCenterExtension,extension.GameCenter.Player=function(){this.playerID="",this.alias="",this.isFriend=!1},extension.GameCenter.LocalPlayer=function(){this.playerID="",this.alias="",this.isAuthenticated=!1},extension.GameCenter.Achievement=function(identifier,percentComplete){this.identifier=identifier,this.percentComplete=percentComplete,this.lastReportedDate=0},extension.GameCenter.AchievementDescription=function(){this.identifier="",this.title="",this.achievedDescription="",this.unachievedDescription="",this.maximumPoints=0},extension.GameCenter.Score=function(userID,score,userName,imageURL,leaderboardID,originalScoreObject){return this.userID=userID,this.score=score||0,this.userName=userName,this.imageURL=imageURL,this.leaderboardID=leaderboardID,this.rank=originalScoreObject.rank,this.originalScoreObject=originalScoreObject,this},extension.GameCenter.Leaderboard=function(category,playerIDs,timeScope,playerScope,rangeStart,rangeLength){this.category=category,this.playerIDs=playerIDs,this.timeScope=timeScope,this.playerScope=playerScope,this.rangeStart=rangeStart,this.rangeLength=rangeLength,this.scores=[],this.localPlayerScore=[],this.localizedTitle=localizedTitle},extension.GameCenter.TimeScope={TODAY:0,WEEK:1,ALL_TIME:2},extension.GameCenter.PlayerScope={GLOBAL:0,FRIENDS:1},extension.SocialGamingServiceGameCenter=function(gcExtension){Cocoon.Social.SocialGamingServiceGameCenter.superclass.constructor.call(this),this.gc=gcExtension;var me=this;return this.gc.onGameCenterLoginStateChanged.addEventListener(function(localPlayer,error){me.onLoginStatusChanged.notifyEventListeners(localPlayer.isAuthenticated,error)}),this},extension.SocialGamingServiceGameCenter.prototype={_cachedAchievements:null,isLoggedIn:function(){return this.gc.isLoggedIn()},login:function(callback){this.gc.login(function(localPlayer,error){callback&&callback(localPlayer.isAuthenticated,error)})},logout:function(callback){callback&&callback({message:"User has to logout from the Game Center APP"})},getLoggedInUser:function(){return fromGCPLayerToCocoonUser(this.gc._currentPlayer?this.gc._currentPlayer:this.gc.getLocalPlayer())},requestUser:function(callback,userId){if(userId)this.gc.loadPlayers([userId],function(response,error){var user=response&&response.length?fromGCPLayerToCocoonUser(response[0]):null;callback(user,error)});else{var me=this;setTimeout(function(){callback(me.getLoggedInUser())})}},requestFriends:function(callback){this.gc.loadFriends(function(friends,error){var users=[];if(friends&&friends.length)for(var i=0;i<friends.length;++i)users.push(fromGCPLayerToCocoonUser(friends[i]));callback(users,error)})},requestScore:function(callback,params){var query={},options=params||{};options.leaderboardID&&(query.category=options.leaderboardID),query.playerIDs=[options.userID||this.getLoggedInUser().userID],this.gc.loadScores(function(response,error){var gcScore=null;options.userID&&response&&response.scores&&response.scores.length?gcScore=response.scores[0]:response&&response.localPlayerScore&&(gcScore=response.localPlayerScore);var loadedScore=gcScore?new Cocoon.Social.GameCenter.Score(gcScore.playerID,gcScore.value,"","",gcScore.category,gcScore):null;callback(loadedScore,error)},query)},submitScore:function(score,callback,params){var options=params||{};this.gc.submitScore({value:score,category:options.leaderboardID||""},function(error){callback&&callback(error)})},showLeaderboard:function(callback,params){var options=params||{};this.gc.showLeaderboards(function(error){callback&&callback(error)},{category:options.leaderboardID||""})},prepareAchievements:function(reload,callback){if(!this._cachedAchievements||reload){var me=this;this.gc.loadAchievementDescriptions(function(response,error){if(error)callback([],error);else{var achievements=[];if(response&&response.length)for(var i=0;i<response.length;i++)achievements.push(fromGCAchievementDescriptionToCocoonAchievement(response[i]));me.setCachedAchievements(achievements),callback(achievements,null)}})}else callback(this._cachedAchievements,null)},requestAllAchievements:function(callback){this.prepareAchievements(!0,callback)},requestAchievements:function(callback){var me=this;this.prepareAchievements(!1,function(allAchievements,error){return error?void callback([],error):void me.gc.loadAchievements(function(response,error){if(error)callback([],response.error);else{var achievements=[];if(response&&response.length)for(var i=0;i<response.length;i++){var ach=me.findAchievement(response[i].identifier);ach&&achievements.push(ach)}callback(achievements,null)}})})},submitAchievement:function(achievementID,callback){if(null===achievementID||"undefined"==typeof achievementID)throw"No achievementID specified";var achID=this.translateAchievementID(achievementID);this.gc.submitAchievements([{identifier:achID,percentComplete:100}],callback)},resetAchievements:function(callback){this.gc.resetAchievements(callback)},showAchievements:function(callback){this.gc.showAchievements(function(error){callback&&callback(error)})}},Cocoon.extend(extension.SocialGamingServiceGameCenter,extension.SocialGamingService),extension}),Cocoon.define("Cocoon.Social",function(extension){function fromCocoonFBStatusToFBAPIState(state){return 0===state?"connected":1===state?"not_authorized":"unknown"}function fromCocoonFBSessionToFBAPISession(response,error){var authResponse=null;return 0===response.state&&(authResponse={accessToken:response.accessToken,expirationDate:response.expirationDate,userID:response.user?response.userID:null,permissions:response.permissions,user:response.user}),{status:fromCocoonFBStatusToFBAPIState(response.state),authResponse:authResponse,error:error}}function fromFBUserToCocoonUser(facebookUser){return new Cocoon.Social.User(facebookUser.id,facebookUser.username?facebookUser.username:facebookUser.first_name+" "+facebookUser.last_name)}function fromCocoonMessageToFBMessage(message){return{link:message.linkURL,description:message.message,name:message.linkText,caption:message.linkCaption,picture:message.mediaURL}}function fromFBScoreToCocoonScore(fbResponse,requestScoreParams){var result=new Cocoon.Social.Score(fbResponse.user.id,fbResponse.score,fbResponse.user.name);return requestScoreParams&&(result.leaderboardID=requestScoreParams.leaderboardID),result.imageURL="https://graph.facebook.com/"+fbResponse.user.id+"/picture",result}function fromFBAchievementToCocoonAchievement(fbResponse){var result=new Cocoon.Social.Achievement(fbResponse.id,fbResponse.title,fbResponse.description,fbResponse.image[0].url,fbResponse.data.points);return result.fbAchievementData=fbResponse,result}if(extension.FacebookExtension=function(){this.nativeExtensionName="IDTK_SRV_FACEBOOK",this.extensionName="Social.Facebook",this.nativeAvailable=!!window.ext&&!!window.ext[this.nativeExtensionName],this.Event=new Cocoon.Social.FacebookEvent(this.nativeAvailable);var me=this;return this.nativeAvailable&&(this.onFacebookSessionStateChanged=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onFacebookSessionStateChanged"),Cocoon.Social.Facebook=this,this.onFacebookSessionStateChanged.addEventListener(function(session,error){var data=fromCocoonFBSessionToFBAPISession(session,error);0==session.state&&me.Event.notify("auth.login",data),me.Event.notify("auth.authResponseChange",data),me.Event.notify("auth.statusChange",data)})),this},extension.FacebookExtension.prototype={_currentSession:null,_appId:null,_socialService:null,init:function(options){if(!options||!options.appId)throw"appId must be specified!";this._appId=options.appId,this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"init",[options],!0):FB.init(options);var me=this;this.Event.subscribe("auth.authResponseChange",function(session){me._currentSession=session,session.authResponse&&!session.authResponse.user&&me.api("me?fields=username",function(response){me._currentSession.authResponse.user=response})})},getSocialInterface:function(){if(!this._appId)throw"You must call init() before getting the Social Interface";return this._socialService||(this._socialService=new Cocoon.Social.SocialGamingServiceFacebook(this)),this._socialService},login:function(callback,options){var me=this;this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"login",[options,function(response,error){me._currentSession=fromCocoonFBSessionToFBAPISession(response,error),callback&&callback(me._currentSession)}],!0):FB.login(function(response){me._currentSession=response,callback&&callback(response)},options)},logout:function(callback){this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"logout",[function(response,error){callback&&callback(fromCocoonFBSessionToFBAPISession(response,error))}],!0):FB.logout(function(response){callback&&callback(response)})},getAuthResponse:function(){if(this.nativeAvailable){var response=Cocoon.callNative(this.nativeExtensionName,"getFacebookSession",[]);return fromCocoonFBSessionToFBAPISession(response)}return FB.getAuthResponse()},getLoginStatus:function(callback,force){if(this.nativeAvailable){var me=this;setTimeout(function(){var response=Cocoon.callNative(me.nativeExtensionName,"getFacebookSession",[]);callback&&callback(fromCocoonFBSessionToFBAPISession(response))},50)}else FB.getLoginStatus(callback,force)},api:function(path,method,params,cb){if(this.nativeAvailable){var openGraph=arguments[0],httpMethod=arguments.length>3?arguments[1]:"GET",options=null;3==arguments.length&&(options=arguments[1]),4==arguments.length&&(options=arguments[2]);var callback=arguments.length>1?arguments[arguments.length-1]:function(){};return Cocoon.callNative(this.nativeExtensionName,"api",[openGraph,httpMethod,options,callback],!0)
}FB.api(path,method,params,cb)},ui:function(params,cb){if(this.nativeAvailable){var params=arguments[0],callback=arguments.length>1?arguments[1]:function(){};return Cocoon.callNative(this.nativeExtensionName,"ui",[params,callback],!0)}navigator.isCocoonJS||FB.ui(params,cb)},requestAdditionalPermissions:function(permissionsType,permissions,callback){if(this.nativeAvailable){var permsArray=permissions.split(",");Cocoon.callNative(this.nativeExtensionName,"requestAdditionalPermissions",[permissionsType,permsArray,function(session,error){callback&&callback(fromCocoonFBSessionToFBAPISession(session,error))}],!0)}else FB.login(callback,{scope:permissions})},getPermissions:function(callback){this.api("me/permissions",function(response){for(var result={},data=response&&response.data?response.data:[],i=0;i<data.length;++i)"granted"===data[i].status&&(result[data[i].permission]=!0);callback(result)})},showShareDialog:function(params,callback){this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"showShareDialog",[params,callback],!0):(params.method="feed",FB.ui(params,callback))},uploadPhoto:function(file,callback){this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"uploadPhoto",[file,callback],!0):callback({error:{message:"Not implemented"}})},showFriendPicker:function(callback){this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"showFriendPicker",[callback],!0):callback({error:{message:"Not implemented"}})}},extension.FacebookEvent=function(nativeAvailable){return this.nativeAvailable=nativeAvailable,this},extension.FacebookEvent.prototype={subscribe:function(name,callback){if(this.nativeAvailable){var eventKey=name+"listeners";this[eventKey]=this[eventKey]||[],this[eventKey].push(callback)}else navigator.isCocoonJS||FB.Event.subscribe(name,callback)},unsubscribe:function(name,callback){if(this.nativeAvailable){var eventKey=name+"listeners",array=this[eventKey];if(array){var index=array.indexOf(callback);-1!==index&&array.splice(index,1)}}else navigator.isCocoonJS||FB.Event.unsubscribe(name,callback)},notify:function(name,param){var eventKey=name+"listeners",array=this[eventKey];if(array)for(var i=0;i<array.length;++i)array[i](param)}},extension.Facebook=new extension.FacebookExtension,extension.SocialGamingServiceFacebook=function(fbExtension){Cocoon.Social.SocialGamingServiceFacebook.superclass.constructor.call(this),this.fb=fbExtension;var me=this;return this.fb.Event.subscribe("auth.authResponseChange",function(session){me.onLoginStatusChanged.notifyEventListeners("connected"==session.status,session.error)}),this},extension.SocialGamingServiceFacebook.prototype={currentPermissions:null,isLoggedIn:function(){return this.fb._currentSession&&"connected"===this.fb._currentSession.status},login:function(callback,options){var me=this;this.fb.login(function(response){callback&&callback(me.isLoggedIn(),response.error)},options)},logout:function(callback){this.fb.logout(function(response){callback&&callback(response.error)})},getLoggedInUser:function(){var authResponse=this.fb._currentSession?this.fb._currentSession.authResponse:null;return authResponse&&authResponse.user?fromFBUserToCocoonUser(authResponse.user):authResponse&&authResponse.userID?new Cocoon.Social.Facebook.User(authResponse.userID,"Loading..."):null},hasPublishPermissions:function(callback){this.fb.getPermissions(function(perms,error){callback(perms.publish_actions,error)})},requestPublishPermissions:function(callback){var me=this;this.fb.requestAdditionalPermissions("publish","publish_actions",function(response){response.error?callback(!1,error):me.hasPublishPermissions(function(granted,error){callback(granted,error)})})},requestUser:function(calback,userId){var apiCall=userId||"me";this.fb.api(apiCall,function(response){var user=response.error?null:fromFBUserToCocoonUser(response);calback(user,response.error)})},requestUserImage:function(callback,userID,imageSize){!userID&&this.isLoggedIn()&&(userID=this.fb._currentSession.authResponse.userID);var fbPictureSize="small";imageSize===Cocoon.Social.ImageSize.THUMB?fbPictureSize="square":imageSize===Cocoon.Social.ImageSize.MEDIUM?fbPictureSize="normal":imageSize===Cocoon.Social.ImageSize.LARGE&&(fbPictureSize="large");var url="https://graph.facebook.com/"+userID+"/picture?type="+fbPictureSize;callback(url)},requestFriends:function(callback,userId){var apiCall=(userId||"me")+"/friends";this.fb.api(apiCall,function(response){var friends=[];if(!response.error)for(var i=0;i<response.data.length;i++)friends.push(fromFBUserToCocoonUser(response.data[i]));callback(friends,response.error)})},preparePublishAction:function(callback){if(this.currentPermissions)if(this.currentPermissions.publish_actions)callback(!0);else{this.currentPermissions=this.currentPermissions|{};var me=this;this.fb.requestAdditionalPermissions("publish","publish_actions",function(response){for(var perms=response&&response.authResponse?response.authResponse.permissions:[],i=0;i<perms.length;++i)me.currentPermissions[perms[i]]=!0;callback(response.error?!1:!0)})}else{var me=this;this.fb.getPermissions(function(perms){me.currentPermissions=perms,perms?me.preparePublishAction(callback):callback(!1)})}},publishMessage:function(message,callback){this.preparePublishAction(function(granted){if(granted){var params=fromCocoonMessageToFBMessage(message),apiCall="me/feed";this.fb.api(apiCall,params,function(response){callback&&callback(response.error)})}else callback&&callback({message:"No publish_actions permission granted"})})},publishMessageWithDialog:function(message,callback){this.fb.showShareDialog(fromCocoonMessageToFBMessage(message),function(response){callback&&callback(response.error)})},requestScore:function(callback,params){var apiCall=(params&&params.userID?params.userID:"me")+"/scores";this.fb.api(apiCall,function(response){if(response.error)callback(null,response.error);else if(response.data&&response.data.length>0){var data=fromFBScoreToCocoonScore(response.data[0]);callback(data,null)}else callback(null,null)})},submitScore:function(score,callback,params){var me=this;this.preparePublishAction(function(granted){granted?me.requestScore(function(currentScore,error){if(error)return void(callback&&callback(error));var topScore=currentScore?currentScore.score:0;if(topScore>=score)return void(callback&&callback(null));var apiCall="/"+(params&&params.userID?params.userID:"me")+"/scores";me.fb.api(apiCall,"POST",{score:score},function(response){callback&&callback(response.error)})},params):callback&&callback({message:"No publish_actions permission granted"})})},showLeaderboard:function(callback){if(!this._leaderboardsTemplate)throw"Please, provide a html template for leaderboards with the setTemplates method";var dialog=new Cocoon.Widget.WebDialog,callbackSent=!1;dialog.show(this._leaderboardsTemplate,function(error){dialog.closed=!0,!callbackSent&&callback&&callback(error)});var me=this;this.fb.api(me.fb._appId+"/scores",function(response){if(!dialog.closed){if(response.error)return void(callback&&(callbackSent=!0,callback(response.error),dialog.close()));var scores=[];if(response.data&&response.data.length)for(var i=0;i<response.data.length;++i){var score=fromFBScoreToCocoonScore(response.data[i]);score.position=i,score.imageURL="https://graph.facebook.com/"+score.userID+"/picture",score.me=score.userID===me.fb._currentSession.authResponse.userID,scores.push(score)}var js="addScores("+JSON.stringify(scores)+")";dialog.eval(js)}})},prepareAchievements:function(reload,callback){if(!this._cachedAchievements||reload){var me=this;this.fb.api(this.fb._appId+"/achievements",function(response){if(response.error)callback([],response.error);else{var achievements=[];if(response.data)for(var i=0;i<response.data.length;i++)achievements.push(fromFBAchievementToCocoonAchievement(response.data[i]));me.setCachedAchievements(achievements),callback(achievements,null)}})}else callback(this._cachedAchievements,null)},requestAllAchievements:function(callback){this.prepareAchievements(!0,callback)},requestAchievements:function(callback,userID){var me=this;this.prepareAchievements(!1,function(allAchievements,error){if(error)return void callback([],error);var apiCall=(userID||"me")+"/achievements";me.fb.api(apiCall,function(response){if(response.error)callback([],response.error);else{var achievements=[];if(response.data)for(var i=0;i<response.data.length;i++){var ach=me.findAchievement((response.data[i].achievement||response.data[i].data.achievement).id);ach&&achievements.push(ach)}callback(achievements,null)}})})},submitAchievement:function(achievementID,callback){if(null===achievementID||"undefined"==typeof achievementID)throw"No achievementID specified";var achID=this.translateAchievementID(achievementID),me=this;this.preparePublishAction(function(granted){granted?me.fb.api("me/achievements","POST",{achievement:achID},function(response){callback&&callback(response.error)}):callback&&callback({message:"No publish_actions permission granted"})})},resetAchievements:function(callback){var me=this;this.preparePublishAction(function(granted){granted?me.requestAchievements(function(achievements,error){if(error)return void(callback&&callback(error));for(var someError=null,remaining=achievements.length,i=0;i<achievements.length;++i)me.fb.api("me/achievements","DELETE",{achievement:achievements[i].fbAchievementData.url},function(response){response.error&&(someError=response.error),remaining--,0==remaining&&callback&&callback(someError)})}):callback&&callback({message:"No publish_actions permission granted"})})},showAchievements:function(callback){if(!this._achievementsTemplate)throw"Please, provide a html template for achievements with the setTemplates method";var dialog=new Cocoon.Widget.WebDialog,callbackSent=!1;dialog.show(this._achievementsTemplate,function(error){dialog.closed=!0,!callbackSent&&callback&&callback(error)});var me=this;this.requestAchievements(function(achievements,error){if(!dialog.closed){if(error)return callbackSent=!0,void(callback&&callback(error));var achs=[];if(me._cachedAchievements)for(var i=0;i<me._cachedAchievements.length;++i){var ach=me._cachedAchievements[i];if(achs.push(ach),achievements&&achievements.length)for(var j=0;j<achievements.length;++j)if(achievements[j].achievementID===ach.achievementID){ach.achieved=!0;break}}var js="addAchievements("+JSON.stringify(achs)+");";dialog.eval(js)}})}},Cocoon.extend(extension.SocialGamingServiceFacebook,extension.SocialGamingService),!(navigator.isCocoonJS||"undefined"!=typeof module&&module.exports)){var parent=document.getElementsByTagName("script")[0],script=document.createElement("script"),prot=location.protocol?location.protocol:"http:";script.src=prot+"//connect.facebook.net/en_US/all.js",parent.parentNode.insertBefore(script,parent)}return extension}),Cocoon.define("Cocoon.Multiplayer",function(extension){return extension.MultiplayerService=function(nativeExtensionName,extensionName){this.nativeExtensionName=nativeExtensionName,this.extensionName=extensionName,this.nativeAvailable=!!window.ext&&!!window.ext[this.nativeExtensionName];var me=this;this.onInvitationReceived=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onInvitationReceived"),this.onInvitationLoaded=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onInvitationLoaded",function(sourceListener,args){var matchID=args[0],error=args[1];matchID&&!error?(me.currentMatch=new Cocoon.Multiplayer.Match(me.nativeExtensionName,me.extensionName,matchID),sourceListener(me.currentMatch,null)):sourceListener(null,error)});var signal=new Cocoon.Signal.createSignal;return signal.register("invitation",{received:this.onInvitationReceived,loaded:this.onInvitationLoaded}),this.on=signal.expose(),this},extension.MultiplayerService.prototype={currentMatch:null,findMatch:function(matchRequest,callback){var me=this;this.nativeAvailable&&Cocoon.callNative(this.nativeExtensionName,"findMatch",[matchRequest,function(matchID,error){matchID&&!error?(me.currentMatch=new Cocoon.Multiplayer.Match(me.nativeExtensionName,me.extensionName,matchID),callback(me.currentMatch,null)):callback(null,error)}],!0)},findAutoMatch:function(matchRequest,callback){var me=this;this.nativeAvailable&&Cocoon.callNative(this.nativeExtensionName,"findAutoMatch",[matchRequest,function(matchID,error){matchID&&!error?(me.currentMatch=new Cocoon.Multiplayer.Match(me.nativeExtensionName,me.extensionName,matchID),callback(me.currentMatch,null)):callback(null,error)}],!0)},cancelAutoMatch:function(){this.nativeAvailable&&Cocoon.callNative(this.nativeExtensionName,"cancelAutoMatch",[],!0)},addPlayersToMatch:function(matchRequest,match,callback){this.nativeAvailable&&Cocoon.callNative(this.nativeExtensionName,"addPlayersToMatch",[matchRequest,match.matchID,callback],!0)},getMatch:function(){return this.currentMatch}},extension.Match=function(nativeExtensionName,extensionName,matchID){if("string"!=typeof nativeExtensionName)throw"The given native extension name '"+nativeExtensionName+"' is not a string.";if("string"!=typeof extensionName)throw"The given extension name '"+nativeExtensionName+"' is not a string.";this.nativeExtensionName=nativeExtensionName,this.extensionName=extensionName,this.nativeAvailable=Cocoon.nativeAvailable&&"undefined"!=typeof window.ext[nativeExtensionName],this.matchID=matchID;var me=this;this.onMatchDataReceived=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onMatchDataReceived",function(sourceListener,args){me.matchID===args[0]&&sourceListener(me,args[1],args[2])}),this.onMatchStateChanged=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onMatchStateChanged",function(sourceListener,args){me.matchID===args[0]&&sourceListener(me,args[1],args[2])}),this.onMatchConnectionWithPlayerFailed=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onMatchConnectionWithPlayerFailed",function(sourceListener,args){me.matchID===args[0]&&sourceListener(me,args[1],args[2])}),this.onMatchFailed=new Cocoon.EventHandler(this.nativeExtensionName,this.extensionName,"onMatchFailed",function(sourceListener,args){me.matchID===args[0]&&sourceListener(me,args[1])});var signal=new Cocoon.Signal.createSignal;signal.register("match",{dataReceived:this.onMatchDataReceived,stateChanged:this.onMatchStateChanged,connectionWithPlayerFailed:this.onMatchConnectionWithPlayerFailed,failed:this.onMatchFailed}),this.on=signal.expose()},extension.Match.prototype={start:function(){this.nativeAvailable&&Cocoon.callNative(this.nativeExtensionName,"startMatch",[this.matchID],!0)},sendDataToAllPlayers:function(data,sendMode){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"sendDataToAllPlayers",[this.matchID,data,sendMode]):void 0},sendData:function(data,playerIDs,sendMode){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"sendData",[this.matchID,data,playerIDs,sendMode]):void 0},disconnect:function(){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"disconnect",[this.matchID],!0):void 0},requestPlayersInfo:function(callback){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"requestPlayersInfo",[this.matchID,callback],!0):void 0},getExpectedPlayerCount:function(){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"getExpectedPlayerCount",[this.matchID]):void 0},getPlayerIDs:function(){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"getPlayerIDs",[this.matchID]):void 0},getLocalPlayerID:function(){return this.nativeAvailable?Cocoon.callNative(this.nativeExtensionName,"getLocalPlayerID",[this.matchID]):""}},extension.SendDataMode={RELIABLE:0,UNRELIABLE:1},extension.ConnectionState={UNKNOWN:0,CONNECTED:1,DISCONNECTED:2},extension.PlayerInfo=function(userID,userName){this.userID=userID,this.userName=userName},extension.MatchRequest=function(minPlayers,maxPlayers,playersToInvite,playerGroup,playerAttributes){return this.minPlayers=minPlayers,this.maxPlayers=maxPlayers,this.playersToInvite=playersToInvite,this.playerGroup=playerGroup,this.playerAttributes=playerAttributes,this},extension}),Cocoon.define("Cocoon.Multiplayer",function(extension){var loopbackServices=[],indexCounter=0,matchServices=[],matchCounter=0;extension.LoopbackService=function(){Cocoon.Multiplayer.LoopbackService.superclass.constructor.call(this,"dummy","dummy"),loopbackServices.push(this),this.playerID=""+indexCounter,indexCounter++},extension.LoopbackService.prototype={findMatch:function(request,callback){this.findMatchCallback=callback;for(var exists=!1,i=0;i<matchServices.length;++i)if(matchServices[i]===this){exists=!0;break}if(exists||matchServices.push(this),matchServices.length>=request.minPlayers){for(var playerIDs=[],i=0;i<matchServices.length;++i)playerIDs.push(matchServices[i].getPlayerID());for(var i=0;i<matchServices.length;++i){var match=new LoopbackMatch(matchServices[i]);match.playerIDs=playerIDs.slice(),matchServices[i].currentMatch=match,matchServices[i].findMatchCallback(match,null)}matchServices=[]}},findAutoMatch:function(matchRequest,callback){this.findMatch(matchRequest,callback)},cancelAutoMatch:function(){},addPlayersToMatch:function(matchRequest,match,callback){callback({message:"Not implemmented"})},getPlayerID:function(){return this.playerID},getMatch:function(){return this.currentMatch}},Cocoon.extend(extension.LoopbackService,extension.MultiplayerService);var LoopbackMatch=function(service){matchCounter++,LoopbackMatch.superclass.constructor.call(this,"","",matchCounter),this.started=!1,this.disconnected=!1,this.pendingData=[],this.service=service};return LoopbackMatch.prototype={start:function(){var me=this;setTimeout(function(){me.started=!0;for(var i=0;i<me.pendingData.length;++i)me.onMatchDataReceived.notifyEventListeners(me.matchID,me.pendingData[i].data,me.pendingData[i].player)},0)},sendDataToAllPlayers:function(data,sendMode){this.sendData(data,this.playerIDs,sendMode)},sendData:function(data,playerIDs){var me=this;setTimeout(function(){for(var i=0;i<loopbackServices.length;++i){for(var destService=null,j=0;j<playerIDs.length;++j)playerIDs[j]===loopbackServices[i].getPlayerID()&&(destService=loopbackServices[i]);destService&&destService.getMatch().notifyDataReceived(data,me.service.getPlayerID())}},0)},disconnect:function(){this.disconnected=!0;for(var i=0;i<this.playerIDs.length;++i)for(var p=this.playerIDs[i],j=0;j<loopbackServices.length;++j)if(loopbackServices[j].getPlayerID()===p){var match=loopbackServices[i].getMatch();match.disconnected||match.onMatchStateChanged.notifyEventListeners(match,this.service.getPlayerID(),Cocoon.Multiplayer.ConnectionState.DISCONNECTED)}},requestPlayersInfo:function(callback){var me=this;setTimeout(function(){for(var playersInfo=[],i=0;i<me.playerIDs.length;++i)playersInfo[i]={userID:me.playerIDs[i],userName:"Player"+me.playerIDs[i]};callback(playersInfo)},1)},getExpectedPlayerCount:function(){return 0},getPlayerIDs:function(){return this.playerIDs},getLocalPlayerID:function(){return this.service.playerID},notifyDataReceived:function(data,fromPlayer){this.started?this.onMatchDataReceived.notifyEventListeners(this.matchID,data,fromPlayer):this.pendingData.push({data:data,player:fromPlayer})}},Cocoon.extend(LoopbackMatch,Cocoon.Multiplayer.Match),extension}),Cocoon.define("Cocoon.Multiplayer",function(extension){return extension.GooglePlayGames=new Cocoon.Multiplayer.MultiplayerService("IDTK_SRV_MULTIPLAYER_GPG","Multiplayer.GooglePlayGames"),extension}),Cocoon.define("Cocoon.Multiplayer",function(extension){return extension.GameCenter=new Cocoon.Multiplayer.MultiplayerService("IDTK_SRV_MULTIPLAYER_GAMECENTER","Multiplayer.GameCenter"),extension});