$(function(){
    
    var p_low = 15;
    var p_high = 15;
    
    clicked = false;
    
    $("#phrase .linkout").hide();

	// sort out the hash
	/*if (location.hash!="#" && location.hash!="" && location.hash!=null)
		var hash=location.hash.substr(1);
    
    if (hash)
        phrase_cycle_to(hash);
    else*/
        phrase_cycle(p_low+Math.floor(Math.random()*p_high));

    $("#phrase_refresh").click(function() {
        clicked = true;
        phrase_cycle(p_low+Math.floor(Math.random()*p_high));
        return false;
    });

});

function phrase_apply(n) {
    $('#phrase').html(phrases[n].h3+phrases[n].h4+phrases[n].link);
}

function phrase_apply_by_id(id) {
    applied = false;
    $.each(phrases, function(i) {
        if (id == this.id) {
            phrase_apply(i);
            applied = true;
            return false;
        }
    });
    if (!applied) { phrase_cycle(10); }
}

function phrase_cycle(i) {
    if (i<1) {
        //if (clicked) { location.hash = $("#phrase_n").attr("href"); }
        $("#phrase .linkout").fadeIn();
        init_tips();
        return false;
    }
    phrase_n = Math.floor(Math.random()*phrases.length);
    phrase_apply(phrase_n);
    setTimeout('phrase_cycle('+(i-1)+')',50);
}
function phrase_cycle_to(n) {
    if (!/^\d+$/.test(n)||n<0) { phrase_cycle(10); }
    phrase_apply_by_id(n);
    $("#phrase .linkout").fadeIn();
    init_tips();
}
function init_tips() {
    $("#phrase .linkout").aToolTip({ fixed: true, xOffset: -200, yOffset: 5 });
    //$("#phrase_n").aToolTip({ fixed: true, xOffset: -214, yOffset: 5 });
}

