
// Objects
var clicker;
var text;
var loserOverlay;
var menuOverlay;
var heartRespawn;
var livesCounter;
var settingsOverlay;
var storeOverlay;
var admobid = {};
var lang = 'en';
var blueInRow = 1;
// Sounds
var tapSound;
var tapSound2;
var achievementSound;
var errorSound;
var purchaseSound;

// State
var playing = false;
var lastClickTime;
var lostTime;
var canRespawn = true;
var score = 0;
var colour = 0; //0 - blue, 1 - red, 2 - green
var heartClippingY = 0;
var numberOfGames = 0;


// Translations
var langStrs = {
    "en":{
        "playButton": "Play",
        "shareButton":"Share",
        "storeButton":"Store",
        "settingsButton":"Settings",
        "freeLife":"1 free life!",
        "watchVideo":"Watch video",
        "loading":"Loading...",
        "textlabel":"Click?",
        "loseReason":"You lost!",
        "loserScore":"You scored <a>0</a> points",
        "heartExplanation":"(Tap heart to continue this game)",
        "shareHighscore":"Share highscore!",
        "shareScore":"Share score",
        "goToMenu":"Menu",
        "goBack":"Back",
        "soundButton":"&nbsp Sound &nbsp",
        "buy":"Buy ",
        "highscore":"New highscore!",
        "points":" points!",
        "notRed":"Not red!",
        "tooSlow":"Too slow!",
        "removeAds":"Remove ads in the store!",
        "description":"Just press the button",
        "shareTitle":"New Clicky score!",
        "shareDescription1":"I got ",
        "shareDescription2":" points in Clicky! How many can you get?",
        "highscoreText":"Highscore: <span>0</span> points",
        "credits":"Credits"
    },
    "fr":{
        "playButton": "Jouer",
        "shareButton":"Partager",
        "storeButton":"Magasin",
        "settingsButton":"Options",
        "freeLife":"1 vie gratuite!",
        "watchVideo":"Regarder la vidéo",
        "loading":"Chargement...",
        "textlabel":"Cliquez",
        "loseReason":"Vous avez perdu!",
        "loserScore":"Vous avez obtenu <a>0</a> points",
        "heartExplanation":"(Appuyez sur le coeur pour continuer)",
        "shareHighscore":"Partagez highscore!",
        "shareScore":"Partagez score",
        "goToMenu":"Menu",
        "goBack":"Retour",
        "soundButton":"&nbsp Son &nbsp",
        "buy":"Acheter ",
        "highscore":"Nouveau highscore!",
        "points":" points!",
        "notRed":"Pas rouge!",
        "tooSlow":"Trop lent!",
        "removeAds":"Enlevez les pubs au magasin!",
        "description":"Appuyez sur le bouton",
        "shareTitle":"Nouveau score Clicky!",
        "shareDescription1":"J'ai eu ",
        "shareDescription2":" points sur Clicky! Peux-tu faire mieux?",
        "highscoreText":"Highscore: <span>0</span> points",
        "credits":"Infos"
    },
    "es":{
        "playButton": "Jugar",
        "shareButton":"Compartir",
        "storeButton":"Tienda",
        "settingsButton":"Ajustes",
        "freeLife":"¡1 vida gratis!",
        "watchVideo":"Ve el vídeo",
        "loading":"Cargando...",
        "textlabel":"Click?",
        "loseReason":"Perdiste",
        "loserScore":"Has obtenido <a>0</a> puntos",
        "heartExplanation":"(Pulsa el corazón para continuar)",
        "shareHighscore":"¡Compartir récord!",
        "shareScore":"Compartir puntuación",
        "goToMenu":"Menú",
        "goBack":"Atrás",
        "soundButton":"&nbsp Sonido &nbsp",
        "buy":"Comprar ",
        "highscore":"¡Nuevo récord!",
        "points":" puntos",
        "notRed":"¡Rojo no!",
        "tooSlow":"¡Muy lento!",
        "removeAds":"¡Quita los anuncios en la tienda!",
        "description":"Pulsa el botón",
        "shareTitle":"¡Nuevo resultado en Clicky!",
        "shareDescription1":"¡He sacado ",
        "shareDescription2":" puntos en Clicky! ¿Puedes superarlo?",
        "highscoreText":"Récord: <span>0</span> puntos",
        "credits":"Créditos"
    }
}

