var popup = ""

$(document).ready(function(){

  // Full screen popups
  $(".open_popup").click(function(){ popup = this.id.replace(/_link/,""); openPopup(); });
  $(".close_popup").click(function(){ closePopup(); });
  $("#popup_background").click(function(){ closePopup(); });
  $(document).keypress(function(e){ if(e.keyCode==27){ closePopup(); } });

  // Asynchronous form posting
  // NOTE: This is a fulsnurra that requires the id of the popup-div to equal the service-URL
  $('.async').submit(function(e) {
      $.post('/async/' + popup, $('#' + popup + ' form').serialize(),
        function(response) {
          closePopup();
          if (popup == "create_feed") { 

            //console.log(response["shortname"]);
            //console.log(response["realname"]);
            //console.log(response["feedname"]);
            
            if (response["error"] == "no name") {
              flash("Du måste ge en ny bevakning ett namn!", "error");               
            } else {
              flash("Skapade bevakningen " + response["realname"] + ".", "accept"); 
              $('ul#treeRoot').append(treeListItem(response)).effect("highlight", { color: "#a6d96a" }, 2000);
              //$("li#" + response["feedname"]).effect("highlight", { color: "#a6d96a" }, 2000);
              bind_feed_tree();
            } 

          } else if (popup == "publish_article") { 

            flash("Publicerade en artikel.", "accept");

          } else if (popup == "add_source") { 

            flash("Lade till en källa.", "accept");
          }
        }, "json");
      e.preventDefault();
  });

  // Fix to preserve the name attributes of submit buttons in the create_feed-popup
  $('#create_feed :submit').lockSubmit();

  // Popup feed menu for adding articles to folders
  var article = ""
  $(".chunk_atf").click(function(event){
      article = this.id
      var pos = $("#" + article).offset();
      $("#popup_feeds_menu").css( { "left": pos.left + "px", "top":pos.top + "px" } );
      $("#popup_feeds_menu").fadeIn();
      event.preventDefault();
    });
  $("#popup_feeds_menu").hover(function(){
      $("#popup_feeds_menu").show();
    }, function() { $("#popup_feeds_menu").fadeOut("slow"); });
  $("#popup_feeds_menu li").click(function(event){
      feed = this.id.replace(/popup_/, ""); 
      $.post('/async/add_to_folder/' + feed + "/" + article.replace(/chunk_atf_/, ""),
        function(response) { $("#popup_feeds_menu").fadeOut("slow"); }
      );
      event.preventDefault();
    });





});

function openPopup(){
  centerPopup();
  $("#popup_background").css({ "opacity": "0.5" });
  $("#popup_background").fadeIn("slow");
  $("#" + popup).fadeIn("slow");
}

function closePopup(){
  $("#popup_background").fadeOut("slow");
  $("#" + popup).fadeOut("slow");
}

function centerPopup(){
  var windowWidth = document.documentElement.clientWidth;
  var windowHeight = document.documentElement.clientHeight;
  var popupHeight = $("#" + popup).height();
  var popupWidth = $("#" + popup).width();
  $("#" + popup).css({
    "position": "absolute",
    "top": windowHeight/2-popupHeight/2,
    "left": windowWidth/2-popupWidth/2
  });
  //force correct height in IE6
  $("#popup_background").css({ "height": windowHeight });
}

// Flash messages
function flash(msg, type) {
  $("#flash").html("<div class='flash_" + type + "'><img src='/icons/" + type + ".png' /> " + msg + "</div>");  
}



// The code below is a heavily stripped down version of the jQuery.lockSubmit plugin
// License: http://www.gnu.org/licenses/lgpl.txt
// Homepage: http://blog.leenix.co.uk/2009/09/jquery-plugin-locksubmit-stop-submit.html

jQuery.fn.lockSubmit = function(options) {
	var clicked=false;
	return this.click(function(e) {		
		if(clicked) { return false; }
		else {
			clicked=true;			
			//insert hidden field with name and value of submit
			jQuery(this).after("<input type='hidden' name='"+jQuery(this).attr("name")+"' value='"+jQuery(this).val()+"'>");
			return true;
		}
	});
};

