// $(document).ready(function() {
//    $("#orderedlist li:first").hover(function() {
//      $(this).addClass("green");
//    },function(){
//      $(this).removeClass("green");
//    });
//  });


jQuery(document).ready(function() {
  $("a.newsPic").colorbox({'scalePhotos':"false"});
  $("a.photoPic").colorbox({'scalePhotos':"false"});
});


jQuery(document).ready(function() {
  $(".photo_news").each(function(j){
    var photo_news=this;
    $(".deletePic",photo_news).each(function(i){
      $(".deletePic:eq("+i+")",photo_news).click(function(event){
        event.preventDefault();
        var photoId=$(".photo_id:eq("+j+")").text();
        var photoFilename=$(".photo_filename:eq("+i+")",photo_news).text();
        var photoPicDiv=$(".photoPicDiv:eq("+i+")",photo_news);
//       alert(photoId + " a "+photoFilename);
        deletePhotoPic(photoId,photoFilename,photoPicDiv);
      });
//     deletePhotoPic($(""));

      $(this).parent().hover(
      function(){
        $(".photoPic",this).css({ 'margin-top':'0px'});
        $(".deletePic:eq("+i+")",photo_news).show();
//       $(this).css({ 'border': 'solid black 2px', 'background-color':'#AAAAAA' });
//       $(this).corner("round tr bl");
      },
      function() {

//         $(this).css({'border':'0px ', 'padding':'2px', 'background-color':'inherit'});
        
        $(".deletePic:eq("+i+")",photo_news).hide();
        $(".photoPic",this).css({ 'margin-top':'15px'});
      });
    });
  });
  
  
  $(".news_news").each(function(j){
    var news_news=this;
    $(".deletePic",news_news).each(function(i){
      $(".deletePic:eq("+i+")",news_news).click(function(event){
        event.preventDefault();
        var newsId=$(".news_id:eq("+j+")").text();
        var photoFilename=$(".photo_filename:eq("+i+")",news_news).text();
        var newsPicDiv=$(".newsPicDiv:eq("+i+")",news_news);
//       alert(photoId + " a "+photoFilename);
        deleteNewsPic(newsId,photoFilename,newsPicDiv);
      });
//     deletePhotoPic($(""));

      $(this).parent().hover(
      function(){
        $(".newsPic",this).css({ 'margin-top':'0px'});
        $(".deletePic:eq("+i+")",news_news).show();
//       $(this).css({ 'border': 'solid black 2px', 'background-color':'#AAAAAA' });
//       $(this).corner("round tr bl");
      },
      function() {

//         $(this).css({'border':'0px ', 'padding':'2px', 'background-color':'inherit'});
        
        $(".deletePic:eq("+i+")",news_news).hide();
        $(".newsPic",this).css({ 'margin-top':'15px'});
      });
    });
  });
  
  
  
});
function deletePhotoPic(photoId,photoFilename,photoPicDiv){
//   alert("dPP")
  $.post('/php/delete_photo_pic.php',{'photoId': photoId, 'photoFilename':photoFilename},function(response,textStatus,xhr){
//     alert(xhr+ ' ' + textStatus);
    var result = $('result', response).text();
//     alert(result);
    if(result=='SUCCESS'){
      photoPicDiv.hide();
//       alert("SUCCESS");
    }else{
      alert("Chyba při mazání!");
    }
    
  
  },"xml");
//   alert("konec");
}
function deleteNewsPic(newsId,photoFilename,newsPicDiv){
//   alert("dPP")
  $.post('/php/delete_news_pic.php',{'newsId': newsId, 'photoFilename':photoFilename},function(response,textStatus,xhr){
//     alert(xhr+ ' ' + textStatus);
    var result = $('result', response).text();
//     alert(result);
    if(result=='SUCCESS'){
      newsPicDiv.hide();
//       alert("SUCCESS");
    }else{
      alert("Chyba při mazání!");
    }
    
  
  },"xml");
//   alert("konec");
}


//discuss reply
jQuery(document).ready(function() {
	// do something here
  $("span.messages_response a").each(function(i) {
      $(this).click(function(event) {
         event.preventDefault();
         var poster = $("div.news_body  span.messages_name:eq("+i+")").text();
         poster=poster.replace("Jméno: ","");
      //poster="bleh";
  $("#discuss_message > textarea").focus();
  $("#discuss_message > textarea").append("@"+poster+": ");
  
              
      });
  });
});