//Ads
/*var isPendingInterstitial = false;
var isAutoshowInterstitial = false;

function prepareInterstitialAd() {
    if (!isPendingInterstitial) { // We won't ask for another interstitial ad if we already have an available one
        admob.requestInterstitialAd({
            autoShowInterstitial: isAutoshowInterstitial
        });
    }
}
function onAdLoadedEvent(e) {
    if (e.adType === admob.AD_TYPE.INTERSTITIAL && !isAutoshowInterstitial) {
        isPendingInterstitial = true;
    }
}
function showInterstitialAd() {
    if (isPendingInterstitial) {
        admob.showInterstitialAd(function () {
                isPendingInterstitial = false;
                isAutoshowInterstitial = false;
                prepareInterstitialAd();
        });
    } else {
        // The interstitial is not prepared, so in this case, we want to show the interstitial as soon as possible
        isAutoshowInterstitial = true;
        admob.requestInterstitialAd({
            autoShowInterstitial: isAutoshowInterstitial
        });
    }
}*/

document.addEventListener("deviceready", onReady, false);

// Load

function load(){
    // Internationalization
    document.getElementById('playButton').innerHTML = langStrs[lang]["playButton"]
    document.getElementById('shareButton').innerHTML = langStrs[lang]["shareButton"]
    document.getElementById('storeButton').innerHTML = langStrs[lang]["storeButton"]
    document.getElementById('settingsButton').innerHTML = langStrs[lang]["settingsButton"]
    var loadingTitles = document.querySelectorAll('#storeOverlay .title')
    for(var i = 0; i < loadingTitles.length; i++){
        loadingTitles[i].innerHTML = langStrs[lang]["loading"]
    }
    document.querySelector('#freeLife .title').innerHTML = langStrs[lang]["freeLife"]
    document.getElementById('watchVideo').innerHTML = langStrs[lang]["watchVideo"]
    document.getElementById('textlabel').innerHTML = langStrs[lang]["textlabel"]
    document.getElementById('loseReason').innerHTML = langStrs[lang]["loseReason"]
    document.getElementById('loserScore').innerHTML = langStrs[lang]["loserScore"]
    document.getElementById('heartExplanation').innerHTML = langStrs[lang]["heartExplanation"]
    document.getElementById('newScore').innerHTML = langStrs[lang]["newScore"]
    document.getElementById('loserGoToMenu').innerHTML = langStrs[lang]["goToMenu"]
    document.getElementById('storeGoToMenu').innerHTML = langStrs[lang]["goToMenu"]
    document.getElementById('settingsGoToMenu').innerHTML = langStrs[lang]["goToMenu"]
    document.getElementById('storeGoToGame').innerHTML = langStrs[lang]["goBack"]
    document.getElementById('storeGoToLoser').innerHTML = langStrs[lang]["goBack"]
    document.getElementById('soundButton').innerHTML = langStrs[lang]["soundButton"]
    document.getElementById('highscoreText').innerHTML = langStrs[lang]["highscoreText"]
    document.getElementById('creditsButton').innerHTML = langStrs[lang]["credits"]
    // Game
    if(localStorage["lives"] == undefined){
        localStorage["lives"] = 3 //3 lives to start with
    }
    if(localStorage["sound"] == undefined){
        localStorage["sound"] = "true";   
    }
    if(localStorage["showAds"] == undefined){
        localStorage["showAds"] = "true";   
    }
    if(localStorage["highscore"] == undefined){
        localStorage["highscore"] = "0";   
    }
    livesCounter = document.getElementById('lives')
    livesCounter.querySelector('#livesCounter').innerHTML = localStorage["lives"]
    clicker = document.getElementById('clicker');
    text = document.getElementById('textlabel');
    loserOverlay = document.getElementById('loserOverlay')
    menuOverlay = document.getElementById('menuOverlay')
    heartRespawn = document.getElementById('heartRespawn')
    settingsOverlay = document.getElementById('settingsOverlay')
    storeOverlay = document.getElementById('storeOverlay')
    try{
        document.createEvent("TouchEvent")
        clicker.addEventListener('touchstart',click,false) 
        loserOverlay.addEventListener('touchstart',restart,false)
        loserOverlay.querySelector("#loserGoToMenu").addEventListener('touchstart',menu,true)
        menuOverlay.querySelector('#playButton').addEventListener('touchstart',restart,false)
        menuOverlay.querySelector('#storeButton').addEventListener('touchstart',goToStore,false)
       'buy' //menuOverlay.querySelector('#highscoreButton').addEventListener('touchstart',goToHighscores,false)
        menuOverlay.querySelector('#settingsButton').addEventListener('touchstart',goToSettings,false)
        document.getElementById('shareButton').addEventListener('touchstart',share,false)
        heartRespawn.addEventListener('touchstart',respawn,false)
        livesCounter.addEventListener('touchstart',goToStore,false)
        settingsOverlay.querySelector('#soundButton').addEventListener('touchstart',toggleSound,false)
        settingsOverlay.querySelector('#settingsGoToMenu').addEventListener('touchstart',menu,false)
        storeOverlay.querySelector('#storeGoToMenu').addEventListener('touchstart',menu,false)
        storeOverlay.querySelector('#storeGoToGame').addEventListener('touchstart',continueGame,false)
        storeOverlay.querySelector('#storeGoToLoser').addEventListener('touchstart',goToLoser,false)
        document.getElementById('newScore').addEventListener('touchstart',shareScore,false)
        document.getElementById('creditsButton').addEventListener('touchstart',openCredits,false)
        document.getElementById('creditsOverlay').addEventListener('touchstart',closeCredits,false)
        var freelife = document.getElementById('freelife').addEventListener('touchstart',function(){
            if(videoTimeLeft <= 0){
                AdMob.showRewardVideoAd();
                videoTimeLeft = 90
                videoRewardCountdown()
                setTimeout(function(){
                    AdMob.prepareRewardVideoAd({adId:"ca-app-pub-5926997736584944/8707157712", autoShow:false, isTesting: false})
                }, 1000)
            }
        },false)
        document.addEventListener('onAdPresent', 
            function(data){ 
                if(data.adType == 'rewardvideo') { 
                    //alert( data.rewardType ); 
                    //alert( data.rewardAmount ); 
                    localStorage["lives"] = parseInt(localStorage["lives"]) + 1
                    livesCounter.querySelector('#livesCounter').innerHTML = localStorage["lives"]
                } 
            });
    }
    catch (e){
        clicker.addEventListener('mousedown',click,false) 
        loserOverlay.addEventListener('mousedown',restart,false)
        loserOverlay.querySelector("#loserGoToMenu").addEventListener('mousedown',menu,true)
        menuOverlay.querySelector('#playButton').addEventListener('mousedown',restart,false)
        //menuOverlay.querySelector('#highscoreButton').addEventListener('mousedown',goToHighscores,false)
        menuOverlay.querySelector('#settingsButton').addEventListener('mousedown',goToSettings,false)
        menuOverlay.querySelector('#storeButton').addEventListener('mousedown',goToStore,false)
        document.getElementById('shareButton').addEventListener('mousedown',share,false)
        heartRespawn.addEventListener('mousedown',respawn,false)
        livesCounter.addEventListener('mousedown',goToStore,false)
        settingsOverlay.querySelector('#soundButton').addEventListener('mousedown',toggleSound,false)
        settingsOverlay.querySelector('#settingsGoToMenu').addEventListener('mousedown',menu,false)
        storeOverlay.querySelector('#storeGoToMenu').addEventListener('mousedown',menu,false)
        storeOverlay.querySelector('#storeGoToGame').addEventListener('mousedown',continueGame,false)
        storeOverlay.querySelector('#storeGoToLoser').addEventListener('mousedown',goToLoser,false)
        document.getElementById('newScore').addEventListener('mousedown',shareScore,false)
        document.getElementById('creditsButton').addEventListener('mousedown',openCredits,false)
        document.getElementById('creditsOverlay').addEventListener('mousedown',closeCredits,false)
    }
}

