﻿(function($) {
    $.fn.dynamicEntity = function(options) {
        var opts = $.extend({}, $.fn.dynamicEntity.defaults, options);

        return this.each(function(i) {
            $this = $(this);

            var container = opts.container;
            var nextIndex = opts.itemCount;
            var itemType = opts.itemType;
            var htmlSource = $(opts.htmlSourceElement).html();
            var deleteItemClassName = opts.deleteItemClassName;
            var onAdd = options.onAdd;

            $(container + " " + deleteItemClassName).live('click', function() {
                var parent = $(this).closest(itemType + '.row');
                var index = $(container + ' ' + itemType).index(parent);
                $(container).find(itemType + ":eq(" + index + ")").remove();
            });

            $this.click(function() {
                var regExp = /{index}*/gi;
                var newHtml = htmlSource.replace(regExp, 'new_' + nextIndex);
                if ($(container).children().size() > 0) {
                    $(container).children(':last').after(newHtml);
                }
                else {
                    $(container).append(newHtml);
                }
                onAdd && onAdd('new_' + nextIndex);
                nextIndex++;
                return false;
            });
            return false;
        });
    };

    $.fn.cascadeDropdown = function(options) {
        var opts = $.extend({}, $.fn.cascadeDropdown.defaults, options);

        return this.each(function(i) {
            $this = $(this);

            var url = opts.url;
            var empty = opts.empty;
            var target = opts.target;

            $this.change(function() {

                var value = $(this).val();
                var totalUrl = url + value;

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: totalUrl,
                    data: "{}",
                    dataType: "html",
                    success: function(data) {
                        if (data.length > 0) {
                            var options = '';
                            for (i in data) {
                                var item = data[i];
                                options += "<option value='" + item.Id + "'>" + item.Naam + "</option>";
                            }
                            $(target).removeAttr('disabled').html(options);
                        }
                        else {
                            $(target).html('<option value=\"\">' + empty + '</option>');
                        }
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        //$("#errorLayer").errorLayer();
                    }
                });

                return false;
            });
        });
    };

    $.fn.errorLayer = function(options) {
        var opts = $.extend({}, $.fn.errorLayer.defaults, options);
        window.onbeforeunload = null;

        return this.each(function(i) {
            var currentId = $(this).attr('id');
            $.fn.colorbox({
                width: "608px",
                opacity: 0.70,
                inline: true,
                overlayClose: false,
                href: '#' + currentId,
                transition: 'elastic'
            });
        });
    };

    $.fn.validatedAjaxPost = function(options) {
        var opts = $.extend({}, $.fn.validatedAjaxPost.defaults, options);

        return this.each(function(i) {
            var $this = $(this);

            var succes = (opts.succes || null);

            if ($this.data("validator")) {
                $this.data("validator").settings.submitHandler = function(form) {
                    $.fn.validatedAjaxPost.send($(form), succes);
                };
            }
            else {
                $this.submit(function() {
                    $.fn.validatedAjaxPost.send($this, succes);
                    return false;
                });
            }
        });
    };

    $.fn.validatedAjaxPost.send = function(form, succes) {
        $.fn.validatedAjaxPost.send($(form), succes, "validationSummary");
    };

    $.fn.validatedAjaxPost.send = function(form, succes, validationSummary) {
        validationSummary = "#" + validationSummary;
        var errorBox = validationSummary + "_errorBox";

        var url = form.attr('action');
        var data = form.serialize();

        $.ajax({
            cache: false,
            data: data,
            type: 'POST',
            success: function(data) {
                if (data == "true" || data == "True") {
                    // Succes so show the succes box
                    if (succes != null) succes(data);
                    /// Hide the errors
                    $(errorBox).hide();
                    /// Hide the summary
                    $(validationSummary).hide();
                    // Show the succes box
                    //$(".succesBox").show("slow");
                    // Hide the succes box after 15 sec
                    //setTimeout(function() { $(".succesBox").hide("slow"); }, 15000);
                }
                else {
                    // First set the html, strange behavior
                    $(".ajaxform").html("");
                    // Then set the html
                    $(".ajaxform").html(data);
                    // Lookup the validation errors and copy them to the outer validation summary.
                    var $errors = $(".validationerrors");
                    if ($errors.length > 0) {
                        $(validationSummary).html($(".validationerrors").html());
                    }
                    // Show the validation summary.
                    $(validationSummary).show();
                    // Show the error box.
                    $(errorBox).show("slow");
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                //$("#errorLayer").errorLayer();
            },
            url: url
        });
    };
    $.fn.validateMiniTix = function() {
        this.each(function() {
            var $t = $(this);
            $t.change(function() {
                //without "06"
                if ($t.val().length == 8) {
                    $.get('/Home/UserHasMiniTix?mobileNumber=' + $t.val(), function(data) {
                        if (data == "true" || data == "True") {
                            $("#imgMiniTix").show();
                        } else {
                            $("#imgMiniTix").hide();
                        }
                    });
                } else {
                    $("#imgMiniTix").hide();
                }
            });
        });

        return this;
    };
})(jQuery);
