/*
 * Comments handling script
 * This script uses prototype.js JS framework
 * 
 * @version 1.0
 * @copyright Copyright (c) 2007, Sorvi.com
 */

/*
 * CALLED FROM HTML
 */

// To be called when file is run -> normal GET request
// TODO: onLoad...
//TODO: Make better onload handling
//getComments(1);

function setObserve(){

	Event.observe('gccomment_area', 'click', function(event) {
		var element = Event.element(event);
		
		// Link can be control links or spam link
		if ('A' == element.tagName) {
			// Notify about spam
			if ('gccomment_spam' == element.readAttribute('id')) {
				element.update(spamSentStr);
				sendSpamNotification(element.readAttribute('cid'));
				
			}
			// Control: like next previous etc.
			else {    		
				getComments(element.readAttribute('sp'));    		
			}
		}
		else if ('INPUT' == element.tagName) {
			//console.log("INPUT Field click");
			if ('gccomment_submit_btn' == element.readAttribute('id')) {
				postComment();	
				//console.log("INPUT - SUBMIT");
			}
		}
		else if ('DIV' == element.tagName) {
			// Title has been clicked
		}
	});

}


/*window.onload = function() {
	//console.log("Onload function");

}*/

// To be called when posting a new comment
function postComment() {
	if (verification_needed) {
		//alert("Verification needed!");
	}
	var vid = $('gccomment_area').readAttribute('prodId');
	var area = $('gccomment_area').readAttribute('area');
	// TODO: fix this using $F.
	var comText = $('gccomment_textarea').value;
	var pars = {'vid': vid, 'comment': comText, 'area': area};
	new Ajax.Request('./inc/ajax_comments_request.php', { 
	    method: 'post',
	    requestHeaders: {Accept: 'application/json'},
	    parameters: pars,
	    onSuccess: handleGetResponse,
	    onFailure: handleGetResponseError,
	    onCreate: function() {
 			if($('inProgress')) {
 				$('inProgress').style.display = 'inline';
 			}
		}
		});
}

function sendSpamNotification(cid) {
	var pars = {'cid': cid};
	new Ajax.Request('./inc/ajax_comments_request.php', { 
	    method: 'post',
	    requestHeaders: {Accept: 'application/json'},
	    parameters: pars
		});
}



/*
 * CALLED INSIDE THE SCRIPT
 */
function getComments(sp) {
	
	//console.log("GetComments");
	sp = typeof(sp) != 'undefined' ? sp : 1; // Default as 1
	var vid = $('gccomment_area').readAttribute('prodId');
	var area = $('gccomment_area').readAttribute('area');
	var pars = {vid: vid, sp: sp, 'area': area};

	new Ajax.Request('./inc/ajax_comments_request.php',
	  {
	    method: 'get',
	    parameters: pars,
	    onSuccess: handleGetResponse,
	    onFailure: handleGetResponseError
	  });
}

function handleGetResponse(transport) {
	
	$('inProgress').style.display = 'none';
	
	//console.log("Successful comment response");
	var json = transport.responseText.evalJSON();
	clearNodes($('gccomment_area'));
	var elements = json.comment_list.comments.length; 
	var numOfPages = json.comment_list.total_pages;	
	if (elements != 0) { 		// Some comments available
		if (numOfPages != 1) {	// More than one pagefull of comments
			
			//console.log("More than one page of comments");
			printCommentsTitle(json);
			printForm(json);
			printCommentsControl(json);
			printComments(json);
			printCommentsControl(json);
			
		}
		else {					// Only one page -> don't print headers
			//console.log("Only one page of comments");
			
			printCommentsTitle(json);
			printForm(json);
			printComments(json);	
			
		}
	}
	else {
		printNoCommentsTitle(json);
		printForm(json);	
			// No comments available -> print only textarea
	}
}

function clearNodes(obj) {
	// so long as obj has children, remove them
	while(obj.firstChild) obj.removeChild(obj.firstChild);
}

function handleGetResponseError(transport) {
	alert('Something went wrong...');
}

