if (!String.prototype.format) {
    String.prototype.format = function() {
        var s = this,
        i = arguments.length;

        while (i--) {
            s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
        }
        return s;
    };
}

if (!String.prototype.contains) {
    String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
}

function showPopup(id, noAnimate) {
    $("#bgpopup").remove();
    $(".popup").css("top", "-1000px");
    $(".popup").css("left", "-1000px");

    $('body').append('<div id="bgpopup"></div>');
    if (noAnimate == true) {
        $("#bgpopup").css("opacity", 0);
    }
    $("#bgpopup").css("height", $(document).height() + "px");
    $('#bgpopup').animate({
        opacity: 0.5
    }, noAnimate == true ? 0 : 500, function() {
    });
    $("#" + id).css("top", $(window).scrollTop() + $(window).height() / 2 - $("#" + id).height() / 2 + "px");
    $("#" + id).css("left", $(window).width() / 2 - $("#" + id).width() / 2 + "px");
    $("#" + id + " .closePopup").click(function(e) {
        e.preventDefault();
        $("#{0} .errorMessage".format(id)).detach();
        hidePopup(id);
    });
}

function hidePopup(id) {
    $('#bgpopup').animate({
        opacity: 0
    }, 500, function() {
        $("#bgpopup").remove();
    });
    $("#" + id).css("top", "-1000px");
    $("#" + id).css("left", "-1000px");
}

function dropErrorBoxInPopup(o) {
    $('#' + o.attr('id') + '_error').detach();
}

function showErrorBoxInPopup(o, ec, em) {
    dropErrorBoxInPopup(o);
    o.closest('.formField').after(ec.format(o.attr('id'), em));
}

function showAjaxErrorMessage(cid, em) {
    $('#' + cid + ' .formBlockError').html('<strong>' + em + '</strong>');
    $('#' + cid + ' .formBlockError').show();
}

function hideAjaxErrorMessage(cid) {
    $('#' + cid + ' .formBlockError').hide();
}

function maskDialog(id, m) {
    $("#" + id).mask(m);
}

function unmaskDialog(id) {
    $("#" + id).unmask();
}

function checkValueMaximumLength(o, doTrim, maximumLength) {
    var value = o;
    if (doTrim === undefined || doTrim === true) {
        value = o.trim();
    }
    if (maximumLength !== undefined && maximumLength > 0 && value.length > maximumLength) {
        return false;
    }
    return true;
}

function checkMaximumLength(o, doTrim, maximumLength) {
    return checkValueMaximumLength(o.val(), doTrim, maximumLength);
}

function checkFieldLength(o) {
    if (o.val().length < 1) {
        return false;
    } else {
        return true;
    }
};

function checkRegexp(o, r) {
    if (!(r.test(o.val()))) {
        return false;
    } else {
        return true;
    }
}

function checkEmailRegexp(o) {
    var regexp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return checkRegexp(o, regexp);
}

function checkPhoneNumber(o) {
    var regexp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
    return checkRegexp(o, regexp);
};

function checkUrl(o) {
    var regexp = new RegExp("^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$", "");
    return regexp.test(o.val());
};

function checkDate(o) {
    var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
    return checkRegexp(o, regexp);
};

function checkTime(o) {
    var regexp = /^(2[0-3])|[01][0-9]:[0-5][0-9]$/;
    return checkRegexp(o, regexp);
};

function isNotMax(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    var code = e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode)

    switch (code) {
        case 13:
        case 8:
        case 9:
        case 46:
        case 37:
        case 38:
        case 39:
        case 40:
            return true;
    }
    return target.value.length <= target.getAttribute('maxlength');
}

function extend(Child, Parent) {
    var F = function() { }
    F.prototype = Parent.prototype
    Child.prototype = new F()
    Child.prototype.constructor = Child
    Child.superclass = Parent.prototype
}

