/*
 * BP 0.2 "Wraper ajaxForm"
 * By Tomasz Rzany (koszi)
 * Copyright (C) 2009 Agencja Interaktywna Blue Paprica
 *
 * last update: 04.10.2009
*/
(function($){


    $(document).ready(function(){
        // podpiecie formularzy ajaxowych
        $('.ajax_form').livequery('submit',function(){
            $(this).bp_sentAjaxForm();
            return false;
        });

    });

    /**
     *  DEAFULTOWE WARTOSCI DLA FORMULARZY
     *  @param: beforeSubmit    - funkcja wykonywana przed wyslaniem formularza
     *  @param: success         - funkcja wykonywana po odebranie odpowiedzi
     *  @param: type            - typ akcji post/get
     *  @param: dataType        - typ zwracanych danych html/json/script
     */
    $.fn.bp_form_defaults = {
        beforeSubmit    : bpBeforeSubmit,
        success         : bpSubmitSucces,
        type            : 'post',
        dataType        : 'json',
        timeout         : 300000,
        target          : null
    }


    $.fn.bp_sentAjaxForm = function(opt) {
        // dolaczenie przekazanych parametrow do opcji
        options = $.extend({}, $.fn.bp_form_defaults, opt);
        // ustalenie id elementu do ktorego ladujemy odpowiedz
        target  = $(this).parent();
        if(!target.attr('id'))
            target.data('id',target.attr('id')).attr('id','form_in_process');
        target_id = target.attr('id');

        if(typeof target != 'object') {
             log('bp_sentAjaxForm: Formularz nie posiada zadnego rodziaca.');
             return false;
        }
        if ($(this).attr('action') == '' ) {
             log('bp_sentAjaxForm: Formularz nie posiada ustawinej akcji.');
             return false;
        }

        /* jezeli zalaczany jest plik musimy zmienic typ danych */
        file = $(this).find('input[type=file]').val();
        if(file != '' && file != undefined) {
            options.dataType = 'script';
        }

        $.fn.bp_form_defaults.target = target;
        dynamic_options = {target: '#'+target_id};
        options = $.extend({}, options, dynamic_options);
        $(this).ajaxSubmit(options);
        
        return this;
    }

    /**
     * Funkcja odpalana przed wyslanie formularza
     * @desc:   Ukrycie buttona submit
     */
    function bpBeforeSubmit() {
        target = $.fn.bp_form_defaults.target;
//        target.find('input[type=submit]').fadeOut('normal');
    };
    
    /**
     * Obsluga odpowiedzi XHR
     */
    function bpSubmitSucces(response,statusText)
    {
        if($('#TB_window').is(':visible')) {
             $('.filler_top, .filler_bottom').remove();
             $('.roundtop, .roundbottom').remove();
        }
              
        target   = $.fn.bp_form_defaults.target;
        response = $.prepareResponse(response);

        // jeśli hide to ukrywa warstwę
        if(typeof response.hide != 'undefined' && response.hide) {
            bp_closeLayer();
            return;
        }

        // jeśli call to wywołaj funkcję funkcje zwrotną
        if(typeof response.call == 'string') {
            eval(response.call + '(response);');
        }

        // jesli jest ustawiony redirect to odrazu robimy przekierowanie
        if(response.redirect) {
            window.location = response.redirect;
        }

        target.html(' ');
        if(response.result) {
            if (typeof response.message == 'string') {
                if($('#TB_window .layer_head_round').html() != null ) {
                   bp_messageSuccess(response.message);
                } else {
                   target.html('<div class="normal_message">'+response.message+'</div>');
                }
            }
            if (typeof response.growl_message == 'string') {
                $.jGrowl(response.growl_message);
            }
            if (typeof response.form == 'string') {
                target.append(response.form);
            }
        }
        else {
            if (typeof response.message == 'string') {
                if($('#TB_window .layer_head_round').html() !=  null ) {
                   bp_messageError(response.message);
                } else {
                    target.html('<div class="error_message">'+response.message+'</div>');
                }
            }
            if (typeof response.growl_message == 'string') {
                $.jGrowl(response.growl_message);
            }
            if (typeof response.form == 'string') {
                target.append(response.form);
            }
        }
        // wyswietlnie bottona submit
        target.find('input[type=submit]').show();

        // post-callBack
        if(typeof response.postCall == 'string') {
            eval(response.postCall + '(response);');
        }
 
        // przywrocenie pierwotnego id
        target.attr('id',target.data('id'));

        // resize warstwy do nowych wymiarow jesli ta istnieje
        if($('#TB_window').is(':visible')) {
            bp_resizeLayer();
        }

        // zamkniecie warsty po okreslonym czasie
        if(typeof response.timeout != 'undefined' && response.timeout) {
            setTimeout(bp_closeLayer, response.timeout);
            return;
        }
    }

    /**
     * Obiekt respone moze trafic w roznej postaci, obiektu wtedy nic nie zmianiemy
     * lub stringa ktory mial byc obiektem json, wtedy musimy go odpowiedni stworzyc
     */
    $.prepareResponse = function(response)
    {

        if (typeof response != 'object') {
            if(response.indexOf("<pre>")>=0) {
                response = response.substring(5),
                response = response.substring(0, response.length-6);
            }
            response = "("+response+")";
            response = eval(response);

            if (typeof response.form == 'string') {
                response.form = response.form.replace(/&lt;/g,'<').replace(/&gt;/g, '>').replace(/&amp;/g,'&');
            }
            if (typeof response.html == 'string') {
                response.html = response.html.replace(/&lt;/g,'<').replace(/&gt;/g, '>').replace(/&amp;/g,'&');
            }
        }
        return response;
    }
    
    /**
     * Logowanie błedów i zdarzen
     */
    log = function (msg)
    {
        if (!window.console || !console) return;
        if (window.console || console.firebug){
                msg = msg || '';
                if(msg !== '') msg += ': ';
                console.log("%s%o", msg, this);
        }
    }
    
})(jQuery);

