if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
  }
}

(function($) {
	var IvAjaxValidatorForms = function(form_name, json) {
		var forms_array = new Array();
		
		$('form').each(function(s, element) {
			forms_array.push(element.id)
		});

		var current_form = $('#' + forms_array[forms_array.indexOf(form_name)]);
		var firstShown = false;
		
		this.showError = function(element, value, show) {
			
			var el = jQuery('#' + element.replace('error_for_', ''));

			if(!el.length) {
				el = jQuery('[id^=' + element.replace('error_for_', '') + ']');
			}
			
			if(el.length && el.eq(0).data('IvAjaxValidation')) {
				jQuery(el).data('IvAjaxValidation').setErrorTipWrong(value);
				
				if(show) {
					jQuery(el).focus();
				}
			}
		};
	};

	$.IvAjaxValidatorForms = function(form_name, json) {
		return new IvAjaxValidatorForms(form_name, json);
	};
})
(jQuery);

(function($) {
	var IvAjaxValidator = function(form_field, conf) {
	    var self = this;
		var form_field = $(form_field);
		var error_container = null;
		var error_field = null;
		var field_dot = null;
		var field_help = null;
		var field_error_tooltip = null;
		var field_help_tooltip = null;
		var isInitialized = false;

		var c = $.extend({
			validation_enabled: true,
			helpers_enabled: false,
			global_enabled: false,
			field_enabled: false,
			textClass: 'text',
			textareaClass: 'textarea',
			global_error_selector: '#form-error-global'
			}, conf || {});

		$.extend(self, {
			bind: function() {
				if (form_field.hasClass(c.textClass)
					|| form_field.hasClass(c.textareaClass)) {

					// trick for always hidden login popup
					var no_global_error = form_field.parents('form').hasClass('no_global_error');
					
					// Check configuration
					c.global_enabled = (!no_global_error && 0 < $(c.global_error_selector).length);
					
					c.field_enabled = (!c.global_enabled || !$(c.global_error_selector).hasClass('global_errors_only'));
					
					c.helpers_enabled = (0 < form_field.parents('div.line').find('div.lineHelpWrapper').length);
					
					c.validation_enabled = ((c.global_enabled || c.field_enabled) && !form_field.hasClass('validation_disabled'));
					// Check configuration - end

					var fna_ = form_field.attr('rel') || form_field.attr('name');

					if('_' == fna_.substr(0, 1)) {
						fna_ = fna_.substr(1);
					}
				
					var reg = /^(.*)\[(.*)\]$/;
					var ar = reg.exec(fna_);
					if (!ar)
					   return;
					
					var form_name_format = ar[1];
					var field_name = ar[2];

				      // special case when form field is checbox or radio
				    var ar_spe = reg.exec(ar[1]);
				    
				    if (ar_spe != null && ar_spe[1] != '' && ar_spe[2] != '') {
				        form_name_format = ar_spe[1];
				        field_name = ar_spe[2];
				    }

				    if(0 <= form_name_format.indexOf('--')) {
				      form_name_format = form_name_format.substr(form_name_format.indexOf('--') + 2);
				    }
				      
					error_container = form_field.parents('div.line').prev('div.lineErrorWrapper');
					error_field = error_container.children('div.form_error');
				
					if(!error_field.length && form_field.attr('rel')) {
						error_field = $('[name=' + form_field.attr('rel') + ']').siblings('.lineError');
					}
				
					if(error_field.length) {
						error_field.attr('id', 'error_for_' + form_name_format + '_' + field_name);
					}
					
					form_field.parents('div.line').attr('id', 'line_' + form_name_format + '_' + field_name);
					form_field.parents('div.line_wrap').attr('id', 'line_wrap_' + form_name_format + '_' + field_name);
					
					if(form_field.parents('div.line').children('div.formDot').length) {
						field_dot = form_field.parents('div.line').children('div.formDot');
					}
					
					if(c.helpers_enabled) {
						field_help = form_field.parents('div.line').find('div.lineHelpWrapper');
					}
				
					if (c.validation_enabled || c.helpers_enabled) {
						if(c.validation_enabled) {
							if(form_field.is('select,:radio')) {
								form_field.change(self.addValidation);
							}
						
							form_field.blur(self.addValidation);
						}
						else {
							form_field.blur(self.hideTooltip);
						}
						
						form_field.focus(self.showTooltip);
					}
				
					isInitialized = true;
				} 
				else {
					isInitialized = false;
				}
			},
			addValidation: function() {
				var serialized_form = form_field.parents('form').serialize();
				
				if (!serialized_form) {
					return false;
				}
				
				// rel for tags, divs
				var elName = form_field.attr('rel') || form_field.attr('name');

				var params = "el=" + elName + "&"
						+ serialized_form;

				$.ajax( {
					url : '/validate/element',
					data : params,
					dataType : 'json',
					type : 'POST',
					beforeSend: function(jqXHR, settings) {
						self.hideTooltip();
					},
					complete: function(data) {
						self.JsonUpdaterElement(data);
					}
				});
			},
			resetValidation: function(text) {
				self.setClassesWrong();
				self.setErrorTip(text, '-');
				self.hideTooltip();
			},
			JsonUpdaterElement: function(xhr) {
				json = system.getHeaderJSON(xhr);

				var numElementsInResponse = 0;

				if (json) {
					numElementsInResponse = json.length;
				} 

				if (numElementsInResponse == 0) {
					self.setErrorTipCorrect();
				} 
				else {
					var elementId;
					var elementText;

					for (var i = 0; i < numElementsInResponse; i++) {
						elementId = json[i][0];
						elementText = json[i][1];

						self.setErrorTipWrong(elementText);
					}
				}
			},
			setClassesWrong: function() {
	            form_field.parents('div.line')
	            	.removeClass('correct')
	            	.addClass('wrong')
	            	.addClass('error');
	            
	            form_field.removeClass('correct').addClass('wrong');
	            
				if(error_field) {
					error_field
						.removeClass('correct')
						.addClass('wrong')
						.addClass('lineError');
				}
				
				if(field_dot) {
					field_dot.removeClass('correct').addClass('wrong');
				}
				
				if(error_container) {
					error_container
						.addClass('errorBox')
						.addClass('infoBox');
				}
			},
			setClassesCorrect: function() {
	            form_field.parents('div.line').removeClass('wrong').addClass('correct');
	            
	            form_field.removeClass('wrong').addClass('correct');
	            
				if(error_field) {
					error_field.removeClass('wrong').addClass('correct');
				}
				
				if(field_dot) {
					field_dot.removeClass('wrong').addClass('correct');
				}
			},
			setErrorTipCorrect: function() {
				self.setClassesCorrect();
				self.setErrorTip('', '');
				self.hideTooltip();
			},
			setErrorTipWrong: function(text) {
				self.setClassesWrong();
				self.setErrorTip(text, '');
				//self.showTooltip();
			},
			setErrorTip: function(text, html) {
				if(text) {
					error_field.find('.span').attr('title', text);
				}
				else {
					error_field.find('.span').removeAttr('title');
				}
				
				if(field_dot) {
					field_dot.text(html);
				}
			},
			isInitialized: function() {
				return isInitialized;
			},
			showTooltip: function() {
				if(c.global_enabled) {
					if(error_field.hasClass('wrong')) {
						var globalError = $('#form-error-global');

						if(globalError.length) {
							var text = error_field.find('.span').attr('title');
							
							globalError.find('p#errorhelp_msg').text(text);
							globalError.show();
							globalError.data('displayed-field', error_field.attr('id'));
						}
					}
				}
				
				if(c.field_enabled && error_field.hasClass('wrong')) {
					if(!field_error_tooltip) {
						field_error_tooltip = $('<div class="popUp"><div class="lineErrorContainer"><div class="lineErrorBox"><div class="lineErrorBorder"></div><div class="lineErrorBg-2"></div></div></div></div>');
					}
					
					field_error_tooltip.find('.lineErrorBorder').html(error_field.find('.span').attr('title'));
					error_field.find('.span').append(field_error_tooltip);
					error_field.show();
					
					if(error_container) {
						error_container.show();
					}
				}
				else if(c.helpers_enabled && field_help && !error_field.hasClass('wrong')) {
					if(!field_help_tooltip) {
						field_help_tooltip = $('<div class="popUp"><div class="lineInfoContainer"><div class="lineInfoBox"><div class="lineInfoBorder"></div><div class="lineInfoBg-1"></div><div class="lineInfoBg-2"></div><div class="lineInfoBg-4"></div></div></div></div>');
					}
					
					field_help_tooltip.find('.lineInfoBorder').html(field_help.html());
					error_field.addClass('lineInfo');
					error_field.find('.span').append(field_help_tooltip);
					error_field.show();
					
					if(error_container) {
						error_container.show();
					}
				}
			},
			hideTooltip: function() {
				if(c.global_enabled) {
					var globalError = $('#form-error-global');
					
					if(globalError.length) {
						if(globalError.data('displayed-field') == error_field.attr('id')) {
							globalError.hide();
							globalError.find('p#errorhelp_msg').text('');
							globalError.removeData('displayed-field');
						}
					}
				}
				
				if(c.field_enabled) {
					error_field.removeClass('lineError');
					error_field.find('.span').empty();
					form_field.parents('div.line').removeClass('error');
					
					if(error_container) {
						error_container.hide();
					}
					
					error_field.hide();
				}
				
				if(c.helpers_enabled && field_help) {
					error_field.removeClass('lineInfo');
					error_field.find('.span').empty();
					
					if(error_container) {
						error_container.hide();
					}
					
					error_field.hide();
				}
			}
		});
		
		self.bind();
	};

	$.fn.IvAjaxValidation = function(conf) {
		return this.each(function() {
			var element = $(this);

			// Return early if this element already has a plugin instance
			if (element.data('IvAjaxValidation')) {
				if(conf && conf.api && conf.api == true) {
					return element.data('IvAjaxValidation');
				}
				else {
					return;
				}
			}
			
			// pass conf to plugin constructor
			var IvAjaxValidation = new IvAjaxValidator(this, conf);
	
			// Store plugin object in this element's data
			element.data('IvAjaxValidation', IvAjaxValidation);
		});
	};
})
(jQuery);

