$(document).ready(function(){  
    
/* Tu w przyszłości(kiedy zakładki będą wykonane w technologi ajax) znajdzie się obsługa przycisku wstecz, przy użyciu biblioteki jquery.history.
$.history.init(function(hash){
        if(hash == "") {
            // initialize your app
        } else {
            // restore the state from hash
        }
});
*/


function form_msg(msg, offset, width, time_to_hide, corner_top, position) {
        width = width || "600px";
        position = position || "fixed"
        var msg_cont = $(document.createElement("div")).css({"position": position, "top": (offset.top-17-$(window).scrollTop())+"px", "left": (offset.left+290)+"px", "background": "url(css/images/msg_corner.png) no-repeat center left", "height": "50px", "z-index": "1000000000", "width": width}).attr("class", "msg").appendTo($("body"));

        var msg_el = $(document.createElement("div")).css({"background": "url(css/images/alert-small.png) no-repeat center left #fff", "border": "1px solid #000","border-left": "none", "height": "48px", "margin-left": "25px", "padding-left": "60px", "padding-right": "10px"}).appendTo(msg_cont);
        
        if(corner_top === true) {
            msg_cont.css({"background": "url(css/images/msg_corner_top.png) no-repeat right top", "top": (offset.top+20-$(window).scrollTop())+"px"});
            msg_el.css({"border": "1px solid #000", "border-top": "0", "margin-left":"0", "margin-top":"10px"});
        }
        
        p_msg = $(document.createElement("p")).css({"display":"table-cell","vertical-align":"middle", "height": "50px", "font-weight": "bold", "text-align": "center"}).html(msg).appendTo(msg_el);
        
        if(time_to_hide == undefined) time_to_hide=2000;
        setTimeout(function() { msg_cont.fadeOut("slow", function() { $(this).remove(); }) }, time_to_hide);
        return msg_cont;
}

function remove_record_question(iframe) {
    //asking for removing record
dom_query = iframe ? iframe.contents().find("img[src=\"images/usun.png\"]") : $("img[src=\"images/usun.png\"]");
dom_query.each(function() {
    $(this).parent().click(function(e) {
        e.preventDefault();
        var this_offs = $(this).offset();
        this_offs.left+=-290-202;
        if(iframe) {this_offs.top+=iframe.offset().top}
         this_offs.top-=7;
        //-290-0.5*width
        var  this_href = $(this).attr("href");
        var msg = form_msg("Usunąć ten rekord?<br><input class=yes type=button value=Tak style=\"margin-top:5px;width:70px\"><input class=no type=button value=Nie style=\"margin-top:5px;margin-left:10px;width:70px\">", this_offs, "230px", 5000, true, "absolute");
        msg.find("input[class=yes]").click(function() {
            //usuń wszystkie wiadomości
            $(".msg").remove();
            if(iframe) {
                //iframe.load(function(){ after_load() });
                iframe.attr("src", this_href);
            } else {
                window.location = this_href;
            }
        });
        msg.find("input[class=no]").click(function() {
            $(".msg").remove();
            
        });
    });
});
}

var form_open=false;

function cancel() {
                $("input, textarea").each(function() {if($(this).attr("type") != "submit" && $(this).attr("type") != "hidden") $(this).val("")});  
                $("select option").each(function() {$(this).removeAttr("selected")}); 
                //select list
                $(".selectbox .active_option").removeClass("active_option");
                $(".selectbox span").text("");
                $(".form").removeClass("unactive");
                form_open=false;
                $(".toremove").remove();
}

function full_textarea() {
//fullscreen dla textarea
$("textarea").each(function() {
    var area = $(this);
    //create area of area to set arrows
    var div_area = $(document.createElement("div")).css("position", "relative");
    div_area.appendTo($(this).parent());
    div_area.append(area);//move area to div container
    var area_width = area.width();
    var area_height = area.height();


    var arrow = $(document.createElement("img")).attr("src", "css/images/fullscreen.png").css({"position": "absolute", "top": "0px", "left": (area_width-22)+"px"}).appendTo(div_area);
    
    var title = $(document.createElement("div")).css({"position": "absolute", "top": "24px", "left": (area_width-110)+"px", "background": "#fff", "border": "1px dotted #BFBFBF"}).text("Przejdź do trybu pełnoekranowego.").appendTo(div_area).hide();
    arrow.mouseover(function(){title.show()});
    arrow.mouseout(function() {title.hide()});
    
    
    var arrow_back = $(document.createElement("img")).attr("src", "css/images/fullscreen_back.png").css({"position": "fixed", "top": "0px", "z-index":"999999"}).appendTo(div_area).hide();
        
    var title_back = $(document.createElement("div")).css({"position": "fixed", "top": "26px", "background": "#fff", "border": "1px dotted #BFBFBF","z-index":"999999"}).text("Opuść tryb pełnoekranowy").appendTo(div_area).hide();
    
    arrow.click(function() {
        area.css({"position": "fixed","left": "0", "top":"0","z-index":"99999", "width":  $(document).width()+"px", "height":  $(document).height()+"px"});
        var new_area_width = area.width();
        
        arrow_back.css("left", new_area_width-24);
        title_back.css("left", new_area_width-100);
        
        arrow_back.show();
        
        arrow_back.mouseover(function(){title_back.show()});
        arrow_back.mouseout(function() {title_back.hide()});
        arrow_back.click(function() {
            area.css({"width": area_width, "height": area_height, "position": "static", "z-index":"auto"});
            $(this).hide();
            title_back.hide();
            
        })
        
    })
        
});

}

function build_form() {
$("form").submit(function (){
    $.blockUI({ message: null }); 
});
try {
//login_off = $('nav .logout').offset().left;
active = $('nav .active');

active_off = active.offset().left;
/*if(active_off >= login_off) {
    marg =  parseInt($('nav .bookmarks').css("margin-left"));
    $('nav .bookmarks').css("margin-left", (marg+login_off-active_off-active.width())+'px'); 
}*/
 //select
var active = new Array();
var el_clicked = new Array();
} catch(e) {}
 $(".form select").each(function (id) {
     var class_attr = $(this).attr("class");
     $(this).hide();
     
     var select = $(this);
     var select_name = select.attr("name");
     select.attr("name", "");
     
     var option_value = "";
     select.children().each(function(){
            if(this.selected == true) {
             option_value = $(this).val();
          }
         
      });

     

     var selectbox = $(document.createElement("div")).addClass("selectbox").appendTo($(this).parent());
     if(class_attr != "combo") {
         selectbox.addClass("selectbox_desin");
         var input = $(document.createElement("input")).hide().attr("name", select_name).val(option_value).appendTo($(this).parent());
        var selectbox_val = $(document.createElement("span")).appendTo(selectbox);//akt_value_of_selectbox
     } else {
        var selectbox_val = $(document.createElement("input")).attr("name", select_name).attr("autocomplete", "off").val(option_value).appendTo(selectbox);
     }

     var x = selectbox.offset().left;
     var y = selectbox.offset().top;
     var ul = $(document.createElement("ul")).appendTo(selectbox);
     var list_width = $(this).width();
     if(list_width < selectbox.width()) {
         ul.css("width", selectbox.css("width"));
     }
     ul.offset({top: y+18, left: x+1});
     ul.attr("id", "select"+id);
     var select_value = "";
     var select_text = "";
     $(this).children().each(function(){
         var li_elm = $(document.createElement("li")).text($(this).text()).attr("data-value", $(this).val());
         if(this.selected == true) {
              select_text = $(this).text();
              select_value = $(this).val();
          if(class_attr != "combo") {
              selectbox_val.text(select_text);
          } else {
              selectbox_val.attr("value", select_text);
              
          }
              if($(this).val() != "") li_elm.addClass("active_option");
          }
        li_elm.appendTo(ul);
        li_elm.click(function () {
            var ul_id = ul.attr("id");
             ul.find(".active_option").removeClass("active_option");
             select_text = $(this).text();
             select_value = $(this).attr("data-value");
             //zaznacz element w prawdziwym select
             
             if(class_attr == "combo") {
               selectbox_val.val(select_text);
               
               active[ul_id] = false;
               ul.hide();    
            } else {
                input.val(select_value);
            }
             // console.log(selectbox_val.val());
             select.value = select_value;
             if($(this).attr("data-value") != "") $(this).addClass("active_option");
        });
        
     });
     
     active[ul.attr("id")] = false;
     el_clicked[ul.attr("id")] = false;
    if(class_attr != "combo") {
     selectbox.click(function() {
         var ul_id = $(this).find("ul").attr("id");
         if(active[ul_id] == false ) {
           active[ul_id] = true;
            selectbox_val.text("");
            ul.animate({height:'500px'}, 600);
         } else {
             active[ul_id] = false;
            selectbox_val.text(select_text);
             ul.animate({height:'0'}, 600);
             ul.hide();
             selectbox_val.text(select_text);
         }
         el_clicked[ul_id] = true;
      });
  } else {
    var ul_top = parseInt(ul.css("top"));
    ul.css({"height": "500px", "top": ul_top+2+"px"});
    selectbox_val.bind('keyup', function(e) {
        var ul_id = ul.attr("id");
        if(ul.find("li:visible").length == 0) {ul.hide(); active[ul_id] = false;return;}
     //   if($(this).val().length == 0) {
    //        ul.hide();
      //      active[ul_id] = false;
        //}// else {
         //   ul.show();
         //   active[ul_id] = true;
         //}
      //  if($(this).val().length >= 1) {
            ul.show();
            active[ul_id] = true;
            //el_clicked[ul_id] = true;
            var input_value = $(this).val();
            ul.children().each(function(){
            //   console.log($(this).text().indexOf(input_value));
                if($(this).text().indexOf(input_value) == -1) {
                    active[ul_id] = false;
                    $(this).hide();
                } else {
                    active[ul_id] = true;
                    $(this).show();
                }
            });
       // }
           
    });
    selectbox.click(function() {
        el_clicked[ul_id] = true;
    });
    selectbox_val.focus(function () {
    //if($(this).val().length >= 1) {
        var ul_id = $(this).parent().find("ul").attr("id"); 
        active[ul_id] = true;
        el_clicked[ul_id] = true;
        ul.show();
   // }
    });



  }
    
 });
//combo
//var combo_array = new Array();
/*$(".form .combo").each(function() {
    $(this).hide();
    var select = $(this);
     var select_name = select.attr("name");
     select.attr("name", "");
     
     var option_value = "";
     select.children().each(function(){
            if(this.selected == true) {
             option_value = $(this).val();
          }
         
      });
     var input = $(document.createElement("input")).hide().attr("name", select_name).val(option_value).appendTo($(this).parent());
     var selectbox = $(document.createElement("div")).addClass("selectbox").appendTo($(this).parent());
     //var selectbox_val = $(document.createElement("span")).appendTo(selectbox);//akt_value_of_selectbox
     var x = selectbox.offset().left;
     var y = selectbox.offset().top;
     var ul = $(document.createElement("ul")).appendTo(selectbox);
     if(list_width < selectbox.width()) {
         ul.css("width", selectbox.css("width"));
     }
     ul.offset({top: y+18, left: x+1});
    input.bind('keyup', function(e) {
    $(this).children().each(function(){    
        var li_elm = $(document.createElement("li")).text($(this).text()).attr("data-value", $(this).val());
       //  if(this.selected == true) {
        //      select_text = $(this).text();
       //       select_value = $(this).val();
      //        selectbox_val.text(select_text);
       //       if($(this).val() != "") li_elm.addClass("active_option");
       //   }
        li_elm.appendTo(ul);
        li_elm.click(function () {
             ul.find(".active_option").removeClass("active_option");
             select_text = $(this).text();
             select_value = $(this).attr("data-value");
             //zaznacz element w prawdziwym select
             input.val(select_value);

             select.value = select_value;
             if($(this).attr("data-value") != "") $(this).addClass("active_option");
        });
      });
    });
});*/


//formularz    
var textarea = false;
var strHref = window.location.href;
var hrefRxp = new RegExp("co=edytuj");
if(hrefRxp.test(strHref)) {
            var any_active = false;
            for(var i in active) {
                if(active[i] == true) { 
                 any_active=true;
                 break;
            }
            }
            if(any_active == true) return; 
            
            $(".form").css('background', '#fff');
            $(".form").stop().animate({width:'330px'},600, "", function() {if(textarea == false) {full_textarea(); textarea=true;}}) 
} else {
        $(".form").hoverIntent({
            
            over: function() {
            if(!$(this).hasClass("unactive")) {
              var any_active = false;
              for(var i in active) {
                  if(active[i] == true) { 
                   any_active=true;
                   break;
              }
              }
              if(any_active == true) return;  
            
              $(this).css('background', '#fff');
              $(this).stop().animate({width:'330px'},600, "", function() {if(textarea == false) {full_textarea(); textarea=true;}})  
        }
        }, 
        
        out: function(e){
        if(!$(this).hasClass("unactive")) {
            var any_active = false;
            for(var i in active) {
                if(active[i] == true) { 
                 any_active=true;
                 break;
            }
            }
            if(any_active == true) return;
                var form = $(this);
                if($("#ui-datepicker-div:visible").attr("style") == undefined || $("#ui-datepicker-div:visible").css("display") == "none") {
                   form.stop().animate({width:'0px'},600, function() {$(this).css('background', ' url(css/images/show_form.png) no-repeat center left #fff')}); 
               }
            
        }
       },
       timeout: 600
       });  
}

//####Table Selectable#######
$(".selectable tr").click(function() {
    if($(this).find('input[type="checkbox"]').attr("checked") == true) {
        $(this).find('input[type="checkbox"]').removeAttr("checked");
        $(this).css("background-color","#fff");
    } else {
      $(this).find('input[type="checkbox"]').attr("checked", "checked");
      $(this).css("background-color","#BFBFBF");
  }});
$(".selectable tr input[type=\"checkbox\"]").click(function() {
    if($(this).attr("checked") == true) {
        $(this).removeAttr("checked");
        $(this).css("background-color","#fff");
    } else {
      $(this).attr("checked", "checked");
      $(this).css("background-color","#BFBFBF");
  }
	
});




      $(document).click(function (e) {
          var strHref = window.location.href;
          var hrefRxp = new RegExp("co=edytuj");
          if(!hrefRxp.test(strHref)) {
          $(".form .selectbox ul").each(function(){ 
            var ul = $(this);
            var ul_id = $(this).attr("id");
            //console.log(ul_id+": "+active[ul_id]+"@"+el_clicked[ul_id]+"@"+ul.parent().parent().find("input").hasClass("combo"));
            //if(active[ul_id] == true && (el_clicked[ul_id] == false || ul.parent().parent().find("select").hasClass("combo") == 1)) {
            if(active[ul_id] == true && el_clicked[ul_id] == false) {
             active[ul_id] = false;
             if(ul.parents("td").find("select").attr("class") != "combo")
                ul.animate({height:'0'}, 600);
             ul.hide();
           }
           el_clicked[ul_id] = false;
          });
          if(!$(".form").hasClass("unactive")) {
			setTimeout(function() {
				var px = e.pageX;
				var py = e.pageY;
				var formbox = $(".form");
				var fwidth = formbox.outerWidth();

				if(px > fwidth && $("#ui-datepicker-div:visible").length == 0) {
					formbox.animate({width:'0px'},600, function() {$(this).css('background', ' url(css/images/show_form.png) no-repeat center left #fff')})
				}
                                }, 600);
		  }
		  //RSSES
		    $('#rsses').slideUp('slow');

      }});


//pola typu number
$("input[type=number]").each(function(){
    var index = $(this).index();
    $(this).bind('keyup', function(e) {
        var dig = /^[0-9]*$/;
        var val = $(this).val();
        
        if(!dig.test(val)) {
          var numbers = val.match(/[0-9]*/g);
          var new_val = "";
          for(var i in numbers) {
              new_val += numbers[i];
          }
         $(this).val(new_val);
         form_msg("W tym polu możesz wprowadzać tylko cyfry.", $(this).offset());
        } 
    });
});
//show comunicat in input
function show_hide_input_com(input, com) {
    if(input.val() == "") {
      input.css({"color": "#BFBFBF"}).val(com);
    }
    input.focus(function() {
    if($(this).val() == com) {
        $(this).css({"color": "#000"}).val("");
    }
    });
    input.focusout(function() {
    if($(this).val() == "") {
        $(this).css({"color": "#BFBFBF"}).val(com);
    }
    });
}//end fn

//wymaganie
var help_val = "oddzielaj punkty normy kropką";
show_hide_input_com($("#wymag"), help_val);


//pola typu date - kalendarz
$("input[type=date]").datepicker({dateFormat: "yy-mm-dd", dayNames: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"], dayNamesMin: ["nd", "pn", "wt", "śr", "czw", "pt", "sob"], 
monthNames:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"] });

//wybór załączników
$("#file-uploader").each(function(index) {
try {
var strHref = window.location.href;

var plan_id = strHref.match(/id=([0-9]*)/)[1];
var url = 'upload_file.php?id='+plan_id;

} catch(e) {
    
}

var file_uploader = $(this);
function add_file_to_list(qq_upload_list, file_name, folder_id) {
      var li = $(document.createElement("li")).attr("class", "qq-upload-success").prependTo(qq_upload_list);
      $(document.createElement("a")).attr("href", "uploads/"+folder_id+"/"+file_name).attr("target", "_blank").attr("title", "Zapisz plik").text(file_name).appendTo(li);
      var remove = $(document.createElement("a")).attr("href", "#").attr("class", "remove").attr("title", "Usuń załącznik").appendTo(li);
      remove.click(function(event) {
            var act_elm = $(this);
            var attrs = act_elm.parent().find("a").attr("href").split("/");//get id and file name
            var id = attrs[1];
            var file = attrs[2];
            $.post("remove_file.php", { "id": id, "file": file },
                function(data){
                var offset = act_elm.parent().offset();
                //var outher_width = act_elm.parent().outerWidth();
                if(data == "added") {
                    var message = "Plik usunięto.";
                    act_elm.parent().remove();//remove li
                } else {
                    var message = "Nie udało się usunąć pliku. Spróbuj ponownie później.";
                }
                form_msg(message, offset);
            });
            event.preventDefault();
      });

}

var uploader = new qq.FileUploader({
    // pass the dom node (ex. $(selector)[0] for jQuery users)
    element: $('#file-uploader')[index],
    // path to server-side upload script
    action: url,
    onComplete: function(id, fileName, responseJSON){
      if(responseJSON.error) {
          //do nothing
      } else {
        function get_ext_and_name_of_file(file) {
            var parts = file.split('.');
             //To jest zalążek kodu odpowiadającego za obsługę plików bez jakiegokolwiek rozszerzenia. Na chwilę obecną on nie działa.
             /* if(parts.length === 1) {
                return [parts[0], ""];
            }*/
            var file_name="";
            for(var i=0;i<parts.length-1;i++) {
                file_name += parts[i];
                if(i != parts.length-2) file_name+=".";
            }
            var ext = parts[parts.length-1];
            return [file_name, ext];
        }
        function change_name_when_exist(old_name, new_name, nr) {
            if(new_name == undefined) new_name=old_name;
            if(nr == undefined) nr=0;
            var lis = new Array();
            file_uploader.find('.qq-upload-list li').each(function(){ lis.push($(this))});//sprawdź czy istnieją załączniki o tej samej nazwie
            for(var i=0;i<lis.length;i++) {
                if(get_ext_and_name_of_file(lis[i].text())[0] == new_name) {
                  nr+=1;
                  return change_name_when_exist(old_name, old_name+"("+nr+")", nr);
                }
            }
            return new_name;
        }

        var li = file_uploader.find(".qq-upload-list li:first-child");
        var li_parent = li.parent();
        li.remove();//usuń stary element
        var split_file = get_ext_and_name_of_file(fileName);
        add_file_to_list(li_parent, change_name_when_exist(split_file[0])+"."+split_file[1], plan_id);
        
      }
    },
    showMessage: function(message){
            var file_list = file_uploader.find(".qq-upload-list");
            form_msg(message, file_list.offset());
    },
    // ex. ['jpg', 'jpeg', 'png', 'gif'] or []
    allowedExtensions: ["pdf"],        
    // size limit in bytes, 0 - no limit
    // this option isn't supported in all browsers
    sizeLimit: 50*1024*1024  
});
var file_uploader = $(this);
try {
$.getJSON('added_files.php','id='+plan_id, function(data) {
  var added_files = data.added_files;

  file_uploader.find(".qq-upload-list").each(function(){
    
    for(var i=0;i<added_files.length;i++) {
      add_file_to_list($(this), added_files[i], plan_id);
    }
  });

});
}catch(e){}
$(this).click(function(){
    var strHref = window.location.href;
    var hrefRxp = new RegExp("co=edytuj");
    if(!hrefRxp.test(strHref)) {
        form_msg("Aby dołączać pliki, musisz zatwierdzić ten rekord. Czy zorbić to teraz?<br /><input type=button value=Tak style=\"margin-top:5px; width:70px;\" id=yes_save />", $(this).offset(), false,5000);

       $("#yes_save").click(function() {
        var form = $(".form");
        $(document.createElement("input")).attr("type", "hidden").attr("name", "edit_after_submit").val("1").appendTo(form);
        form.parent().submit();
        });
        return false;
    }
});

});

//menu zakładek
var stop=true;
var min_margin=0;
var timer;

function go_to_end_anim() {

    last_child= $("nav .bookmarks li[class!=logout]").last();
    last_child_offset = last_child.offset().left+last_child.width()-3;
    if(x_skrajny >= last_child_offset) { stop=true;  }
    if(stop == false) {
        marg =  parseInt($('nav .bookmarks').css("margin-left"))-3;
        $('nav .bookmarks').css("margin-left", marg+'px');
    } else {
        clearTimeout(timer);
    }
}

function go_to_end(end_x) {
    x_skrajny = end_x;
    timer = setInterval(function(){go_to_end_anim()}, 40);
}

function go_to_begin_anim() {
    marg =  parseInt($('nav .bookmarks').css("margin-left"))+3;
    if(marg > 54) marg = 54;
    if(stop == false) {
        $('nav .bookmarks').css("margin-left", marg+'px');    
    } else {
        clearTimeout(timer);
    }
}

function go_to_begin() {
    timer = setInterval(function(){go_to_begin_anim()}, 40);
}

var back = $(document.createElement('div')).addClass('button').attr('id', 'back').html('&#60;');

back.mousedown(function() { 
        back.mouseup(function() { stop=true });
        stop=false;
        go_to_begin();
    })
    
var forward = $(document.createElement('div')).addClass('button').attr('id', 'forward').html('&#62;');

forward.mousedown(function() { 

        forward.mouseup(function() { stop=true; });
        
        pasek_offset = $('nav .logout').offset().left;
        stop=false;
        go_to_end(pasek_offset);
        
    })

var buttons_container = $(document.createElement('div')).attr('id', 'buttons_container');

$('nav').prepend(buttons_container);
$(buttons_container).prepend(forward);
$(buttons_container).prepend(back);
//#######################
$(".cancel").click(function() {
    cancel();
});
if($("form").length == 1 && !$("form").hasClass("noinfo")) {
      //przycisk pomocy do formularza - możliwe, że w przyszłośći, kiedy aplikacja zostyanie przeniesiona na Kohanę ta funkcja będzie się znajdować po stronie serwera.
var help_url = "www.isoslownik.pl"
function functions_help_map(funkcja) {
    var map = new Array();
    map['spostrzezenie'] = 'spostrzezenia';
    map['zalozplanu'] = 'przeglady';
    map['zaplanowanieprzegladu'] = 'szczegoly_przegladu';
    map['zalozeniekarty'] = 'karty';
    if(map[funkcja] == null) {
        return funkcja;
    } else {
        return map[funkcja];
    }
}

    
var url = $("form").attr("action");
var index = url.indexOf("?");
var data = url.substr(index+1);
var splitted = data.split("&");
var funkcja;
for(var i=0;i<splitted.length;i++) {
  if(splitted[i].indexOf("funkcja") != -1) {
      funkcja_array = splitted[i].split("=");
      funkcja = funkcja_array[1];
      if(funkcja == "zalozplanu") {
          if(url.indexOf("co=zaplanowanieprzegladu") != -1) {
              funkcja = "zaplanowanieprzegladu";
          }
      } else if(funkcja == "zalozeniekarty") {
          if(url.indexOf("co=dzialania") != -1) {
              funkcja = "dzialania";
          } 
      }
      break;
  }
}

var helpbox = $(document.createElement("a")).attr("class", "helpbox").attr("href", "http://"+help_url+"/doku.php?id=bds:"+functions_help_map(funkcja)).text("").prependTo($("form table:first")); 
//przekopiowane z textarea - może kiedyś trzeba będzie pomyśleć o DRY ;)
 var title = $(document.createElement("div")).css({"position": "absolute", "top": "24px", "left": "180px", "background": "#fff", "border": "1px dotted #BFBFBF", "width": "140px"}).text("Uzyskaj dodatkowe informacje o tej tabeli.").appendTo($(".form")).hide();
if(functions_help_map(funkcja) == 'karty') {
    helpbox.css({"left": "774px", "top":"5px"});
}
helpbox.mouseover(function(){title.show()});
helpbox.mouseout(function() {title.hide()});
}

remove_record_question();

}//end build_form
//#######################
//zaplanowanie_przegladu
$(".zaplanowanie_przegladu, .zaplanowaniedzial").click(function(event) {
     var table = $(this).parents("table");
     $(this).parents("tr").siblings(":not(:first-child)").hide();
     //$("form").hide();
     $("form").remove();
     //zawiń pozostałe rekordy, w przypadku gdy są zbyt długie
     $(this).parent().parent().find("td:visible").each(function() {
        var td_text = $(this).html();
        $(this).html("");
        $(document.createElement("div")).css({"height": "100px", "overflow": "auto"}).appendTo($(this)).html(td_text);    
     });
     var button = $(document.createElement("div"));
     if ($(this).hasClass("zaplanowaniedzial")) {
         button.html("<a href=\"strefakon_main.php?funkcja=zalozeniekarty\">Powrót do podglądu wszystkich kart.</a>");
     } else {
        //dodaj przycisk powrotu do "Zarządzania przeglądami"
        button.html("<a href=\"strefakon_main.php?funkcja=zalozplanu\">Powrót do podglądu wszystkich przeglądów.</a>");
     }
     button.css({"width": "300px", "height": "30px", "text-align": "center", "vertical-align": "middle", "background": "#E5E5E5", "display": "table-cell"}).appendTo($(document.createElement("div")).css({"width": "300px"," height": "30px", "margin": "0 auto"}).appendTo($("body")));
       //var body = 
       
      var iframe = $(document.createElement("iframe")).attr("src", $(this).attr("href")+"&without_js=1").css({"border": "0", "width": "100%", "height": ($(window).height() - 100 - 100)+"px"}).attr("id", "zaplanowanie_przegladu_frame").attr("name", "table_frame").hide().appendTo($("body"));//ukryj na chwilę ramkę, do czasu kiedy z niej usuniesz nawigację

      function edit(ifr) {//alert(ifr.attr("href"));//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        var hrefRxpS = new RegExp("funkcja=spostrzezenie");
        var hrefRxp = new RegExp("funkcja=zalozeniekarty");
	  
        ifr.contents().find('img[src="images/edyt.png"]').each(function() {$(this).parent().click(function(e) {
		//var href = ifr.attr("href");
        var href = $(this).attr("href");
		var strHref = window.location.href;

                $.getJSON(href+"&json=1", function(data){
		    
                    if(hrefRxp.test(strHref)) {
                       $(document.createElement("input")).attr("type", "hidden").attr("name", "idakcji").addClass("toremove").prependTo($("form")); 
                   } else if(hrefRxpS.test(href)) {
                      var opcja_parent = $("input[name=opcja]").parent();
                       var span_value =  opcja_parent.find("select option[value="+data.opcja+"]").text();
                       $("input[name=opcja]").attr("value", data.opcja);
                       opcja_parent.find("div span").text(span_value);

                       $("input[name=co]").remove();
                       $(document.createElement("input")).attr("type", "hidden").attr("name", "nr_przegladu").addClass("toremove").prependTo($("form")); 
                       $(document.createElement("input")).attr("type", "hidden").attr("name", "id").addClass("toremove").prependTo($("form")); 
                       $("#wymag").css({"color": "#000"});
                   } else {
                        $(document.createElement("input")).attr("type", "hidden").attr("name", "id_planowania").addClass("toremove").prependTo($("form"));
                        $(document.createElement("input")).attr("type", "hidden").attr("name", "id_raportu_plan").addClass("toremove").prependTo($("form"));  
                   }
                    $("input, textarea").each(function() {$(this).val(data[$(this).attr("name")])});  
                    if(form_open == false) {
						$(".form").addClass("unactive");
						$(".form").css('background', '#fff');
						$(".form").stop().animate({width:'330px'},600, function() {full_textarea();form_open=true;}); 
					}
                });
                e.preventDefault();
            });
            });
          }
     
     var iframe_load = function(that) {
      //var this_fnc = iframe_load.apply(null, [that]);
      return function() {   
		form_open=false;
        var hrefRxpS = new RegExp("funkcja=spostrzezenie");
        var hrefRxp = new RegExp("funkcja=zalozeniekarty");
        $(".toremove").remove();
          cancel();
          edit($(that));
          remove_record_question($(that));
          if(hrefRxpS.test($("form").attr("action"))) {
        
             $.get("strefakon_main.php?funkcja=spostrzezenie&co=next_nr&json=1", {}, function(data) {
                   $("form").find("input[name=nr]").val(data);
             });
         
       
           var Today = new Date(); 
           var Month = Today.getMonth(); 
           var Day = Today.getDate(); 
           var Year = Today.getFullYear(); 

           $("form").find("input[name=data]").val(Year+"-"+Month+"-"+Day);
         }
       $.unblockUI();
      }
     }
     
      $(iframe).load(function() 
       {    
          $(this).unbind("load");
          var ifr = $('iframe#zaplanowanie_przegladu_frame');
          table.find("img").parents("td, th").remove();
          //TO TREBA USUNĄĆ PO PRZEJŚĆIU APLIKACJI W FAZĘ STABLE
          ifr.contents().find("body").css({"background": "transparent"});
          ifr.contents().find("nav").remove();
          ifr.contents().find("#top_nav").remove();
          ifr.contents().find("form").clone().insertAfter($("#top_nav"));  
          ifr.contents().find("form").remove();
          remove_record_question(ifr);
          ifr.slideDown(3000);

          build_form();
          edit(ifr);
          
          //$("form").submit(function() {
            $(iframe).load(iframe_load(this));
        //});
    });
     event.preventDefault();
});

//tabelka
// na obeczną chwilę kod działa wadliwie.
/*var th_offset = new Array();
var th_width = new Array();
var th_height = new Array();
var th = new Array();
$(".autofiltr th").each(function(index) {
    th[index] = $(this);
    th_offset[index] = th[index].offset();
    th_width[index] = th[index].width();
    th_height[index] = th[index].height();
});
var td_top_offset = $(".autofiltr tr:first-child").offset().top;
$(".autofiltr th").each(function(index) {
    th[index].css({"position": "fixed", "top": td_top_offset+"px", "left": th_offset[index].left+1+"px", "width": th_width[index]+"px", "height": th_height[index]+"px"});
});*/




build_form();

//tego tutaj nie powinno być, ale musi  (;
/*$("#instrukcja").css({"width": "99%", "height": ($(window).height()-10)+"px", "overflow": "none"});


$('.logger_button').click(function() {
	var color = $(this).css('background');
	if(color == 'none repeat scroll 0% 0% rgb(255, 255, 255)') {
		$("#dziennik tr").show();
	} else {
		$("#dziennik tr").each(function() {
				if($(this).css('background') == color) {
					$(this).show();
				} else
				{
					$(this).hide();
				}
		});
	}
});*/


$('#rss_button').click(function()
{
	$('#rsses').slideDown('slow');
	return false;
});


/*$("#pass_change input[name=confirm_new]").blur(function() {
  	
});*/
});      