function printCommentsTitle(json) {
	/*
	var comTitle = json.comment_list.comments_txt;
	var comDiv = new Element("div", {'class': 'gccomment_comment_text'});
	comDiv.appendChild(document.createTextNode(comTitle));
	$('gccomment_area').appendChild(comDiv);
	*/
}

function printNoCommentsTitle(json) {
	$('gccomment_area').insert(new Element("div", {
		"id" : "no_comments_div"
	}).update(json.comment_list.no_comments_txt))
}

function printCommentsControl(json) {
	var currPage = json.comment_list.current_page;
	var totalPages = json.comment_list.total_pages;
	
	var elemArr = Array(
		"Page: " + currPage + "/" + totalPages
		, 
		currPage == 1 ? json.comment_list.newest_title : 
		new Element('a', {'href': "javascript:void(0)",
						'onclick': "return false;",
		    			'sp': 1
		    		}).update(json.comment_list.newest_title)
		, 
		currPage == 1 ? json.comment_list.previous_title : 
		new Element('a', {'href': "javascript:void(0)",
						'onclick': "return false;",
	    			    'sp': (parseInt(currPage) - 1)
	    		}).update(json.comment_list.previous_title)
		,
		currPage == totalPages ? json.comment_list.next_title : 
		new Element('a', {'onclick': "return false;",
			'href': "javascript:void(0)",						
	    			    'sp': (parseInt(currPage) + 1)
	    		}).update(json.comment_list.next_title)
	    , 
	    currPage == totalPages ? json.comment_list.oldest_title : 
		new Element('a', {'href': "javascript:void(0)",
						'onclick': "return false;",
	    			    'sp': (parseInt(totalPages))
	    		}).update(json.comment_list.oldest_title)
	);
	
	// Creating the header element
	var headerDiv = new Element("div", {'class': 'gccomment_header',
		'id': 'gccomment_header'
		}); 	
		
	
	elemArr.each(function(s) { 
		headerDiv.insert(new Element("div", {
			"class" : "header_item"
		}).insert(s));
	})

	//headerDiv.insert(s);
	
	
	//headerDiv.insert(headerTable);
	
		
		
		
		
		// headerDiv.insert(s);

		
	$('gccomment_area').insert(headerDiv);
}

function printComments(json) {
	var gccomment_area = $('gccomment_area');


	spamStr = json.comment_list.spam_txt;
	
	gccomment_area.insert(new Element('div', {
			"class": "clear"
	}));
	
	for (var i = 0; i < json.comment_list.comments.length; i++) {
		/*
		// DIV for the title
		var titleDiv = new Element('div', {'class': 'gccomment_title',
										   'id'   : 'gccomment_title'
		});
		*/
		// username (time ago), username as a link to public profile
		var linkTemplate = new Template(
			'#{title} | ' + // Seconds ago
			'<a target="_blank" href="index.php?page=user&action=' +
			'#{commentor}">#{commentor}</a> | ' + // Commentor and link to profile
			'<a href="javascript:void(0)"  ' + // Spam link
			'cid="#{cid}" id="gccomment_spam">' + spamStr + '</a> ' 
			
			);
		
		/*	
		titleDiv.update(linkTemplate.evaluate({
			commentor: json.comment_list.comments[i].commentor,
			title: json.comment_list.comments[i].title,
			cid: json.comment_list.comments[i].cid
			}));
			*/
		//gccomment_area.insert(titleDiv);
		
		// COMMENT TEXT
		if (json.comment_list.comments[i].type != "") {
			var one_comment = new Element('div', {
			"class": "celeb_comment"
			});
			
			one_comment.insert(new Element('img', {
			"src": "img/neutral/gc_star_comment_celeb.gif",
			"class": "comment_star"
			}));	
		}
		else {
			var one_comment = new Element('div', {
			
			});
			
			one_comment.insert(new Element('img', {
				"src": "img/neutral/trans-gc_star_black_small.png",
				"class": "comment_star"
			}));
		}
		
		
		/*
		one_comment.insert(new Element('img', {
			"src": "img/neutral/gc_star_black_small.gif",
			"class": "comment_star"
			
		}));
		*/
		
		
		
		one_comment.insert(new Element('span', {
			"class": "comment_text"
			}).update(json.comment_list.comments[i].text));
		
	
		one_comment.insert(new Element('div', {
			"class": "signature"
		}).update(linkTemplate.evaluate({
			commentor: json.comment_list.comments[i].commentor,
			title: json.comment_list.comments[i].title,
			cid: json.comment_list.comments[i].cid
			})));
			
		gccomment_area.insert(one_comment);
	}
}

