var PROJECT_CAN_VOTE_STATUS = false;
var THIS_PROJECT_NAME = '';

var SORT_ORDER = 'topIdeas';
var CURRENT_SEARCH_REQUEST_HANDLER = 0;
var LAST_SEARCH_REQUEST_HANDLER = 0;
var LAST_SUCCESS_SEARCH_REQUEST_HANDLER = 0;
var FEEDS_PER_PAGE = 10;
//var BETAEASY_BACKEND = 'http://vg.betaeasy/';

var ADD_COMMENT_BLOCK = ['<div class="commtop-white" <img src="/default/images/comusername.gif" height="18" width="16">',
                                        '<span>{$author}</span>',
                                        '<div class="timedump">{$time}</div>',
                                        '<div class="commbody">',
                                                '{$comment}',
                                        '</div>',
                                '</div>'

].join('');

var SUJESTION_FORUM_BLOCK = ['<div class="forum">',
                                '<div class="topic" style="float:left">',
                                        '<div class="left">',
                                            '<h2><img alt="{thread_type_title}" src="/default/images/{$thread_type}.gif" />',
                                                '<a href="/thread/{$thread_id}" title="{$thread_type_title}">',
                                                    '{$thread_subject}',
                                                '</a></h2>',
                                                '<p>',
                                                    '{$message}',
                                                '</p>',
                                        '</div>',
                                        '<div class="date">' + _('Added on') + ' {$date} &nbsp;' + _('by') + '&nbsp;{$author}&nbsp;</div>',
                                        '<div class="comment"><a href="/thread/{$thread_id}#comments"> <b>{$comments_count}</b>&nbsp;{$comments_word}</a></div>',
                                '</div>',
                                        '{$voteControl}',
                            '</div><br />'].join('');

var NOT_VOTED_TEMPLATE = ['<div class="right-noact">',
                             '<span>{$votes}</span>',
                             _('votes') + '<br />',
                             '<input type="button" class="btnv" value="' + _('I like it!') + '" rel="{$thread_id}" />',
                          '</div>',].join('');

var VOTED_TEMPLATE =['<div class="right">',
                        '<span>{$votes}</span>',
                        _('votes') + '<br />',
                     '</div>'].join('');


function tplCompile(tpl, params) {
    return tpl.replace(/\{\$([^}]+)}/g,
        function(fullMatchNotUsed, match) {
            return params[match];
        }
    );
}