//ban discuss item
jQuery(document).ready(function() {
  $("span.messages_ban_spam>a").each(function(i){
    $(this).click(function(event){
      event.preventDefault();
      var messageId=$("span.messages_id:eq("+i+")").text();
      banMessage(messageId);
      $("div.message:eq("+i+")").hide("slow");
    });
  });
});

jQuery(document).ready(function() {
  $("span.messages_delete>a").each(function(i){
    $(this).click(function(event){
      event.preventDefault();
      var messageId=$("span.messages_id:eq("+i+")").text();
//       alert(messageId);
      deleteMessage(messageId,$("div.message:eq("+i+")"));
//       $("div.message:eq("+i+")").hide("slow");
    });
  });
});





//border around news
jQuery(document).ready(function() {
  $("div.news_news div.news_admin_tools").each(function(i){
    $("div.news_news:eq("+i+")").hover(function(event){
      $("div.news_news").hover(
        function(){
          $(this).css({ 'border': 'solid black 2px', 'padding':'3px', 'background-color':'#AAAAAA' });
          $(this).corner("round tr bl");
        },
        function() {
          var visible=$("div.news_news div.news_visible:eq("+i+")").text();
//           alert(visible);
          if(visible=="0"){
      
            $("div.news_news:eq("+i+")").css({'border':'solid grey 2px', 'padding':'3px', 'background-color':'#BBBBBB'});
            $("div.news_news:eq("+i+")").corner("round tr bl");
//             $("div.news_news img.minimize:eq("+i+")").attr('src','img/graphics/maximize.png');
//             $("div.msg:eq("+i+")").hide();
          }else{
            $("div.news_news:eq("+i+")").css({'border':'0px ', 'padding':'5px', 'background-color':'inherit'});
          }
        });
    });
  });
});


// hide news item
jQuery(document).ready(function() {
  $("div.news_news").each(function(i){
//     event.preventDefault();
    var visible=$("div.news_visible", this).text();
    if(visible=="0"){
      hideNewsCSS(this);
//       $("div.news_news:eq("+i+")").css({'border':'solid grey 2px', 'padding':'3px', 'background-color':'#BBBBBB'});
//       $("div.news_news:eq("+i+")").corner("round tr bl");
//       $("div.news_news:eq("+i+") img.minimize").attr('src','img/graphics/maximize.png');
//       $("div.news_news:eq("+i+") img.minimize").removeClass('minimize').addClass('maximize');
//       $("div.news_news:eq("+i+") a.hide").removeClass('hide').addClass('show');
//       $("div.msg:eq("+i+")").hide();
    }

  });
});

// delete news item
// jQuery(document).ready(function() {
//   $("div.news_admin_tools span.delete>a").each(function(i){
//     $(this).click(function(event){
//       event.preventDefault();
//       var newsId=$("div.news_news:eq("+i+") span.news_id").text();
//       banMessage(messageId);
//       alert(messageId);
//       $("div.news_news:eq("+i+")").css({'background-color':'#DDDDDD','border': 'solid grey 2px', 'padding':'3px'});
//       deleteNews(newsId,$("div.news_news:eq("+i+")"));
//       $("div.news_news:eq("+i+")").hide("slow");
//     });
//   });
// });

// bind photo admin tools
jQuery(document).ready(function() {
  $("div.photo_news div.photo_admin_tools").each(function(i){
    var photoId=$("div.photo_news:eq("+i+") span.photo_id").text();
    $("a.delete",this).click(function(event){
      event.preventDefault();
//       alert("klik");
      deletePhoto(photoId,$("div.photo_news:eq("+i+")"));
      //delete
    });
    
//     $("a.hide",this).click(function(event){
//       event.preventDefault();
//       visibleNews(newsId,$("div.news_news:eq("+i+")"),0);
// //       alert("Klik na hide");
//       //hide
//     });
    
//     $("a.show",this).click(function(event){
//       event.preventDefault();
//       visibleNews(newsId,$("div.news_news:eq("+i+")"),1);
//       //show
//     });
    
//     $("a.edit",this).click(function(event){
//       event.preventDefault();
//       editNews(newsId,$("div.news_news:eq("+i+")"));
//       //show
//     });
  });
});