function onReady(){
    // Let's try to contact the store
    try{
        store.register({
          id: "20lives",
          alias: "20 lives",
          type: store.CONSUMABLE
        });
        store.register({
          id: "50lives",
          alias: "50 lives",
          type: store.CONSUMABLE
        });
        store.register({
          id: "200lives",
          alias: "200 lives",
          type: store.CONSUMABLE
        });
        store.register({
          id: "removeads",
          alias: "Remove ads",
          type: store.NON_CONSUMABLE
        });
        store.when("20lives").updated(refreshStore);
        store.when("50lives").updated(refreshStore);
        store.when("200lives").updated(refreshStore);
        store.when("removeads").updated(refreshStore);
        store.when("20lives").approved(function(product) {
            localStorage["lives"] = parseInt(localStorage["lives"]) + 20
            document.getElementById('livesCounter').innerHTML = localStorage["lives"]
            product.finish();
            playSound("purchase")
        });
        store.when("50lives").approved(function(product) {
            localStorage["lives"] = parseInt(localStorage["lives"]) + 50
            document.getElementById('livesCounter').innerHTML = localStorage["lives"]
            product.finish();
            playSound("purchase")
        });
        store.when("200lives").approved(function(product) {
            localStorage["lives"] = parseInt(localStorage["lives"]) + 200
            document.getElementById('livesCounter').innerHTML = localStorage["lives"]
            product.finish();
            playSound("purchase")
        });
        store.when("removeads").approved(function(product) {
            localStorage["showAds"] = "false"
            product.finish();
            try{
                AdMob.hideBanner();
                AdMob.removeBanner();
            }
            catch(e){}
            playSound("purchase")
        });
        store.refresh();
    }
    catch(e){}
    // Sounds
    try{
        tapSound = new Media("file:///android_asset/www/sounds/tap.ogg");
        tapSound2 = new Media("file:///android_asset/www/sounds/tap2.ogg");
        achievementSound = new Media("file:///android_asset/www/sounds/achievement.mp3");
        errorSound = new Media("file:///android_asset/www/sounds/error.mp3");
        purchaseSound = new Media("file:///android_asset/www/sounds/purchase.mp3");
    }
    catch(e){}
    // Ads
    /*if(localStorage["showAds"] == "true"){
        admob.setOptions({
            publisherId:          "ca-app-pub-5926997736584944/3066080116" ,  // Required
            interstitialAdId:     "ca-app-pub-5926997736584944/6019546518",  // Optional
        });
        document.addEventListener(admob.events.onAdLoaded, onAdLoadedEvent);
        prepareInterstitialAd();
        admob.createBannerView();
    }*/
    try{
        if(localStorage["showAds"] == "true"){
            admobid = {
                banner: 'ca-app-pub-5926997736584944/3066080116', 
                interstitial: 'ca-app-pub-5926997736584944/6019546518'
            };
            setTimeout(function(){
                AdMob.createBanner({
                    isTesting: false,
                  adId: admobid.banner,
                  position: AdMob.AD_POSITION.BOTTOM_CENTER,
                  autoShow: true,
                    success: function(){
                        //alert('yeai')
                        //alert(AdMob.AD_POSITION.BOTTOM_CENTER)
                        AdMob.showBanner(AdMob.AD_POSITION.BOTTOM_CENTER)
                    },
                    error: function(){
                        //alert('failed to create banner');
                    }});
                AdMob.prepareInterstitial( {adId:admobid.interstitial, autoShow:false, isTesting: false} );
                AdMob.prepareRewardVideoAd({adId:"ca-app-pub-5926997736584944/8707157712", autoShow:false, isTesting: false}, function(){
                    //alert('yep')
                }, function(){
                    //alert('nope')
                });
            }, 50)
        }
        videoRewardCountdown()
    }
    catch(e){}
    try{
    navigator.globalization.getPreferredLanguage(function (language) {
            var language = language.value.split('-')[0]
            switch(language){
                case 'fr': lang = 'fr'; break;
                case 'de': lang = 'dr'; break;
                case 'es': lang = 'es'; break;
                case 'en': lang = 'en'; break;
                default: lang = 'en'; break;
            }
            load()
            setTimeout(function(){
                document.body.className = "menu"
            }, 2500)
            //alert(lang)
        })
        // Load the game
    }
    catch(e){}
}

