/**
 * Binds a phone validator to a DOM-element
 * 
 * @param {} selectors Selectors of elements, that was linked with this object
 * @param {} newClass Added element have been had this class with postfix "_id"
 * @return {}
 */
var ValidatorBinder = function(selectors, newClass) {
    var that        = this;
    
    that._selectors = selectors;
    that._path       = {};
    that._node       = null;
    that._validators = [];
    that._count      = 0;
    
    $.each(
        selectors,
        function(key, value) {
            that._path[key] = $(value);
        }
    );
    
    /**
     * Links DOM-element with object
     */
    that.bind = function() {
        that._node = that._path.list.find('li:first').remove();
        
        $.each(
            that._path.list.find('li'),
            function(_, node) {
                that.linkTo($(node));
            }
        )
        
        that._path.addLink
            .click(that.add)
            .attr('href', 'javascript:void(null)');
            
        that._path.delLink
            .click(that.del)
            .attr('href', 'javascript:void(null)');
            
            
	    if(that._path.list.find('li').length > 4) {
	    	$(that._selectors.addLink + ':first').css('display', 'none');
	    }
    }
    
    that.linkTo = function(node) {
        node.addClass(newClass + '_' + that._count);
        that._validators.push(new PhoneValidator(node, selectors));
        that._count++;
    }
    
    /**
     * Add new row
     */
    that.add = function() {
    	if (that._count < 5) {
        	var newNode = that._node.clone(true)
            	.appendTo(that._path.list)
            	.addClass(newClass + '_' + that._count);
            
        	that._validators.push(new PhoneValidator(newNode, selectors));
        	if (that._count == 4) {
        		$(that._selectors.addLink + ':first').css('display', 'none');
        	}
        	that._count++;
    	}
    }
    
    /**
     * Delete row
     */
    that.del = function() {
        var parent = $(this).parents('li[class^=' + newClass + ']');
        var id = parseInt(parent.attr('class').split('_')[1]);
        
        parent.remove();
        delete that._validators[id];
        that._count--;
        if (that._count < 5) {
        	$(that._selectors.addLink + ':first').css('display', 'block');
        }
    }
    
    that.cnt = function() {
        return that._count;
    }
    
    return {
        bind: that.bind,
        del : that.del,
        add : that.add,
        cnt : that.cnt
    }
}