function deletePhoto(photoId,photoDiv){
//   alert("dPP")
  $.post('/php/delete_photo.php',{'photoId': photoId},function(response,textStatus,xhr){
//     alert(xhr+ ' ' + textStatus);
    var result = $('result', response).text();
//     alert(result);
    if(result=='SUCCESS'){
      photoDiv.hide();
//       alert("SUCCESS");
    }else{
//       alert("Chyba při mazání!");
      alert(result);
    }
    
  
  },"xml");
//   alert("konec");
}






// bind news admin tools
jQuery(document).ready(function() {
  $("div.news_news div.news_admin_tools").each(function(i){
    var newsId=$("div.news_news:eq("+i+") span.news_id").text();
    $("a.delete",this).click(function(event){
      event.preventDefault();
      
      deleteNews(newsId,$("div.news_news:eq("+i+")"));
      //delete
    });
    
    $("a.hide",this).click(function(event){
      event.preventDefault();
      visibleNews(newsId,$("div.news_news:eq("+i+")"),0);
//       alert("Klik na hide");
      //hide
    });
    
    $("a.show",this).click(function(event){
      event.preventDefault();
      visibleNews(newsId,$("div.news_news:eq("+i+")"),1);
      //show
    });
    
    $("a.edit",this).click(function(event){
      event.preventDefault();
      editNews(newsId,$("div.news_news:eq("+i+")"));
      //show
    });
  });
});




// show/hide news form
jQuery(document).ready(function() {
  $("#news_form_show").click(function(event){
    event.preventDefault();
//     var messageId=$("span.messages_id:eq("+i+")").text();
//     banMessage(messageId);
    
    var test=$("#news_form_show>a").text();
    if(test=="Show"){
      $("#news_form").show("slow");
      $("#news_form_show>a").html("Hide");
    }else if(test=="Hide"){
      $("#news_form").hide("slow");
      $("#news_form_show>a").html("Show");
    }
  });
  //show/hide poll form
  $("#poll_form_show").click(function(event){
    event.preventDefault();
    
    var test=$("#poll_form_show>a").text();
    if(test=="Show"){
      $("#poll_form").show("slow");
      $("#poll_form_show>a").html("Hide");
    }else if(test=="Hide"){
      $("#poll_form").hide("slow");
      $("#poll_form_show>a").html("Show");
    }
  });
  //add poll option
  $("#poll_form a.poll_form_add").click(function(event){
    event.preventDefault();
    $("#poll_form div.poll_form_option:last").clone(true).insertAfter($("#poll_form div.poll_form_option:last"));
  });
  
  $("div.poll_form_option a.poll_form_del").click(function(event){
    event.preventDefault();
    $(this).parent().remove();
    
  });
  
  $("#photo_form_show").click(function(event){
    event.preventDefault();
    
    var test=$("#photo_form_show>a").text();
    if(test=="Show"){
      $("#photo_form").show("slow");
      $("#photo_form_show>a").html("Hide");
    }else if(test=="Hide"){
      $("#photo_form").hide("slow");
      $("#photo_form_show>a").html("Show");
    }
  });
  
//   $("#photo_form form").submit(function(event){
//     event.preventDefault();
//     alert($(this).serialize());
//     $.post("php/add_photo.php",$(this).serialize(), function(data){
// 
//     });
//     return false;
//   });
  
  
});



$(document).ready(function() { 
  var options = { 
    target:        '#photo_form_response',   // target element(s) to be updated with server response 
    beforeSubmit:  checkPhoto,  // pre-submit callback 
    success:       photoResponse,  // post-submit callback 
    dataType:  'xml'       // 'xml', 'script', or 'json' (expected server response type) 
    
 
        // other available options: 
        //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 
  }; 
 
    // bind form using 'ajaxForm' 
  $('#photo_form form').ajaxForm(options); 
  
//   $('#photo_form form').attr({'enctype':'multipart/form-data'});
//   $('input[name=step]').attr({'value':'second'});
//   $('input[name=submitButton]', '#photo_form form').attr({'value':'Připojit foto','id':'subSecondStep'});
//   $('div.firstStep', '#photo_form form').removeClass('firstStep').addClass('secondStep');
//   var secondStepForm='<div>Foto:  <input class="multi" type="file" name="photo[]" /></div>\n'+
//       '<input type="hidden" name="photoId" value="55" />\n';
//   $('div.secondStep', '#photo_form form').replaceWith(secondStepForm);
});

