/*
    Wrapper on jQuery Dialog and ajaxForm(). Handles multi step ajax forms.
*/
$.fn.popup = function(options){
    var defaultOptions = {

        // --------------------- General Options --------------------

        // URL from which modal content will be taken. If it's not defined gets 
        // link's 'href' attribute value. It's used only for the initial load, 
        // later urls are taken from the form action attribute.
        url: null,

        // Form which will be serialized and sent automatically. By default it's 
        // first form in modal if it doesn't have class .not-setup-form.
        formSelector: 'form:not(.not-setup-form):first',

        // Multistep Wizard mode. Handles multistep forms and reloads Dialog 
        // content. If the flag is true then dataType option is always set to null.
        multiStepWizard: false,

        // How validation erros will be displayed. Available options:
        // 'tooltip', 'base', null
        validatorType: 'tooltip',

        // Initial GET data send with request.
        initialData: null,

        // Function to create initial GET data send with request (don't use with 
        // initialData parameter).
        createInitialData: null,

        // Close modal window in the end.
        closeWhenDone: true,

        // Data type which sent with response. Available values are:
        // 'json', 'html', 'script', 'xml', null
        dataType: 'json',

        // Use jQuery .live() method for click event.
        useLiveClick: false,

        // Automatically handles TinyMCE activation/deactivation for fields 
        // which match this selector.
        tinyMCESelector: '.tinymce-widget',

        // If the action cookie contains key passed in this parameter then 
        // Dialog instance will be displayed automatically after the page will 
        // be loaded.
        actionKey: null,

        // Name of the action cookie. Have to be same as the name set on 
        // server-side.
        actionCookieName: 'actionCookie',

        // Selector to login form. If login form will appear in HTML response
        // then all events are cancelled and validator is set to 
        // signInFormValidator. Useful for modals which require user to be 
        // logged, but we want to display him modal as form of encourage.
        // User privs are recognized on server side, but if sign in form
        // is found in response then we know that login form is displayed,
        // not one originally set in popup.
        // If set to null this option is not used.
        signInFormSelector: '#signinForm',
        signInFormValidator: 'base',

        // --------------------- General Options --------------------


        // --------------------- Events ----------------------

        // Called before everything sending AJAX request
        // beforeLoad($dialog)
        beforeLoad: null,

        // Called just after loading of jQuery Dialog content.
        // onLoad(response, $form, $dialog)
        onLoad: null,

        // Called before request is submitted.
        // beforeSubmit($form, $dialog)
        beforeSubmit: null,

        // Called just of receiving ajax response. If defined default helpers
        // (tinymce, hooks) are not called so it have to handled manually.
        // If function returns true then Dialog will be closed imediatelly.
        // onSuccessSubmit(response, statusText, xhr, $form, $dialog)
        onSuccessSubmit: null,

        // Called after the success response was received. Allows customize how 
        // handles successfull operations. When used the default confirmation
        // message is NOT displayed.
        // onSuccessResponse(response, statusText, xhr, $form, $dialog)
        onSuccessResponse: null,

        // Called after response, and after onSuccessSubmit and
        // onSuccessResponse
        // onAfterResponse(response, statusText, xhr, $form, $dialog)
        onAfterResponse: null,

        // Called before the dialog is closed.
        // beforeClose(event, ui, $dialog)
        beforeClose: null,

        // Called after success response was received and after success handler.
        // It means that success message will be always displayed.
        // If returns true close the modal, if false don't close it, if null use 
        // closeWhenDone setting.
        // onSuccessClose(response, statusText, xhr, $form, $dialog)
        onSuccessClose: null, 

        // Called when modal is closed by Cancel button or X in top right corner.
        // onCancelClose($dialog)
        onCancelClose: null,

        // Called when modal is closed (doesn't matter how).
        // beforeClose(event, ui, $dialog)
        onClose: null,

        // --------------------- Events ----------------------


        // ------------- jQuery Dialog options ---------------

        title: null,
        width: 800,
        height: 'auto',
        resizable: false,
        position: 'center'

        // ------------- jQuery Dialog options ---------------
    };

    var settings = $.extend(defaultOptions, options);

    // if Multistep Wizard mode then some settings are forced
    if (settings.multiStepWizard) {
        settings.dataType = null;
    }

    // Called for every element in chain separately to make sure each instance
    // will be called with own context.
    $(this).each(function() {
        // set parameters which may be specific for each element in chain
        var url = settings.url || strip($(this).attr('href'));
        var title = settings.title || strip($(this).attr('title'));

        if (settings.useLiveClick) {
            // match click handler to selector for now and for future
            $(this).live('click', function(event) {
                event.preventDefault();
                $(this).callPopup(settings, url, title);
                return false;
            });
        } else {
            // match click handler to selector only if was created before
            $(this).click(function(event) {
                event.preventDefault();
                $(this).callPopup(settings, url, title);
                return false;
            });
        }
    });

    // If action key is set and action cookie exists and booth have same value
    // then display this modal (if there is more than one in chain display 
    // first one only).
    if (settings.actionKey) {
        if (typeof actionCookieValue == 'undefined') {
            actionCookieValue = $.cookie(settings.actionCookieName);
            $.cookie(settings.actionCookieName, null, options={path: '/'});
        }
        if (actionCookieValue && settings.actionKey == actionCookieValue) {
            $(this).slice(0).trigger('click');
            actionCookieValue = null;
        }
    }

    return this;
};