// Store
function refreshStore(){
    // 20 lives
    try{
        var product20 = store.get("20lives");
        document.querySelector('#buy20lives .title').innerHTML = langStrs[lang]["buy"]+ product20.title.replace(/ *\([^)]*\) */g, "");
        document.querySelector('#buy20lives .price').innerHTML = product20.price
        document.querySelector('#buy20lives').addEventListener('touchstart',function(){
            store.order("20lives");
        },false)
    }
    catch(e){}
    // 50 lives
    try{
        var product50 = store.get("50lives");
        document.querySelector('#buy50lives .title').innerHTML = langStrs[lang]["buy"]+ product50.title.replace(/ *\([^)]*\) */g, "");
        document.querySelector('#buy50lives .price').innerHTML = product50.price
        document.querySelector('#buy50lives').addEventListener('touchstart',function(){
            store.order("50lives");
        },false)
    }
    catch(e){}
    // 200 lives
    try{
        var product200 = store.get("200lives");
        document.querySelector('#buy200lives .title').innerHTML = langStrs[lang]["buy"]+ product200.title.replace(/ *\([^)]*\) */g, "");
        document.querySelector('#buy200lives .price').innerHTML = product200.price
        document.querySelector('#buy200lives').addEventListener('touchstart',function(){
            store.order("200lives");
        },false)
    }
    catch(e){}
    // Remove ads
    try{
        var removeads = store.get("removeads");
        document.querySelector('#removeads .title').innerHTML = removeads.title.replace(/ *\([^)]*\) */g, "");
        document.querySelector('#removeads .price').innerHTML = removeads.price
        if(removeads.state == store.OWNED){
            localStorage["showAds"] = "false"
            document.querySelector('#removeads').classList.add("owned")
            AdMob.hideBanner();
            AdMob.removeBanner();
        }
        else{
            document.querySelector('#removeads').addEventListener('touchstart',function(){
                store.order("removeads");
            },false)
        }
    }
    catch(e){}
}


