(function($)
{
    var config = {};
    var alreadyRepeatedCount = 0;
    var popup = null;
    var timerId = 0;
    var ajaxLoaderTimer = 0;
    var isClosed = false;

    $.fn.quickdemoForm = function() {
        ajaxLoaderTimer = 0;

        $(this).submit(function(event) {
            event.preventDefault();
            
            $(':text', this).each(function() {
                var val = $(this).val();
                var defaultVal = $('label[for='+$(this).attr('id')+']').text();
                if(defaultVal == val) {
                    $(this).val('');
                }
            });
            
            $(":submit", this).attr('disabled', 'disabled');
            var form = this;
            ajaxLoaderTimer = setTimeout(showAjaxLoader, 1000);
            $.post($(this).attr('action'), $(this).serializeArray(), function(data) {
                clearTimeout(ajaxLoaderTimer);
                $.unblockUI();
                /*$(form).parent().html($('#quickdemoFormWrappingDiv', data).html());*/
                $(form).parent().html($(data).html());
            }, 'html');
        });
    };

    $.fn.changeEmailForm = function() {
        $(this).submit(function(event) {
            event.preventDefault();
            
            $(':text', this).each(function() {
                var val = $(this).val();
                var defaultVal = $('label[for='+$(this).attr('id')+']').text();
                if(defaultVal == val) {
                    $(this).val('');
                }
            });
            
            $(":submit", this).attr('disabled', 'disabled');
            var form = this;
            $.post($(this).attr('action'), $(this).serializeArray(), function(data) {
                var html = '';
                if(data.indexOf('<html')!= -1) {
                    html = $(data).html();
                } else {
                    html = data;
                }

                $(form).parent().html(html);
            }, 'html');
        });
    };

    $.fn.formDefaultValues = function() {
        $(':text').each(function() {
            var val = $(this).val();
            var defaultVal = $('label[for='+$(this).attr('id')+']').text();
            if(!val.length || defaultVal == val) {
                $(this).val(defaultVal).addClass('defaultValue');
            }

            $(this).focus(function() {
                if($(this).val() == defaultVal) {
                    $(this).val('').removeClass('defaultValue');
                }
            });

            $(this).blur(function() {
                if(!$(this).val().length || $(this).val() == defaultVal)
                $(this).val(defaultVal).addClass('defaultValue');
            });
        });
    };

    $.fn.quickdemoPopup = function(options) {
        config = options;
        popup = this;
        alreadyRepeatedCount = 0;
        timerId = 0;
        isClosed = false;

        $.pauseAllVimeoPlayers();

        $(popup).modal({
            close: false,
            opacity: 65,
            onClose: closeDialog
        });

        $(popup).find('.correct a').click(function(event) {
            event.preventDefault();
            $(popup).find('form').show();
            $(popup).find(':input[name=id]').val(config.siteId);
            $(popup).find(':input[name=email]').val('').focus();
            $(this).hide();
        });
        
        $(popup).find('.buttons .close').click(function(event) {
            event.preventDefault();
            closeDialog();
        });

        $(document).ajaxError(function(event, request, settings) {
            if (settings.url.toString().search(config.checkUrl) != -1) {
                runAgain();
            }
        });

        checkDemoStatus();
    };

    var checkDemoStatus = function()
    {
        alreadyRepeatedCount++;
        $.getJSON(config.checkUrl, {'site_id': config.siteId}, function(data) {
            if (data.created) {
                $(popup).find('.progress').hide();
                $(popup).find('.success').show();
                $(popup).find('.buttons').show();
                $(popup).addClass('complete');
            } else {
                runAgain();
            }
        });
    };

    var runAgain = function() {
        if (isClosed) {
            return;
        }

        if (alreadyRepeatedCount < config.repeatCount) {
            timerId = setTimeout(checkDemoStatus, config.waitTime * 1000);
        } else {
            $(popup).find('.progress').hide();
            $(popup).find('.fail').show();
            $(popup).find('.buttons').show();
            $(popup).addClass('complete');
        }
    };

    var closeDialog = function() {
        isClosed = true;
        clearTimeout(timerId);
        $.modal.close();
    };

    var showAjaxLoader = function() {
        $.pauseAllVimeoPlayers();
        $('#quickdemo .error').hide();

        $.blockUI({
            message: $('<div id="loader"></div>'),
            css: {
                background: 'transparent',
                border:'none'
            },
            overlayCSS: {
                backgroundColor: '#000000',
                opacity: 0.65
            }
        });
    };

})(jQuery);