function checkPhoto(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
//   var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
//   alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
  
  //if step==second => check size of sumbmitted files
  
  var form = jqForm[0]; 
  if (form.step.value=="first") { 
//     alert('first');
    return true;
  }else if(form.step.value=="second"){
//     alert('second');
    return true;
  }
  
  return true; 
} 
 
// post-submit callback 
function photoResponse(responseXML, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
//   if (xhr.readyState==4){//process is completed
//     if (xh.status==200){
   if(responseXML==""){
//      alert("responseXML je prazdny");
   }
//    alert('status: "' + statusText + '"\n\nresponseText: \n"' + responseXML + 
//       '"\n\nThe output div should have already been updated with the responseText.'); 
   
//   console.log(responseXML + statusText);
//    alert("responseXML " + $(responseXML).text());
  
  var result = $('result', responseXML).text(); 
  while(result== ""){
    alert("Soubory se stále nahrávají na server, vydrž!\n(Po chvíli klikni na OK)");
    var result = $('result', responseXML).text(); 
  }
//   alert("readyState: "+ xhr.readyState+ "\n xhr.status: " + xhr.status);
//   alert($('html', responseXML).text()); 
  if(result=='SUCCESS'){
    var step = $('step', responseXML).text(); 
    if(step=='first'){
      var photoId = $('photoId', responseXML).text(); 
      var fileName= $('filename', responseXML).text();
      var filenameInput='';
      if (fileName!=''){
        filenameInput='<input type="hidden" name="filename" value="'+ fileName +'" />';
      }
      alert("photoId:" + photoId);
      $('#photo_form form').attr({'enctype':'multipart/form-data'});
      $('input[name=step]').attr({'value':'second'});
      $('input[name=submitButton]', '#photo_form form').attr({'value':'Připojit foto','id':'subSecondStep'});
      $('div.firstStep', '#photo_form form').removeClass('firstStep').addClass('secondStep');
      var secondStepForm='<div>Foto:  <input class="multi" type="file" name="photo[]" accept="image/jpg, image/JPG, image/png" /></div>\n'+
          '<input type="hidden" name="photoId" value="'+ photoId +'" />\n' +
          filenameInput;
      $('div.secondStep', '#photo_form form').replaceWith(secondStepForm);
      $("input[type=file].multi").MultiFile();
      
      
      var photoDate = $('photoDate', responseXML).text();
      var photoPlace = $('photoPlace', responseXML).text();
      var photoEvent = $('photoEvent', responseXML).text();
      var photoCreated = $('photoCreated', responseXML).text();
      var usersLogin = $('usersLogin', responseXML).text();
      var photoText = $('photoText', responseXML).text();
      
      var photoDiv='<div class="news_news">\n'+
      '<span class="news_id">'+ photoId +'</span>'+
      '<div class="news_head" ><a href="photo.php?photo_id='+ photoId +'">'+ photoDate +' '+ photoPlace + ' ' + photoEvent + '</a></div>\n'+             
      '<div class="news_created">Vloženo '+ photoCreated +' uživatelem '+ usersLogin +'</div>\n'+
      '<div class="msg">'+ photoText+'</div>\n'+
      '</div>\n';
      $('#photo_form').prepend(photoDiv);
      
      
      
      var completeForm='<form method="post" action="php/add_photo.php" id="complete_form">\n'+
      '<input type="hidden" name="step" value="third" />\n'+
      '<input type="hidden" name="photoId" value="'+ photoId +'" />\n'+
      '<div><input type="submit" value="Dokončit fotogalerii" name="submitButton" id="subThirdStep"></div>\n'+
      '</form>';
      $('#photo_form').append(completeForm);
      var options = {
        beforeSubmit:  checkPhoto,  // pre-submit callback 
        success:       photoResponse,  // post-submit callback 
        dataType:  'xml'       // 'xml', 'script', or 'json' (expected server response type) 
      }; 
 
    // bind form using 'ajaxForm' 
      $('#complete_form').ajaxForm(options); 
      
      
    }else if (step=='second'){
//       alert(responseXML);
//       var extension= $('extension', responseXML).text();
//       alert("extension: " + extension);
      
      var photoId= $('input[name=photoId]').val();
//       var fileName= $('filename', responseXML).text();
      $('filename', responseXML).each(function(i) {
//         alert("ahoj");
        var fileName = $(this).text();
        var tooBig = $('fileTooBig',this).text;
        if(tooBig==fileName){
          $('#photo_form_response').append('<a href="http://www.vranovskyzleb.cz/img/photo/'+ photoId +'/' + encodeURI(fileName) + '" rel="photo'+ photoId +'" class="newsPic"><img src="http://www.vranovskyzleb.cz/img/photo/'+ photoId +'/'+ encodeURI(fileName) + '" border="0px" alt="foto" width="130px" ></a>');
          
        }else{
          $('#photo_form_response').append('<a href="http://www.vranovskyzleb.cz/img/photo/'+ photoId +'/' + encodeURIComponent(fileName) + '" rel="photo'+ photoId +'" class="newsPic"><img src="http://www.vranovskyzleb.cz/img/photo/'+ photoId +'/small/'+ encodeURIComponent(fileName) + '" border="0px" alt="foto" width="130px" ></a>');
        }
        $("a.newsPic").colorbox({'scalePhotos':"false"});
      });
      
      
    }else if (step=='third'){
//       alert("third step");
      location.reload();
    }
  }else{
//     alert("result: " +result);
//     $('#photo_form_response').append(responseXML.html());
    
  }
} 