// Click
function click(){
    lastClickTime = new Date().getTime();
    // Blue and green buttons just let you go
    if(colour == 0 || colour == 2){
        score++
        if(parseInt(localStorage["highscore"])+1 == score && localStorage["highscore"] != "0"){
            logMessage(langStrs[lang]["highscore"])
            playSound("achievement")
        }
        playSound("tap")
        if(score == 25 || score == 50 || (score%100 == 0 && score!=0)){
            logMessage(score+langStrs[lang]["points"])
            playSound("achievement")
        }
        shuffle()
    }
    // Red buttons make you lose
    else if(colour == 1){
        lose(langStrs[lang]["notRed"]);
    }
    
}

// Logging messages
function logMessage(mssg, time){
    if(time==undefined){
        time = 1500
    }
    var messageDiv = document.getElementById('message')
    messageDiv.innerHTML = mssg
    messageDiv.style.color = "rgba(88,88,88,1)"
    messageDiv.style.top = "8%"
    setTimeout(function(){
        var messageDiv = document.getElementById('message')
        messageDiv.style.color = "rgba(88,88,88,0)"
        messageDiv.style.top = "-2%"
        setTimeout(function(){
            var messageDiv = document.getElementById('message')
            messageDiv.style.top = "13%"
        }, 800)
    }, time)
}

// Create a new button
function shuffle(){
    var x = Math.random();
    if(blueInRow>5){
        console.log("Capped blues")
        x = 0.8;
    }
    // Blue
    if(x < (0.3 + 0.45*Math.exp((-score) / 1200))){ 
        colour = 0 
        blueInRow++
    }
    // Red
    else if(x < (0.67 + 0.25*Math.exp((-score) / 900))){
        blueInRow = 0
        colour = 1
        setTimeout(function(){
            if(playing){
                colour = 0;
                update()
            }
        }, Math.min(Math.max(460 + 400*Math.exp((-score) / 100) - 30*Math.log(score) + (Math.random()-0.5)*200, 400), 900));
    }
    // Green
    else{ 
        blueInRow = 0
        colour = 2
        setTimeout(function(){ 
            var t = new Date().getTime();
            if(t - lastClickTime > Math.max(750 - 4*score, 350)){
                lose(langStrs[lang]["tooSlow"]);
            }
        }, Math.min(460 + 400*Math.exp((-score) / 100) - 30*Math.log(score), 900));
    }
    update()
}
// Update the screen
function update(){
    if(colour == 0){clicker.className = "button round-button blue"}
    if(colour == 1){clicker.className = "button round-button red"}
    if(colour == 2){clicker.className = "button round-button green"}
    if(score == 0){
        text.innerHTML = langStrs[lang]["textlabel"]
    }
    else{
        text.innerHTML = score;
    }
}

