function FormFieldSet(fieldset) {
    this.fadeSpeed = 500;
    this.fieldset = fieldset;
    this.hint = fieldset.find('.hint');
    this.error = fieldset.find('.errorlist');
    this.validatorCache = [];
};
FormFieldSet.prototype.initialize = function() {
    this.hideHint();
    var formFieldSet = this;
    this.fieldset.find(':input, :text').each(function() {
        var emptyData = formFieldSet.getData()
        for (var key in emptyData) { 
            emptyData[key] = ''; 
        };
        var cacheKey = serializeData(emptyData)
        /* no pre-validation hack
        if ($(this).hasClass('required')) {
            formFieldSet.validatorCache[cacheKey] = 
                    {'status': 'ok', 'errors': ['This field is required.']};
        } else if (!formFieldSet.validatorCache[cacheKey]) {
            formFieldSet.validatorCache[cacheKey] = 
                    {'status': 'ok', 'errors': []};
        };
        */
    });
    var clickCallback = function() { 
        formFieldSet.showHint() 
    }
    var blurCallback = function() {
        formFieldSet.hideHint(); 
        formFieldSet.validateForm() 
    }
    this.fieldset.find(':input, :text').each(function() {
        $(this).click(clickCallback);
        $(this).blur(blurCallback);
    });
}
FormFieldSet.prototype.getData = function() {
    var validationData = {};
    this.fieldset.find(':input, :text').each(function() {
        if ($(this).attr('name'))
            validationData[$(this).attr('name')] = $(this).val();
    });
    return validationData;
};
FormFieldSet.prototype.getId = function() { 
    return this.fieldset.attr('id');
};
FormFieldSet.prototype.toString = function() {
    return '<FormFieldSet id="' + this.getId() + '"';
}
FormFieldSet.prototype.showHint = function() {
    if (this.error.length && this.error.css('display') != 'none')
        return;
    if (this.hint.length && this.hint.css('display') == 'none')
        this.hint.fadeIn(500);
};
FormFieldSet.prototype.hideHint = function() {
    if (this.hint.css('display') != 'none')
        this.hint.fadeOut(500);
};
FormFieldSet.prototype.showErrors = function(errors) {
    var makeFadeIn = this.error.css('display') == 'none';
    if (!this.error.length) {
        this.fieldset.append('<ul class="errorlist"> </ul>');
        this.error = this.fieldset.find('.errorlist');
        makeFadeIn = true;
    };
    if (errors) {
        error_html = '';
        for (var error in errors)
            error_html += '<li>' + errors[error] + '</li>';
        this.error.html(error_html);
    };
    if (this.error.html())
        this.hideHint();
    if (makeFadeIn) {
        this.error.css('display', 'none');
        this.error.fadeIn(this.fadeSpeed);
    }
};
FormFieldSet.prototype.hideErrors = function() {
    if (this.error.css('display') != 'none')
        this.error.fadeOut(this.fadeSpeed);
};
FormFieldSet.prototype.validationCallback = function(response, cacheKey) {
    if (cacheKey) {
        this.validatorCache[cacheKey] = response;
    }
    try {
        if (response.status == 'ok' && response.errors.length) {
            this.showErrors(response.errors);
        } else {
            this.hideErrors();
        }
    } catch(e) {
        $.log.debug('Exception: ' + e);
    };
};
FormFieldSet.prototype.validateForm = function(data) {
    var data = data || this.getData();
    var cacheKey = serializeData(data);
    if (cacheKey in this.validatorCache) {
        response = this.validatorCache[cacheKey];
        this.validationCallback(response);
    } else {
        data.xhr = true;
        var formField = this;
        var callback = function(response) {
            formField.validationCallback(response, cacheKey);
        };
        $.post(".", data, callback, "json");
    }
};

function serializeData(inputData) {
    serializedData = '';
    for (var inputKey in inputData) {
        var inputValue = inputData[inputKey] || '<null>';
        serializedData += '@' + inputKey + ':' + inputValue;
    };
    return serializedData;
}

placementForms = {}

function updateFormFieldSets(forms) {
	$('fieldset').each(function() {
        var form = new FormFieldSet($(this));
        form.initialize();
        placementForms[form.getId()] = form;
    });
};


function import_script(script_name) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = script_name;
    document.getElementsByTagName('head')[0].appendChild(script);
}

function reload_post(element, post, search) {
    var element = $(element);
    element.html('<img src="' + AJAX_LOADER_SMALL_IMG_URL + '"/>');
	var _timestamp = new Date().getTime();
    $.post('./?xhr=' + element.attr('id') + search + '&noCache='+_timestamp, post, function(data) {
        var post_data = data;
		var _timestampGet = new Date().getTime();
        /* zkh @ refactoring needed */
	    $.get('./?xhr=' + element.attr('id') + search + '&noCache='+_timestampGet, null, function(data) {
            var rx_pass = /type="password" id="id_password" class="vPasswordField" name="password"/;
            var rx_err = /<ul class="errorlist">/;
            var pass_test = (rx_pass.test(post_data) && rx_pass.test(data));
            var err_test = (rx_err.test(post_data) && !rx_err.test(data));
            if (pass_test || err_test) {
                element.replaceWith(post_data);
            } else {
                element.replaceWith(data);
            }
		    $('#advert_form').trigger('update_focusables');
            updateFormFieldSets();
		});
    });
}