/*
    Calls jQuery Dialog. Should be called by popup(). Look there for docs.
*/
$.fn.callPopup = function(settings, url, title) {
    var $dialog = null;

    // prevents from multiple dialogs by double clicking
    var eventSource = $(this);
    if (eventSource.attr('hasDialogOpened') == '1') {
    	return this;
    }
    eventSource.attr('hasDialogOpened', '1');

    // set initial data
    if (settings.createInitialData) {
        settings.initialData = settings.createInitialData();
    }

    // if base dialog container doesn't exist create it
    if (!$dialog) {
        $dialog = $('<div class="dialog"></div>');
    }

    if (settings.beforeLoad) {
        settings.beforeLoad($dialog);
    }

    $dialog.load(url, settings.initialData, function(response, statusText, xhr) {
		$form = $('form', this);
        if (xhr.status == 205)
        {
            document.location = ".";
            return false;
        }
        if (statusText == 'error') {
            displayErrorMessage(xhr, statusText);
        } else {
            // open modal window when all content is loaded
            $(this).dialog('open');

            // If login form was sent it means user is not logged in and have
            // to go through login procedure. Sign In form is displayed and
            // all previously defined events are cancelled, validator is set
            // to defined sign in validator.
            if (settings.signInFormSelector) {
                if ($(response).find(settings.signInFormSelector).length) {
                    settings.validatorType = settings.signInFormValidator;
                    for (var opt in settings) {
                        if (typeof settings[opt] == 'function') {
                            settings[opt] = null;
                        }
                    }
                }
            }
			
			// IE TinyMCE bug
			if ($.browser.msie && $form.has('.tinymce-widget').length){$form.submit(function(){});}

            // activate TinyMCE widgets
            $(settings.tinyMCESelector, this).each(function() { activateTinyMCE(this.id); });

            // call onLoad event
            if (settings.onLoad) {
                settings.onLoad(this);
            }

            // handle onClose event
            $('input[type=button][action=close]', this).live('click', function() {
                var readyToClose = true;
                if (settings.onCancelClose) {
                    readyToClose = settings.onCancelClose($dialog);
                }
                if (readyToClose) {
                    $dialog.dialog('close');
                }
            });

            // handle going back if in Multistep Wizard mode
            if (settings.multiStepWizard) {
                $("#id_go-back", this).live('click', function() {
                    var data = $(settings.formSelector, $dialog).serialize();
                    var url = $("#id_go-back-url").val()+"?go_back=True";
                    $.manageAjax.add('defaultQueue', {
                        success: function(response) {
                            $(settings.tinyMCESelector, $dialog).each(function() { deactivateTinyMCE(this.id); });
                            $validator = $dialog.html(response).find(settings.formSelector).initValidator(settings.validatorType);
                            applyHooks();
                            $(settings.tinyMCESelector, $dialog).each(function() { activateTinyMCE(this.id); });
                        },
                        url: url,
                        cacheResponse: false,
                        data: data
                    });
                    return false;
                });
            }
            // connect ajax form handler to form in modal
            $("form:not(.not-setup-form):first", this).ajaxForm({
                dialog: this, 
                dataType: settings.dataType, 
                beforeSubmit: settings.beforeSubmit, 
                onSuccessSubmit: settings.onSuccessSubmit, 
                onSuccessResponse: settings.onSuccessResponse, 
                onAfterResponse: settings.onAfterResponse,
                onSuccessClose: settings.onSuccessClose,
                closeWhenDone: settings.closeWhenDone,
                tinyMCESelector: settings.tinyMCESelector,
                multiStepWizard: settings.multiStepWizard,
                formSelector: settings.formSelector,
                validatorType: settings.validatorType
            });

            // when Enter button pressed triggers form submit
            $('input', $form).keyup(function(e){
                if (e.keyCode == 13) {
                    $('button[type=submit] .default').click();
                    return false;
                }
                return true;
            });
        }
    }).dialog({ 
        autoOpen: false, // we open dialog when it's loaded (prevents dialog positioning problems)
        modal: true,
        position: settings.position,
        title: title,
        height: settings.height,
        width: settings.width,
        open: function(event, ui){
		    // focus on first input in form
			$('textarea,input[type=text]', this).filter(':visible:first').blur();
            // Disabled scrollbars issue workaround (for Webkit browsers)
            if ($.browser.webkit) {
                window.setTimeout(function(){
                    jQuery(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay');
                }, 100);
            }
        },
        beforeClose: function(event, ui) {
            $(settings.tinyMCESelector, $dialog).each(function() { deactivateTinyMCE(this.id); });
            // handle beforeClose event
            if (settings.beforeClose) {
                return settings.beforeClose(event, ui, $dialog);
            } else {
                return true;
            }
        },
        close: function(event, ui) {
            // handle onClose event
            if (settings.onClose) {
                settings.onClose(event, ui, $dialog);
            }
            if ($(this) != null) {
                $(this).html('').dialog('destroy');
                $dialog = null;
            }
            eventSource.removeAttr('hasDialogOpened');
        },
        resizable: settings.resizable
    });

    return this;
};

function loadCustomValidators(){
	// Phone validator
	$.validator.addMethod("phone", function(phone_number, element) {
	var digits = "0123456789";
	var phoneNumberDelimiters = "()- ext.";
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	var minDigitsInIPhoneNumber = 9;
	s=stripCharsInBag(phone_number,validWorldPhoneChars);
	return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
	}, "Please provide valid phone number");
	
	// Helper functions
	function isInteger(s)
	{ var i;
	for (i = 0; i < s.length; i++)
	{
	// Check that current character is number.
	var c = s.charAt(i);
	if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
	}
	function stripCharsInBag(s, bag)
	{ var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++)
	{
	// Check that current character isn't whitespace.
	var c = s.charAt(i);
	if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
	}
}


$.fn.initValidator = function(validatorName) {
	loadCustomValidators();
    var $validator = null;
    if (validatorName == 'base') {
        $validator = $(this).validate();
    } else if (validatorName == 'tooltip') {
        $validator = $(this).tooltipValidate();
    }
    return $validator;
};

/*
    Disables submit button and adds loader for time when request is processed.
*/
$.fn.disableSubmitButtons = function($el) {
	$(this).each(function() {
        currentClass = $(this).attr("class").split(" ")[0];
        disabledClass = currentClass + '-disabled';
        $(this).attr("disabled", true).addClass(disabledClass);
        if ($(this).parent().first().is('div')) {
			$(this).parent().addClass(disabledClass);
        }
    });
	if($el)
		$(".button-box", $el).after("<div class='clear'><span class='processing-submit-form'></span></div>");
    return this;
};


/*
    Activates submit button and removed loader icon after receiving response.
*/
$.fn.enableSubmitButtons = function($el) {
	$(this).each(function() {
        currentClass = $(this).attr("class").split(" ")[0];
        disabledClass = currentClass + '-disabled';
        $(this).attr("disabled", false).removeClass(disabledClass);
        if ($(this).parent().first().is('div')) {
            ;//$(this).parent().removeClass(disabledClass).addClass(currentClass); 
			//code make crush in signup form
        }
	});
	if($el)
		$(".processing-submit-form", $el).parent().remove();
    return this;
};

/*
    Handles ajax form submit.
*/
$.fn.ajaxForm = function(options) {
    var defaultOptions = {
        // Data type which sent with response. Available values are:
        // 'json', 'html', 'script', 'xml', null
        dataType: 'json',

        // Events callback functions.
        beforeSubmit: null,
        onSuccessSubmit: null,
        onSuccessResponse: null,
        onAfterResponse: null,

        // Automatically handles TinyMCE activation/deactivation for fields 
        // which match this selector.
        tinyMCESelector: '.tinymce-widget',

        // How validation erros will be displayed. Available options:
        // 'tooltip', 'base', null
        validatorType: 'tooltip',

        // Options used only when ajaxForm works inside of jQuery Dialog.
        dialog: null, 
        onSuccessClose: null,
        closeWhenDone: false,
        multiStepWizard: false,
        formSelector: null
    };

    var settings = $.extend(defaultOptions, options);
    var $form = $(this);
    var $validator = $form.initValidator(settings.validatorType);
	if ($.browser.msie && $.browser.version < 9.0){
		$(this).find("input[type='submit'],button[type='submit']").live('click',function(event){
		    $(this).parents('form:first').submit(function(event){
				handleSubmit(settings, $(this), $validator, event);
			});
	    });
	}
    return $(this).live('submit', function(event) {
        handleSubmit(settings, $(this), $validator, event);
    });
};

function handleSubmit(settings, $form, $validator, event){
        var $dialog = settings.dialog != null ? $(settings.dialog) : null;
		$submitButtons = $("input[type='submit']", $form);
        event.preventDefault();

        var url = $form.attr('action');
        var data = $form.serializeArray();

		if (settings.beforeSubmit)
			settings.beforeSubmit($form);
		
        $.manageAjax.add('defaultQueue', {
            url: url,
            data: data,
            type: $form.attr('method'),
            cacheResponse: false,
            dataType: settings.dataType,
            error: function(xhr, statusText, errorThrown) {
                displayErrorMessage(xhr, statusText);
                $submitButtons.enableSubmitButtons($dialog);
            },
			beforeSend: function showRequest(formData, jqForm, options){
				$submitButtons.disableSubmitButtons($dialog);
			},
            success: function showResponse(res, statusText, xhr){
				$submitButtons.enableSubmitButtons($dialog);
				
                // handle onSuccessSubmit event
                if (settings.onSuccessSubmit) {
                    if (settings.onSuccessSubmit(res, statusText, xhr, $form, $dialog)) {
						if ($dialog) {
                            $dialog.dialog('close');
                        }
					}

                // default submit handling
                } else {
                    // if data type is not set
                    if (settings.dataType == null) {
                        if (res != null && typeof res.success == 'undefined' && (settings.onSuccessResponse || settings.multiStepWizard)) {

                            // deactivate TinyMCE widgets
                            $(settings.tinyMCESelector, $dialog).each(function() { deactivateTinyMCE(this.id); });

                            if (settings.onSuccessResponse) {
                                $validator = null;
                                settings.onSuccessResponse(res, statusText, xhr, $form, $dialog);
                            } else if ($dialog) {
                                $validator = $dialog.html(res).find(settings.formSelector).initValidator(settings.validatorType);
                            }

                            applyHooks();
							
                            // activate TinyMCE widgets
                            $(settings.tinyMCESelector, $dialog).each(function() { activateTinyMCE(this.id); });
                        }
                    }

                    if (res != null && typeof res.success != 'undefined') {
                        // if form proceeds successfully
                        if (parseInt(res.success)) {

                            if (!settings.onSuccessResponse) {
                                // if confirmation message passed display it (in modal or jGrowl)
                                if (typeof res.message == 'string') {
                                    if (res.modal_confirm) { 
                                        $('body').confirmationPopup(res.message);
                                    } else {
										if(!res.url){
											$.jGrowl(res.message, {header:'Success'});
										}
                                    }
                                }

                                // if url in response redirect to given url
                                if (typeof res.url != 'undefined') {
                                    window.location = res.url;
                                }
                            } else {
                                // if url in response redirect to given url
                                if (typeof res.url != 'undefined') {
                                    window.location = res.url;
                                }

                                // handle onSuccessResponse event
                                $validator = null;
								settings.onSuccessResponse(res, statusText, xhr, $form, $dialog);
                                applyHooks();
                            }

                            if ($dialog) {
                                // handle onSuccessClose event
                                if (settings.onSuccessClose) {
                                    var closeDialog = settings.onSuccessClose(res, statusText, xhr, $form, $dialog);
                                    if (closeDialog == null) {
                                        closeDialog = settings.closeWhenDone;
                                    }
                                } else {
                                    var closeDialog = settings.closeWhenDone;
                                }

                                // if success and we want close modal
                                if (closeDialog) {
                                    $dialog.dialog('close');
                                }
                            }
                        }
                        // if there are form errors
                        else {
                            // if validator is set and message is array of errors
                            if ($validator && typeof res.message != 'string') {
                                var errors = {};
                                $.each(res.message, function(fieldName, errorMsg) { 
                                    errors[fieldName] = String(errorMsg); 
                                });
                                try {
                                    $validator.showErrors(errors);
                                } catch(ex) {
                                    logger(ex.stack);
                                }
                            // if validator is not set or message is string
                            } else {
                                $form.callErrorPopup({ msg: res.message });
                            }
                        }
                    }
                }
                if (settings.onAfterResponse)
                    settings.onAfterResponse(res, statusText, xhr, $form, $dialog);
            }
        });
    return false;
}


/*
    Set of hooks fixing minor issues.
*/
function applyHooks() {
    // required class causes conflict between jquery.validate and Django Map widget
    $('textarea.vWKTField').removeClass('required');
}

function displayErrorMessage(xhr, statusText) {
    if (typeof DEBUG != 'undefined' && DEBUG) {
        win = window.open('', '_blank', "location=0,resizable=1,scrollbars=1,toolbar=0,status=0,width=800,height=600");
        if (win != null) {
            win.document.write(xhr.responseText);
            win.document.close();
        } else {
            alert(statusText + "\nEnable popups to see more");
        }
    } else {
        $.jGrowl('An error occured during processing your request.', {header:'ERROR'});
    }
}

$.fn.deletePopup = function(params) {
    defaultParams = {
        confirmMsg: "Item removed successfully.",
        questionMsg: "Do You realy want to remove item?",
        width: 330,
        onSuccessRemoval: null
    }
    var settings = $.extend(defaultParams, params);
    var $button = $(this);

    function invokeAction($dialog, url) {
        $.manageAjax.add('defaultQueue', {
            success: function(response, status, xhr) {
                $.jGrowl(settings.confirmMsg, {header:'Success'});
                if (settings.onSuccessRemoval) {
                    settings.onSuccessRemoval(response, status, xhr);
                }
            },
            url: url,
            type: 'POST',
            data: $button.next().find('[name=csrfmiddlewaretoken]').serializeArray(),
            cacheResponse: false
        });
        $dialog.dialog("close");
    }

    $(this).click(function() {
        var url = this.href;
        $("body").prepend('<div id="delete-dialog">'+settings.questionMsg+'</div>');
        $("#delete-dialog").dialog({
            modal: true,
            title: this.title,
            height: 'auto',
            width: settings.width,
            resizable: false,
            buttons: {
                "Cancel": function() { 
                    $(this).dialog("close");
                },
                "OK": function() {
                    invokeAction($(this), url);
                }
            },
            close: function() { $("#delete-dialog").remove(); }
        });
        return false;
    });
    return this;
};

$.fn.confirmationPopup = function(msg) {
    $(this).prepend('<div id="confirm-message-dialog">'+msg+'</div>');
    $("#confirm-message-dialog").dialog({
        modal: true,
        title: 'Success',
        height: 'auto',
        width: 330,
        resizable: false,
        buttons: {"OK": function() { $(this).dialog("close"); } },
        close: function() { $("#confirm-message-dialog").remove(); }
    });
    return this;
};

$.fn.warningPopup = function(params) {
    $(this).live('click', function() {
	    defaultParams = {
	        msg: '',
	        msgFunc: null,
	        width: 330,
	        title: 'Warning',
	        onCancel: null,
	        onConfirm: null,
	        onClose: null,
			labelCancel: 'Cance',
			labelConfirm: 'OK'
	    }
	    var settings = $.extend(defaultParams, params);
	    $obj = $(this);

	    if (settings.msgFunc) {
	        settings.msg = settings.msgFunc($obj);
	    }
		var btns = {};
		btns[settings.labelCancel] = function() { 
            $(this).dialog("close");
            if (settings.onCancel) {
                settings.onCancel($obj);
            }
        }
		btns[settings.labelConfirm] = function() {
            $(this).dialog("close");
            if (settings.onConfirm) {
                settings.onConfirm($obj);
            }
        }

        $("body").prepend('<div id="warning-dialog">'+settings.msg+'</div>');
        $("#warning-dialog").dialog({
            modal: true,
            title: settings.title,
            height: 'auto',
            width: settings.width,
            resizable: false,
            buttons: btns,
            close: function() { 
                $("#warning-dialog").remove(); 
                if (settings.onClose) {
                    settings.onClose($obj);
                }
            }
        });
        return false;
    });
    return this;
};

$.fn.callErrorPopup = function(params) {
    defaultParams = {
        msg: '',
        width: 330,
        title: 'Form Error'
    }
    var settings = $.extend(defaultParams, params);
    $("body").prepend('<div id="error-message-dialog">'+settings.msg+'</div>');
    $("#error-message-dialog").dialog({
        modal: true,
        title: settings.title,
        height: 'auto',
        width: settings.width,
        resizable: false,
        buttons: {"OK": function() { $(this).dialog("close"); } },
        close: function() { $("#error-message-dialog").remove(); }
    });
};

$.fn.addDreamDialog = function() {
    $(this).popup({
        width:950,
        position:['auto', 10],
        multiStepWizard: true,
        onSuccessClose: function(res, statusText, xhr, $form, $dialog) {
        	if (res.extra_data.cookie_name){
	        	var date = new Date();
	            date.setTime(date.getTime() + (10 * 1000));
	        	$.cookie(res.extra_data.cookie_name, res.extra_data.cookie_value, {expires:date, path:'/'});
	        	window.location = res.extra_data.url;
	        }
        }
    });
    return this;
};


$.fn.addLocationDialog = function(on_close) {
    $(this).unbind('click').popup({
        width: 950,
        position: ['auto', 10],
        multiStepWizard: true,
        actionKey: 'add-location-dialog',
        onClose: function(res, statusText, xhr, $form, $dialog) {
            tbMaps.reloadMap();
            $("#dream-main-locations-plugin").removeClass('content-loaded').find('.plugin-content').remove();
            if ($("#locations-map-list-plugin").tabs('option', 'selected') == 3) {
                $("#locations-map-list-plugin").tabs('select', 2).tabs('select', 3);
            }
            $("#dream-upcoming-events-plugin").removeClass('content-loaded').find(".dream-events-plugin").remove();
			if(on_close){
				on_close();
			}
        }
    });
    return this;
};

$.fn.addSetCurrentLocationDialog = function() {
	$(this).popup({
        width:950,
        position:['auto', 10],
		onSuccessClose : function(res, statusText, xhr, $form) {
            var truncated_location_name = truncate_chars(res.extra_data.selected_location,80);
            $('#set-current-location-link').html(truncated_location_name);
		}
	});
	return this;
};

$.fn.handleAjaxSubmit = function(options) {
    var defaultOptions = {
        beforeSubmit: null,
        onSuccessResponse: null,
        onLoad: null,
        manageButtons: true 
    }
    var settings = $.extend(defaultOptions, options);
	var $dialog = null;

    $(this).live("submit", function() {
        $form = $(this);
        var $submitButtons = $("input[type='submit']", $form);
        if (settings.manageButtons) {
			$submitButtons.disableSubmitButtons($form);
        }
        if (settings.beforeSubmit) {
            settings.beforeSubmit($form, $dialog);
        }
        $.manageAjax.add('defaultQueue', {
            success: function(res) {
                if (settings.manageButtons) {
					$submitButtons.enableSubmitButtons($form);
                }
                if (settings.onSuccessResponse) {
                    settings.onSuccessResponse(res);
                }
                if (typeof res == 'object') {
                    if (typeof $validator != 'undefined' && typeof res.message != 'string') {
                        var errors = {};
                        $.each(res.message, function(i, v){
                            $('#id_'+i+'_ifr').contents().find('body').css('background', '#FAE6E6');
                            $('#id_'+i+'_container').before('<div class="rte-error">'+v+'</div>');
                            errors[i] = ' ' + v;
                        });
                        $validator.showErrors(errors);
                    }
                    else if (parseInt(res.success)) {
						$.jGrowl(res.message, {header:'Success'});
						}
					else {
                        $(this).callErrorPopup({
                            msg: res.message
                        });
                    }
                } else {
                    if (settings.onLoad) {
                        settings.onLoad(res, $form, $dialog);
                    } else {
                        $("#content").html(res);
                    }
                }
            },
            error: function() {
                if (settings.manageButtons) {
					$submitButtons.enableSubmitButtons($form);
                }
            },
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            cacheResponse: false
        });
        return false;
    });
    return this;
};

$.fn.underConstruction = function() {
    $(this).popup({
        width:350,
		title: 'Under Construction',
        url: '/under_construction',
		onLoad: function(){$("body").trigger('click')}
    });
    return this;
};


