$(document).ready(function(){
        $('.tabs a').bind("click", function(eo){
		var obj = $(this).parent().parent();
		$('.tab', obj).removeClass('active');
		$(this).parent().addClass('active');
	});
});

Function.prototype.bind = function(){
 if (arguments.length < 2 && arguments[0] == null) return this;
    var __method = this, args = jQuery.makeArray(arguments), object = args.shift();
    return function() {
        return __method.apply(object, args.concat( jQuery.makeArray(arguments)));
    }
};

var QuickSearch = {
    initRecursive : function(object, defaultText)
    {        
         if(jQuery.isFunction(jQuery(object).each)){
             jQuery(object).each(function(){
                 QuickSearch.init(jQuery(this), defaultText);
             });
         } else {
             QuickSearch.init(object, defaultText);
         }        
    },
    init : function(object, defaultText)
    {
        var formObject = jQuery(object).parents('form:eq(0)') || null;
                
        if(formObject != null && !jQuery(formObject).data('QuickSearch::Initialized')) {

            jQuery(formObject).data('QuickSearch::Initialized', true);

            if(QuickSearch.isEmpty(object))
                jQuery(object).val(defaultText).addClass('empty');

            jQuery(formObject).data('threadId', null)

            jQuery(object).focus((function(event){

                clearTimeout(jQuery(this).data('threadId'));
                jQuery(this).data('threadId', null).removeClass('errors');

                if(jQuery(event.target).hasClass('empty'))
                    jQuery(event.target).val('').removeClass('empty');

            }).bind(formObject)).blur((function(event){

                if(QuickSearch.isEmpty(event.target))
                    jQuery(event.target).val(this).addClass('empty');

            }).bind(defaultText));

            formObject.submit(function() {

                if(jQuery(this).find('input.empty').length > 0){

                    jQuery(this).addClass('errors').data('threadId',
                        setTimeout((function(){
                            jQuery(this).removeClass('errors');
                        }).bind(jQuery(this)), 1500)
                    );

                    return false;
                }

                return true;
            });
            
        }
        
    },
    isEmpty:function(textInput)
    {
        return jQuery(textInput).val().replace(/^\s+|\s+$/g, '') == '';
    }
};

var ObjectWatcher = function()
{    
    if(arguments.length == 0)
        throw 'Undefined watched object';

    var object = arguments[0];
    
    this.watchLength = function(outputFn, maxLength)
    {
        if(!jQuery(object).filter(':input').size())
            throw 'Undefined input object';

        maxLength = maxLength || parseInt(jQuery(object).attr('maxlength'));

        watchLength(object, maxLength, outputFn).keyup(function(){
            watchLength(object, maxLength, outputFn);
        }).change(function(){
            watchLength(object, maxLength, outputFn);
        }).blur(function(){
            watchLength(object, maxLength, outputFn);
        })
    };

    function watchLength(object, maxLength, fn)
    {
        object = jQuery(object);
        
        var value = object.val();
        var length = value.length;

        if(length > maxLength)
            jQuery(object).val(value.substring(0, maxLength));

        setTimeout(function(){            
            fn(maxLength, Math.min(length, maxLength));
        }, 10);

        return object;
    };
        
};


var Comments = {

    inSubmitProgress : false,
    preloader : '<img src="/img/preloader.gif" width="128" height="15" />',
    
    load : function(buttonObject, container , url)
    {
        jQuery.get(url, (function(response) {
            jQuery(this.container).append(response);
            Comments.resetCommentsDecorations(this.container);
            jQuery(this.preloader).remove();
        }).bind({container : container, preloader : jQuery(buttonObject).parent()}));
        
        jQuery(buttonObject).replaceWith(Comments.preloader);
    },

    resetCommentsDecorations : function(container)
    {     
        jQuery(container).children('.first:not(.comment-item:first)').removeClass('first');
        jQuery(container).children('.last:not(.comment-item:last)').removeClass('last');
    },

    clearForm : function(formObject)
    {
        jQuery(formObject).find('input[type="text"], textarea').val('').trigger('change');
    },
    
    submit : function(formObject, url)
    {
        if(Comments.inSubmitProgress)
            return false;

        Comments.inSubmitProgress = true;
        
        jQuery(formObject).find('ul.comments-errors').remove();
        var preloader = jQuery('<div class="form-row">'+Comments.preloader+'</div>').insertBefore(jQuery(formObject).find('.form-row:last').hide());
        var serializedPostData = jQuery(formObject).serializeArray();
                                    
        jQuery.post(url, serializedPostData, (function(response){
            if(!response.isValid) {                
                
                var errorsContainer = jQuery('<ul class="comments-errors" style="display: none;"></ul>').insertBefore(jQuery(this.formObject).children()[0]);
                jQuery(errorsContainer).append('<li><span class="red-block"><!-- --></span>' + response.errors.join('</li><li><span class="red-block"><!-- --></span>') + '</li>');
                errorsContainer.fadeIn();
                
                this.preloader.css('position','absolute').fadeOut(function(){jQuery(this).remove()});
                jQuery(this.formObject).find('.form-row:last').fadeIn();
                Comments.inSubmitProgress = false;
                
            } else {
                                
                jQuery.post(jQuery(this.formObject).attr('action'), this.serializedPostData , (function(response){
                     if(response.success && response.comment.htmlObject) {
                        Comments.clearForm(this.formObject);
                        jQuery(response.comment.htmlObject).css('display', 'none').insertAfter(jQuery(this.formObject).parent()).fadeIn();
                        jQuery(this.formObject).parent().parent().find('.article-comments-count:eq(0)').text('('+response.comment.commentsCount+')');
                        Comments.resetCommentsDecorations(jQuery(this.formObject).parent().parent());                        
                    }
                    this.preloader.css('position','absolute').fadeOut(function(){jQuery(this).remove()});
                    jQuery(this.formObject).find('.form-row:last').fadeIn();
                   
                    Comments.inSubmitProgress = false;
                    
                }).bind({formObject : this.formObject, preloader: this.preloader}),'JSON');

            }
        }).bind({formObject : formObject, preloader : preloader, serializedPostData : serializedPostData}),'JSON');
        
        return false;
    }
};


Function.prototype.bind = function(arguments){ 
 if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = jQuery.makeArray(arguments), object = args.shift();
    return function() {
        return __method.apply(object, args.concat( jQuery.makeArray(arguments)));
    }
}
function createCookie(name, value, days){
    var expires = "";
    if(isNumber(days)){
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function deleteCookie(name) {
    createCookie(name,"",-1);
}
function isNull(object){
    return object == null || object == undefined;
}
function isUndefined(object){
    return object == undefined;
}
function isArray(object){
    if (isNull(object) || object.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}
function isObject(object){
    if (isNull(object) || object.constructor.toString().indexOf("Object") == -1)
      return false;
   else
      return true;
}
function isNumber(object){
    return !isNull(object) && (/^-{0,1}\d*\.{0,1}\d+$/.test(object.toString()));
}
