// JavaScript library for comments

// MAKE TEXTAREA AUTO GROW
var autoHeightTextarea = function(textareaID, minHeight) {
	// GET THE TEXTAREA
	var textArea = getID(textareaID);
	if(!textArea){
		return false;	
	}
	Dom.setStyle(textArea, 'overflow', 'hidden');
	
	var hiddenID = textareaID+'-hidden';
	var hiddenTextarea=getID(hiddenID);  
	if (!hiddenTextarea) {    
		// The dark layer doesn't exist, it's never been created.  So we'll    
		// create it here and apply some basic styles.    
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917    
		var tbody = document.getElementsByTagName("body")[0];    
		var tnode = document.createElement('textarea');       // Create the layer.        
		tnode.style.position='absolute';                 // Position absolutely        
		tnode.style.top='-10000px';                           // In the top        
		tnode.style.left='-10000px';                          // Left corner of the page        
		tnode.style.height = minHeight;
		tnode.style.overflow='auto';                   // Try to avoid making scroll bars                    

		//tnode.style.display='none';                      // Start out Hidden        
		tnode.id=hiddenID; 						// Name it so we can find it later  
		//tnode.style.zIndex = 0;
		  
		Dom.insertAfter(tnode,textArea);                        // Add it to the web page    
		hiddenTextarea=getID(hiddenID);  // Get the object. 
		
		// GIVE THE HIDDEN TEXTAREA THE SAME STYLES AS THE REAL TEXTAREA SO WE CAN GET THE SAME WRAP POINT
		Dom.addClass(hiddenTextarea, 'comment-input');
		Dom.setStyle(hiddenTextarea, 'font-size', Dom.getStyle(textArea,'font-size')); 
		Dom.setStyle(hiddenTextarea, 'font-family', Dom.getStyle(textArea,'font-family')); 		
		Dom.setStyle(hiddenTextarea, 'line-height', Dom.getStyle(textArea,'line-height')); 
		
			
		Dom.setStyle(hiddenTextarea, 'width',   (parseInt(Dom.getStyle(textArea,'width'),10) + 15)  + 'px');
	}  
	
	
	
	// SET THE HIDDEN TEXTAREA CONTENT TO MATCH
	hiddenTextarea.value = textArea.value;
	
	
	// GET THE HIDDEN TEXTAREA'S SCROLL HEIGHT
	hiddenHeight = parseInt(hiddenTextarea.scrollHeight, 10);
	
	// GET OLD TEXTAREA HEIGHT
	var height = parseInt(Dom.getStyle(textArea, 'height'), 10);
	
	var newHeight = hiddenHeight + 12;
	if (newHeight < parseInt(minHeight, 10)) {
		newHeight = parseInt(minHeight, 10);
	}
	if ((height != newHeight)) {   
		Dom.setStyle(textArea, 'height', newHeight + 'px');
		if (YAHOO.env.ua.ie > 0) {
			//Internet Explorer needs this
			//Dom.setStyle(textArea,'height', '99%');
			//Dom.setStyle(textArea,'zoom', '1');
			
			//window.setTimeout(function() {
			//	Dom.setStyle(textArea,'height', '100%');
			//}, 1);
		}
	}
}
var autoHeightListener = function(textareaID, minHeight){
	// shortcut to autoHeightTextarea function
	var handleAutoHeight = function(){autoHeightTextarea(textareaID, minHeight)}
	
	// auto resize as soon as it is available in the DOM
	YAHOO.util.Event.onContentReady(textareaID, handleAutoHeight , this, true);
	
	// get click listeners (if there are any)
	listeners = YAHOO.util.Event.getListeners ( textareaID , 'click' );
	if(listeners == null){	
		YAHOO.util.Event.on(textareaID, "keyup", handleAutoHeight, true);
		//YAHOO.util.Event.on(textareaID, 'keypress', handleAutoHeight, true);
		//YAHOO.util.Event.on(textareaID, "mouseleave", handleAutoHeight, true);
	}
}