function reload_get(element, search) {
    var element = $(element);
    element.html('<img src="' + AJAX_LOADER_SMALL_IMG_URL + '"/>');
    $.get('.' + search, { xhr: element.attr('id') },
    function(data) {
        element.replaceWith(data);
		$('#advert_form').trigger('update_focusables');
        updateFormFieldSets();
    });
}

function submit_advert_form() {
    if ($.browser.msie) {
        // _ie_sux is zkh for IE
        var _ie_sux = {
            'checked': $('input:checked'), 
            'notchecked': $('input:not(:checked)')
        };
    };
    if ($('.ajax_reload_post').size() || ($('.ajax_reload_get').size())) {
        $('#advert_form').submit();
        return;
    }
    $('#advert_form_content').children(':not(form,[name="next"])').each(function() {
        $('#advert_form').append($(this));
    });
    if ($.browser.msie) {
        _ie_sux['checked'].each(function() { $(this).attr('checked', true); });
        _ie_sux['notchecked'].each(function() { $(this).removeAttr('checked'); });
    }
    $('#advert_form_content').hide();
    $('#advert_form').submit();
    return false;
}

function phoneCheckboxesInit() {
    var privacyNumberCheckbox = $('#id_want_privacy_number');
    if (!privacyNumberCheckbox.length) {
        return false;
    }
    var mobilePhone = $('#id_mobile_phone');
    var mobilePhoneCheckbox = $('#id_mobile_phone_checkbox');
    var landLine = $('#id_land_line');
    var landLineCheckbox = $('#id_land_line_checkbox');
    var privacyNumberCheckboxUpdate = function() {
        if (!landLineCheckbox.attr('checked') && !mobilePhoneCheckbox.attr('checked')) {
            privacyNumberCheckbox.removeAttr('checked');
        }
    }
    var privacyNumberCheckboxClick = function() {
        if (privacyNumberCheckbox.attr('checked')) {
            $.trim(landLine.val()).length && landLineCheckbox.attr('checked', true);
            $.trim(mobilePhone.val()).length && mobilePhoneCheckbox.attr('checked', true);
        }
    }
    privacyNumberCheckbox.click(privacyNumberCheckboxClick);
    landLineCheckbox.click(privacyNumberCheckboxUpdate);
    mobilePhoneCheckbox.click(privacyNumberCheckboxUpdate);
};


$(document).ready(function() {
    updateFormFieldSets();
    phoneCheckboxesInit();

	$('input[name="next"]').click(function() {
        if($('.mainColumn.options')){
			$('.mainColumn.options div.buttons').hide();
		}
		if($('.mainColumn .form_errors').css('display')!='none'){
			$('.mainColumn .form_errors').hide();
		}
		submit_advert_form();
        setTimeout('phoneCheckboxesInit();', 4000);
        return false;
    });
    $('#advert_form').submit(function() {
        if ($('.ajax_reload_post').size()) {
            var search = location.search.replace(/\?/, '&');
            $('.ajax_reload_post').each(function() {
                var post = {};
                $(this).find(':input:not(:checkbox),:checkbox:checked').each(function() {
                    post[$(this).attr('name')] = $(this).val();
                });
                $(this).find('select > option:selected').each(function() {
                   post[$(this).parent().attr('name')] = $(this).val();
                });
                reload_post(this, post, search);
            });
            return false;
        }
        if ($('.ajax_reload_get').size()) {
            var search = '/' + location.search;
            $('.ajax_reload_get').each(function() {
                reload_get(this, search);
            });
            return false;
        }
    });
});


var EventPlacment = {
	hintClass: "hint",
	errorlistClass: "errorlist",
	timeIn: 500,
	timeOut: 100,
	errorColor: "#FFBFCE",
	init: function(){
		$("input,textarea,select").each(function(){
			$(this).click(function(){
				if($(this).parent().hasClass("error")){
					$(this).css({
						"background-color":"#FFF"
					})
					$(this).parent().find("."+EventPlacment.errorlistClass).hide();
				}
				var id = $(this).attr("id");
				$("#"+id+"_"+EventPlacment.hintClass).fadeIn(EventPlacment.timeIn);
			});
			if ($(this).parent().hasClass("error") && $(this).attr("type")!="checkbox" && $(this).attr("type")!="radio") {
				$(this).css({
					"background-color":EventPlacment.errorColor
				})
			}
			$(this).blur(function(){
				var id = $(this).attr("id");
				$("#"+id+"_"+EventPlacment.hintClass).fadeOut(EventPlacment.timeOut);
				if ($(this).parent().hasClass("error") && $(this).attr("type")!="checkbox" && $(this).attr("type")!="radio" && $(this).val()=='') {
					$(this).css({
						"background-color":EventPlacment.errorColor
					})
					$(this).parent().find("."+EventPlacment.errorlistClass).show();
				}
			})
		})	
	}
}
