
/***** print_object(szablon_html, obiekt_json)  = obiekt_html ****************
html:  <div id="osoba">
          <div id="osoba_Tpl.id" class="template">Imię: Tpl.imie## Nazwisko: Tpl.nazwisko</div>   
       </div>
 
js:    obiekt_json = {"id":"5", "imie":"Marcin", "nazwisko":"Nowak"}
       obiekt_html = ptint_object('#osoba .temlate', obiekt_json);
       $('#osoba').append(obiekt_html);   
*/
 
function print_object( template, object ){
    var what = jQuery(template).clone('true').removeClass('template').wrap('<div></div>');
    what = what.parent().html();  
    for ( key  in object ) what = what.replace(new RegExp('Tpl.'+ key,'g'), object[key]);
    
    return what;
} 

/**************************************************************************************************/
/**** AJAXOWE POWIADOMIENIA  http://pines.sourceforge.net/pnotify/  ***/
/**** 2 wywolania
 * a) przekazanie obiektu message = {body:"tekst",type:"error"} zwróconego z serwera z funkcji JSONresponse: print_message(message)
 * b) przekazanie wartosci, skrócony zapis do innych zastosowań: print_message("tekst","error")
 * domyslny typ to "notice"
 */
var message_pnotify = null;
function print_message(body, type){
    if ( typeof arguments[0] == 'object'){
        type = body.type;
        body = body.body;
        //title = body.body;
    }

    var delay = (body.length / 5) * 800;  //czas wyswietlania w zaleznosci od dlugosic tekstu
    var title = (type == 'error')? 'Błąd' : 'Informacja';
    if( !type ) type = 'notice';

    //console.log( 'print_message(' + body + ', ' + type + ')' );
    if ( message_pnotify && message_pnotify.pnotify_remove){
        message_pnotify.opts.pnotify_animation = 'none';
        message_pnotify.pnotify_remove();
    }

    message_pnotify = jQuery.pnotify({
        pnotify_title: title,
        pnotify_type: type,
        pnotify_text: body,
        pnotify_hide: true,
        pnotify_delay: delay,
        pnotify_animation: 'fade'
    });
}

/**************************************************************************************************/
function selected_object_id (model){
    var zaznaczony = jQuery('#'+model+" .on");
    if (!zaznaczony.size()){print_message("Żadna pozycja nie jest zaznaczona. Poprzez kliknięcie wybierz, pozycję z tabeli."); return 0; }
    id = zaznaczony.attr("id").replace(model + '_','');
    return id;
}

/**************************************************************************************************/

function delete_object( model, id ){
    if(!id) id = selected_object_id(model);

    if(id){
        if( confirm('Czy napewno chcesz usunąć?') ){
            var object = jQuery('#'+ model +'_'+ id);
            var url = object.find('.del').attr("href");
            if(url=='' || object.is('.on')) url = MAIN_URL+'?action='+model+'&mode=del&ID='+id;

            jQuery.getJSON(url, function(data) {
               print_message(data.message);
               if(data.message.type!='error') object.fadeOut(300,function(){jQuery(this).remove();});
            });
            
            return false;
        }
    }
}

/**************************************************************************************************/

// przechwytywanie powiadomień starego typu (html) i wyswietlani ich jako powiadomienia nowego typu (js)
function reprint(){
    jQuery(".message_notice, .message_error").each(function(){
        var type =  (jQuery(this).is('.message_error'))? "error":"notice";
        var body =  jQuery(this).html();
        print_message(body,type);
    });
}
/***********************************************************************/
/***** AJAXOWE FORMULARZE **********************************************/
/***********************************************************************

parent np TBODY,DIV do którego wstawiamy musi mieć zdefiniowane id i zawierać element z klasą template
np.
<form class="ajax" name="model_form">...</form>

<table>
<tbody id="model">
<tr class="template" id="model_Tpl.id"><td>Tpl.nazwa</td></tr>
...
</tbody>
</table>

taki formularz z automatu wstawi/zaktualizuje obiekt do tabeli o takiej strukturze
mozna nadpisac funkcje ajax_form_options.done jesli potrzeba innej funkcjonalnosci po zwroceniu obiektu
/******/