// FUNCTION TO SUBMIT THE "ADD COMMENT FORM" VIA AJAX
function sgCommentAdd(id_suffix){
	// BUILD THE HTML IDS FROM THE SUFFIX
	var formID 				= 'comment-add-' + id_suffix;
	var textareaID			= 'comment-details-' + id_suffix;
	var newCommentAnchorID	= 'comment-new-anchor-' + id_suffix;
	
	// IF THE FORM DOESN'T EXIST, JUST RETURN FALSE
	var myForm		= getID(formID);
	var textarea	= getID(textareaID);
	if(!myForm || !textarea){
		return false;	
	}
	
	// CHECK TO MAKE SURE THE FORM DOESN'T JUST HAVE THE DEFAULT TEXT
	var comment = YAHOO.lang.trim(textarea.value);
	if(comment == 'write a comment...' || comment == 'write a reply...' || comment == ''){
		return false;	
	}
	
	YAHOO.util.Connect.setForm(formID, true);			
	var callback = {		  
		upload: function(o) {
			if(o.responseText == ''){
				alert('Connection to server failed. Please try again.');
				return false;
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If failure, show error, otherwise, redirect.
				if(resp.success == 0){
					waitingPanel.hide();
					return false;
				}else{
					waitingPanel.setHeader('Add Successful.  Updating Current Page...');
					textarea.value = "";
					sgInsertNewComment(resp.customObj.comment_id, id_suffix);					
					waitingPanel.hide();
				}

			}
		},
		failure: function(o){
			alert('Connection to server interrupted. Please try again.');
			return false;
		}
	};
	
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Adding...  Please wait...<br />[<a href="javascript:void(0);" onClick="stopIt();waitingPanel.hide()">Stop Submit</a>]');
	
	// Show the Panel
	waitingPanel.show();
	
	// Perform Upload Call
	window.oConnect = YAHOO.util.Connect.asyncRequest('POST', window.location.protocol + '//' + window.location.hostname + '/index.php', callback);
}


// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function sgInsertNewComment(newCommentID, id_suffix){
	
	// BUILD THE HTML IDS FROM THE SUFFIX
	var newCommentAnchorID	= 'comment-new-anchor-' + id_suffix;
	
	// IF THE FORM DOESN'T EXIST, JUST RETURN FALSE
	var newCommentAnchor	= getID(newCommentAnchorID);
	if(!newCommentAnchor){
		return false;	
	}
	
	// EXTRACT TYPE AND ITEM (BEING COMMENTED ON) ID FROM THE SUFFIX
	var suffix_parts	= id_suffix.split('-');
	var type_id			= parseInt(suffix_parts[0], 10);
	var item_id			= parseInt(suffix_parts[1], 10);
	
	// SAY 'LOADING'
	newCommentAnchor.innerHTML = '<img src="/images/ajax-loader.gif">Loading...';
	
	// CREATE DIV ABOVE NEW COMMENT ANCHOR TO PLACE THE NEW HTML
	var el = document.createElement('div');
	el.id = 'new-comment-' + id_suffix + uniqid();		
	yui_el = Dom.get(el.id);
	Dom.insertBefore(el, newCommentAnchor);
	this.el = el;
	
	// GET NEW DIMENSIONS
	var dimensions = Dom.getRegion(el.id);
	
	Dom.setStyle(el.id, 'height', 0);
	Dom.setStyle(el.id, 'overflow', 'hidden');
	
	// BEGIN URL TO FETCH COMMENT
	var getCommentURL = window.location.protocol + '//' + window.location.hostname +'/fa/main-ajax_comment_dsp/type_id-'+ type_id +'/id-'+ item_id +'/comment_id-'+ newCommentID;
	
	// BUILD VARIABLES TO GET A COMMENT THAT MATCHES OUR CURRENT CONFIG
	config_name = type_id+'-'+item_id;
	if(YAHOO.lang.isObject(YAHOO[config_name])){
		for(i in YAHOO[config_name]){
			getCommentURL += '/'+ i +'-'+ YAHOO[config_name][i];
		}
	}
	
	
	
	
	// FUNCTION TO ADD FINAL ATTRIBUTES TO NEW DIV
	this.finish = function(){
		Dom.setStyle(this.getEl(), 'overflow', 'visible');
		Dom.setStyle(this.getEl(), 'height', 'auto');
	}
	this.animate_me = function(){
		this.newel = this.el;
		// HIDE 'LOADING'
		newCommentAnchor.innerHTML = '';	
		if(this.el.innerHTML == ''){
			return false;	
		}
		var attributes = {   
			height: { from: 0, to: 30 } 
		}; 
		var anim = new YAHOO.util.Anim(this.el, attributes, .75, YAHOO.util.Easing.easeOut);
		anim.onComplete.subscribe( this.finish );
		anim.animate(); 
	}
	//setTimeout(animate_me, 2000);
	
	// GET STATUS ENTRY AND LOAD IT INTO NEW DIV
	new simpleAjaxContent( el.id, getCommentURL, false, this.animate_me );
	
	
}

// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function sgCommentDelete(commentID, id_suffix){
	
	// BUILD THE HTML IDS FROM THE SUFFIX
	var container_id	= "comment-" + id_suffix;
	
	// IF THE FORM DOESN'T EXIST, JUST RETURN FALSE
	var commentContainer	= getID(container_id);
	if(!commentContainer){
		return false;	
	}
	
	// EXTRACT TYPE AND ITEM (BEING COMMENTED ON) ID FROM THE SUFFIX
	var suffix_parts	= id_suffix.split('-');
	var type_id			= parseInt(suffix_parts[0], 10);
	var item_id			= parseInt(suffix_parts[1], 10);
	var comment_id		= parseInt(suffix_parts[2], 10);// not used in this function, but good to know
	
	
	
	// BEGIN URL TO FETCH COMMENT
	var poststr = 'sg=main.ajax_comment_delete&type_id='+ type_id +'&id='+ item_id +'&comment_id='+ commentID;
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				alert('Delete Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					alert(resp.message);
					return false;
					
				}else{					
					waitingPanel.hide();
					var obj =Dom.get(container_id);
					obj.parentNode.removeChild(obj);

				}
			}
			
		},
		
		failure: function(o) {
			alert('DELETE failed');
		}
		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Deleting Reply.  Please wait...<br />[<a href="javascript:void(0);" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', window.location.protocol + '//' + window.location.hostname + '/index.php', callback, poststr );
	
}

// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function sgInsertOlderComments(datetime, id_suffix){
	
	// BUILD THE HTML IDS FROM THE SUFFIX
	var oldCommentAnchorID	= 'comment-old-anchor-' + id_suffix;
	this.oldCommentLinkID	= 'comment-old-link-' + id_suffix;
	
	// IF THE ANCHOR DIV DOESN'T EXIST, JUST RETURN FALSE
	var oldCommentAnchor	= getID(oldCommentAnchorID);
	if(!oldCommentAnchor){ 
		return false;	
	}
	
	
	
	// EXTRACT TYPE AND ITEM (BEING COMMENTED ON) ID FROM THE SUFFIX
	var suffix_parts	= id_suffix.split('-');
	var type_id			= parseInt(suffix_parts[0], 10);
	var item_id			= parseInt(suffix_parts[1], 10);
	
	// SAY 'LOADING'
	oldCommentAnchor.innerHTML = '<img src="/images/ajax-loader.gif">Loading...';
	
	// CREATE DIV ABOVE NEW COMMENT ANCHOR TO PLACE THE NEW HTML
	var el = document.createElement('div');
	el.id = 'new-comment-' + id_suffix;// + uniqid();		
	yui_el = Dom.get(el.id);
	Dom.insertAfter(el, oldCommentAnchor);
	this.el = el;
	el.oldCommentLinkID = this.oldCommentLinkID;// attach it to the dom element so we can use it below in animate_me
	
	// SET IT TO 0 HIEGHT, SO WE CAN SLIDE IT OPEN AND LOOK COOL	
	Dom.setStyle(el.id, 'height', 0);
	Dom.setStyle(el.id, 'overflow', 'hidden');
	
	// BEGIN URL TO FETCH COMMENT
	var getCommentURL = window.location.protocol+ '//' + window.location.hostname + '/fa/main-ajax_comments_older_dsp';
	getCommentURL += '/type_id-'+ type_id;
	getCommentURL += '/id-'+ item_id;
	getCommentURL += '/datetime-' + encodeURI(datetime);
	getCommentURL += '/is_reversed-1';
	getCommentURL += '/include_item-1';
	getCommentURL += '/link_details-1';
	getCommentURL += '/leave_unread-1';	
	
	
	// BUILD VARIABLES TO GET A COMMENT THAT MATCHES OUR CURRENT CONFIG
	config_name = type_id+'-'+item_id;
	if(YAHOO.lang.isObject(YAHOO[config_name])){
		for(i in YAHOO[config_name]){
			getCommentURL += '/'+ i +'-'+ YAHOO[config_name][i];
		}
	}
	
	
	
	
	// FUNCTION TO ADD FINAL ATTRIBUTES TO NEW DIV
	this.finish = function(){
		Dom.setStyle(this.getEl(), 'overflow', 'visible');
		Dom.setStyle(this.getEl(), 'height', 'auto');
		// remove 'get older' link
		var obj =Dom.get(this.getEl().oldCommentLinkID);
		obj.parentNode.removeChild(obj);
	}
	this.animate_me = function(){
		this.newel = this.el;
		// HIDE 'LOADING'
		oldCommentAnchor.innerHTML = '';	
		if(this.el.innerHTML == ''){
			return false;	
		}
		var attributes = {   
			height: { from: 0, to: 30 } 
		}; 
		var anim = new YAHOO.util.Anim(this.el, attributes, .75, YAHOO.util.Easing.easeOut);
		anim.onComplete.subscribe( this.finish );
		anim.animate(); 
		
		
	}
	//setTimeout(animate_me, 2000);
	
	// GET STATUS ENTRY AND LOAD IT INTO NEW DIV
	new simpleAjaxContent( el.id, getCommentURL, false, this.animate_me );
	
	
}