function printForm(json) {
	orTitle = json.comment_list.or_title;
	ifTitle = json.comment_list.if_title
	regTitle = json.comment_list.reg_title;
	loginTitle = json.comment_list.login_title;
	postBtnTitle = json.comment_list.post_button_title;
	commentQuestion = json.comment_list.comment_question_txt;
	spamStr = json.comment_list.spam_txt;
	spamSentStr = json.comment_list.spam_sent_txt;
	userID = json.comment_list.userID;
	chars_per_comment = "" != json.comment_list.max_chars_per_comment ? 
		json.comment_list.max_chars_per_comment : 250; // If empty, default as 250
	
	verification_needed = 'undefined' != typeof(json.comment_list.verification_needed) ?
		json.comment_list.verification_needed : true;

	var comArea = $('gccomment_area');
		
	//alert("User ID: " + userID);
	if (userID == 'GUEST') {
		// Register of login if you're already a member
		
		loginPar = new Element("p");
		
		
		loginPar.insert(commentQuestion + "<br><br>");
		
		loginPar.insert(new Element('a', {	
			'href': 'index.php?page=registration&action=registration'
			}).update(regTitle));
		loginPar.insert("&nbsp;" + orTitle + "&nbsp;");
		loginPar.insert(new Element('a', {
			'href': 'index.php?page=login'
			}).update(loginTitle));
		loginPar.insert("&nbsp;" + ifTitle);
		comArea.insert(loginPar);
	}
	
	else {
		var formDiv = new Element('div', {
			"id" : "gccomment_form_div",
			"class" : "float_right"	
		});
				
		// Char Counter
		formDiv.insert(new Element('input', {
			"id" : "counter-gccomment_textarea",
			"class": "gccomment_counter",
			"type": "text",
			"value": "300",
			"readonly": "true"
			}));	
					
   		formDiv.insert(" " + json.comment_list.counter_title);
			
		// Form	
		var form = new Element('form', {
			id: 'gccomment_form',
            method: "post" 
        });        
        form.insert(new Element('textarea', {
			'id': 'gccomment_textarea',
			'rows': 5,
			'name': 'comment' 
		}));		
		form.insert(new Element('input', {
			'type': 'button',
			'id': 'gccomment_submit_btn',
			'class': "button",
			'value': postBtnTitle
		}));
		
		// Clear DIV
		var clear = new Element('div', {
			"class" : "clear"
		});
		
        formDiv.insert(form);
        formDiv.insert(clear);
		comArea.insert(formDiv);

		// Calling the char count method		
		makeItCount('gccomment_textarea',chars_per_comment);
		
	}
}


// Functions charCounter and makeItCount are
// part of the script released by (under MIT):
// http://blog.ninedays.org/2008/01/17/limit-characters-in-a-textarea-with-prototype/
function charCounter(id, maxlimit, limited){
	if($F(id).length >= maxlimit){
		if(limited){	$(id).value = $F(id).substring(0, maxlimit); }
		$('counter-'+id).addClassName('charcount-limit');
		$('counter-'+id).removeClassName('charcount-safe');
	} else {	
		$('counter-'+id).removeClassName('charcount-limit');
		$('counter-'+id).addClassName('charcount-safe');
	}
	$('counter-'+id).value =  $F(id).length + '/' + maxlimit ;	
}

function makeItCount(id, maxsize, limited){
	if(limited == null) limited = true;
	if ($(id)){
		Event.observe($(id), 'keyup', function(){charCounter(id, maxsize, limited);}, false);
		Event.observe($(id), 'keydown', function(){charCounter(id, maxsize, limited);}, false);
		charCounter(id,maxsize,limited);
	}
}
