// leave the semicolon at the start!
;jQuery(function($){

    // handles response from server after voting
    var onVote = function(xhr) {
        // <ratingDisplay ceoId="123">
        //    <ratingCount>$display.ratingCount</ratingCount>
        //    <ratingMeanAverage>$display.ratingMeanAverage</ratingMeanAverage>
        //</ratingDisplay>

        /* @Dan: update following 3 vars so they pull from whatever the results are */
        //var count = parseInt( $("ratingCount", xhr).text() );
        var count = parseInt( jQuery("ratingCount", xhr).text() );
        //var count = parseInt( xhr.getElementsByTagName("ratingCount")[0].textContent );
        //var avg = parseFloat( $("ratingMeanAverage", xhr).text() );
        var avg = parseFloat( jQuery("ratingMeanAverage", xhr).text() );
        //var avg = parseFloat( xhr.getElementsByTagName("ratingMeanAverage")[0].textContent );
        //var ceoId = $("ratingDisplay", xhr).attr("ceoId");
        var ceoId = jQuery("ratingDisplay", xhr).attr("ceoId");
        //var ceoId = xhr.getElementsByTagName("ratingDisplay")[0].getAttribute("ceoId").textContent;
        // calc some values
        var avgInt = parseInt(avg);
        var half = (avg-avgInt >= 0.5);             
        // find raters for this ceoId
        var $raters = $('.rater.ceoId-'+ceoId);
        // now update results
        $raters
            .find('.value')
            .text(count) // number of votes
            .end()
            .each(function(){
            $(this)
                .find('.results.images img') // find all the result images
                .each(function(idx){
                $(this)
                    .removeClass('on off half')
                    .addClass((idx<avgInt) ? 'on' : (idx==avgInt && half) ? 'half' : 'off');
                });
            })
            .find('.wait')
            .hide()
            .end()
            .find('.thanks,.links')
            .show();
    };

    // which events are we interested in?
    var events = 'click keydown mouseover mouseout focus blur';

    // which keys can be used to send a rating when a link has focus?
    var keys = {13:true, 32:true};

    // vars used to prevent flickering of images during interaction
    var timer, timerFn;

    // handles user clicking on a star
    var vote = function(event) {
        // what was the target of the event (eg. what was clicked)?
        var $target = $(event.target);
        // if target is an image, select it's parent
        if (!$target.is('a')) $target = $target.parent();
        // we're only interested in clicks on the links...
        if ($target.is('a')) {
            // do different stuff based on event
            switch (event.type) {
                // mouse moves over
                case 'mouseover':
                case 'focus':
                    clearTimeout(timer); // clear mouseout timer
                    if (!!timerFn) timerFn(); // trigger the fn to clear past state
                    $target
                        .prevAll('a')
                            .andSelf()
                                .addClass('over'); // highlight user selection
                    return false; // prevent default
                case 'mouseout':
                case 'blur':
                    timer = setTimeout(timerFn = function(){
                        $target
                            .siblings('a')
                                .andSelf()
                                    .removeClass('over');
                    },100);
                    return false; // prevent default
                case 'click':
                case 'keydown':
                    // if not a valid key, ignore
                    if (event.type == 'keydown' && !keys[event.which]) return;
                    // clear timer and the fn
                    clearTimeout(timer);
                    timerFn = null;
                    // work out ceo id
                    var classes = String($target.parents('.rater').eq(0).attr('class')).split(' ');
                    var x, ceoId;
                    $.each(classes,function(idx,val){
                        x = val.indexOf('-');
                        if (x > -1) ceoId = val.slice(x + 1);
                    });
                    // work out rating value (1 - 5)
                    var rating = $target.prevAll('a').length+1;
                    // find all raters with this ceoClass (there could be several on a page)
                    var $raters = $('.rater.ceoId-'+ceoId);
                    // unbind event handler, sink future events
                    $raters
                        .find('.links')
                            .unbind(events,vote);
                    // remove focus rect
                    $target.blur();
                    // Grab the URL split in two
                    var href = $target.attr('href').split('?');
                    // hide '.vote' and '.vote .caption', show '.vote .thanks' and '.wait'
                    $raters
                        .find('.vote')
                            .hide()
                            .find('.caption')
                                .hide()
                            .end()
                            .find('.thanks')
                                .show()
                            .end()
                            .addClass('disabled')
                        .end()
                        .each(function(){
                            // update classes on links to show users' vote
                            $(this)
                                .find('.links a') // find all the vote links
                                    // TODO: store this elsewhere so that we can re-reate (e.g. on error)
                                    // http://docs.jquery.com/Internals/jQuery.data
                                    .removeAttr('href') // kill the links (important!)
                                    .each(function(idx){
                                        $(this)
                                            .removeClass('over out')
                                            .addClass((idx<rating) ? 'over' : 'off');
                                    });
                        })
                        .find('.wait')
                        .show();
                    // Strip off "&amp;redirect=true" from the end of the URL
                    var boom = href[1].split('&');
                    boom.pop();
                    href[1] = boom.join("&");
                    // Send it on it's way
                    $.ajax( { type: "GET", url: href[0], data: href[1], success: onVote } );
                    /* @Dan: send your rating - vars are: rating, ceoId */
                    return false; // prevent default
            }
        }
    };

    $('.rater .links').bind(events,vote); // bind events to active raters

    /* below is just to test server response handler - vape this once your code is wired in */
    $('.testResponse').click(onVote);
});