/* Javascript utilities */

window.addEvent('domready',function() {
	var t = new Tips('.tip');
	$$('.tip').each(function(tip){
		var imgSrc = tip.retrieve('tip:text');
		var imgAlt = tip.retrieve('tip:title');
		tip.store('tip:text', new Element('img',{'src':imgSrc,'alt':imgAlt}));
	});
})

/*
 Operacje na divach
*/
var Div = {
        fadeOut : function(div){
            new Fx.Morph(div, { 'duration': '500', onComplete:function(){$(div).setStyle('display','none');  } }).start({'opacity': [1,0]});
        }    , 
        
        fadeIn : function(div){
            this.show(div); // najpierw pokaz DIV
            new Fx.Morph(div, { 'duration': '500' }).start({'opacity': [0,1]});
        }    ,
        slideIn : function(div){
            new Fx.Slide(div).hide().slideIn();
        },
        slideOut : function(div){
            new Fx.Slide(div).slideOut();
        },
        slideOutAfter : function(div,time){
            setTimeout("new Fx.Slide('"+div+"').slideOut()",time);
        },
        hide : function(div){
            $(div).setStyle('display','none');
        },
        show : function(div){
            $(div).setStyle('display','block');
        },
        toggle: function (div){
            if($(div).getStyle('display')!='none')
                this.hide(div);
            else
                this.show(div);
        },
        toggleFade : function(div){
            if($(div).getStyle('display')!='none')
                this.fadeOut(div);
            else
                this.fadeIn(div);            
        }
}

/*
 Funkcje formularza
*/
var Form = {

        /**
         * Fills up a form select
         * Wypelnia select wartosciami z bazy
         */
        load_select : function(id,entity,params){
            var s = $(id);
            // Wybierak wylaczony - nie ruszaj!
            if(s.disabled)
                return;
            // Parametr okresla, czy nadpisywac stara zawartosc wybieraka
            // nowa, lecz pusta zawartoscia
            if(!params['_override_only_if_set']){
                s.options.length = 0;
            }
            $(id).disabled=true;
            new Request({
                url : "/xhr/get_"+entity+".xml",
                method : 'post',
                data : params,
                noCache : true,
                onRequest : function(){
                    if(!params['_override_only_if_set']) 
                       s.options[ s.options.length ] = new Option('Czekaj...','Ładuję listę...');
                },
                onSuccess : function(text, xml)
                {
                    if(xml) var pozycja=xml.getElementsByTagName(entity);
                    if(!xml || !pozycja.length){
                        if(!params['_override_only_if_set'])   {
                            s.options.length = 0; 
                            s.options[ s.options.length ] = new Option('- Brak -', 0);    
                        }
                    } else {
                        s.options.length = 0; 
                        s.options[ s.options.length ] = new Option('dowolne',0);    
                        for(i=0;i<pozycja.length;i++)
                        {
                            wartosc=pozycja[i].childNodes[0].childNodes[0].nodeValue;
                            _id=pozycja[i].childNodes[1].childNodes[0].nodeValue;
                            s.options[ s.options.length ]=new Option( wartosc, _id );
                        }
                    }
                    $(id).disabled=false;                    
                },
                onError : function()
                {
                    alert ('Wystąpił błąd!');
                }
                
            }).send();
            
            return false;
        },
        
        
        /**
         Wlacza/wylacza dany element formularza
        */
        toggle : function(id) {
             var e = $(id);
             e.disabled=e.disabled == false ? true:false;
        },
        
        check : function(id) {
             var e = $(id);
             e.checked = true;
        },
        
        select : function(id, value) {
            var e = $(id);
            for(i=0;i<e.options.length;i++)
                if(e.options[i].value==value)
                    e.selectedIndex=i;
        },
        
        disable : function(id) {
             var e = $(id);
             e.disabled = true;            
        },

        enable : function(id) {
             var e = $(id);
             e.disabled = false;            
        },
        
        enable_some : function(_class,limit){
            el = document.getElements('fieldset[class='+_class+']');       
            $each(el,function(e,index){
               if(index<limit) {
                   e.setStyle('display','block');
                   e.erase('disabled');
                   // wlacz selekty i inputy ;-)
                   inputs = e.getElements('input'); selects = e.getElements('select');  
                   $each(inputs,function(input){ input.erase('disabled')});
                   $each(selects,function(select){ select.erase('disabled')});

               }
            });
        },
        
        enable_all : function(_class){
            el = document.getElements('fieldset[class='+_class+']');
            if(!el) 
                return;
            $each(el,function(e){
                inputs = e.getElements('input'); selects = e.getElements('select');  
                // wylacz wszystkie inputy i selecty
                $each(inputs,function(input){ input.erase('disabled')});
                $each(selects,function(select){ select.erase('disabled')});

                e.setStyle('display','block');
                e.erase('disabled');
            });            
        },
        
        disable_all : function(_class){
            el = document.getElements('fieldset[class='+_class+']');
            if(!el) 
                return;
            $each(el,function(e){
                inputs = e.getElements('input'); selects = e.getElements('select');  
                // wylacz wszystkie inputy i selecty
                $each(inputs,function(input){ input.setProperty('disabled',true)});
                $each(selects,function(select){ select.setProperty('disabled',true)});

                e.setStyle('display','none');
                e.setProperty('disabled',true);
            });
        } ,
        
        // Wlaczaj / wylaczaj elementy formatki  fieldset
        toggle_all : function(_class){
             el = document.getElements('fieldset[class='+_class+']');
             $each(el.getProperty('disabled'),function(disabled){ return disabled ? Form.enable_all(_class) : Form.disable_all(_class)});
        },
        
        value_of_select : function(id){
            s = $(id);
            return !s ? 0 : s.options[s.selectedIndex].value;
        },
        
        value_of_check : function(id){
            c = $(id);
            return !c ? false : c.checked;
        }
        
        
}