function json_insert( data, model ){   //wstawia obiekt zwrócony z serwera do HTML
    var insert = jQuery(print_object('#'+ model +' .template', data.object));
    if ( data.mode == 'edit' ){
        jQuery('#'+ model +'_' + data.object.id).replaceWith(insert);
    } else {
      insert.css("display","none");
      jQuery('#'+ model).append(insert); insert.fadeIn("slow");
    }
}

function set_default(object, model){  //ustawia wstawiony obiekt na domyslny
    if( object.domyslny ) {
         jQuery('#'+ model +'_'+ object.id + ' input:radio').attr("checked","true");
         jQuery('#'+ model +' input:radio:checked').attr("checked","false");
    }
}

/**************************************************************************************************/

jQuery(document).ready(function (){
    jQuery('.model .del').click( function(){
        var model = jQuery(this).parents('.model').attr('id');
        var id = jQuery(this).parents("[id^='"+model+"_']").attr('id').replace(model+"_",'');
        delete_object(model,id);
    });

    jQuery.ajaxSetup({ contentType: 'application/x-www-form-urlencoded; charset=iso-8859-2' });

    jQuery('.select').live('click', function(){
        jQuery(this).parents('.model').find('.select').removeClass('on');
        jQuery(this).addClass('on');
    });

    ajax_form_options = {
        success: function(data){
            hideLoading();

            jQuery('#dialog').dialog( "enable" );

            print_message(data.message);

            if ( data.object ){
                jQuery('#dialog').dialog('close');
                
                json_insert(data, this.objectModel);
                set_default(data.object, this.objectModel);
            }
        },
        
       dataType:  'json', // 'xml', 'script', or 'json' (expected server response type)
       // target:        '#dialog'   // target element(s) to be updated with server response 
       beforeSubmit:  function(){
            jQuery('#dialog').dialog("disable");
            showLoading(0, 0, 1100);
       },  // pre-submit callback
       //url:       url         // override for form's 'action' attribute 
       //type:      type        // 'get' or 'post', override for form's 'method' attribute 
       //clearForm: true        // clear all form fields after successful submit 
       //resetForm: true        // reset the form after successful submit 
       //$.ajax options can be used here too, for example:
       //timeout:   3000 
       
       //dopisne dla e-commerce
       objectModel: ''
    };


    jQuery('form.ajax').live('submit', function(){
        ajax_form_options.objectModel = jQuery(this).attr("name").replace('_form','');
        jQuery(this).ajaxSubmit(ajax_form_options); return false;
    });

    jQuery('form.ajax .submit').live('click', function(){
        jQuery(this).parents('form').submit(); return false;
    });

    reprint();

/**************************************************************************************************/
/******************************* OKNO DIALOGOWE ***************************************************/

    var dialog_options = {
          title: '',
          bgiframe: true,
          show: 'clip',
          hide: 'clip',
          width: 'auto',
          height: 'auto',
          minWidth: 300,
          minHeight: 100,
          maxWidth: 800,
          closeOnEscape: true,
          modal: false,
          draggable: true,
          close: function(){
              hideTlo();
          }
    };

    var dialog = jQuery('<div id="dialog"></div>').appendTo('body');
    jQuery('#dialog .close').live('click', function(){
       jQuery(this).parents('#dialog').dialog('close');
    });

    jQuery('a.dialog').live('click', function(){
        showTlo();
        showLoading();
        var url = this.href;
        dialog_options.title = this.title;

        dialog.load(url, {}, function () {
            hideLoading();
            dialog.dialog(dialog_options);
        });

        return false;
    });

    open_dialog = function(adres, nazwa, width, height ){
        var dialog_opcje = dialog_options;
        
        if ( arguments.length == 0 ) {
            return false;
        }
        
        if ( arguments.length == 2 && typeof(nazwa) == 'object' ) {
            var opts = nazwa;
            for( var o in opts ) dialog_opcje[o]  = opts[o];

            nazwa = ( opts.title ) ? opts.title : (( opts.nazwa ) ? opts.nazwa : '');
        }

        if ( !nazwa || nazwa.length == 0 ) nazwa = 'okno';
        
        cx = (screen.availWidth - width) / 2;
        cy = (screen.availHeight - height) / 2;

        showTlo();
        dialog_options.title = nazwa;

        //console.log("open_dialog(" + adres + ", " + nazwa + ", "+ width+ ", " +height+ "); ");
        if ( adres.substring(0,1) == '#' ){
            //var $dialog_contents = jQuery(adres).clone('true').css('display', 'block');
            //dialog.html($dialog_contents.html());
            //dialog.dialog(dialog_opcje);
            jQuery(adres).dialog(dialog_opcje);
        } else {
            showLoading();
            
            dialog.load(adres, {}, function (){
                hideLoading();
                dialog.dialog(dialog_opcje);
            });
        }
        
        return false;
    }

//********* GLOWNE MENU  ********************//

jQuery('ul#menu li').not('.on').hover(
   function() {    
                jQuery(this).find('span.bg').stop().animate({ opacity: 1.0 }, 500 );
                jQuery(this).find('span.hide').stop().animate({ opacity: 0.0 }, 500 );
        },   
   function() {  
                jQuery(this).find('span.bg').stop().animate({ opacity: 0.0 }, 600 );
                jQuery(this).find('span.hide').stop().animate({ opacity: 1.0  }, 400 );
    });


  jQuery('input, textarea').bind('focus',
        function() {jQuery(this).addClass('focus');}
  );

  jQuery('input, textarea').bind('blur',
        function() {jQuery(this).removeClass('focus');}
  );
    
    
//ikonki w produktach ukrywanie/pokazywanie po najechaniu
    jQuery('.produkt .icon').css({opacity:0.0} );
                      
    jQuery('.produkt').hover(
        function() {jQuery(this).find('.icon').stop().animate({ opacity: 1.0 }, 300 );},   
        function() {jQuery(this).find('.icon').stop().animate({ opacity: 0.0 }, 300 );}
    );

//ustawienie <lebel> wewnątrz <input> np w polach do logowania
    jQuery('label.infield').each(function(){
        jQuery(this).css('position','absolute').position({ my: 'left middle', at: 'left  middle', of: '#' + jQuery(this).attr('for') ,offset: "8 0"}).inFieldLabels();
        if(jQuery('#' + jQuery(this).attr('for')).val()!=""){
            jQuery(this).hide(); //jesli przegladarka wypelni z altomatu
        }
    });
});//koniec document ready  



