$(document).ready(function () {
	$("span.rstar").hover(function (e) {
        var tips = {
            0 : 'Poor',
            1 : 'Below Average',
            2 : 'Average',
            3 : 'Good',
            4 : 'Excellent'
        }
		$('body').append('<div id="valuableTip" class="valuableTip"></div>');
        $('#valuableTip').text(tips[$(this).prevAll('.rstar').length]).css({'top' : e.pageY + 10, 'left' : e.pageX + 10}).fadeIn('fast');
    },
	function () {
		$("#valuableTip").remove();
    });

	$("span.rstar").mousemove(function (e) {
		$("#valuableTip").css({'top' : e.pageY + 10, 'left' : e.pageX + 10});
	});

    $('input.findTitle').autocomplete('/jax/index.php/api/title20', {
        width: 400,
        selectFirst: false,
        minChars: 3,
        delay: 200,
        mustMatch: true,
        extraParams: {
            apiKey: '8118b4b754aff98d81a2ed64df5508c97fa81a7b',
            method: 'findTitles'
        }
    });

    $('input.findTitle').result(function(event, data, formatted) {
        if (data) {
            // This implementation doesn't allow the use of more than one of these
            // fields in each form, but it works with HTML_Quickform.
            $(this).parents('form').find('input.findTitleID').val(data[1]);

            // This implementation is better, but it requires the target field to
            // immediately follow the autocomplete field.  This doesn't work with
            // HTML_Quickform because hidden fields are always placed at the top
            // of the form.

            //$(this).next('input.findTitleID').val(data[1]);
        }
    });
});

function popUp(URL,width,height,resize,scroll)
{
  if (typeof(width)=="undefined") {
  var width = 400;
  }
  if (typeof(height)=="undefined") {
  var height = 400;
  }
  if (typeof(resize)=="undefined") {
  var resize = 1;
  }
  if (typeof(scroll)=="undefined") {
  var scroll = 1;
  }

  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=' + scroll + ',location=0,statusbar=0,menubar=0,resizable=' + resize + ',width=' + width + ',height=' + height);");
}

function orderPopUp(URL,width,height)
{
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=1,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=' + width + ',height=' + height);");
}

function do_delete(url,msg)
{
  var agree=confirm(msg);
  if (agree)
  {
    location = url;
  }
}

$('#addFavorite').click(function() {
    var username = $(this).attr('title');
    var id = $(this).attr('rel');
    var type = $(this).attr('type');

    $('#addFavorite').parent().hide();
    $('#loader').show();

    $.get('/api/enotes/1.0/addFavorite?id=' + id + '&type=' + type, function(response) {
        if ($('error', response).text().length > 0) {
            alert('Error: ' + $('error', response).text());
            return false;
        }

    $('#addFavorite').parent().empty().html('<a href="/people/' + username + '">Your favorites</a> have been updated!').fadeIn('slow');

    $('#loader').hide();

    });
    return false;
});

$('a.deleteFavorite').click(function() {
    var id = $(this).attr('rel');
    var type = $(this).attr('type');
    $.get('/api/enotes/1.0/removeFavorite?id=' + id + '&type=' + type, function(response) {
        if ($('error', response).text().length > 0) {
            alert('Error: ' + $('error', response).text());
            return false;
        }

    });

    $(this).parent().empty().html("Removed. Thank you.");
    return false;
});

jQuery.fn.istars = function(callback) {
    $(this).attr('score', $(this).children('span.s').size());
    if (callback) {
        $(this).each(function()
        {
            this.callback = callback;
        });
    }

    $('span', this).hover(function()
    {
        // Locked? Do nothing.
        if ($(this).parent().is('.locked')) {
            return false;
        }

        // Find the current score
        var score = $('span', this.parentNode).index(this) + 1;

        // Set the score.
        $(this).parent().attr('currentScore', score);

        // Update star display
        $('span', this.parentNode).removeClass('s').slice(0, score).addClass('s');

    }, function()
    {
        // Revert to the saved score
        var ss = $(this).parent().attr('score');
        $('span', this.parentNode).removeClass('s').slice(0, ss).addClass('s');

    }).click(function(e) {

        //locked?
        if ($(this).parent().is('.locked')) {
            return false;
        }

        //hide
        $(this).parent().hide();

        //lock
        $(this).parent().addClass('locked');

        // call the callback
        if (this.parentNode.callback) {
            this.parentNode.callback(
                $(this).parent().attr('currentScore'),
                this.parentNode
            );
        }

        var vs = $(this).parent().siblings("input.votes").val(); //total votes
        var ts = $(this).parent().siblings("input.tscore").val(); //total score

        // Explicitly set these values to 0 if there are no .votes or .tscore elements to match above.
        // This is necessary because val() returns undefined instead of null in this circumstance as of jQuery 1.2. -pd
        vs = vs ? Number(vs) : 0;
        ts = ts ? Number(ts) : 0;

        //if they haven't voted adjust counts
        if ($(this).parent().siblings("input.avoted").val() == 0) {
            var vs = vs + 1;
            var ts = ts + Number($(this).parent().attr('currentScore'));

            var us = Math.round((ts / vs) * 10)/10; //average rounded to 1 decimal
            var ns = Math.round(us); //average integer to reset star

            //set to new average score and append text
            $(this).parent().attr('score', ns);
            var msg = 'Thank you. (' + vs + ' votes, average ' + us + ' of 5)';
        } else {
            var msg = "You've already voted!"; //message after voting
        }

        $('#valuableTip').text(msg).css({'top' : e.pageY + 10, 'left' : e.pageX + 10}).fadeIn('fast').attr('id', 'stickyTip');
        setTimeout(function () { $('#stickyTip').fadeOut(); }, 1500);

        //now show
        $(this).parent().fadeIn("slow");

        return false;
    });
};

jQuery.fn.charsLimit = function(id, max) {
    this.each(function() {
        $(this).keyup(function() {
            var remaining = (max - $(this).val().length);
            if (remaining < 0) {
                $(this).val($(this).val().substring(0, max));
                remaining = 0;
            }

            $(id).empty().append(remaining);
        });
    });

    return this;
};
