// version 0.0.1
// created by: Polder Knowledge
(function ($) {
  $.fn.LightBoxForm = function (options) {
	  var defaults = {
		validation:"",
		link:"",
		close_link:".close",
		send_link:".spacial_link",
		default_show:true,
		beforeShow:function(){return true}
	 }
	var options = $.extend(defaults, options);

    return this.each(function () {
		if($("#tranparent_layer").length ==0){
			$("body").prepend($('<div/>').attr("id","tranparent_layer"));
		}
		var $FormBox = $(this);
		if(typeof(options.validate)=='object'){
			$("> form",$FormBox).validate(options.validate);
		}
		$(options.link).bind("click",function(){
			options.beforeShow()
			if(options.default_show==true){
				$('#tranparent_layer').addClass("blocklayer").fadeTo("fast",0.2,function(){
					$(".top_frame").fadeTo("fast",1.0);
				});
				$FormBox.addClass("top_frame").center().css("display","block");
			}
			return false;
		});
		$(this).find(options.close_link).bind("click",function(){
			close_info_box()
			return false;
		});
		$(document).keyup(function(e) {
		  if (e.keyCode == 27) {
			  close_info_box();
		  }   // esc
		})
		$(options.send_link,$(this)).live("click",function(){
				var Form = $("> form",$FormBox);
				if(typeof(options.validate)=='object'){
					if(Form.valid()){
					//-- send ajax call
						$.post(document.location.href,Form.serialize(),function() {
							setTimeout(function(){
								Form.each(function(){
										this.reset();
								});
								close_info_box()
							},500)
						});
					}
				}else{
					$.post(document.location.href,Form.serialize(),function() {
							setTimeout(function(){
								Form.each(function(){
										this.reset();
								});
								close_info_box()
							},500)
						});
				}
				
			return false;			
		});
		function close_info_box(){
			$('.top_frame').removeClass("top_frame").css("display","none");
			$("#tranparent_layer").fadeTo("slow",0.0,function(){
				$("#tranparent_layer").removeClass("blocklayer");
			});
			if(typeof(options.validate)=='object'){
				var v = $("> form",$FormBox).validate();
				if(v!=undefined){
					v.resetForm();
					v.hideErrors();
				}
			}
		}

		//options.onComplete();
    });
  };
})(jQuery);

jQuery.fn.center = function () {
	this.css("position","fixed");
	//Set the popup window to center
	this.css('top',  $(window).height()/2- this.height()/2);
	this.css('left', $(window).width()/2- this.width()/2);
    return this;
}