/***** KARTA EDYCJI PROFILU ***********************************************************************/

function on_password_change( o_form ){
    var err_komunikat = '';
    
    if( trim(o_form.HASLO.value) == '' ){
        err_komunikat = 'Aby zmienić hasło musisz podać dotychczasowe hasło!'
        zmien_kolor_obramowania(o_form.HASLO, true, err_komunikat);
        print_message(err_komunikat,"error");
        return false;
    }else{
        zmien_kolor_obramowania(o_form.HASLO, false, '');
    }

    if( trim(o_form.HASLO2.value) == '' ){
        err_komunikat = 'Podaj nowe hasło';
        zmien_kolor_obramowania(o_form.HASLO2, true, err_komunikat);
        print_message(err_komunikat,"error");
        return false;
    }else{
        zmien_kolor_obramowania(o_form.HASLO2, false, '');
    }

    if( o_form.HASLO2.value != o_form.REHASLO2.value ){
        err_komunikat = 'Podane hasło się nie zgadzają!';
        zmien_kolor_obramowania(o_form.REHASLO2, true, err_komunikat);
        print_message(err_komunikat,"error");
        return false;
    }else{
        zmien_kolor_obramowania(o_form.REHASLO2, false, '');
    }


    if ( confirm('Uwaga zamierzasz zmienić hasło. Jesteś pewien że chcesz kontynuować?') ){
        o_form.submit();
    }else{
        return false;
    }
}