// UI
function lose(reason){
    if(parseInt(localStorage["highscore"]) < score && localStorage["highscore"] != 0){ // New Highscore
        document.getElementById('newScore').className = 'highscore'
        document.getElementById('newScore').innerHTML = langStrs[lang]["shareHighscore"]
    }
    else{ //Normal score
        document.getElementById('newScore').className = 'normalScore'
        document.getElementById('newScore').innerHTML = langStrs[lang]["shareScore"]
    }
    // Update highscore
    if(localStorage["highscore"] < score){
        localStorage["highscore"] = score
    }
    document.querySelector('#highScoretext span').innerHTML = localStorage["highscore"]
    playSound("error")
    playing = false;
    lostTime = new Date().getTime()
    console.log("You lost", score)
    document.body.className = "loser"
    loserOverlay.querySelector('#loseReason').innerHTML = reason
    loserOverlay.querySelector('a').innerHTML = score;
    // Start counting heart down
    if(canRespawn){
        heartClippingY = 0;
        heartRespawn.style['margin-top'] = heartClippingY+"px"
        heartRespawn.style['background-position-y'] = -heartClippingY+"px"
        heartRespawn.style['height'] = 100-heartClippingY+"px"
        document.getElementById("heartExplanation").style.color = "rgba(200,200,200,0.8)"
        setTimeout(respawnCountdown, 1200)
    }
    else{
        heartClippingY = 100;
        respawnCountdown();
    }
}
function restart(){
    var t = new Date().getTime();
    if((lostTime == undefined || t > lostTime+500) && playing==false){ //So that user doesn't restart unwillingly
        playing = true;
        score = 0
        colour = 0
        heartClippingY = 0
        canRespawn = true;
        update()
        document.body.className = "playing"
        numberOfGames++
        if(localStorage["showAds"] == "true" && numberOfGames%5 == 4){
            //showInterstitialAd()
            AdMob.showInterstitial();
            setTimeout(function(){
                AdMob.prepareInterstitial( {adId:admobid.interstitial, autoShow:false, isTesting: false} );
            }, 500)
            setTimeout(function(){
                logMessage(langStrs[lang]["removeAds"], 4000)
            }, 1000)
        }
    }
}
function menu(event){
    playing = false;
    event.stopPropagation();
    document.body.className = "menu"
}
function share(){
    facebookConnectPlugin.showDialog({
        method: "share",
        href: "https://play.google.com/store/apps/details?id=com.clicky.clicky",
        caption: "Clicky",
        description: langStrs[lang]["description"],
        picture: "https://lh6.googleusercontent.com/AJvJVPTZ-l89nHSggNa6gwtDofahCQCQujivDO2et5vi2tNxl4ybOQgLRk7qLXlFOXPMLlEC=w371",
        share_feedWeb: true, // iOS only
    }, function(){}, function(){})
}
var resCountdown;
function respawnCountdown(){
    if(heartClippingY < 95){
        heartClippingY += 1;
        heartRespawn.style['margin-top'] = heartClippingY+"px"
        heartRespawn.style['background-position-y'] = -heartClippingY+"px"
        heartRespawn.style['height'] = 100-heartClippingY+"px"
        
        //heartRespawn.style['clip-path'] = "inset("+heartClippingY+"px 0px 0px 0px)"
        //heartRespawn.style.webkitClipPath = "inset("+heartClippingY+"px 0px 0px 0px)"
        //heartRespawn.style['background-position-x'] = x+"px"
        resCountdown = setTimeout(respawnCountdown, 80)
    }
    else{ //You can't respawn anymore
        //heartRespawn.style['clip-path'] = "inset("+200+"px 0px 0px 0px)"
        //heartRespawn.style.webkitClipPath = "inset("+200+"px 0px 0px 0px)"
        heartRespawn.style['margin-top'] = 99+"px"
        heartRespawn.style['background-position-y'] = -99+"px"
        heartRespawn.style['height'] = 100-99+"px"
        canRespawn = false;
        document.getElementById("heartExplanation").style.color = "rgba(200,200,200,0)"
    }
}
function respawn(event){
    console.log('respawning')
    event.stopPropagation();
    if(parseInt(localStorage["lives"]) > 0){ //Still lives left
        if(canRespawn){
            // Continue from whenever we were with blue button
            playing = true;
            canRespawn = false
            colour = 0
            update()
            document.body.className = "playing"
            // Take one life off
            localStorage["lives"] = parseInt(localStorage["lives"]) - 1
            livesCounter.querySelector('#livesCounter').innerHTML = localStorage["lives"]
        }
    }
    else{ // Need to buy lives
        goToStore(undefined,true)
        heartClippingY = 0
        clearTimeout(resCountdown)
        heartRespawn.style['margin-top'] = 0+"px"
        heartRespawn.style['background-position-y'] = -0+"px"
        heartRespawn.style['height'] = 100-0+"px"
    }
}
function goToSettings(){
    document.body.className = "settings"
    if(localStorage["sound"] == "false"){
        settingsOverlay.querySelector("#soundButton").className = "offButton"
    }
    else{
        settingsOverlay.querySelector("#soundButton").className = ""
    }
}
function goToStore(event, backToLoser){
    document.body.className = "store"
    if(playing){
        storeOverlay.querySelector('#storeGoToMenu').style.display = "none"
        storeOverlay.querySelector('#storeGoToGame').style.display = "block"
        storeOverlay.querySelector('#storeGoToLoser').style.display = "none"
    }
    else if(backToLoser != undefined){
        storeOverlay.querySelector('#storeGoToMenu').style.display = "none"
        storeOverlay.querySelector('#storeGoToGame').style.display = "none"
        storeOverlay.querySelector('#storeGoToLoser').style.display = "block"
    }
    else{
        storeOverlay.querySelector('#storeGoToMenu').style.display = "block"
        storeOverlay.querySelector('#storeGoToGame').style.display = "none"
        storeOverlay.querySelector('#storeGoToLoser').style.display = "none"
    }
    keepRefreshingStore()
}
function keepRefreshingStore(){
    if(document.body.className == "store"){
        store.refresh()
        setTimeout(keepRefreshingStore, 1000)
    }
    else{
        store.refresh()
    }
}
function continueGame(){
    document.body.className = "playing"
}
function goToLoser(){
    document.body.className = "loser"
}
function toggleSound(){
    if(localStorage["sound"] == "false"){
        localStorage["sound"] = "true"
    }
    else{
        localStorage["sound"] = "false"
    }
    goToSettings()
}

