/**
*	Comments controller for web-T::CMS
*	@version 0.88
*	@author goshi
*	@package javascript::portal
*
*	Changelog:
*		0.88	27.06.10/goshi	add scrolling to the comment
*		0.87	13.06.10/goshi	fix lost events on reply pressed
*		0.86	02.06.10/goshi	add _postLoad method
*		0.83	01.06.10/goshi	some little improvements
*		0.82	13.10.09/goshi	attach events on loading or saving
*		0.8	10.04.09/goshi	add rating comment
*		0.71	09.04.09/goshi	remove bug with two 1-st images
*		0.7	02.04.09/goshi	add on ready callback function
*		0.6	31.03.09/goshi	add images uploading!
*		0.5	05.02.09/goshi	remove bug with autoupdate
*		0.4	23.01.09/goshi	added register tabs and autoupdate system
*		0.3	21.01.09/goshi	improve usability - add Ctrl+Enter eventer and tabindex
*		0.2	31.01.09/goshi	added window.comments array with comments object on page
*		0.1	17.01.09/goshi	remove javascript's code from templates
*/	


// constructor
function oComments(objid, options){

	this._init(objid, options);
		
}


// prototype
oComments.prototype = {

	_ppage:			'',		// current number of opened page
	_has_loaded:		false, 		// flag set to true, when comments were loaded
	_curr_node: 		0,		// id of current selected node of comments
	_comm_add_tpl: 		'',		// temporary storage of add comment template 
	_autoupdate:		false,		// autoupdate flag
	_autoID:		false,		// autoupdate container for timer
	_autofocus:		false,		// flag for autofocusing in input field after do load comments

	_ajx_href:		null,
	_ajax_controller_href:	null,

	_isCtrl:		false,		// if user press Ctrl in textarea - setting to true
	
	_ratings:		{},		// object of ratings
	
	_error: 		0,		// current error level
	
	_obj: 			null,		// temporary storage for comment object
	
	_onready:		null,		// calling ONE time, when object are ready (when loading comments)

	_hash:	'comments',
	
	_init: function(objid, options){
		// getting object
		if (!window.comments){
			window.comments = new Array();
		}
		
		this._obj = objid;
		
		// getting object
		this._obj = objid;
		
		this._ajax_controller_href = '/ajax.php?resource=rating&data=comments';
		this._ajx_href = options.ajx_href || this._ajax_controller_href;
		
		this._autoupdate = options.autoupdate;
		this._autofocus = options.autofocus;
		
		this._onready = options.onready;
		this._ppage = 1;

		window.comments[window.comments.length] = this;
							
	},
	
	changePostType: function(objid){
	
		var rmark = $_('regbmark_'+this._obj);
		var amark = $_('anonbmark_'+this._obj);
	
		if (rmark)
			rmark.className = "comm-mark-pass";
		if (amark)
			amark.className = "comm-mark-pass";
		
		if (objid){
			$_(objid).className="comm-mark-act";
			
			if (objid == 'regbmark_'+this._obj){
				if ($_('comm_log_div_'+this._obj) != undefined)
					$_('comm_log_div_'+this._obj).style.display = '';
				$_('add_type_'+this._obj).value = 'reg';
				$_('comm_nick_div_'+this._obj).style.display = 'none';
			} else {
				if ($_('comm_log_div_'+this._obj) != undefined)
					$_('comm_log_div_'+this._obj).style.display = 'none';
				$_('add_type_'+this._obj).value = 'anonym';
				$_('comm_nick_div_'+this._obj).style.display = '';
			}
			
		}
	
	},
	
	_postLoad : function(response){
	
		var athis = this;
		
		this._has_loaded = true;
		
		athis._autoupdate = response.autoupdate;
		athis._ppage = response.ppage;
				
		if (athis._autoupdate == 1) athis.setAutoUpd();
		if (response.is_reload == 1) document.location.reload();
		
		// scrolling to the first elemtn
		var result = portal.hash.parse();
		if ($('.b-comm-item-first').length > 0 && result && 'comments' in result){
			$.scrollTo('.b-comm-item-first', 500);
		}
		
		// creating ratings
		if (typeof response.ratings != null){
			athis._ratings = new Array;
				
			/*for (var i in response.ratings){
				if ((typeof(response.ratings[i])).toLowerCase() != "function"){
						
						athis._ratings[i] = window['Rating'+response.ratings[i]['objid']] = new Rating(
									'oRatElem'+response.ratings[i]['objid'], 
									response.ratings[i]['objid'], 
									athis._ajax_controller_href+'&id='+response.ratings[i]['id'], 
									portal.mess.rating.again_vote_phrase,  
									response.ratings[i]);
				}
			}*/
				
		}


		athis._connectEvents();
					
		// eval onready code
		if (athis._onready != null){
			if (typeof athis._onready == "function")
				athis._onready();
			else
				eval(athis._onready);
		}
					
		if (typeof oImgContainer != "undefined") oImgContainer.removeAll();
		
	},
	
	_connectEvents : function(){
	
		var athis = this;
						
		if ($_('comm_nick_'+this._obj)){
			portal.events.attach($_('comm_nick_'+this._obj), "click", function (e){
			 	if ($_('comm_nick_'+athis._obj).value == $_('comm_nick_'+athis._obj).getAttribute('defvalue'))
			 		$_('comm_nick_'+athis._obj).value = '';
			 	});
			portal.events.attach($_('comm_nick_'+this._obj), "blur", function (e){
			 	if ($_('comm_nick_'+athis._obj).value == '')
			 		$_('comm_nick_'+athis._obj).value = $_('comm_nick_'+athis._obj).getAttribute('defvalue');
			 	});
 	
		}
		
		if ($_('comm_email_'+this._obj)){
			
			portal.events.attach($_('comm_email_'+this._obj), "click", function (e){
			 	if ($_('comm_email_'+athis._obj).value == $_('comm_email_'+athis._obj).getAttribute('defvalue'))
			 		$_('comm_email_'+athis._obj).value = '';
			 	});

			portal.events.attach($_('comm_email_'+athis._obj), "blur", function (e){
			 	if ($_('comm_email_'+athis._obj).value == '')
			 		$_('comm_email_'+athis._obj).value = $_('comm_email_'+athis._obj).getAttribute('defvalue');
			 	});
			 	
		}
		
		// attach event on form
		if ($_('addCommForm')){
			portal.events.attach($_('comment_descr_'+athis._obj), 'keyup', function (e){athis.checkUp(e)});
			portal.events.attach($_('comment_descr_'+athis._obj), 'keydown', function (e){athis.checkDown(e)});
			portal.events.attach($_('tuning_'+athis._obj), 'keyup', function (e){athis.checkUp(e)});
			portal.events.attach($_('tuning_'+athis._obj), 'keydown', function (e){athis.checkDown(e)});
			portal.events.attach($_('comment_nick_'+athis._obj), 'keyup', function (e){athis.checkUp(e)});
			portal.events.attach($_('comment_nick_'+athis._obj), 'keydown', function (e){athis.checkDown(e)});
			portal.events.attach($_('addCommForm'), 'submit', function (e){athis.Save(); return false;});
		}
	
	},

	Save: function(){
		
		this._error = 0;
		this._isCtrl = false; // turn off Ctrl button
		
		// checking for input data
		/*if ($_('add_type_'+this._obj).value=='anonym' && $_('comment_nick_'+this._obj).value == ''){
			alert(portal.mess.comments.post_no_nick);
			this._error = 1;
		}*/
		
		// checking for input data
		if ($_('comment_descr_'+this._obj).value == ''){
			alert(portal.mess.comments.post_no_text);
			this._error = 1;
		}

		if (this._error != 1){
		
			var req = new JsHttpRequest();

			this._has_loaded = false;
			
			var _send_obj = {
				'save': 1,
				'ch_elem' : {
					'descr': $_('comment_descr_'+this._obj).value,
					'nick': $_('comm_nick_'+this._obj) ? $_('comm_nick_'+this._obj).value : '',
					'email': $_('comm_email_'+this._obj) ? $_('comm_email_'+this._obj).value : '',
					'parent_id': this._curr_node				
				},
				/*'hh': $_('hh_'+this._obj).value,
				'tuning': $_('tuning_'+this._obj).value,
				'add_type': $_('add_type_'+this._obj).value,*/
				'username': $_('cmnt_username_'+this._obj) ? $_('cmnt_username_'+this._obj).value : '',
				'password': $_('cmnt_password_'+this._obj) ? $_('cmnt_password_'+this._obj).value : '',
				'is_enter': $_('cmnt_enter_'+this._obj) ? $_('cmnt_enter_'+this._obj).checked : '',
				'ppage': this._ppage,
				/*'img0' : $_("img0_"+this._obj),
				'img1' : $_("img1_"+this._obj),
				'img2' : $_("img2_"+this._obj),*/
				'obj': this._obj};
			
			
			var ticket = portal.loader.create('oComments_'+this._obj, {"mode" : "float"});
			var athis = this;

			req.onreadystatechange = function (){
				
				if (req.readyState == 4){

					portal.loader.destroy(ticket);										
					$_('oComments_'+athis._obj).innerHTML = req.responseJS.content;
					
					// check if saved complete w/o errors
					if (req.responseJS.saved)
						athis._curr_node = 0;
						
					// clearing post form 
					athis._comm_add_tpl = '';
					athis.Reply(athis._curr_node);
					
					athis._postLoad(req.responseJS);
																	
				}
			
			}
	
			req.open(null, this._ajx_href, true);
			req.send(_send_obj);
		} else return this._error;
	},

	Load: function(is_hidden){

		// show uploader
		if (!is_hidden || typeof is_hidden == 'undefined'){
			var ticket = portal.loader.create('oComments_'+this._obj, {"mode" : "float"});
			
		}

		var req = new JsHttpRequest();
		
		this._has_loaded = false;
		this._isCtrl = false; // turn off Ctrl button

		var athis = this;
		
		req.onreadystatechange = function (){
			
			if (req.readyState == 4){

				if (typeof ticket != 'undefined')
					portal.loader.destroy(ticket);
				$_('oComments_'+athis._obj).innerHTML = req.responseJS.content;
				
				if (athis._autofocus)
					athis.Reply(athis._curr_node);
					
				athis._postLoad(req.responseJS);							
						
			}
		
		}
	
		req.open(null, this._ajx_href, true);
		req.send({'ppage' : this._ppage,
			'obj': this._obj});

		
	},

	Delete: function(id){
	
		//showLoader('oComments_'+this._obj, {'layered' : true});
		var ticket = portal.loader.create('oComments_'+this._obj, {"mode" : "float"});
		var req = new JsHttpRequest();
		
		this._has_loaded = false;
		var athis = this;
		
		req.onreadystatechange = function (){
			
			if (req.readyState == 4){
				
				portal.loader.destroy(ticket);
				$_('oComments_'+athis._obj).innerHTML = req.responseJS.content;
				
				athis.Reply(athis._curr_node);
				athis._postLoad(req.responseJS);
			}
		
		}
		
		req.open(null, this._ajx_href, true);
		req.send({'id' : id,
			'del' : 1,
			'ppage' : this._ppage,
			'obj': this._obj
			});
	},

	
	setAutoUpd: function(){
		if (this._autoupdate == 1){
			if (this._autoID) window.clearInterval(this._autoID);
			this._autoID = setInterval("oComments_"+this._obj+".Load(true)", 120000);
		}
	},
	
	Hide: function(){
		// remove old inner
		$_('comm_add_tpl_'+this._obj).innerHTML = this._comm_add_tpl;
		//this._comm_add_tpl.innerHTML = '';
		$_('add_comm_'+this._obj+'_'+this._curr_node).innerHTML = '';
		
	},

	Reply: function(parent_id){
		// remove old inner
		if (this._comm_add_tpl == ''){
			this._comm_add_tpl = $_('comm_add_tpl_'+this._obj).innerHTML;
			$_('comm_add_tpl_'+this._obj).innerHTML = '';
		}
		
		$_('add_comm_'+this._obj+'_'+this._curr_node).innerHTML = '';
		this._curr_node = parent_id;
		$_('add_comm_'+this._obj+'_'+this._curr_node).innerHTML = this._comm_add_tpl;
		
		// scrolling to the comment for reply
		if ($.scrollTo){
			$.scrollTo(parent_id == '0' ? '#add_comm_'+this._obj+'_'+this._curr_node : '#comments-'+this._obj+'_'+this._curr_node, 300);
		}
		
		this._connectEvents();
		//$_('comment_descr_'+this._obj).focus();
		return void(0);
	},


	updPage: function(new_ppage){
		this._ppage = new_ppage;
		this.Load();
		
		// update hash
		portal.hash.set(this._hash+"="+new_ppage);
	},
	
	/* for checking of input keys */
	checkUp: function(event){
		if ({17:17}[event.which||event.keyCode])
			this._isCtrl = false;
	},
	
	checkDown: function(event, force){
		
		// check - if forcing send comment - it is use, when press key send button - then - checking for Enter buton
		if (typeof force != "undefined" && force)
			this._isCtrl = true;
			
		if ({17:17}[event.which||event.keyCode]){
			this._isCtrl = true;
		} else if (this._isCtrl && {13:1}[event.which||event.keyCode]){
			this.Save();
			return false;
		}
		
		if (typeof force != "undefined" && force)
			this._isCtrl = false;
		
	},
	
	keyChecker: function(event, func){
	
		if ({13:1}[event.which||event.keyCode]){
			eval(func);
			return false;
		}
	
	}

	
};