function htmlspecialchars(text)
    {
       var chars = Array("&", "<", ">", '"', "'", "\n");
       var replacements = Array("&amp;", "&lt;", "&gt;", "&quot;", "'", "<br />");
       for (var i=0; i<chars.length; i++)
       {
           var re = new RegExp(chars[i], "gi");
           if(re.test(text))
           {
               text = text.replace(re, replacements[i]);
           }
       }
       return text;
    }

  function filterFeedbacks(first_index, action) {
        if ($('input[name="q"]').attr('placeholder') == $('input[name="q"]').val()) {
            var search_word = '';
        }
        else {
            var search_word = $('input[name="q"]').val();
        }
        
        $('#no_results').css('display','none');
        if (action == 'search') {
            $('#forum_board').css('display','none');
        }
        $('#loader').css('display','block');
        search_word = search_word.replace(/[\.\,]+/,'');
        
        CURRENT_SEARCH_REQUEST_HANDLER +=1;

        if (LAST_SUCCESS_SEARCH_REQUEST_HANDLER == LAST_SEARCH_REQUEST_HANDLER) {
            LAST_SEARCH_REQUEST_HANDLER = CURRENT_SEARCH_REQUEST_HANDLER;
        $.ajax({
            type: 'POST',
            url: '/search-thread/'  + $('input[name="project_id"]').val() + '/' ,
            data: 'first=' + first_index + '&search_word=' + search_word + '&order_by=' + SORT_ORDER + '&sr=' + CURRENT_SEARCH_REQUEST_HANDLER,
            success: function(data) {
                eval("data = " + data);

                if(!data.success) {
                    return;
                }

                LAST_SUCCESS_SEARCH_REQUEST_HANDLER = data.sr;
                    if (data.feedback.length > 0) {

                        if (action == 'search') {
                            $('#forum_board').css('display','none');
                            $('#forum_board').empty();
                            $('#loader').css('display','block');
                            $('.more-feedbacks').css('display','none');
                        }
                        for (var i = 0; i < data.feedback.length; i++) {

                           var voteControl = '';

                           if($.cookie('vf'+data.feedback[i].id) || !PROJECT_CAN_VOTE_STATUS || data.feedback[i].status > 3 || !data.anonymous_vote_check) {
                               voteControl = tplCompile(VOTED_TEMPLATE, {votes: data.feedback[i].votes});
                           } else {
                               voteControl = tplCompile(NOT_VOTED_TEMPLATE, {
                                   votes: data.feedback[i].votes,
                                   thread_id: data.feedback[i].id
                               });
                           }
                           
                           if(!data.feedback[i].description)
                               data.feedback[i].description = '';
                           var messageDecode = htmlspecialchars(data.feedback[i].description);
                           if(!messageDecode)
                               messageDecode = '';
                           messageDecode = messageDecode.replace(/\<br([^\>]|)+\>/gi, '</p><p>');

                           var block = tplCompile(SUJESTION_FORUM_BLOCK, {
                               thread_type: data.feedback[i].type,
                               thread_type_title: data.feedback[i].type + (data.feedback[i].type == 'bug' ? ' report' : ' request'),
                               message: messageDecode,
                               thread_id: data.feedback[i].id,
                               thread_subject: '&nbsp;' + htmlspecialchars(data.feedback[i].subject),
                               comments_count: data.feedback[i].comment_count,
                               comments_word: ngettext(' comment', ' comments', data.feedback[i].comment_count),
                               date: data.feedback[i].created_at,
                               author: data.feedback[i].author,
                               voteControl: voteControl
                           });
                           $('#forum_board').html($('#forum_board').html() + block);
                        }
                         $('.more-feedbacks').css('display','block');
                         $('#leave_feedback').css('display','none');
                    }
                    
                    if (data.feedback.length < window.FEEDS_PER_PAGE) {
                        $('.more-feedbacks').css('display','none');
                        $('#leave_feedback').css('display','block');

                    }
                    if (data.feedback.length == 0 && action != 'more') {
                       $('#forum_board').empty();
                       $('#leave_feedback').css('display','none');
                       $('.no-results-text').css('display','block');
                       $('#no_results').css('display','block');
                       $('#leave_feedback').css('display','none');
                       //$('#no_results form input[name="subject"]').focus();
                    }
                    $('#loader').css('display','none');
                    $('#forum_board').css('display','block');
                }
       });
       }

       return false;
    }


