$(document).ready(function(){
     if($.browser.msie && parseInt($.browser.version)<9){
        alert("Internet Explorer still don't support OpenType fonts. Please, update your browser.");
     }
    
    if ($("#abc").length>0){
        // view
        $("#editor-text").focus();
        var abcs = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 ! ? @ & … « » “ ” [ . : , ] - ( – — ) # * / € £ $ % ™".split(" ");               
        $.each(abcs, function(i, s){            
            $("#abc").append('<span id="char-'+s+'">'+s+'</span> ');           
        });    
        
        var shrdlu = get(window.location.search, "shrdlu");
        if (shrdlu.length>10){
            var etaoin = decodeFromHex(shrdlu);
            var color = get(etaoin, "color");
            var size = get(etaoin, "size");
            var text = get(etaoin, "text");
            // we got etaoinshrdlu!
            $("#abc").fadeOut(800);
            $("#text").animate({
                marginLeft: 80
            }, 1000, function(){
                $("#abc").remove();
            });
            $("#text").css("color", "#"+color).css("font-size", parseInt(size)).html(text);
            $("#editor-text").val(text); 
            $("#colorSelector").css("background-color", "#"+color);               
        } else {
            $("span[id^='char-']").mouseenter(function(){
                var symbol = $(this).html();
                $("#editor-text").val(symbol);
                $("#text").html(symbol);                  
                $(this).css("cursor", "e-resize");                
                $(this).click(function(){
                    $("#editor-text").focus();
                });
            });          
        }
    }

    // clicks
    $("#editor-text").keyup(function(){
        $("#text").text($("#editor-text").val());                
        if ($("#editor-text").val().length>2){
            $("#abc").fadeOut(800);
            $("#text").animate({
                marginLeft: 80
            }, 1000, function(){
                $("#abc").remove();
            });
        }
    });
    $("#editor-plus").click(function(){
        var newsize = parseInt($("#text").css("font-size").replace("px", "")) +10;
        $("#text").css("font-size", newsize );        
    });
    $("#editor-minus").click(function(){
        var newsize = parseInt($("#text").css("font-size").replace("px", "")) -10;
        $("#text").css("font-size", newsize);
    });    
    $("#editor-save").click(function(){
        var text = $("#editor-text").val(); 
        var textToSave = trim(text);        
        if (textToSave=="") {
            return false
        }
        $(this).val("Saving...");
        text = trim(textToSave.replace('"', ""));
        var color = rgb2hex($("#text").css("color"));
        var size = $("#text").css("font-size").replace("px", "");        
        var domain = "http://" + window.location.host + window.location.pathname;
        var etaoin = "?shrdlu=";
        var shrdlu = encodeToHex("?text="+text+"&color="+color+"&size="+size);
        shortURL(domain + etaoin + shrdlu); 
    });
    $(".background").click(function(){        
        var newAlign = "justify";
        var actualAlign = $(".background").css("text-align");
        if (actualAlign == "justify"){
            newAlign = "left";
        } else if (actualAlign == "left"){
            newAlign = "center";
        }            
        $(".background").css("text-align", newAlign);
    });
    
});

function get(from, name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec(from);
    if( results == null )
        return "";
    else
        return results[1];
}

function rgb2hex(rgb){
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    return ""+
    ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}

function shortURL(longUrl){
    console.log(longUrl);
    var defaults = {
        version:    '2.0.1',
        login:      'rafpolo',
        apiKey:     'R_47e16ee73807ab1f047d4dcc75711f02',
        history:    '0'
    };

    var api = "http://api.bit.ly/shorten?"
    +"version="+defaults.version
    +"&longUrl="+encodeURIComponent(longUrl)
    +"&login="+defaults.login
    +"&apiKey="+defaults.apiKey
    +"&history="+defaults.history
    +"&format=json&callback=?";

    // Utilize the bit.ly API
    $.getJSON(api, function(data){                       
        for (var key in data.results) {
            var shortURL = data.results[key].shortUrl
        }
        $("#editor-short").fadeIn(1000);
        $("#editor-link").html("<a class='shortLink' href='"+shortURL+"'>"+shortURL+"</a>");
        $("#editor-save").val("Save");
    });
}

function trim(str){
    return str==null ? "" : str.replace(/^\s+|\s+$/g,"").replace(/\s+/, " ");
}
function encodeToHex(str){
    var r="";
    var e=str.length;
    var c=0;
    var h;
    while(c<e){
        h=str.charCodeAt(c++).toString(16);
        while(h.length<3) h="0"+h;
        r+=h;
    }
    return r;
}
function decodeFromHex(str){
    var r="";
    var e=str.length;
    var s;
    while(e>=0){
        s=e-3;
        r=String.fromCharCode("0x"+str.substring(s,e))+r;
        e=s;
    }
    return r;
}

function fundirTipos(tipos){
    $(document).ready(function(){
        $.each(tipos, function(i, tipo){
            var id = tipo.toLowerCase();        
            $("#tipos").append("<a id='"+id+"' href='font-"+id+"'>"+id.toUpperCase()+"</a>");
            if (tipos.length > i+1){ // not at last
                $("#tipos").append(" / ");
            }
        });
        
    });
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-3761913-14']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();

