$(function() {
		$('#dialog').dialog({
			autoOpen: false,
      modal: true,
      width: 800
		});
    tooltip();
    multiMenu();
    datepicker();


    $('.lightbox').colorbox();
    $(".lightbox-frame").colorbox({width:"80%", height:"80%", iframe:true});


    $(".print").click(function () {
      window.print();
    });

    if($("#imageRotator").is(":visible"))
    {
      rotate_init();
    }

    ajaxSetup();
})

function loaderStart(element)
{
  //loaderStop(); /*usuniecie poprzednich ew. loaderow*/

  var id;
  var width;
  var height;
  var style;
  if(element)
  {
    id = element;
    //width = $(id).innerWidth();
    //height = $(id).innerHeight(true);

    style = '';

   // $(".ajax_div").html("");
  }
  else
    id = "body";
  
  $(id).prepend('<div id="loader" '+ style +'><p>Trwa ładowanie</p></div>');
}

function loaderStop()
{
  $("#loader").remove();
}



function tooltip()
{
  var hideDelay = 1;
  var currentID;
  var hideTimer = null;

  var container = $('<div id="tooltip"><div id="tooltip-body"></div></div>');

   $('body').append(container);
   $('.none,.tt').live('mouseover', function(e)
   {

       var title = $(this).attr('title');

       if (title == ''){
         var noTitle = 1;
         return;
       }

       if (hideTimer)
          clearTimeout(hideTimer);

       $(this).attr('title',''); /* usuniecie atr title */
       $('#tooltip-body').html(title);


      $(this).mousemove(function(e){
        var width = e.pageX;
        var height = e.pageY;

        container.css({
            left: width + 20 + 'px',
            top: height - 10 + 'px'
          });
    
       });



      container.css('display', 'block');
       $('.none,.tt').live('mouseout', function(event)
       {
           if (hideTimer)
               clearTimeout(hideTimer);
           hideTimer = setTimeout(function()
           {
               container.css('display', 'none');
           }, hideDelay);

           if(noTitle != 1)
           {
              $(this).attr('title',title); /* przywrocenie atr title */
              return;
           }
       });

       $('#tooltip').mouseover(function()
       {
           if (hideTimer)
               clearTimeout(hideTimer);
       });


       $('#tooltip').mouseout(function()
       {
           if (hideTimer)
              clearTimeout(hideTimer);
          hideTimer = setTimeout(function()
          {
              container.css('display', 'none');
          }, hideDelay);
      });
     });
}

function myForm(objForm,objLoad){
    var loadIN = "";
    loadIN = jQuery.makeArray(objLoad);

    loaderStart(objForm["loaderStart"]);

    $(objForm["loadTo"]).load(objForm["loadWhere"], {'catalog': loadIN}).
      ajaxSuccess(function(){
        if(objForm["loader"]=="TRUE")
         loaderStop();
    });
}

function myFormAfter(objForm){
   $.ajax({
     url: objForm["loadWhere"],
     success: function(data) {

     $(objForm["loadAfter"]).append(data);
    if(objForm["loader"]=="TRUE")
     loaderStop();
     }
   });
}

function loadDefaultSelect(id){
  $(id).html("");
  $(id).append($(document.createElement("option")).
                        attr("value","").text("-- wybierz --"));

}


function multiMenu(){
  $(document).click(function() {
    if($(".multi-menu-content").is(":visible"))
      {
      $(".multi-menu-content").slideUp("fast");
      $(".multi-menu .icon").removeClass("multimenu-hover");
      }
  });
  $(".multi-menu .icon").click(function(e) {

    if($(this).next().is(":visible"))
      {
      $(this).next().slideUp("fast");
      $(this).removeClass("multimenu-hover");
      }
    else
      {
      $(this).next().slideDown("fast");
      $(this).addClass("multimenu-hover");
      }
     e.stopPropagation();
  });
}



/* dla entry */
function setSize(elem)
{
  var page_width = $(document).width();
  var page_height = $(document).height();

  $(elem).css({
                width: page_width
            })
}

function popUp(url, name, width, height)
{
  if(width == '')
    width = 500;
  if(height == '')
    height = 500;
  if(name == '')
    name = '';

	newwindow=window.open(url,name,'height='+height+',width='+width);
	if (window.focus) {newwindow.focus()}
	return false;
}




function rotate_init() {


	imgs = $("#imageRotator img");
	for(i=1;i<imgs.length;i++) imgs[i].xOpacity = 0;
	imgs[0].style.display = "block";
	imgs[0].xOpacity = .99;

	setTimeout(image_fade,3000);
}

function image_fade() {
	cOpacity = imgs[current].xOpacity;
	nIndex = imgs[current+1]?current+1:0;

	nOpacity = imgs[nIndex].xOpacity;

	cOpacity-=.05;
	nOpacity+=.05;

	imgs[nIndex].style.display = "block";
	imgs[current].xOpacity = cOpacity;
	imgs[nIndex].xOpacity = nOpacity;

	setOpacity(imgs[current]);
	setOpacity(imgs[nIndex]);

	if(cOpacity<=0) {
		imgs[current].style.display = "none";
		current = nIndex;
		setTimeout(image_fade,3000);
	} else {
		setTimeout(image_fade,50);
	}

	function setOpacity(obj) {
		if(obj.xOpacity>.99) {
			obj.xOpacity = .99;
			return;
		}
		obj.style.opacity = obj.xOpacity;
		obj.style.MozOpacity = obj.xOpacity;
		obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
	}
}

function datepicker()
{
  $.datepicker.regional['pl'] = {
    closeText: 'Zamknij',
    prevText: '&#x3c;Poprzedni',
    nextText: 'Następny&#x3e;',
    currentText: 'Dziś',
    monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
    'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
    monthNamesShort: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
    'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
    dayNames: ['Niedziela','Poniedzialek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
    dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
    dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
    dateFormat: 'yy-mm-dd',
    firstDay: 1,
    duration:  'fast',
    changeMonth: true,
    changeYear: true,
    buttonText: 'odsłoń',
    isRTL: false
  };

  $.datepicker.setDefaults($.datepicker.regional['pl']);
}


function ajaxSetup()
{
 $.ajaxSetup({
   error:function(x,e){
           try {
             var error_msg;
             if(x.status==0){
               error_msg = "Brak połączenia z Internetem!!\n Proszę sprawdzić swoje połączenie sieciowe.";
             }else if(x.status==401){
               alert("Sesja wygasła!\n Proszę się ponownie zalogować");
               return;
             }else if(x.status==404){
               error_msg = 'Strona o podanym adresie nie istnieje.';
             }else if(x.status==500){
               error_msg = 'Błąd wewnętrzny serwera.';
             }else if(e=='parsererror'){
               error_msg = 'Błąd parsowania JSON.';
             }else if(e=='timeout'){
               error_msg = 'Upłynął czas oczekiwania na połączenie.';
             }else {
               error_msg = 'Nieznany błąd.\n'+x.responseText;
             }
             alert('Błąd AJAX: '+error_msg);
           }catch(err){
             error_msg = 'Upłynął czas oczekiwania na połączenie.';
             alert('Błąd AJAX: '+error_msg);
           }
         },
   timeout: 20000
 });
}
