
/*jslint indent:4 */
/*global $, document, console, alert, log, user_avatar_filename, record_event, window, jQuery, SC, following, answered, liked */

/* check if SHOW is actually defined, else initialize to all */
if (typeof window.SHOW === 'undefined') {
    window.SHOW = 'all';
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, start) {
        var i, j;
        for (i = (start || 0), j = this.length; i < j; i += 1) {
            if (this[i] === obj) { return i; }
        }
        return -1;
    };
}
var parse_question = function (api_question) {
    // console.log('Adding new q with timestamp', api_question.timestamp);

    return {'text': api_question.question,
            'timestamp': api_question.timestamp.replace('T', ' ').replace(':', ':'),
            'timestampiso': api_question.timestampiso.replace('T', ' ').replace(':', ':'),
            'timestamp_latest_answer': api_question.timestamp_latest_answer.replace('T', ' ').replace(':', ':'),
            'id': api_question.id,
            'username': api_question.asker.username,
            'userid': api_question.asker.id,
            'avatarfilename': api_question.asker.sellerprofile.avatar.filename,
            'answers': api_question.answers,
            'is_answered': api_question.is_answered,
            'recently_answered': api_question.recently_answered
           };
};

var parse_answer = function (api_answer) {
    var answer = {'text': api_answer.answer,
                  'timestamp': api_answer.timestamp.replace('T', ' ').replace(':', ':'),
                  'id': api_answer.id,
                  'username': api_answer.answerer.username,
                  'userid': api_answer.answerer.id,
                  'avatarfilename': api_answer.answerer.sellerprofile.avatar.filename,
                  'n_thanks': api_answer.n_thanks,
                  'n_agrees': api_answer.n_agrees
                 };
    if (answer.text.length >= 60 * 5) {
        answer.is_long = true;
        answer.short_text = answer.text.substr(0, 50 * 5) + ' ...';
    } else {
        answer.is_long = false;
        answer.short_text = '';
    }
    return answer;
};

var alter_answer = function (new_answer_dom, parsed_answer) {
    var $a_stat, $a_stats, n_agrees;
    new_answer_dom.data('aid', parsed_answer.id);
    new_answer_dom.attr('data-aid', parsed_answer.id);
    new_answer_dom.find('a:first').attr('href', '/profiles/' + parsed_answer.userid);
    new_answer_dom.find('img').eq(0).attr('src', '/static/images/avatar/' + parsed_answer.avatarfilename);
    new_answer_dom.find('a.username').attr('href', '/profiles/' + parsed_answer.userid).text(parsed_answer.username);
    new_answer_dom.find('span.full_text').text(parsed_answer.text); // TODO: If the answer text is too long, hide some of it
    if (parsed_answer.is_long) {
        new_answer_dom.find('span.comment_text').text(parsed_answer.short_text).show();
        new_answer_dom.find('a.view_all').show();
        new_answer_dom.find('span.full_text').hide();
    } else {
        new_answer_dom.find('span.comment_text').text(parsed_answer.text).hide();
        new_answer_dom.find('a.view_all').hide();
        new_answer_dom.find('span.full_text').show();
    }
    new_answer_dom.find('span.date').text(parsed_answer.timestamp);
    new_answer_dom.find('.ag_cnt').text(parsed_answer.n_agrees);
    new_answer_dom.find('.ag_people').text(parsed_answer.n_agrees === 1 ? "agree" : "agrees");
    new_answer_dom.find('.tx_people').text(parsed_answer.n_thanks === 1 ? "thank" : "thanks");

    $a_stats = new_answer_dom.find('.a_stats');
    n_agrees = parseInt(parsed_answer.n_agrees, 10);
    // reset all classes first
    $a_stats.removeClass('noone_liked someone_liked i_liked i_didnt_like my_answer not_my_answer');
    // now add appropriate classes
    $a_stats.addClass(n_agrees === 0 ? 'noone_liked' : 'someone_liked');
    $a_stats.addClass(liked.indexOf(parseInt(parsed_answer.id, 10)) > -1 ? 'i_liked' : 'i_didnt_like');
    $a_stats.addClass(answered.indexOf(parseInt(parsed_answer.id, 10)) > -1 ? 'my_answer' : 'not_my_answer');
    new_answer_dom.find('ag_cnt').text(n_agrees);

};