function hideNewsCSS(newsDiv){
  $("div.news_visible", newsDiv).html("0");
  $(newsDiv).css({'border':'solid grey 2px', 'padding':'3px', 'background-color':'#BBBBBB'});
  $(newsDiv).corner("round tr bl");
  $("img.minimize", newsDiv).attr({src:"img/graphics/maximize.png", title: "Zobrazit"});
  $("img.minimize", newsDiv).removeClass('minimize').addClass('maximize');
  $("a.hide", newsDiv).removeClass('hide').addClass('show');
  
  var newsId=$("span.news_id",newsDiv).text();
  $("div.news_admin_tools a.show",newsDiv).click(function(event){
    event.preventDefault();
    visibleNews(newsId,newsDiv,1);
  });
//       $("div.msg:eq("+i+")").hide();
  
}

function showNewsCSS(newsDiv){
  $("div.news_visible", newsDiv).html("1");
  $(newsDiv).css({'border':'0', 'padding':'5px', 'background-color':'inherit'});
//   $(newsDiv).corner("round tr bl");
  $("img.maximize", newsDiv).attr({src:"img/graphics/minimize.png", title: "Skrýt"});
  $("img.maximize", newsDiv).removeClass('maximize').addClass('minimize');
  $("a.show", newsDiv).removeClass('show').addClass('hide');
  
  var newsId=$("span.news_id",newsDiv).text();
  $("div.news_admin_tools a.hide",newsDiv).click(function(event){
    event.preventDefault();
    visibleNews(newsId,newsDiv,0);
  });
  
//       $("div.msg:eq("+i+")").hide();
  
}