function BaseForm(formId) {
    this.isValid = false;
    this._formId = formId;

    this._errorContainer = '<div id="{0}_error" class="errorMessage"><strong>{1}</strong></div>';

    this.getControlById = function(parentControlId, controlId, option) {
        if (controlId != undefined && controlId != null) {
            if (option != undefined && option != null) {
                return $('#{0} #{1} #{2} {3}'.format(this._formId, parentControlId, controlId, option));
            }
            return $('#{0} #{1} #{2}'.format(this._formId, parentControlId, controlId));
        }
        if (option != undefined && option != null) {
            return $('#{0} #{1} {2}'.format(this._formId, parentControlId, option));
        }
        return $('#{0} #{1}'.format(this._formId, parentControlId));
    };

    this.registerMandatoryField = function(o) {
        o.keypress(function() {
            dropErrorBoxInPopup(o);
        });
        o.change(function() {
            dropErrorBoxInPopup(o);
        });
    };

    this.showErrorBox = function(o, em) {
        showErrorBoxInPopup(o, this._errorContainer, em);
        this.isValid = false;
    };

    this.clearErrorBoxes = function() {
        $('#' + this._formId + ' .errorMessage').detach();
    };
}

function SendLinkForm(formId) {
    SendLinkForm.superclass.constructor.call(this, formId);

    this.emailFromId = 'emailFrom';
    this.emailToId = 'emailTo';
    this.emailMessageId = 'emailMessage';
    this.emailFromRequiredMessage = '';
    this.emailFromWrongFormatMessage = '';
    this.emailToRequiredMessage = '';
    this.emailToWrongFormatMessage = '';
    this.messageRequiredMessage = '';
    this.pageLinkUrl = '';

    var serviceUrl = '/Services/EventSendLink.axd';

    this.init = function(emailFromId, emailToId, emailMessageId) {
        this.emailFromId = emailFromId;
        this.emailToId = emailToId;
        this.emailMessageId = emailMessageId;
        this.registerMandatoryField(this.getControlById(this.emailFromId));
        this.registerMandatoryField(this.getControlById(this.emailToId));
        this.registerMandatoryField(this.getControlById(this.emailMessageId));

        var me = this;
        this.getControlById(this.emailFromId).keypress(function() {
            me.getControlById('{0}_ok'.format(me.emailFromId)).hide();
            me.getControlById('{0}_err'.format(me.emailFromId)).hide();
        });
        this.getControlById(this.emailFromId).change(function() {
            me.isValid = true;
            me.validateEmailFrom();
            if (me.isValid) {
                me.getControlById('{0}_ok'.format(me.emailFromId)).show();
                me.getControlById('{0}_err'.format(me.emailFromId)).hide();
            } else {
                me.getControlById('{0}_ok'.format(me.emailFromId)).hide();
                me.getControlById('{0}_err'.format(me.emailFromId)).show();
            }
        });

        this.getControlById(this.emailToId).keypress(function() {
            me.getControlById('{0}_ok'.format(me.emailToId)).hide();
            me.getControlById('{0}_err'.format(me.emailToId)).hide();
        });
        this.getControlById(this.emailToId).change(function() {
            me.isValid = true;
            me.validateEmailTo();
            if (me.isValid) {
                me.getControlById('{0}_ok'.format(me.emailToId)).show();
                me.getControlById('{0}_err'.format(me.emailToId)).hide();
            } else {
                me.getControlById('{0}_ok'.format(me.emailToId)).hide();
                me.getControlById('{0}_err'.format(me.emailToId)).show();
            }
        });
    };

    this.validateEmailFrom = function() {
        if (!checkFieldLength(this.getControlById(this.emailFromId))) {
            this.showErrorBox(this.getControlById(this.emailFromId), this.emailFromRequiredMessage);
        } else if (!checkEmailRegexp(this.getControlById(this.emailFromId))) {
            this.showErrorBox(this.getControlById(this.emailFromId), this.emailFromWrongFormatMessage);
        }
    };

    this.validateEmailTo = function() {
        if (!checkFieldLength(this.getControlById(this.emailToId))) {
            this.showErrorBox(this.getControlById(this.emailToId), this.emailToRequiredMessage);
        } else if (!checkEmailRegexp(this.getControlById(this.emailToId))) {
            this.showErrorBox(this.getControlById(this.emailToId), this.emailToWrongFormatMessage);
        }
    };

    this.showForm = function() {
        this.getControlById(this.emailFromId).val('');
        this.getControlById(this.emailToId).val('');
        this.getControlById(this.emailMessageId).val('');
        showPopup(this._formId);
        this.getControlById(this.emailFromId).focus();
    };

    this.performValidation = function() {
        this.isValid = true;
        hideAjaxErrorMessage(this._formId);
        this.validateEmailFrom();
        this.validateEmailTo();
        if (!checkFieldLength(this.getControlById(this.emailMessageId))) {
            this.showErrorBox(this.getControlById(this.emailMessageId), this.messageRequiredMessage);
        }
    };

    this.resetFields = function() {
        this.getControlById(this.emailFromId).val('');
        this.getControlById(this.emailToId).val('');
        this.getControlById(this.emailMessageId).val('');
        this.getControlById(this.emailFromId).focus();
        this.getControlById('{0}_ok'.format(this.emailFromId)).hide();
        this.getControlById('{0}_err'.format(this.emailFromId)).hide();
        this.getControlById('{0}_ok'.format(this.emailToId)).hide();
        this.getControlById('{0}_err'.format(this.emailToId)).hide();
    };

    this.trySend = function(loadingMessage, errorRequestMessage) {
        this.performValidation();
        if (!this.isValid) {
            return;
        }
        maskDialog(this._formId, loadingMessage);
        var postData = {
            from: this.getControlById(this.emailFromId).val(),
            to: this.getControlById(this.emailToId).val(),
            message: this.getControlById(this.emailMessageId).val(),
            pagelink: this.pageLinkUrl,
            command: 'tellFriend'
        };
        var me = this;
        $.ajax({
            type: 'POST',
            url: serviceUrl,
            cache: false,
            data: postData,
            dataType: 'json',
            success: function(result) {
                if (result.IsValid) {
                    me.getControlById(me.emailFromId).val('');
                    me.getControlById(me.emailToId).val('');
                    me.getControlById(me.emailMessageId).val('');
                    hidePopup(me._formId);
                    unmaskDialog(me._formId);
                } else {
                    unmaskDialog(me._formId);
                    showAjaxErrorMessage(me._formId, result.ErrorMessage);
                }
            },
            error: function() {
                unmaskDialog(me._formId);
                showAjaxErrorMessage(me._formId, errorRequestMessage);
            }
        });
    };
}
extend(SendLinkForm, BaseForm);