var alter_question = function (new_question, parsed_question) {
    // make the appropriate changes to new question
    var new_answer, parsed_answer, new_answer_dom, i_answer, n_answers, new_question_answer_container, last_answer_box, new_answer_box, latest_answer;

    new_question.find('div.previous_comments li').remove();
    // new_question.find('textarea').val(''); // FIXME: Should we remove the answer text if the user views a new question?
    // new_question.find('textarea').blur();

    new_question.removeClass('q_answered').removeClass('q_unanswered');

    if (parsed_question.is_answered) {
        new_question.addClass('q_answered');
    } else {
        new_question.addClass('q_unanswered');
    }

    if (window.SHOW === "all") {
        new_question.show();
    }

    if (window.SHOW === "unans") {
        if (parsed_question.is_answered) {
            new_question.hide();
        } else {
            new_question.show();
        }
    }

    new_question.attr('q_id', parsed_question.id);
    new_question.find('div.helptext a').text(parsed_question.text);
    new_question.find('a.username').text(parsed_question.username);
    new_question.find('a.username').attr('href', '/profiles/' + parsed_question.userid);
    new_question.find('img.useravatar').attr('src', '/static/images/avatar/' + parsed_question.avatarfilename);
    new_question.find('a.question_text').attr('href', '/answer_me/' + parsed_question.id);
    new_question.find('span.sharethis a').attr('href', '/share/' + parsed_question.id);
    new_question.find('span.followthis a').attr('href', '/follow/' + parsed_question.id);
    new_question.find('span.questiondate').text(parsed_question.timestamp);
    new_question.find('div.answer_count').remove();

    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (obj, start) {
            var i, j;
            for (i = (start || 0), j = this.length; i < j; i += 1) {
                if (this[i] === obj) { return i; }
            }
            return -1;
        };
    }
    if (typeof following !== 'undefined') {
        if (following.indexOf(parseInt(parsed_question.id, 10)) > -1) {
            new_question
                .find('span.followthis a')
                .text('unfollow')
                .attr('href', '/unfollow/' + parsed_question.id)
                .addClass('unfollow_question')
                .removeClass('follow_question')
                .attr('title', 'unfollow this question');
        } else {
            new_question
                .find('span.followthis a')
                .text('follow')
                .attr('href', '/follow/' + parsed_question.id)
                .addClass('follow_question')
                .removeClass('unfollow_question')
                .attr('title', 'follow this question');
        }
    }
    new_question_answer_container = new_question.find('div.previous_comments ul');

    // append "View All answers" box and update answer count
    n_answers = parsed_question.answers.length;

    if (n_answers > 3) {
        last_answer_box = $($('div.answer_count')[0]);
        new_answer_box = last_answer_box.clone(true);
        new_answer_box.find('span.no_ans').text(n_answers);
        //console.log("showing n answer", n_answers);
        new_question.find('div.previous_comments').prepend(new_answer_box);
        new_answer_box.show();
    }


    // append answers
    latest_answer = $('div.previous_comments li:last');
    if (latest_answer.length === 0) {
        // no latest answer to clone
        latest_answer = $('<li class="comment hidden" style="display: list-item;">'
                          + '<a href="" class=""> <img src=""></a><div class="text">'
                          + '<a class="username" href="">me</a>&nbsp;'
                          + '<span style="display:inline" class="full_text">&nbsp;</span>'
                          + '<span class="date">&nbsp;</span>'
                          + '<!--span class="ans_flagthis q_extra" style="display: none; "><a class="agree" href="#" title="Agree This">Agree</a></span>'
                          + '<span class="ans_flagthis q_extra" style="display: none; "><a class="thank" href="#" title="Thank This">Thank</a></span-->'
                          + '</div>'
                          + '<div class="a_stats">'
                          + '<img src="/static/images/thumbs_up.png" width="10" style="width:15px">'
                          + '<!--span> <span class="agree_stat"> <span class="ag_cnt">0 </span> <span class="ag_people">sellers</span> agree</span><span class="comma_stat">,</span><span class="tx_cnt"> 0 </span></span><span class="thank_stat"> <span class="tx_people">sellers</span> said thanks</span></span-->'
                          + '</div>'
                          + '</li>');


    }

    for (i_answer = n_answers - 1; i_answer >= 0; i_answer -= 1) {
        new_answer = parsed_question.answers[i_answer];
        parsed_answer = parse_answer(new_answer);
        new_answer_dom = latest_answer.clone(true);
        alter_answer(new_answer_dom, parsed_answer);
        if (window.SHOW === "recent" && i_answer === 0) {
            new_answer_dom.addClass('latest_answer');
        } else {
            new_answer_dom.removeClass('latest_answer');
        }

        // hide answers except last 3
        if ((n_answers >= 3) &&  (i_answer >= 3)) {
            new_answer_dom.hide();
        }
        new_question_answer_container.append(new_answer_dom);
    }
};