new function($) {
    $.fn.placeholder = function(settings) {
        settings = settings || {};
        var key = settings.dataKey || "placeholderValue";
        var attr = settings.attr || "placeholder";
        var className = settings.className || "placeholder";
        var values = settings.values || [];
        var block = settings.blockSubmit || false;
        var blank = settings.blankSubmit || false;
        var submit = settings.onSubmit || false;
        var value = settings.value || "";
        var position = settings.cursor_position || 0;


        return this.filter(":input").each(function(index) {
            $.data(this, key, values[index] || $(this).attr(attr));
        }).each(function() {
            if ($.trim($(this).val()) === "")
                $(this).addClass(className).val($.data(this, key));
        }).focus(function() {
            if ($.trim($(this).val()) === $.data(this, key))
                $(this).removeClass(className).val(value)
                if ($.fn.setCursorPosition) {
                  $(this).setCursorPosition(position);
                }
        }).blur(function() {
            if ($.trim($(this).val()) === value)
                $(this).addClass(className).val($.data(this, key));
        }).each(function(index, elem) {
            if (block)
                new function(e) {
                    $(e.form).submit(function() {
                        return $.trim($(e).val()) != $.data(e, key)
                    });
                }(elem);
            else if (blank)
                new function(e) {
                    $(e.form).submit(function() {
                        if ($.trim($(e).val()) == $.data(e, key))
                            $(e).removeClass(className).val("");
                        return true;
                    });
                }(elem);
            else if (submit)
                new function(e) {$(e.form).submit(submit);}(elem);
        });
    };
}(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$('#drawer').live('click', function() {
    $(this).fadeOut();
});

EasyGrowl = {
    notify: function(text, time) {
        if(jQuery.browser.msie && jQuery.browser.version == '6.0') {
            $('#drawer').css('position', 'absolute');
            $('#drawer').css('z-index', '999999');
            $('#drawer').css('top', '-5px');
        }
        $('#drawer').hide();
        $('#drawer').slideDown(function()  {
            $('#drawer').css({"backgroundColor": "#ccc"});
            
            $('#drawer').html(text);

            setTimeout(function() {
                $('#drawer').css({"backgroundColor": "#fff"});
            }, 1000);

            if(!time) {
                time = 30000;
            }
            
            setTimeout(function() {
                $('#drawer').fadeOut('slow');
            }, time);
            
        });
    }
};




//-------------------------libraries end



$(document).ready(function() {
    $('input').placeholder();
    var BETAEASY_BACKEND = 'http://app.betaeasy.com/';
    if ($('#no_results').css('display') == 'block') {
        setTimeout(function(){$('#no_results form input[name="subject"]').focus()},1000);

    }
//------------------------- subscribtion for thread

var thread;

$('#subscribe_btn').live('click', function() {
    $('.subscribe_btn').css('display','none');
    $('#loader-subscr').css('display','block');
    window.thread = $('#subscribe_btn').attr('rel');
        $.ajax({
            type: 'POST',
            url: '/subscribe/'  + window.thread,
            data: '',
            success: function(data) {
                eval("data = " + data);
                if (data.success) {
                    $('.subscribe_btn').css('display', 'none');
                    $('.unsubscribe_btn').css('display', 'block');
                    $('#loader-subscr').css('display','none');
                }

            }
    });

    return false;
});

//------------------------- unsubscribtion for thread
$('#unsubscribe_btn').live('click', function() {
    $('.unsubscribe_btn').css('display','none');
    $('#loader-subscr').css('display','block');
    var thread = $('#unsubscribe_btn').attr('rel');
        $.ajax({
        type: 'POST',
        url: '/un-subscribe/'  + thread,
        data: '',
        success: function(data) {
            eval("data = " + data);
            if (data.success) {
                $('.subscribe_btn').css('display', 'block');
                $('.unsubscribe_btn').css('display', 'none');
                $('#loader-subscr').css('display','none');
            }
        }
    });
    return false;
});
//------------------------- change tabs action

    $('.tr #tabs ul li a').click(function(e) {
        $('.more-feedbacks').css('display','none');

        $('#tabs ul li a').removeClass('active_tab');
        $(this).addClass('active_tab');
        
        if ($(this).attr('id') != 'contribute-tab') {
            SORT_ORDER = $(this).attr('id');

            $('.box').val('');
            $('#more').attr('last', window.FEEDS_PER_PAGE);
            filterFeedbacks(0,'search');
        }

        e.stopPropagation();

        return false;
    });

    $('#contribute-tab, #leave_feedback').click(function(){
        $('#forum_board').css('display','none');
        $('#no_results').css('display','block');
        $('#leave_feedback').css('display','none');
        $('#no_results form input[name="subject"]').focus();
        $('.no-results-text').css('display','none');

        $('#tabs ul li a').removeClass('active_tab');
        $('#contribute-tab').addClass('active_tab');
    })



 //----------------------------------------------- more feedback block
    $('.more-feedbacks').click(function(e) {
        var first_index = parseInt($('#more').attr('last'));
        $('.more-feedbacks').addClass('box');
        
        filterFeedbacks(first_index, 'more');
        first_index += window.FEEDS_PER_PAGE;
        $('#more').attr('last', first_index);

        e.stopPropagation();
        return false;
    });
//------------------------------------------------ login to backend action

//    $('.backend_login').click(function() {
//        $.getJSON(BETAEASY_BACKEND + "index/auth/?aid=" + $('.backend_login').attr('aid') + "&callfrom=front&p=?",
//            function(data) {
//                if (data.success == true)
//                {
//                  window.open(BETAEASY_BACKEND);
//                }
//
//        });
//
//        return false;
//    });


//------------------------------------------------ search feedback sujestions
   $('input[name="q"]').live('keyup',function(e){
       
        if (!(/144$|16$|32$|17$|27$|37$|38$|39$|40$/.test(e.keyCode)) ) {
            $('#more').attr('last', window.FEEDS_PER_PAGE);
            $('.more-feedbacks').css('display','none');
            filterFeedbacks(0,'search');
       }
       
        return false;
    });

    $('#isugest-btn').click(function(){
        $('.more-feedbacks').css('display','none');
        //$('#tabs ul li a').removeClass('active_tab');
        //$('#tabs ul li a:first').addClass('active_tab');
        //$('#forum_board').css('display','none');
        filterFeedbacks(0,'search');
    });


    //------------------------------------------------------ begin - add comment

    $('.sbmt').live('click', function(){
        // --- checking, that comment block is not empty ---
        if($('#message_ta').val() != '') {
            $('#loader-comment').css('display','block');
            $('.sbmt').css('display','none');
            $.ajax({
                    type: 'POST',
                    url: '/add-comment/'  + $('#thread').val(),
                    data: $("#submit_comment_form").serialize(),
                    success: function(data) {
                        eval("data = " + data);
                        if (data.success) {
                            window.location.reload();
/*
                            $('#no_comments').css('display','none');
                            var message = tplCompile(ADD_COMMENT_BLOCK, {
                                comment: htmlspecialchars($('.ta').val()),
                                time: data.time,
                                author: data.author
                            });
                            $('.commblock').append(message);


                            $(".commblock>div:nth-child(odd)").addClass('commtop-white');
                            $(".commblock>div:nth-child(odd)").removeClass('commtop');

                            $(".commblock>div:nth-child(odd)").addClass('commtop');
                            $(".commblock>div:nth-child(odd)").removeClass('commtop-white');

                            var count_comments = parseInt($("#comments_count").text());
                            count_comments++;

                            $('textarea[name=message]').val('');

                            $("#comments_count").text(count_comments);
                            $('#loader-comment').css('display','none');
                            $('.sbmt').css('display','block');
*/
                       }

                    }
            });
        } else {
            EasyGrowl.notify(_('Please enter your comment.'));
        }
    });
    
    //---------------------------------------------------votes mechanism
    $('.btnv').live('click', function() {
        var $button = $(this);

        $button.parents('.right-noact').fadeOut('slow');

        $.ajax({
            type: 'POST',
            url: '/vote/'  + $button.attr('rel'),
            success: function(data) {
                eval("data = " + data);

                if (data.success) {
                    $button.parents('.right-noact').replaceWith(tplCompile([
                        '<div class="right">',
                          '<span>{$votes}</span>',
                          _('votes'),
                        '</div>'
                    ].join(''), {votes: data.votes}));

                    $.cookie('vf' + $button.attr('rel'), true, {path: '/'});
                } else {
                    //TODO: notify about error
                }
            }
        });
    });

    $('#more').click(function() {
        return false;
    });

    // --- admin comment actions -----------------------------------------------

    $('button.comment_by_admin_action').click(function() {
        $('.admin-commform-place').each(function() {
            $(this).css('display', 'none');
        })

        $('#admin_commform_extended_place_' + $(this).attr('rel')).css('display', 'block');
        $('#commform_standart_place').css('display', 'none');
    });

    $('.cnclbtn').click(function() {
        $('.admin-commform-place').each(function() {
            $(this).css('display', 'none');
        })
        $('#commform_standart_place').css('display', 'block');
    });

    var answer_id = 0;
    $('.admsbmt').click(function(){
        window.answer_id = $(this).attr('rel');
        if($('#response_comment_form_' + window.answer_id + ' textarea[name=message]').val() != '') {
            $('#response_comment_form_' + window.answer_id + ' img[name=loader]').css('display','block');
            $('#response_comment_form_' + window.answer_id + ' input[name=submit]').css('display','none');
            $('#response_comment_form_' + window.answer_id + ' input[name=cancel]').css('display','none');

            $.ajax({
                    type: 'POST',
                    url: '/add-response/'  + $('#thread').val(),
                    data: $("#response_comment_form_" + window.answer_id).serialize(),
                    success: function(data) {
                        eval("data = " + data);
                        window.answer_id = 0;
                        if (data.success) {
                            window.location.reload();
                       }

                    }
            });
        } else {
            EasyGrowl.notify(_('Please enter your comment.'));
        }
    });
});