var Util = {
// Funkcje zaczerpniete z http://www.alistapart.com/articles/zebratables/

// this function is needed to work around 
  // a bug in IE related to element attributes
  hasClass : function(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
  },

  // metoda "koloruje tabelki kolorami, ktore chcemy"
  stripe : function(id) {

    // the flag we'll use to keep track of 
    // whether the current row is odd or even
    var even = false;
  
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#fff";
    var oddColor = arguments[2] ? arguments[2] : "#eee";
  
    // obtain a reference to the desired table
    // if no such table exists, abort
    var table = document.getElementById(id);
    if (! table) { return; }
    
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // &lt;tbody&gt;s 
    var tbodies = table.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
    
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

        // avoid rows that have a class attribute
        // or backgroundColor style
        if (! this.hasClass(trs[i]) &&
            ! trs[i].style.backgroundColor) {
           
          // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
          var ths = trs[i].getElementsByTagName("th");
          
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {
        
            var mytd = tds[j];

            // avoid cells that have a class attribute
            // or backgroundColor style
            if (! this.hasClass(mytd) &&
                ! mytd.style.backgroundColor) {
        
              mytd.style.backgroundColor =
                even ? evenColor : oddColor;
            
            }
          }

          // A teraz elementy TH...
          for (var j = 0; j < ths.length; j++) {
        
            var myth = ths[j];

            // avoid cells that have a class attribute
            // or backgroundColor style
            if (! this.hasClass(myth) &&
                ! myth.style.backgroundColor) {
        
              myth.style.backgroundColor =
                even ? evenColor : oddColor;
            
            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
  }
    
}

/* ---- currency changer ---- */
window.addEvent( 'domready', function()
{
    var select = $( 'currencyChanger' );
    
    if( !select )
    {
        return false;
    }
    
    var form = select.getParent( 'form' );
        
    if( !form )
    {
        return false;   
    }
    
    form.getElement( 'input' ).destroy();
    
    select.addEvent( 'change', function()
    {
        form.submit();
    } );
} );

/* ---- help notice ---- */
window.addEvent( 'domready', function()
{
    var helps = $$( '.formHelp' );
    
    if( !helps.length )
    {
        return false;
    }
    
    var tip = new Element( 'div',
    {
        'class': 'formTip'
    } ).addClass( 'globalNotice' ).addClass( 'globalHelp' );
    
    tip.addEvent( 'mouseout', function()
    {
        tip.setStyle( 'display', 'none' );
    } );
    
        document.body.adopt( tip );
    
    helps.each( function( element )
    {
        element.addEvent( 'mouseover', function()
        {
            console.log( document.body.getElement( 'div' ).getCoordinates() );
            
            tip.setStyles( 
            {
                'left': element.getPosition().x - 5,
                'top': element.getPosition().y - 5,
                'right': document.body.getCoordinates().width - document.body.getElement( 'div' ).getCoordinates().right,
                'width': 'auto',
                'display': 'block',
                'cursor': 'help'
            } );
            
            tip.set( 'text', element.getElement( 'span' ).get( 'text' ) );
        } );
    } );
} );