//hide news item
function visibleNews(newsId, newsDiv, visible){
  //hide message
  var xmlHttp = createXmlHttpRequestObject();
  if (xmlHttp){
    try{
    //try to connect to server
      	//create string of parameters
      var params = "news_id=" + newsId + "&visible=" + visible;
      xmlHttp.open("POST", "/php/visibility_news.php", true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
      xmlHttp.setRequestHeader("Content-length", params.length);
      xmlHttp.onreadystatechange = function() { handleRequestVisibilityNews(newsDiv)};
      xmlHttp.send(params);
    }
    catch (e){
      alert("Can't connect to server:\n" + e.toString());
    }
  }

}

function editNews(newsId, newsDiv){
  var xmlHttp = createXmlHttpRequestObject();
  if (xmlHttp){
    try{
    //try to connect to server
      	//create string of parameters
      var params = "news_id=" + newsId;
      xmlHttp.open("POST", "/php/edit_news.php", true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
      xmlHttp.setRequestHeader("Content-length", params.length);
      xmlHttp.onreadystatechange = function() { handleRequestEditNews(newsDiv)};
      xmlHttp.send(params);
    }
    catch (e){
      alert("Can't connect to server:\n" + e.toString());
    }
  }
  
}



function banMessage(messageId){
  //ban message
  var xmlHttp = createXmlHttpRequestObject();
  if (xmlHttp){
    try{
    //try to connect to server
      	//create string of parameters
      var params = "message_id=" + messageId;
      xmlHttp.open("POST", "/php/ban_message.php", true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
      xmlHttp.setRequestHeader("Content-length", params.length);
      xmlHttp.onreadystatechange = handleRequestBanMessage;
      xmlHttp.send(params);
    }
    catch (e){
      alert("Can't connect to server:\n" + e.toString());
    }
  }

}

//delete news
function deleteNews(newsId,newsDiv){
  //ban message
  var xmlHttp = createXmlHttpRequestObject();
  if (xmlHttp){
    try{
    //try to connect to server
      	//create string of parameters
      var params = "news_id=" + newsId;
      xmlHttp.open("POST", "/php/delete_news.php", true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
      xmlHttp.setRequestHeader("Content-length", params.length);
      xmlHttp.onreadystatechange = function() { handleRequestDeleteNews(newsDiv)};
      xmlHttp.send(params);
    }
    catch (e){
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

//delete message from discussion
function deleteMessage(messageId,messageDiv){
  //ban message
  var xmlHttp = createXmlHttpRequestObject();
  if (xmlHttp){
    try{
    //try to connect to server
      	//create string of parameters
      var params = "message_id=" + messageId;
      xmlHttp.open("POST", "/php/delete_message.php", true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
      xmlHttp.setRequestHeader("Content-length", params.length);
      xmlHttp.onreadystatechange = function() { handleRequestDeleteMessage(messageDiv)};
      xmlHttp.send(params);
    }
    catch (e){
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function createXmlHttpRequestObject(){
  //creates XMLHttpRequest object if it is possible
  var xmlhttp
  try {
  //should work on all browsers except IE6 or older
    xmlHttp = new XMLHttpRequest();
  }
  catch (e){
    //browser is IE6 or older
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    catch (e){
      //ignore error
    }
  }
  if (!xmlHttp)
    alert ("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}




function handleRequestBanMessage(){
  //request state has changed
  if (xmlHttp.readyState==4){//process is completed
    if (xmlHttp.status==200){
    //http status is OK
      try {
        var xmlResponse = xmlHttp.responseXML;
        //process response
        var xmlRoot = xmlResponse.documentElement;
        var responseText = xmlRoot.firstChild.data;
        if(responseText!="SUCCESS"){
//           alert(responseText);
        }
//         respDiv = document.getElementById("response");
//         respDiv.innerHTML = "";
//         respDiv.innerHTML += responseText;
//        return xmlResponse;
      }
      catch (e){
        alert("Error reading the response: " + e.toString());
      }
    }
  }
}
   
function handleRequestDeleteNews(newsDiv){
  //request state has changed
  if (xmlHttp.readyState==4){//process is completed
    if (xmlHttp.status==200){
    //http status is OK
      try {
        var xmlResponse = xmlHttp.responseXML;
        //process response
        var xmlRoot = xmlResponse.documentElement;
        var responseText = xmlRoot.firstChild.data;
        if(responseText=="SUCCESS"){
          alert("Smazáno!");
          $(newsDiv).hide("slow");
        }else{
          alert(responseText);
        }
      }
      catch (e){
        alert("Error reading the response: " + e.toString());
      }
    }
  }
}

function handleRequestDeleteMessage(messageDiv){
  //request state has changed
  if (xmlHttp.readyState==4){//process is completed
    if (xmlHttp.status==200){
    //http status is OK
      try {
        var xmlResponse = xmlHttp.responseXML;
        //process response
        var xmlRoot = xmlResponse.documentElement;
        var responseText = xmlRoot.firstChild.data;
        if(responseText=="SUCCESS"){
          alert("Smazáno!");
          $(messageDiv).hide("slow");
        }else{
          alert(responseText);
        }
      }
      catch (e){
        alert("Error reading the response: " + e.toString());
      }
    }
  }
}


function handleRequestVisibilityNews(newsDiv){
  //request state has changed
  if (xmlHttp.readyState==4){//process is completed
    if (xmlHttp.status==200){
    //http status is OK
      try {
        var xmlResponse = xmlHttp.responseXML;
        //process response
        var response = xmlResponse.getElementsByTagName("response")[0];
        var result = response.childNodes[0].childNodes[0];
        var visible = response.childNodes[1].childNodes[0];
//         var xmlRoot = xmlResponse.documentElement;
//         var response = xmlRoot.firstChild;
//         var responseText = response.firstChild.data;
        if(result.nodeValue=="SUCCESS"){
          if(visible.nodeValue=="0"){
//             alert("SUCCESS 0 -> "+ visible.nodeValue);
            hideNewsCSS(newsDiv);
          }else if(visible.nodeValue=="1"){
//             alert("SUCCESS 1 -> "+ visible.nodeValue);
            showNewsCSS(newsDiv);
//           $(newsDiv).hide("slow");
          }
//           alert(visible.nodeValue);
        }else{
          alert(result.NodeValue);
        }
      }
      catch (e){
        alert("Error reading the response: " + e.toString());
      }
    }
  }
}



function handleRequestEditNews(newsDiv){
  //request state has changed
  if (xmlHttp.readyState==4){//process is completed
    if (xmlHttp.status==200){
    //http status is OK
      try {
        var xmlResponse = xmlHttp.responseXML;
        //process response
        var response = xmlResponse.getElementsByTagName("response")[0];
        var result = response.childNodes[0].childNodes[0];
        var form = response.childNodes[1].childNodes[0];
        if(result.nodeValue=="SUCCESS"){
          
          $("div.news_head",newsDiv).replaceWith(form.nodeValue);
          $("div.news_created", newsDiv).remove();
          $("div.msg", newsDiv).remove();
        }else{
          alert(result.NodeValue);
        }
      }
      catch (e){
        alert("Error reading the response: " + e.toString());
      }
    }
  }
}



/*!
 * jQuery corner plugin: simple corner rounding
 * Examples and documentation at: http://jquery.malsup.com/corner/
 * version 2.11 (15-JUN-2010)
 * Requires jQuery v1.3.2 or later
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Authors: Dave Methvin and Mike Alsup
 */

/**
 *  corner() takes a single string argument:  $('#myDiv').corner("effect corners width")
 *
 *  effect:  name of the effect to apply, such as round, bevel, notch, bite, etc (default is round). 
 *  corners: one or more of: top, bottom, tr, tl, br, or bl.  (default is all corners)
 *  width:   width of the effect; in the case of rounded corners this is the radius. 
 *           specify this value using the px suffix such as 10px (yes, it must be pixels).
 */
;(function($) { 

  var style = document.createElement('div').style,
  moz = style['MozBorderRadius'] !== undefined,
  webkit = style['WebkitBorderRadius'] !== undefined,
  radius = style['borderRadius'] !== undefined || style['BorderRadius'] !== undefined,
  mode = document.documentMode || 0,
  noBottomFold = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8),

  expr = $.browser.msie && (function() {
    var div = document.createElement('div');
    try { div.style.setExpression('width','0+0'); div.style.removeExpression('width'); }
    catch(e) { return false; }
    return true;
  })();

  $.support = $.support || {};
  $.support.borderRadius = moz || webkit || radius; // so you can do:  if (!$.support.borderRadius) $('#myDiv').corner();

  function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
  };
  function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
  };
  function gpc(node) {
    while(node) {
      var v = $.css(node,'backgroundColor'), rgb;
      if (v && v != 'transparent' && v != 'rgba(0, 0, 0, 0)') {
        if (v.indexOf('rgb') >= 0) { 
          rgb = v.match(/\d+/g); 
          return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
        }
        return v;
      }
      if (node.nodeName.toLowerCase() == 'html')
      break;
      node = node.parentNode; // keep walking if transparent
    }
    return '#ffffff';
  };

  function getWidth(fx, i, width) {
    switch(fx) {
      case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
      case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
      case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
      case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
      case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
      case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
      case 'curl':   return Math.round(width*(Math.atan(i)));
      case 'tear':   return Math.round(width*(Math.cos(i)));
      case 'wicked': return Math.round(width*(Math.tan(i)));
      case 'long':   return Math.round(width*(Math.sqrt(i)));
      case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
      case 'dogfold':
          case 'dog':    return (i&1) ? (i+1) : width;
      case 'dog2':   return (i&2) ? (i+1) : width;
      case 'dog3':   return (i&3) ? (i+1) : width;
      case 'fray':   return (i%2)*width;
      case 'notch':  return width; 
      case 'bevelfold':
          case 'bevel':  return i+1;
    }
  };

  $.fn.corner = function(options) {
    // in 1.3+ we can fix mistakes with the ready state
    if (this.length == 0) {
      if (!$.isReady && this.selector) {
        var s = this.selector, c = this.context;
        $(function() {
          $(s,c).corner(options);
        });
      }
      return this;
    }

    return this.each(function(index){
      var $this = $(this),
            // meta values override options
      o = [$this.attr($.fn.corner.defaults.metaAttr) || '', options || ''].join(' ').toLowerCase(),
      keep = /keep/.test(o),                       // keep borders?
      cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]),  // corner color
      sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]),  // strip color
      width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10, // corner width
      re = /round|bevelfold|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dogfold|dog/,
      fx = ((o.match(re)||['round'])[0]),
      fold = /dogfold|bevelfold/.test(o),
      edges = { T:0, B:1 },
      opts = {
        TL:  /top|tl|left/.test(o),       TR:  /top|tr|right/.test(o),
        BL:  /bottom|bl|left/.test(o),    BR:  /bottom|br|right/.test(o)
      },
            // vars used in func later
      strip, pad, cssHeight, j, bot, d, ds, bw, i, w, e, c, common, $horz;
        
      if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
      opts = { TL:1, TR:1, BL:1, BR:1 };
            
        // support native rounding
      if ($.fn.corner.defaults.useNative && fx == 'round' && (radius || moz || webkit) && !cc && !sc) {
        if (opts.TL)
        $this.css(radius ? 'border-top-left-radius' : moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
        if (opts.TR)
        $this.css(radius ? 'border-top-right-radius' : moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
        if (opts.BL)
        $this.css(radius ? 'border-bottom-left-radius' : moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
        if (opts.BR)
        $this.css(radius ? 'border-bottom-right-radius' : moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
        return;
      }
            
      strip = document.createElement('div');
      $(strip).css({
        overflow: 'hidden',
        height: '1px',
        minHeight: '1px',
        fontSize: '1px',
        backgroundColor: sc || 'transparent',
        borderStyle: 'solid'
      });
    
      pad = {
        T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
        B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
      };

      if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
      if (!keep) this.style.border = 'none';
      strip.style.borderColor = cc || gpc(this.parentNode);
      cssHeight = $(this).outerHeight();

      for (j in edges) {
        bot = edges[j];
            // only add stips if needed
        if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
          strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
          d = document.createElement('div');
          $(d).addClass('jquery-corner');
          ds = d.style;

          bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

          if (bot && cssHeight != 'auto') {
            if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
            ds.position = 'absolute';
            ds.bottom = ds.left = ds.padding = ds.margin = '0';
            if (expr)
            ds.setExpression('width', 'this.parentNode.offsetWidth');
            else
              ds.width = '100%';
          }
          else if (!bot && $.browser.msie) {
            if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
            ds.position = 'absolute';
            ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
            if (expr) {
              bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
              ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
            }
            else
              ds.width = '100%';
          }
          else {
            ds.position = 'relative';
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
          }

          for (i=0; i < width; i++) {
            w = Math.max(0,getWidth(fx,i, width));
            e = strip.cloneNode(false);
            e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
            bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
          }
                
          if (fold && $.support.boxModel) {
            if (bot && noBottomFold) continue;
            for (c in opts) {
              if (!opts[c]) continue;
              if (bot && (c == 'TL' || c == 'TR')) continue;
              if (!bot && (c == 'BL' || c == 'BR')) continue;
                        
              common = { position: 'absolute', border: 'none', margin: 0, padding: 0, overflow: 'hidden', backgroundColor: strip.style.borderColor };
              $horz = $('<div/>').css(common).css({ width: width + 'px', height: '1px' });
              switch(c) {
                case 'TL': $horz.css({ bottom: 0, left: 0 }); break;
                case 'TR': $horz.css({ bottom: 0, right: 0 }); break;
                case 'BL': $horz.css({ top: 0, left: 0 }); break;
                case 'BR': $horz.css({ top: 0, right: 0 }); break;
              }
              d.appendChild($horz[0]);
                        
              var $vert = $('<div/>').css(common).css({ top: 0, bottom: 0, width: '1px', height: width + 'px' });
              switch(c) {
                case 'TL': $vert.css({ left: width }); break;
                case 'TR': $vert.css({ right: width }); break;
                case 'BL': $vert.css({ left: width }); break;
                case 'BR': $vert.css({ right: width }); break;
              }
              d.appendChild($vert[0]);
            }
          }
        }
      }
    });
  };

  $.fn.uncorner = function() { 
    if (radius || moz || webkit)
    this.css(radius ? 'border-radius' : moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
    $('div.jquery-corner', this).remove();
    return this;
  };

// expose options
  $.fn.corner.defaults = {
    useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
    metaAttr:  'data-corner' // name of meta attribute to use for options
  };
    
})(jQuery);