// array reverse
( function($) {
	$.fn.reverse = [].reverse;
})
(jQuery);

function IvAV_JSONUpdater(xhr, hidden_id, form_id) {
	var json = system.getHeaderJSON(xhr);

	if(!json) {
		return;
	}

	var current_form = jQuery.IvAjaxValidatorForms(form_id, json);
	var numElementsInResponse = json.length;

	if (numElementsInResponse == 0) {
		eval(String(jQuery('#' + hidden_id).val()));
	} 
	else {
		jQuery.iv.IvAV.preventSend('#' + hidden_id.replace('eval_onsuccess', 'prevent_send_'), false);
		
		var elementId;
		var elementText;

		for ( var i = 0; i < numElementsInResponse; i++) {
			elementId = json[i][0];
			elementText = json[i][1];

			current_form.showError(elementId, elementText, (i == 0));
		}
	}
}

(function($) {
	$.iv = $.iv || {};
	$.iv.IvAV = {
		preventSend: function(field, setval) {
			if($(field).length) {
				$(field).val((setval?1:0));
			}
		},
		isPreventedSend: function(field) {
			var prevented = false;
			
			if($(field).length) {
				prevented = (0 != $(field).val());
			}
			
			return prevented;
		}
	};
})
(jQuery);

function initFormValues(sel) {
	sel = sel || '';

	jQuery(sel + 'input[type=text]:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'input[type=hidden]:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'input[type=password]:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'input[type=date]:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'textarea:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'input[type=radio]:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'select:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'div.text:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery(sel + 'select.text:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
	jQuery('input[type=checkbox]:not(.novalid)').each( function(s, e) {
		jQuery(e).IvAjaxValidation();
	});
}

jQuery(document).ready(function() { initFormValues(); });

