/*********************************************************************************/
/**			copyright (c) PlanetCalc.com, 2007  			**/
/**		    	Ajax Commenter								*/
/*********************************************************************************/

function Commenter(outerdivid, url ) {
	this.OuterDivID = outerdivid;
	this.URL = url;

	this.SetTable = function ( tbl ) {
		this.Comments = tbl;
	}

	this.initdialog =  function (dialog) { 
		this.Dialog = dialog;
	}; 

	this.onchanged = function ( controlid ) {	
	}; 	

	this.onkeypressed = function ( controlid, evt ) { 
		return true; 
	};

	this.oncommand = function ( buttonid ) { 
		clearLastError(); 
		if ("ok" == buttonid) {
			if ( this.Dialog.Validate() ) {
				this.Send();
			}
		} else if ("cancel" == buttonid)
			this.Discard();
	}; 

	this.Send = function ( ) {
		if ( this.Dialog.Validate() ) {
			this.Dialog.Busy();
			BSMakePOSTRequest( this.URL, this, GetDialogData(this.Dialog) );			
		}
	}

	this.Discard = function ( ) {
		SetVisible(this, false);
	}                   

	function SetVisible(commenter, show) {
		var elem = document.getElementById(commenter.OuterDivID);
		elem.style.display = show ? "block" : "none";		
	}

	this.OnResponse = function( obj ) {
		this.Dialog.Free();
		ShowAndReload(this);
	}

	this.OnError = function( obj ) {
		this.Dialog.Free();
		this.ResetCaptcha();
		this.Dialog.ShowError(null, obj);
		return true;
	}                                    

	this.ResetCaptcha = function () {
		if ( commenter.Dialog.captcha ) {
			commenter.Dialog.captcha.SetValue("");
			document.getElementById(this.Dialog.GetElement().id + '_captcha_image').src = '/captcha/?' + Math.random();
		}
	}

	function GetDialogData(dialog) {
		var data = { "id" : dialog.comment_id.GetValue(),
			     "message" : dialog.message_text.GetValue(), 
			     "parent" : dialog.parent.GetValue() };					
		if (undefined != dialog.captcha) { 
			data.captcha = dialog.captcha.GetValue();
		}
		if ( undefined != dialog.sender ) {
			data.sender = dialog.sender.GetValue();
		}
	        return data;		
	}

	function ShowAndReload(commenter) {
		commenter.ResetCaptcha();
		commenter.Dialog.message_text.SetValue("");
		commenter.Comments.Reload();
	}
}    
