if (typeof(AC) === "undefined") {
    MNML = {}
}

MNML.Detector = {
    getAgent: function () {
        return navigator.userAgent.toLowerCase()
    },
    isWebKit: function (b) {
        if (this._isWebKit === undefined) {
            var a = b || this.getAgent();
            this._isWebKit = !! a.match(/AppleWebKit/i);
            this.isWebKit = function () {
                return this._isWebKit
            }
        }
        return this._isWebKit
    },
    isiPhone: function (b) {
        var a = b || this.getAgent();
        return this.isMobile(a)
    },
    isiPad: function (b) {
        var a = b || this.getAgent();
        return !!(this.isWebKit(a) && a.match(/ipad/i))
    },
    isMobile: function (b) {
        var a = b || this.getAgent();
        return this.isWebKit(a) && (a.match(/Mobile/i) && !this.isiPad(a))
    },
}


var smilies = [":D", ":]", ":)", ":P", ":[", ":(", ":|"]
function get_smilie(){
    return smilies[Math.floor(Math.random() * smilies.length)];
}
function redrawLogo(which){
    var color = "#000"
    if(which){
        color = "#fff";
    }
    drawLogo(color)
}
function drawLogo(color){
    var canvas = $("#⠇⠕⠛⠕").get(0);
    var context = canvas.getContext('2d');
    context.restore()
    context.save();
    context.clearRect(0, 0, canvas.width, canvas.height)
    context.fillStyle = color;
    context.scale(2,1.3)
    context.scale(.8, .8)
    context.translate(0, 9);
    context.fillRect(0, 0, 7, 23);
    context.fillRect(11, 0, 7, 23);
    context.fillRect(22, 0, 7, 23);
    context.fillRect(33, -9, 7, 32);
    context.fillRect(44, 0, 7, 32);
}

var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']; 
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
var th = ['','thousand','million', 'billion','trillion'];

function toWords(s){
    s = s.toString(); s = s.replace(/[\, ]/g,''); if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i=0; i < x; i++) {if ((x-i)%3==2) {if (n[i] == '1') {str += tn[Number(n[i+1])] + ' '; i++; sk=1;} else if (n[i]!=0) {str += tw[n[i]-2] + ' ';sk=1;}} else if (n[i]!=0) {str += dg[n[i]] +' '; if ((x-i)%3==0) str += 'hundred ';sk=1;} if ((x-i)%3==1) {if (sk) str += th[(x-i-1)/3] + ' ';sk=0;}} if (x != s.length) {var y = s.length; str += 'point '; for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';} return str.replace(/\s+/g,' ');}

window.done = function(j){
    $("#✌").attr("href", "http://twitter.com/#search?q="+j.url).text(toWords(j.count));
    $("#⚡").fadeIn(300);
};

function getTweets(){
    var url = "http://mnmly.com";
    $.getScript('http://urls.api.twitter.com/1/urls/count.json?url='+url+'&callback=done');
}

function updateLocation(position){
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var accuracy = position.coords.accuracy;
    var timestamp = position.timestamp;
    console.log(latitude, longitude, accuracy, timestamp);
    var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latitude+","+longitude + "&sensor=true"
    $.ajax({
        url: url,
        type: "GET",
        complete: function(data){  
            console.log(data.responseText);
        }
    })}

function updateStatus(str){
    console.log(str);
}

function handleLocationError(error){
    switch (error.code) {
        case 0: 
            updateStatus("There was an error while retrieving your location: " + error.message);
        break;
            case 1: updateStatus("The user prevented this page from retrieving a location.");
        break;
        case 2:
            updateStatus("The browser was unable to determine your location: " + error.message);
        break;
        case 3:
            updateStatus("The browser timed out before retrieving the location.");
        break;
    }
}

function getPosition() {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError);
    } else {
        return false;
    }
}


function detectAppleProducts(){
    if(MNML.Detector.isiPhone() || MNML.Detector.isiPad()){
        $("#⚐").removeAttr('id', '⚐');
    }else{
        console.log('nope');
    }
}

$(document).ready(function(){
    //    getPosition()
    
    detectAppleProducts();

    drawLogo("#000");

    getTweets();
    $("#☺").text(get_smilie()); 

    $("a[href=#☹]").click(function(){
      if ( $('body').hasClass('☹') ){
        $('#◌').fadeOut(300, function(){
          $('body').removeClass('☹');
        });
      } else{ 
        $('body').addClass('☹');
        $('#◌').fadeIn(300);
      }
        return false;
    });

    $("#☝").click(function(){
        $('#◌').fadeOut(300, function(){
            $('body').removeClass('☹')
        
        });
        return false; 
    });

    $("#☺").click(function(){
        $(this).removeAttr("title")
        $(this).text(get_smilie());
        if($(this).text()==":D"){
            $(this).attr("title", "Personally, I like this guy the best");
        }
        return false;
    });

    // baby
    $("#⚇").click(function(){
        $("figure").css({'display':'block', 'opacity':0, 'height':0}).animate({opacity: 1, height:180}, 300);
        $(this).unbind("click").bind("click", function(){
            return false
        });
        return false;
    })

    $("#⠇⠕⠛⠕").css({'left': $("# p").offset().left - 90});

    $("#⠇⠕⠛⠕").click(function(){
        $("body").toggleClass("☯");
        redrawLogo($("body").is(".☯"))
        return false;
    })

    $(window).resize(function(){
        $("#⠇⠕⠛⠕").css({'left': $("# p").offset().left - 90});
    })
});

