var omsDinamic = false;

(function( $ ) {
    var Form = function() {
        this._options = {};
        this.errors = {};
		this.fieldsCh = {};
        this.timerCheck;
        
        return this;
    };

    Form.prototype = {
        init: function(target, options) {
            var self = this;
            this._original = {
                target: target,
                placeholder: false
            };
            
            this._options = $.extend(this._original, options);
            if(!this._options.notredraw){
				this.redrawTextFields();
			
            if(this._options.requiredFields.length && !this._options.noSubmit)
				$(this._original.target).submit(function() {
					res = self.formSubmitChecker.call(self);
					if(res)
						return true;
					else
						return false;
				});
			}
            $.each(this._options.allFields, function(k, v) {
                var elem = '#' + self._options.elemIdPref +  '-' + v;
                
                $('body').delegate(elem, 'blur', function() {
                    var value = $.trim($(this).val());
                    self.errors[v] = [];
                    
					$(this).stopTime('timer');
                    if ($.inArray(v, self._options.requiredFields) < 0){
                        var inArray = false;
                    } else {
                        var inArray = true;
                    }
                    
                    if(self._options.requiredFields.length && inArray && $(elem).length > 0) {
                        self.basicValidate.call(self, value, v);
                    }
						
					if($.trim($(this).val())) {
						self.getMoreValidate.call(self, v, this);
					}
					
					self.showErrors.call(self, this);
					self.hideErrors();
					
					//self.formSubmitChecker.call(self);
                });
            });
        },
        
        redrawInit: function(target, options) {
            var self = this;
            this._original = {
                target: target,
                placeholder: true
            };
            
            this._options = $.extend(this._original, options);
            /* $.each(this._options.allFields, function(k, v) {
                self.errors[v] = [];
            }); */

			
            if(!this._options.notredraw)
				this.redrawTextFields();
				
        },
        
        /* clearErrors: function(target, options){
            $.each(this._options.allFields, function(k, v) {
                
            })
        } */
        
		formSubmitChecker: function() {
            //alert ('submit');
            var sbm = $('.content :submit, .contic :submit');
			var self = this;
			var errors = 0;
			var fieldsCh = 0;
            
            //console.log(stepPath[curStep - 1]);
            
            
            $.each(self.errors, function(k,v) {
                if(v.length)
                    errors++;
            });
            
			$.each(self._options.requiredFields, function(k,v) {
                var curElem = '#'+self._options.elemIdPref+'-'+v;
                if (omsDinamic){
                    curElem = '#tbl-' + stepPath[curStep - 1] + ' ' + curElem;
                }
                if ($(curElem).is(':radio')){
                    curElem = '.' + self._options.elemIdPref+'-' + v + '.checked';
                    valTemp = $(curElem).val();
                    //alert(valTemp);
                } else {
                    valTemp = $(curElem).val();
                    //console.log('i' + valTemp + 'i');
                }
				if(valTemp || !$(curElem).length){
					fieldsCh++;
                }
			});
			
			if(errors==0 && fieldsCh==self._options.requiredFields.length) {
                if (omsDinamic) {
                    sbm.attr('disabled', 'disabled');
                    $('.loading').show();
                    curStep++;
                    //alert ('check!');
                    getFields(curStep);
                    return false;
                }
                sbm.attr('disabled', 'disabled');
				return true;
			}
            
            self.showErrorsAll.call(self);
			
			$('.tipStatus .alert').siblings('.tipCont').show();
			$('.tipStatus .tipCont').oneTime(5000, function() {
				$(this).hide();
			});
			
			$('.tipStatus .ico.alert').toolTip();
			return false;
		},
		
        basicValidate: function(value, name) {
            if($.trim(value)=='') {
                var errorMessage = (this._options.fieldOptions[name].errorMessage.basic)?this._options.fieldOptions[name].errorMessage.basic:$.miniTmplater({name: this._options.fieldOptions[name].label}, this._options.defMessageReq);
                this.errors[name] = errorMessage;
				
            } else {
				this.errors[name] = '';
			}
            
			this.fieldsCh[name] = 1;
        },
        
        getMoreValidate: function(name, elem) {
            var self = this;
            if(this._options.fieldOptions[name].validators)
                $.each(this._options.fieldOptions[name].validators, function(k, v) {
                    self[v].call(self, name, elem);
                });
        },
        
        email: function(name, elem) {
            var email = $.trim($(elem).val());
            
            var filterEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
            
            if(!filterEmail.test(email))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },
        
	   minlen: function(name, elem) {
            var pass = $.trim($(elem).val());
            
            if(pass.length<6)
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },
		
        phone: function(name, elem) {
            var phone = $.trim($(elem).val());
            
            var filterPhone = /^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/;
            var filterPhone = /[^0-9\-\(\)\+\s]/;
            
            if(filterPhone.test(phone))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },
        
        onlyDigits: function(name, elem) {
            var digit = $.trim($(elem).val());
            var filterDigit = /^\d+$/;
            if(!filterDigit.test(digit))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },

        onlyText: function(name, elem) {
            var phone = $.trim($(elem).val());
            
            var filterText = /[^à-ÿ¸\-\s]/i;
           //alert(phone+'=='+filterText.test(phone));
            if(filterText.test(phone))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },
        onlyTextExDigits: function(name, elem) {
            var phone = $.trim($(elem).val());
            
            var filterText = /[^à-ÿ¸0-9\-\s\.\,]/i;
            
            if(filterText.test(phone))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },

        onlyTextEx: function(name, elem) {
            var phone = $.trim($(elem).val());
            
            var filterText = /[^à-ÿ¸\-\s\.\,]/i;
            
            if(filterText.test(phone))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },
        
        onlyTextDigits: function(name, elem) {
            var phone = $.trim($(elem).val());
            
            var filterText = /[^à-ÿ¸\-\s\.\,0-9]/i;
            
            if(filterText.test(phone))
                this.errors[name] = this._options.fieldOptions[name].errorMessage.format;
                
        },
        
        
        ajax: function(name, elem) {
            var self = this;
            $.post('/serverValid.php', {
                    name: name,
                    value: $(elem).val(),
                    day: $(elem).parents('tr').find('select:first').val(),
                    month: $(elem).parents('tr').find('select').eq(1).val(),
                    year: $(elem).parents('tr').find('select').eq(2).val(),
                    b_day: $('#oms-frm-date_birth_d').val(),
                    b_month: $('#oms-frm-date_birth_m').val(),
                    b_year: $('#oms-frm-date_birth_y').val()
                    
                }, function (respond){
                    if (respond == 'bad'){
                          //console.log(name);
                        self.errors[name] = self._options.fieldOptions[name].errorMessage.uniq;
                        self.showErrors.call(self, elem);
                    }
                }
            );
        },
        
        showErrors: function(elem) {
            var self = this;
			
            $.each(this.errors, function(k, v) {
                if (v.length != 0){
                    $('#err_' + self._options.elemIdPref+'-'+k + ' .tipStatus .middle').html(v).parents('.tipCont').siblings('.ico').addClass('alert');
                    if ($(elem).attr('id') == self._options.elemIdPref + '-' + k) 
                        $('#err_' + self._options.elemIdPref+'-'+k + ' .tipStatus').show().find('.tipCont').show();
                }else {
                    $('#err_' + self._options.elemIdPref+'-'+k + ' .tipStatus').show().find('.tipCont').hide(0, function(){
                        $(this).find('.middle').html('');
                    }).siblings('.ico').removeClass('alert').unbind();
                }
            });
        },
        
        showErrorsAll: function() {
            var self = this;
			
            $.each(self._options.requiredFields, function(k, v) {
                if ($('#'+self._options.elemIdPref+'-'+v).is(':radio')){
                    valTemp = $('.'+self._options.elemIdPref+'-'+v + ':checked').val();
                } else {
                    valTemp = $.trim($('#'+self._options.elemIdPref+'-'+v).val());
                }
				//alert(self.errors[v]);
				
                if (!omsDinamic){
                
    				if(!valTemp) {
    					$('#err_' + self._options.elemIdPref+'-'+v + ' .tipStatus .middle').html(self._options.fieldOptions[v].errorMessage.basic).parents('.tipCont').siblings('.ico').addClass('alert'); 
                        $('#err_' + self._options.elemIdPref+'-'+v + ' .tipStatus').show().find('.tipCont').show();
    				} else if(self.errors[v]) {
    					$('#err_' + self._options.elemIdPref+'-'+v + ' .tipStatus .middle').html(self.errors[v]).parents('.tipCont').siblings('.ico').addClass('alert'); 
                        $('#err_' + self._options.elemIdPref+'-'+v + ' .tipStatus').show().find('.tipCont').show();
    				} else {
    					$('#err_' + self._options.elemIdPref+'-'+v + ' .tipStatus').show().find('.tipCont').hide(0, function(){
                            $(this).find('.middle').html('');
                        }).siblings('.ico').removeClass('alert').unbind();
    				}
                    
                } else{
                    
                    if(!valTemp) {
    					$('#tbl-' + stepPath[curStep - 1] + ' #err_' + self._options.elemIdPref+'-'+v + ' .tipStatus .middle').html(self._options.fieldOptions[v].errorMessage.basic).parents('.tipCont').siblings('.ico').addClass('alert'); 
                        $('#tbl-' + stepPath[curStep - 1] + ' #err_' + self._options.elemIdPref+'-'+v + ' .tipStatus').show().find('.tipCont').show();
    				} else if(self.errors[v]) {
    					$('#tbl-' + stepPath[curStep - 1] + ' #err_' + self._options.elemIdPref+'-'+v + ' .tipStatus .middle').html(self.errors[v]).parents('.tipCont').siblings('.ico').addClass('alert'); 
                        $('#tbl-' + stepPath[curStep - 1] + ' #err_' + self._options.elemIdPref+'-'+v + ' .tipStatus').show().find('.tipCont').show();
    				} else {
    					$('#tbl-' + stepPath[curStep - 1] + ' #err_' + self._options.elemIdPref+'-'+v + ' .tipStatus').show().find('.tipCont').hide(0, function(){
                            $(this).find('.middle').html('');
                        }).siblings('.ico').removeClass('alert').unbind();
    				}
                    
                }
            });
			
        },
        
        hideErrors: function() {
			$(this).oneTime(3000, 'timer', function() {
            $('.tipStatus .ico.alert').siblings('.tipCont').hide();
			});
        },
        
        placeholder: function() {
            $(this._options.target).find('input.placeholder').each(function() {
                if($(this).val() == '')
                    $('#' + $(this).attr('id') + '-l').show();
                
                $(this).focus(function() {
                    if($(this).val() == '')
                        $('#' + $(this).attr('id') + '-l').fadeTo(300, 0.2);
                })
                .keydown(function() {
                    $('#' + $(this).attr('id') + '-l').hide();
                })
                .blur(function() {
                    if($(this).val() == '') {
                        $('#' + $(this).attr('id') + '-l').fadeTo(300, 1);
                    }
                });
            });
        },
        
        redrawTextFields: function() {
            $(this._options.target).find('input:text, input:password').each(function(){
                $(this).before('<div class="uf-txt-left"></div>').after('<div class="uf-txt-right"></div><div class="clear"></div>').wrap('<div class="uf-txt-center"></div>');
                var width = $(this).outerWidth() - ($(this).parent().prev().outerWidth() + $(this).parent().next().outerWidth());
                var height = $(this).parent().outerHeight();
                //alert ($(this).parent().prev().outerWidth() + $(this).parent().next().outerWidth());
                $(this).css({
                    'width': width + 'px',
                    'border':'none',
                    'height': height + 'px',
                    'background': 'none',
                    'line-height' : height + 'px'
                });
                if ($(this).hasClass('myFile')){
                    width = width + 160;
                }
                if ($(this).hasClass('double-type-field')){
                    height = height + 25;
                }
                $(this).parents('.uf-txt-center').parent().css({
                    'width': (width + 20) + 'px',
                    'height': (height + 2) + 'px'
                });
            });
// ------------------------------------------------
/*
            $(this._options.target).find('textarea').each(function(){
                $(this).after('<div class="clear"></div>');
                var width = $(this).outerWidth() - ($(this).parent().prev().outerWidth() + $(this).parent().next().outerWidth());
                var height = $(this).parent().outerHeight();
                //alert ($(this).parent().prev().outerWidth() + $(this).parent().next().outerWidth());
                $(this).css({
                    'width': width + 'px',
                    'height': height + 'px',
                });


            });            
*/

            $(this._options.target).find('input:radio').filter(':not(.no-r)').each(function(){
                var radioBtn = $(this);
                var checked = ($(this).attr('checked') == 'checked')?'act':'';
                var lbl = $(this).next('label').text();
                $(this).next('label').remove();
                $(this).before('<div class="myRadio ' + checked + ' ">' + lbl + '</div>');
                $('.myRadio').css({
                    'color':'#3c3c3c'
                });
                $('.myRadio').bind('click', function(){
                    var myRadio = $(this);
                    var radName = myRadio.next('input:radio').attr('name');
                    //alert (radName);
                    $('input:radio').each(function(){
                        if($(this).attr('name') == radName){
                            $(this).removeAttr('checked').removeClass('checked').prev('.myRadio').removeClass('act');
                            myRadio.addClass('act').next('input:radio').attr('checked','checked').addClass('checked');
                        }
                    
                    });
                    //alert (radioBtn.attr('id'));
                    radioBtn.blur();
                });
                $(this).hide();
            });
            
            $(this._options.target).find('input:checkbox').each(function(){
                var checked = ($(this).attr('checked') == 'checked')?'act':'';
                var lbl = $(this).next('label').text();
                $(this).next('label').remove();
                $(this).before('<div class="myCheckbox ' + checked + ' ">' + lbl + '</div>');
                $('.myCheckbox').css({
                    'color':'#3c3c3c'
                });
                
                $(this).prev().bind('click', function(){
                    if ($(this).next().attr('class') != 'disa'){
                        $(this).toggleClass('act');
                        if($(this).hasClass('act'))
                            $(this).next('input').attr('checked', 'checked');
                        else
                            $(this).next('input').removeAttr('checked');
                    }
                });
                
                $(this).hide();
            });
            
            $(this._options.target).find('select').each(function(){
                var valSel = $(this);
                var sWidth = $(this).outerWidth() ? $(this).outerWidth() : parseFloat($(this).css('width'));
                //console.log('w ' + sWidth);
                if (sWidth >= 100 && sWidth < 170){
                    var wClass = 'PX_100';
                    sWidth = 100;
                } else if (sWidth == 315){
                    var wClass = 'PX_315';
                } else if (sWidth == 170){
					var wClass = 'PX_170';
                }
                
				var styleMore = '';
				if($(this).hasClass('right'))
					styleMore = "float:right;";
                $(this).before('<div style="'+styleMore+'" class="mySelect ' + wClass + '"><div class="lister"></div><div class="list"></div></div>');
                $(this).prev('.mySelect').css({
                    'position':'relative',
                    'z-index':'99'
                });
                var listerText = $(this).find('option[selected = "selected"]').text();
                if(!listerText)
                    listerText = $(this).find('option:eq(0)').text();
                $(this).prev('.mySelect').find('.lister').css({
                    'width':(sWidth - 45) + 'px',
                    'height':'22px',
                    'padding':'8px 40px 0px 5px',
                    'overflow':'hidden',
                    'line-height':'18px'
                }).text(listerText);
                $(this).find('option').each(function(){
                    var attrClick = $(this).attr('onclick');
                    if (attrClick){
                        attrClick = 'onclick="' + attrClick + '"';
                    }
                    var sText = $(this).text();
                    $(this).parents('select').prev('.mySelect').find('.list').append('<div ' + attrClick + ' class="unit">' + sText + '</div>');
                });
                $(this).prev('.mySelect').find('.list').css({
                    'width':sWidth + 'px',
                    'position':'absolute',
                    'left':'0',
                    'top':'30px',
                    'display':'none'
                }).append('<div class="sBot"></div>');
                $(this).prev('.mySelect').find('.list .unit').first().css({
                    'color':'#8C8C8C',
                    'padding-bottom':'8px'
                });
                var mySel = $(this).prev('.mySelect');
                mySel.find('.lister').bind('click', function(){
                    if ($(this).parents('.mySelect').find('.list').css('display') == 'none') {
                        $('.mySelect .list').hide().prev('.lister').removeClass('act');
                        $('.mySelect').removeClass('op').css('z-index', '99');
                        $(this).addClass('act').parents('.mySelect').find('.list').show();
                        mySel.addClass('op').css('z-index', '110');
                    } else {
                        $(this).removeClass('act').parents('.mySelect').find('.list').hide();
                        mySel.removeClass('op').css('z-index', '99');
                    }
                });
                mySel.find('.list .unit').bind('click', function(){
                    var uTxt = $(this).text();
                    var selInd = $(this).index();
                    if ($(this).parents('.list').attr('class') == 'list scrollable'){
                        selInd -=1;
                    }
                    $(this).parents('.mySelect').next('select').find('option').removeAttr('selected');
                    $(this).parents('.mySelect').next('select').find('option:eq(' + selInd + ')').attr('selected','selected');
                    $(this).parents('.mySelect').find('.lister').text(uTxt).removeClass('act');
                    $(this).parents('.mySelect').find('.list').hide();
                    valSel.blur();
                }).bind('mouseover', function(){
                    $(this).addClass('hover');
                }).bind('mouseout', function(){
                    $(this).removeClass('hover');
                });
                
                $(document).bind('click', function(e){
                    var curClick = e.target.className;
                    if (curClick != 'lister' && curClick != 'lister act' && curClick != 'list' && curClick != 'mySelect' && curClick != 'scrollTop' && curClick != 'scrollBot' && curClick != 'scrollBot inact'  && curClick != 'scrollTop inact'){
                        $('.mySelect .list').hide();
                        $('.mySelect .lister').removeClass('act');
                    }
                }); 
                
                //öåïëÿòü ëè ïðîêðóòêó??
                var visCount = 6;
                
                var selSize = $(this).find('option').size();
                if (selSize >= visCount){
                    $(this).prev('.mySelect').find('.list').addClass('scrollable');
                    $(this).prev('.mySelect').find('.list .unit').hide();
                    $(this).prev('.mySelect').find('.list .unit:last').addClass('last');
                    $(this).prev('.mySelect').find('.list .unit:first').addClass('first');
                    for (var i = 0; i <= visCount - 1; i++){
                        $(this).prev('.mySelect').find('.list .unit:eq(' + i + ')').show();
                    }
                    
                    $(this).prev('.mySelect').find('.list').prepend('<div class="scrollTop inact"></div>');
                    $(this).prev('.mySelect').find('.scrollTop').bind('mouseover', function(){
                        if ($(this).is(':not(.inact)')) {
                            var scroller = $(this);
                            scroller.everyTime(70, 'sBot', function(){
                                var list = $('.mySelect .list:visible');
                                list.find('.scrollBot').removeClass('inact');//.show();
                                list.find('.unit:visible:first').prev().show(0, function(){
                                    if ($(this).is('.first')){
                                        list.find('.scrollTop').addClass('inact');//.hide();
                                        scroller.stopTime('sBot');
                                    }
                                }).show();
                                list.find('.unit:visible:last').hide();
                            });
                        }
                    }).bind('mouseout', function(){
                        var scroller = $(this);
                        scroller.stopTime('sBot');
                    });
                    
                    $(this).prev('.mySelect').find('.list .sBot').before('<div class="scrollBot"></div>');
                    $(this).prev('.mySelect').find('.scrollBot').bind('mouseover', function(){
                        if ($(this).is(':not(.inact)')) {
                            var scroller = $(this);
                            scroller.everyTime(70, 'sTop', function(){
                                var list = $('.mySelect .list:visible');
                                list.find('.scrollTop').removeClass('inact');//.show();
                                list.find('.unit:visible:last').next().show(0, function(){
                                    if ($(this).is('.last')){
                                        list.find('.scrollBot').addClass('inact');//.hide();
                                        scroller.stopTime('sTop');
                                    }
                                }).show();
                                list.find('.unit:visible:first').hide();
                            });
                        }
                    }).bind('mouseout', function(){
                        var scroller = $(this);
                        scroller.stopTime('sTop');
                    });
                }
                
                $(this).hide();
            });
            
            if(this._options.placeholder)
                this.placeholder();
        }
    };

    $.fn.myForm = function(options) {
        return this.each(function() {
            var form = new Form();
            form.init(this, options);
        });
    };
    
    $.fn.myFormRedraw = function() {
        return this.each(function() {
            var formRed = new Form();
            formRed.redrawInit(this);
        });
    };
    
    /* $.fn.clearErrors = function() {
        return this.each(function() {
            var clErr = new Form();
            clErr.clearErrors(this);
        });
    }; */
}(jQuery));