var add_answer = function (parsed_answer) {
    var last_anwer, new_question;

};

var add_question = function (parsed_question) {
    var last_question, new_question, container;
    if (window.SHOW === "recent") {
        container = $("#questions_recent_container");
    } else {
        container = $("#questions_all_container");
    }

    last_question = container.find('div.helplist.clearfix:last');
    new_question = last_question.clone();
    alter_question(new_question, parsed_question);
    last_question.after(new_question);
    //console.log("New question added");
};


var n_unanswered = 0;

$(document).ready(function () {



    $('.load_more_qs').click(function (e) {
        var post_data, that, tokens, question_category, container, load_button;
        if ($(this).attr('disabled') === 'disabled') {
            // do not go on if already disabled
            log('returning');
            return false;
        }
        $(this).attr('disabled', 'disabled');

        record_event("load more qs");

        that = $(this);
        tokens = that.attr('id').split('_');
        question_category = tokens[tokens.length - 1];
        if (window.SHOW !== "recent") {
            container = $("#questions_all_container");
        } else {
            container = $("#questions_recent_container");
        }

        container.find('.load_more_qs input[type="submit"]')
            .attr('value', 'Loading more questions');

        load_button = container.find('.load_more_qs input[type="submit"]');

        SC.utils.addLoadingImg(load_button);
        SC.utils.addFixedLoadingImg(load_button);

        e.preventDefault();
        // /api/v1/question/?limit=20&timestamp_gt=2011-01-01%2000:00"
        /*
          post_data = {'timestamp__lt': $('.last-question-t').val(),
          'limit': 10,
          'format': 'json'}; */

        if (window.SHOW !== 'recent') {
            post_data = 'timestamp__lt=' + container.find('.last-question-t').val().replace('T', ' ').replace(' ', '%20');
        } else {
            post_data = 'timestamp_latest_answer__lt=' + container.find('.last-question-t').val().replace('T', ' ').replace(' ', '%20') + '&timestamp_latest_answer__gt=2000-01-01%2000:00:00&order_by=-timestamp_latest_answer';
        }

        if (window.SHOW === "unans") {
            post_data = post_data + '&limit=100';
        } else {
            post_data = post_data + '&limit=25';
        }

        post_data = post_data + '&format=json';

        if (typeof window.asker_id !== 'undefined' && window.asker_id !== 0) {
            post_data += '&askeranswerer=' + String(window.asker_id);
        }

        $.ajax({
            type: 'GET',
            data: post_data,
            url: "/api/v1/question/",
            dataType: "json",
            processData: false,
            success: function (data) {
                var i, l, new_question, questions = data.objects;



                for (i = 0, l = data.objects.length; i < l; i += 1) {
                    new_question = parse_question(questions[i]);
                    add_question(new_question);
                    if (!new_question.is_answered && window.SHOW === "unans") {
                        n_unanswered += 1;
                    }
                    //console.log(new_question);
                }

                if (l <= 9) {
                    //console.log('no more questions, loaded', l);
                    container.find('.load_more_qs input[type="submit"]')
                        .attr('value', 'No more questions')
                        .attr('disabled', 'disabled')
                        .addClass('loadmorebtn-dis');

                } else {
                    // update hidden load more comments button value
                    //console.log("Hidden value now" , new_question.timestamp);
                    if (window.SHOW !== 'recent') {
                        container.find('.last-question-t').val(new_question.timestampiso);
                    } else {
                        log(new_question.timestamp_latest_answer);
                        container.find('.last-question-t').val(new_question.timestamp_latest_answer);
                    }
                    container.find('.load_more_qs').removeAttr('disabled');
                    container.find('.load_more_qs input[type="submit"]')
                        .attr('value', 'Load more questions');
                    that.removeAttr('disabled');

                }



                SC.utils.removeLoadingImg(load_button);
                SC.utils.removeFixedLoadingImg(load_button);

                /*              if (l > 9 && SHOW === "unans" && n_unanswered < 10) {
                                load_button.click();
                                } else {
                                if (n_unanswered >= 10) {
                                n_unanswered = 0;
                                }
                                }
                */



            },
            error: function (err) {
                //console.log('Something wrong');
                container.find('.load_more_qs').removeAttr('disabled');
                SC.utils.removeLoadingImg(load_button);
                SC.utils.removeFixedLoadingImg(load_button);
                that.removeAttr('disabled');

            }

        });

    });


});




$(document).ready(function () {

});