// Sounds
function playSound(sound){
    try{
        if(localStorage["sound"] == "true"){
            if(sound == "tap"){
                if(score%2 == 0){
                    tapSound.seekTo(0)
                    tapSound.play()
                } else{
                    tapSound2.seekTo(0)
                    tapSound2.play();
                }
            }
            else if(sound =="achievement"){
                achievementSound.play()
            }
            else if(sound == "error"){
                errorSound.play()
            }
            else if(sound == "purchase"){
                purchaseSound.play()
            }
        }
    }
    catch(e){}
}

// High scores
/*function goToHighscores(){
    //alert(2)
    facebookConnectPlugin.login(["user_friends"], function(obj){
        //alert("Worked1")
       // localStorage["link"] = "https://graph.facebook.com/oauth/access_token_info?client_id=APPID&access_token="+obj["authResponse"]["accessToken"]
        //alert(localStorage["link"])
        //document.getElementById('soundButton').innerHTML=obj["authResponse"]["accessToken"]
    },
    function(str){
        //alert("Didn't work")
        //alert(str)
        //navigator.notification.alert("Facebook access is needed to get highscores.", function(){}, "Could not open highscores")
    })
}*/

function shareScore(event){
    event.stopPropagation();
    facebookConnectPlugin.showDialog({
        method: "share",
        href: "https://play.google.com/store/apps/details?id=com.clicky.clicky",
        caption: langStrs[lang]["shareTitle"],
        description: langStrs[lang]["shareDescription1"]+score+langStrs[lang]["shareDescription2"],
        quote: langStrs[lang]["shareDescription1"]+score+langStrs[lang]["shareDescription2"],
        share_feedWeb: true, // iOS only
    }, function(){}, function(){})
}

// Video reward countdown
var videoTimeLeft = 60
function videoRewardCountdown(){
    videoTimeLeft--
    if(videoTimeLeft>0){
        document.getElementById('videoCountdown').innerHTML = "(" + videoTimeLeft + "s)"
        setTimeout(videoRewardCountdown, 1000)
        document.getElementById('freelife').className="storeButton disabled"
    }
    else{
        document.getElementById('videoCountdown').innerHTML = ""
        document.getElementById('freelife').className="storeButton"
    }
}

// Credits
function openCredits(){
    document.body.className = "credits"
}
function closeCredits(){
    document.body.className = "settings"
}

