Post = {}

PostsHash = new Hash()

Post.vote = function(score, id) {
  notice('Voting for post #' + id + '...');

  new Ajax.Request("/post/vote", {
    asynchronous: true,
    method: "post",
    postBody: "post_id=" + id + "&score=" + score,
    onComplete: function(req) {
	  notice(req.responseText);
      resp = eval("(" + req.responseText + ")")
      if (resp["success"]) {
		notice("Vote saved for post #" + id);  
		$("rating-block").style.display = "none";
		$("rating-around").innerHTML = "<strong>Thanks for voting!</strong>";
        
      } else {
		notice("" + resp["reason"]);	
		$("rating-block").style.display = "none";
		$("rating-around").innerHTML = "<strong>" + resp["reason"] + "</strong>";  
		
      }
    }
  })
}



Post.register = function(post_id, tags)
{
  PostsHash.set(post_id, {"tags": tags.match(/\S+/g)})
}

Post.update= function(post_id, tags) {
  notice('Updating post #' + post_id)
  
  new Ajax.Request("/post/edit", {
    asynchronous: true,
    method: "post",
    postBody: "post_id=" + post_id + "&post_tags=" + tags,
    onComplete: function(req) {
	 	 
	  notice("(" + req.responseText + ")")
      resp = eval("(" + req.responseText + ")")
      if (resp["success"]) {
		notice("Post Updated");  
        
      } else {
		notice("" + resp["reason"]);
      }
    }
  })
}

Post.resize_image = function()
{
    var img = $("image");

    if ((img.scale_factor == 1) || (img.scale_factor == null)) {
      img.original_width = img.width;
      img.original_height = img.height;
      var client_width = $("Image_Around").clientWidth - 15;
      var client_height = $("Image_Around").clientHeight;

      if (img.width > client_width) {
        var ratio = img.scale_factor = client_width / img.width;
        img.width = img.width * ratio;
        img.height = img.height * ratio;
      }
	  Note.hide();
    } else {
      img.scale_factor = 1;
      img.width = img.original_width;
      img.height = img.original_height;
	  Note.show();
    }

}

Favorite = {}

Favorite.add = function(post_id) {
  notice('Adding post #' + post_id)

  new Ajax.Request('/favorite/add', {
    asynchronous: true,
    method: 'post',
		postBody: 'post_id='+post_id,
    onComplete: function(req) {
      notice( req.responseText);
	  var resp = eval("(" + req.responseText + ")")

      if (req.status == 409) {
        notice("Post #" + post_id + " " + resp.reason)
      } else if (req.status == 500) {
        notice("You are not logged in")
      } else {
        notice("Post #" + post_id + " added to favorites")
              
      }
    }
  })
}

Favorite.remove = function(post_id) {
    if ($("del-mode") && $("del-mode").checked == true) {
	  notice("Removing post...")
      new Ajax.Request('/favorite/remove', {
        asynchronous: true,
        method: 'post',
        postBody: 'post_id=' + post_id,
        onComplete: function(req) {
		 
          var resp = eval("(" + req.responseText + ")")
		  if (req.status == 409){notice("Error: " + resp.reason)}
		  else if (req.status == 500){notice("Error: " + resp.reason)}
		  else
		  {
			  notice("Post Removed")
		      Element.remove('p' + resp.post_id)
		  }
  
        }
      })

      return false
    } else {
      return true
    }
  }
  
PostModeMenu = {
  init: function() {
    if (Cookie.get("mode") == "") {
      Cookie.put("mode", "view")
      $("mode").value = "view"
    } else {
      $("mode").value = Cookie.get("mode")
    }
  
    this.change()  
  },

  change: function() {
	var s = $F("mode")
		
	Cookie.put("mode", s, 7)
	
    if (s == "view") {
      document.bgColor = "#FFFFFF"
    } else if (s == "fav") {
      document.bgColor = "#FFFFAA"
    } else if (s == "vote5") {
      document.bgColor = "#AAFFAA"
    } else if (s == "vote4") {
      document.bgColor = "#AAFFAA"
    } else if (s == "vote3") {
      document.bgColor = "#AAFFAA"
    } else if (s == "vote2") {
      document.bgColor = "#AAFFAA"
    } else if (s == "vote1") {
	  document.bgColor = "#AAFFAA"
	} else if (s == "edit") {
	  document.bgColor = "#AAAAAA"
	} else if (s == "apply-tag-script") {
	  document.bgColor = "#AA33AA"
	} else if (s == "edit-tag-script") {
	  document.bgColor = "#FFFFFF"
	  var script = prompt("Enter a tag script")
	  if (script)
	  {
  	    Cookie.put("tag-script", script)
  	  }
	  Cookie.put("mode", "view", 7)
  	  $("mode").value = "view"
	} else {
      document.bgColor = "#AAFFAA"
    }
  },

  click: function(post_id) {
    var s = $("mode")

    if (s.value == "view") {
      return true
    } else if (s.value == "fav") {
      Favorite.add(post_id)
    } else if (s.value == "edit") {
      var post = PostsHash.get(post_id)
      $("post_id").value = post_id
      $("post_tags").value = post.tags.join(" ")
      $("quick-edit").show()
	  $("post_tags").scrollTo()
	  	 
      return false
    } else if (s.value == "vote5") {
      Post.vote(5, post_id)
    } else if (s.value == 'vote4') {
      Post.vote(4, post_id)
    } else if (s.value == 'vote3') {
      Post.vote(3, post_id)
    } else if (s.value == 'vote2') {
	  Post.vote(2, post_id)
	} else if (s.value == 'vote1') {
	  Post.vote(1, post_id)
	} else if (s.value == 'apply-tag-script') {
	  var tag_script = Cookie.get("tag-script")
      var commands = TagScript.parse(tag_script)
      var post = PostsHash.get(post_id)
	  var old_tags = post.tags.join(" ")
	  var new_tags = ""
	 
      commands.each(function(x) {
         post.tags = TagScript.process(post.tags, x)
      })
	  
	  new_tags = post.tags.join(" ")
	  
	  if(new_tags == old_tags)
	  {
		  notice("No Update Needed")
	  }
	  else
	  {
		  Post.update(post_id, new_tags)
	  }
	  
	} else {
	  return true	
	}
     

    return false
  }
}

TagScript = {
  parse: function(script) {
    return script.match(/\[.+?\]|\S+/g)
  },

  test: function(tags, predicate) {
    var split_pred = predicate.match(/\S+/g)
    var is_true = true

    split_pred.each(function(x) {
      if (x[0] == "-") {
        if (tags.include(x.substr(1, 100))) {
          is_true = false
          throw $break
        }
      } else {
        if (!tags.include(x)) {
          is_true = false
          throw $break
        }
      }
    })

    return is_true
  },

  process: function(tags, command) {
    if (command.match(/^\[if/)) {
      var match = command.match(/\[if\s+(.+?)\s*,\s*(.+?)\]/)
      if (TagScript.test(tags, match[1])) {
        return TagScript.process(tags, match[2])
      } else {
        return tags
      }
    } else if (command == "[reset]") {
      return []
    } else if (command[0] == "-") {
      return tags.reject(function(x) {return x == command.substr(1, 100)})
    } else {
      tags.push(command)
      return tags
    }
  }
}