function CreateUserPostForm(formId) {
    CreateUserPostForm.superclass.constructor.call(this, formId);

    var _self = this;

    this.userPostData = {
        name: '',
        organizer: '',
        type: null,
        typeText: '',
        category: null,
        categoryText: '',
        description: '',
        startdate: '',
        enddate: '',
        lastdateofreg: '',
        startingtime: '',
        endingtime: '',
        city: '',
        location: '',
        cost: '',
        targetgroup: '',
        email: '',
        phonenumber: '',
        webpage: '',
        emaildm: '',
        phonenumberdm: ''
    };

    this.step1 = {
        Id: 'formRegister1',
        Fields: {
            NameId: 'event_name',
            OrganizerId: 'event_organizer',
            TypeId: 'event_type',
            CategoryId: 'event_category',
            DescriptionId: 'event_description'
        },
        Messages: {
            NameRequired: '',
            OrganizerRequired: '',
            DescriptionRequired: '',
            TypeRequired: '',
            CategoryRequired: '',
            DescriptionTooLong: ''
        },
        DescriptionMaximumLength: 0
    };

    this.step2 = {
        Id: 'formRegister2',
        Fields: {
            StartDateId: 'event_startdate',
            EndDateId: 'event_enddate',
            LastDateOfRegId: 'event_lastdateofreg',
            StartingTimeId: 'event_startingtime',
            EndingTimeId: 'event_endingtime',
            CityId: 'event_city',
            LocationId: 'event_location',
            CostId: 'event_cost',
            TargetGroupId: 'event_targetgroup'
        },
        Messages: {
            StartDateRequired: '',
            StartDateInvalid: '',
            CityRequired: '',
            EndDateInvalid: '',
            StartingTimeInvalid: '',
            EndingTimeInvalid: '',
            WrongEventRegistrationLastDate: ''
        }
    };

    this.step3 = {
        Id: 'formRegister3',
        Fields: {
            EmailId: 'event_email',
            PhoneNumberId: 'event_phonenumber',
            WebPageId: 'event_webpage',
            EmailDmId: 'event_emaildm',
            PhoneNumberdmId: 'event_phonenumberdm',
            SameAsAboveId: 'event_sameasabove'
        },
        Messages: {
            EmailInvalid: '',
            EmaildmRequired: '',
            EmaildmInvalid: '',
            WebpageInvalid: ''
        }
    };

    this.step4 = {
        Id: 'formRegister4',
        Fields: {
            NameId: 'userpost_name',
            OrganizerId: 'userpost_organizer',
            DescriptionId: 'userpost_description',
            StartdateId: 'userpost_startdate',
            CityId: 'userpost_city',
            EmaildmId: 'userpost_emaildm',
            TypeId: 'userpost_type',
            CategoryId: 'userpost_category',
            EnddateId: 'userpost_enddate',
            LastdateofregId: 'userpost_lastdateofreg',
            StartingtimeId: 'userpost_startingtime',
            EndingtimeId: 'userpost_endingtime',
            LocationId: 'userpost_location',
            CostId: 'userpost_cost',
            TargetgroupId: 'userpost_targetgroup',
            EmailId: 'userpost_email',
            WebpageId: 'userpost_webpage',
            PhoneNumberId: 'userpost_phonenumber',
            PhoneNumberdmId: 'userpost_phonenumberdm'
        },
        Messages: {
            SuccesfullySaved: ''
        }
    };

    var serviceUrl = '/Services/CreateUserPost.axd';

    var copyContactInfoForDM = function() {
        with (_self) {
            getControlById(step3.Id, step3.Fields.EmailDmId).val(getControlById(step3.Id, step3.Fields.EmailId).val());
            getControlById(step3.Id, step3.Fields.EmailDmId).attr('disabled', 'disabled');
            getControlById(step3.Id, step3.Fields.PhoneNumberdmId).val(getControlById(step3.Id, step3.Fields.PhoneNumberId).val());
            getControlById(step3.Id, step3.Fields.PhoneNumberdmId).attr('disabled', 'disabled');
            dropErrorBoxInPopup(getControlById(step3.Id, step3.Fields.EmailDmId));
            dropErrorBoxInPopup(getControlById(step3.Id, step3.Fields.PhoneNumberdmId));
        }
    };

    var enableChangeDMInfo = function() {
        with (_self) {
            getControlById(step3.Id, step3.Fields.EmailDmId).removeAttr('disabled');
            getControlById(step3.Id, step3.Fields.PhoneNumberdmId).removeAttr('disabled');
        }
    };

    var validateStep1 = function() {
        with (_self) {            
            isValid = true;
            if (!checkFieldLength(getControlById(step1.Id, step1.Fields.NameId))) {
                showErrorBox(getControlById(step1.Id, step1.Fields.NameId), step1.Messages.NameRequired);
            }
            if (!checkFieldLength(getControlById(step1.Id, step1.Fields.OrganizerId))) {
                showErrorBox(getControlById(step1.Id, step1.Fields.OrganizerId), step1.Messages.OrganizerRequired);
            }
            if (!checkFieldLength(getControlById(step1.Id, step1.Fields.DescriptionId))) {
                showErrorBox(getControlById(step1.Id, step1.Fields.DescriptionId), step1.Messages.DescriptionRequired);
            }
            if (getControlById(step1.Id, step1.Fields.TypeId, 'option:selected').length == 0) {
                showErrorBox(getControlById(step1.Id, step1.Fields.TypeId), step1.Messages.TypeRequired);
            }
            if (getControlById(step1.Id, step1.Fields.CategoryId, 'option:selected').length == 0) {
                showErrorBox(getControlById(step1.Id, step1.Fields.CategoryId), step1.Messages.CategoryRequired);
            }
            if (!checkMaximumLength(getControlById(step1.Id, step1.Fields.DescriptionId), true, step1.DescriptionMaximumLength)) {
                showErrorBox(getControlById(step1.Id, step1.Fields.DescriptionId), step1.Messages.DescriptionTooLong);
            }
        }
    };

    var validateStep2 = function() {
        with (_self) {
            isValid = true;
            if (!checkFieldLength(getControlById(step2.Id, step2.Fields.StartDateId))) {
                showErrorBox(getControlById(step2.Id, step2.Fields.StartDateId), step2.Messages.StartDateRequired);
            } else if (!checkDate(getControlById(step2.Id, step2.Fields.StartDateId))) {
                showErrorBox(getControlById(step2.Id, step2.Fields.StartDateId), step2.Messages.StartDateInvalid);
            } else if (checkFieldLength(getControlById(step2.Id, step2.Fields.LastDateOfRegId)) && checkDate(getControlById(step2.Id, step2.Fields.LastDateOfRegId))) {
                var startDate = new Date(getControlById(step2.Id, step2.Fields.StartDateId).val());
                var lastDate = new Date(getControlById(step2.Id, step2.Fields.LastDateOfRegId).val());
                if (lastDate > startDate) {
                    showErrorBox(getControlById(step2.Id, step2.Fields.LastDateOfRegId), step2.Messages.WrongEventRegistrationLastDate);
                }
            }
            if (!checkFieldLength(getControlById(step2.Id, step2.Fields.CityId))) {
                showErrorBox(getControlById(step2.Id, step2.Fields.CityId), step2.Messages.CityRequired);
            }
            if (checkFieldLength(getControlById(step2.Id, step2.Fields.EndDateId))) {
                if (!checkDate(getControlById(step2.Id, step2.Fields.EndDateId))) {
                    showErrorBox(getControlById(step2.Id, step2.Fields.EndDateId), step2.Messages.EndDateInvalid);
                }
            }
            if (checkFieldLength(getControlById(step2.Id, step2.Fields.StartingTimeId))) {
                if (!checkTime(getControlById(step2.Id, step2.Fields.StartingTimeId))) {
                    showErrorBox(getControlById(step2.Id, step2.Fields.StartingTimeId), step2.Messages.StartingTimeInvalid);
                }
            }
            if (checkFieldLength(getControlById(step2.Id, step2.Fields.EndingTimeId))) {
                if (!checkTime(getControlById(step2.Id, step2.Fields.EndingTimeId))) {
                    showErrorBox(getControlById(step2.Id, step2.Fields.EndingTimeId), step2.Messages.EndingTimeInvalid);
                }
            }
        }
    };

    var validateStep3 = function() {
        with (_self) {
            isValid = true;
            if (checkFieldLength(getControlById(step3.Id, step3.Fields.EmailId))) {
                if (!checkEmailRegexp(getControlById(step3.Id, step3.Fields.EmailId))) {
                    showErrorBox(getControlById(step3.Id, step3.Fields.emailId), step3.Messages.EmailInvalid);
                }
            }
            if (!checkFieldLength(getControlById(step3.Id, step3.Fields.EmailDmId))) {
                showErrorBox(getControlById(step3.Id, step3.Fields.EmailDmId), step3.Messages.EmaildmRequired);
            } else if (!checkEmailRegexp(getControlById(step3.Id, step3.Fields.EmailDmId))) {
                showErrorBox(getControlById(step3.Id, step3.Fields.EmailDmId), step3.Messages.EmaildmInvalid);
            }
            if (checkFieldLength(getControlById(step3.Id, step3.Fields.WebPageId))) {
                if (!checkUrl(getControlById(step3.Id, step3.Fields.WebPageId))) {
                    showErrorBox(getControlById(step3.Id, step3.Fields.WebPageId), step3.Messages.WebpageInvalid);
                }
            }
        }
    };

    var fillDropDownSelectedVaues = function(stepId, controlId, listValues) {
        listValues.id = '';
        listValues.text = '';
        var types = _self.getControlById(stepId, controlId, 'option:selected').each(function() {
            if ($(this).val().length > 0) {
                if (listValues.id.length > 0) {
                    listValues.id = listValues.id + '|';
                    listValues.text = listValues.text + ', ';
                }
                listValues.id = listValues.id + $(this).val();
                listValues.text = listValues.text + $(this).text();
            }
        });
    };

    var fillUserPostDataOnStep1 = function() {
        with (_self) {
            userPostData.name = getControlById(step1.Id, step1.Fields.NameId).val();
            userPostData.organizer = getControlById(step1.Id, step1.Fields.OrganizerId).val();

            var listValues = { id: userPostData.type, text: userPostData.typeText };
            fillDropDownSelectedVaues(step1.Id, step1.Fields.TypeId, listValues);
            userPostData.type = listValues.id;
            userPostData.typeText = listValues.text;

            listValues = { id: userPostData.category, text: userPostData.categoryText };
            fillDropDownSelectedVaues(step1.Id, step1.Fields.CategoryId, listValues);
            userPostData.category = listValues.id;
            userPostData.categoryText = listValues.text;

            userPostData.description = getControlById(step1.Id, step1.Fields.DescriptionId).val();
        }
    };

    var fillUserPostDataOnStep2 = function() {
        with (_self) {
            userPostData.startdate = getControlById(step2.Id, step2.Fields.StartDateId).val();
            userPostData.enddate = getControlById(step2.Id, step2.Fields.EndDateId).val();
            userPostData.lastdateofreg = getControlById(step2.Id, step2.Fields.LastDateOfRegId).val();
            userPostData.startingtime = getControlById(step2.Id, step2.Fields.StartingTimeId).val();
            userPostData.endingtime = getControlById(step2.Id, step2.Fields.EndingTimeId).val();
            userPostData.city = getControlById(step2.Id, step2.Fields.CityId).val();
            userPostData.location = getControlById(step2.Id, step2.Fields.LocationId).val();
            userPostData.cost = getControlById(step2.Id, step2.Fields.CostId).val();
            userPostData.targetgroup = getControlById(step2.Id, step2.Fields.TargetGroupId).val();
        }
    };

    var fillUserPostDataOnStep3 = function() {
        with (_self) {
            userPostData.email = getControlById(step3.Id, step3.Fields.EmailId).val();
            userPostData.phonenumber = getControlById(step3.Id, step3.Fields.PhoneNumberId).val();
            userPostData.webpage = getControlById(step3.Id, step3.Fields.WebPageId).val();
            userPostData.emaildm = getControlById(step3.Id, step3.Fields.EmailDmId).val();
            userPostData.phonenumberdm = getControlById(step3.Id, step3.Fields.PhoneNumberdmId).val();
        }
    };

    var fillPreviewData = function() {
        with (_self) {
            // mandatory
            getControlById(step4.Id, step4.Fields.NameId).html(userPostData.name);
            getControlById(step4.Id, step4.Fields.OrganizerId).html(userPostData.organizer);
            getControlById(step4.Id, step4.Fields.DescriptionId).html(userPostData.description);
            getControlById(step4.Id, step4.Fields.StartdateId).html(userPostData.startdate);
            getControlById(step4.Id, step4.Fields.CityId).html(userPostData.city);
            getControlById(step4.Id, step4.Fields.EmaildmId).html(userPostData.emaildm);

            // optional
            if (userPostData.type != null) {
                getControlById(step4.Id, step4.Fields.TypeId).html(userPostData.typeText);
            } else {
                getControlById(step4.Id, step4.Fields.TypeId).html('');
            }
            if (userPostData.category != null) {
                getControlById(step4.Id, step4.Fields.CategoryId).html(userPostData.categoryText);
            } else {
                getControlById(step4.Id, step4.Fields.CategoryId).html('');
            }
            getControlById(step4.Id, step4.Fields.EnddateId).html(userPostData.enddate);
            getControlById(step4.Id, step4.Fields.LastdateofregId).html(userPostData.lastdateofreg);
            getControlById(step4.Id, step4.Fields.StartingtimeId).html(userPostData.startingtime);
            getControlById(step4.Id, step4.Fields.EndingtimeId).html(userPostData.endingtime);
            getControlById(step4.Id, step4.Fields.LocationId).html(userPostData.location);
            getControlById(step4.Id, step4.Fields.CostId).html(userPostData.cost);
            getControlById(step4.Id, step4.Fields.TargetgroupId).html(userPostData.targetgroup);
            getControlById(step4.Id, step4.Fields.PhoneNumberId).html(userPostData.phonenumber);
            getControlById(step4.Id, step4.Fields.PhoneNumberdmId).html(userPostData.phonenumberdm);
            getControlById(step4.Id, step4.Fields.EmailId).html(userPostData.email);
            getControlById(step4.Id, step4.Fields.WebpageId).html(userPostData.webpage);
        }
    };

    var resetFields = function() {
        with (_self) {
            getControlById(step1.Id, step1.Fields.NameId).val('');
            getControlById(step1.Id, step1.Fields.OrganizerId).val('');
            getControlById(step1.Id, step1.Fields.TypeId, 'option').each(function() {
                $(this).attr('selected', false);
            });
            getControlById(step1.Id, step1.Fields.TypeId).dropdownchecklist("refresh");
            getControlById(step1.Id, step1.Fields.CategoryId, 'option').each(function() {
                $(this).attr('selected', false);
            });
            getControlById(step1.Id, step1.Fields.CategoryId).dropdownchecklist("refresh");
            getControlById(step1.Id, step1.Fields.DescriptionId).val('');

            getControlById(step2.Id, step2.Fields.StartDateId).val('');
            getControlById(step2.Id, step2.Fields.EndDateId).val('');
            getControlById(step2.Id, step2.Fields.LastDateOfRegId).val('');
            getControlById(step2.Id, step2.Fields.StartingTimeId).val('');
            getControlById(step2.Id, step2.Fields.EndingTimeId).val('');
            getControlById(step2.Id, step2.Fields.CityId).val('');
            getControlById(step2.Id, step2.Fields.LocationId).val('');
            getControlById(step2.Id, step2.Fields.CostId).val('');
            getControlById(step2.Id, step2.Fields.TargetGroupId).val('');

            getControlById(step3.Id, step3.Fields.EmailId).val('');
            getControlById(step3.Id, step3.Fields.PhoneNumberId).val('');
            getControlById(step3.Id, step3.Fields.WebPageId).val('');
            getControlById(step3.Id, step3.Fields.EmailDmId).val('');
            getControlById(step3.Id, step3.Fields.PhoneNumberdmId).val('');
            enableChangeDMInfo();
            getControlById(step3.Id, step3.Fields.SameAsAboveId).attr('checked', false);
        }
    };

    this.goStep2 = function() {
        $('#ui-datepicker-div').css('z-index', '6');
        window.tinyMCE.triggerSave();
        validateStep1();
        if (this.isValid) {
            fillUserPostDataOnStep1();
            showPopup(this.step2.Id, true);
        }
    };

    this.goStep3 = function() {
        validateStep2();
        if (this.isValid) {
            fillUserPostDataOnStep2();
            showPopup(this.step3.Id, true);
        }
    };

    this.goStep4 = function() {
        hideAjaxErrorMessage(this._formId);
        validateStep3();
        if (this.isValid) {
            fillUserPostDataOnStep3();
            showPopup(this.step4.Id, true);
            fillPreviewData();
        }
    };

    var showSuccesfullMessage = function() {
        showMessageBox(_self.step4.Messages.SuccesfullySaved);
    };

    this.sendUserPost = function() {
        var postData =
		        {
		            name: this.userPostData.name,
		            organizer: this.userPostData.organizer,
		            description: this.userPostData.description,
		            startdate: this.userPostData.startdate,
		            city: this.userPostData.city,
		            emaildm: this.userPostData.emaildm,
		            type: this.userPostData.type,
		            typeText: this.userPostData.typeText,
		            category: this.userPostData.category,
		            categoryText: this.userPostData.categoryText,
		            enddate: this.userPostData.enddate,
		            lastdateofreg: this.userPostData.lastdateofreg,
		            startingtime: this.userPostData.startingtime,
		            endingtime: this.userPostData.endingtime,
		            location: this.userPostData.location,
		            cost: this.userPostData.cost,
		            targetgroup: this.userPostData.targetgroup,
		            email: this.userPostData.email,
		            phonenumber: this.userPostData.phonenumber,
		            webpage: this.userPostData.webpage,
		            phonenumberdm: this.userPostData.phonenumberdm
		        };
        $.ajax({
            type: 'POST',
            url: serviceUrl,
            cache: false,
            data: postData,
            dataType: 'json',
            beforeSend: function(xmlHttpReq) {
                maskDialog(_self.step4.Id, _self.loadingMessage);
            },
            complete: function(xmlHttpReq) {
                unmaskDialog(_self.step4.Id);
            },
            success: function(result) {
                if (!result.IsValid) {
                    showAjaxErrorMessage(_self.step4.Id, result.ErrorMessage);
                    return;
                }
                showSuccesfullMessage();
            },
            error: function(xmlHttpReq, ajaxOptions, thrownError) {
                showAjaxErrorMessage(_self.step4.Id, thrownError || _self.errorRequestMessage);
            }
        });
    };

    var initMandatoryFields = function() {
        with (_self) {
            // formRegister1
            registerMandatoryField(getControlById(step1.Id, step1.Fields.NameId));
            registerMandatoryField(getControlById(step1.Id, step1.Fields.OrganizerId));
            registerMandatoryField(getControlById(step1.Id, step1.Fields.TypeId));
            registerMandatoryField(getControlById(step1.Id, step1.Fields.CategoryId));
            registerMandatoryField(getControlById(step1.Id, step1.Fields.DescriptionId));
            // formRegister2
            registerMandatoryField(getControlById(step2.Id, step2.Fields.StartDateId));
            registerMandatoryField(getControlById(step2.Id, step2.Fields.EndDateId));
            registerMandatoryField(getControlById(step2.Id, step2.Fields.LastDateOfRegId));
            registerMandatoryField(getControlById(step2.Id, step2.Fields.CityId));
            registerMandatoryField(getControlById(step2.Id, step2.Fields.StartingTimeId));
            registerMandatoryField(getControlById(step2.Id, step2.Fields.EndingTimeId));
            // formRegister3
            registerMandatoryField(getControlById(step3.Id, step3.Fields.WebPageId));
            registerMandatoryField(getControlById(step3.Id, step3.Fields.EmailId));
            registerMandatoryField(getControlById(step3.Id, step3.Fields.EmailDmId));
        }
    };

    var initCloseHandlers = function() {
        with (_self) {
            getControlById(step1.Id, null, 'a.closePopup').click(function(e) { e.preventDefault(); resetFields(); });
            getControlById(step2.Id, null, 'a.closePopup').click(function(e) { e.preventDefault(); resetFields(); });
            getControlById(step3.Id, null, 'a.closePopup').click(function(e) { e.preventDefault(); resetFields(); });
            getControlById(step4.Id, null, 'a.closePopup').click(function(e) { e.preventDefault(); resetFields(); });
        }
    };

    var initCopyBehaviour = function() {
        _self.getControlById(_self.step3.Id, _self.step3.Fields.SameAsAboveId).click(function(e) {
            if ($(this).is(':checked')) {
                copyContactInfoForDM();
            } else {
                enableChangeDMInfo();
            }
        });
    };

    var initButtonsEvents = function() {
        _self.getControlById(_self.step1.Id, null, 'a[href="#next"]').click(function(e) { e.preventDefault(); _self.goStep2(); });

        _self.getControlById(_self.step2.Id, null, 'a[href="#next"]').click(function(e) { e.preventDefault(); _self.goStep3(); });
        _self.getControlById(_self.step2.Id, null, 'a[href="#prev"]').click(function(e) { e.preventDefault(); showPopup(_self.step1.Id); });

        _self.getControlById(_self.step3.Id, null, 'a[href="#next"]').click(function(e) { e.preventDefault(); _self.goStep4(); });
        _self.getControlById(_self.step3.Id, null, 'a[href="#prev"]').click(function(e) { e.preventDefault(); showPopup(_self.step2.Id); });

        _self.getControlById(_self.step4.Id, null, 'a[href="#next"]').click(function(e) { e.preventDefault(); _self.sendUserPost(); });
        _self.getControlById(_self.step4.Id, null, 'a[href="#prev"]').click(function(e) { e.preventDefault(); showPopup(_self.step3.Id); });
    };

    this.init = function(typeId, categoryId) {
        _self.step1.Fields.TypeId = typeId;
        _self.step1.Fields.CategoryId = categoryId;
        initMandatoryFields();
        initCloseHandlers();
        initCopyBehaviour();
        initButtonsEvents();
    };

    this.showForm = function() {
        resetFields();
        this.clearErrorBoxes();
        hideAjaxErrorMessage(this._formId);

        showPopup(this.step1.Id);
        this.getControlById(this.step1.Id, this.step1.Fields.NameId).focus();
    };
}
extend(CreateUserPostForm, BaseForm);
