var commentActive = "";

/*
* open box to post bottom the product in the list
*/
function comment_open(obj,nro, imageProductUrl) {
	// image to send to FB
	$('#imageProductUrl').val(siteComments+imageProductUrl);
	
	// hide comment to box
	$('#CommentBox').hide();
	
	// if box to comment is the same close it
	// else open box to comment in new position	
	if(commentActive == obj.id){
		commentActive = "";
		comment_reset();
	}else{
		comment_reset();
		$(obj).parent().append($('#CommentBox'));
		if(nro == 1)
			$('#CommentBox').attr('style', 'margin-left:0px;');
		else if(nro == 5)
			$('#CommentBox').attr('style', 'margin-left:-180px;');
		else
			$('#CommentBox').attr('style', 'margin-left:-90px;');
		$('#CommentBox').show();
		commentActive = obj.id;
	}
}

/*
* open box in the bottom page
*/
function comment_open_global(obj) {

	// if global comment set default image	
	if(obj.id.split("_")[0] == "home")
		$('#imageProductUrl').val('http://www.sendstar.com.uy/images/sendstar.com.uy-logo.png');
	
	// if box to comment is the same close it
	// else open box to comment in new position	
	if(commentActive == obj.id){
		commentActive = "";
		$('#CommentBox').hide();
		comment_reset();
	}else{
		comment_reset();
		if ($('#CommentList').css("display") != "none") {
			hideCommentList();
		}
		$('#CommentBox').hide();
		$('.list_message_actions').append($('#CommentBox'));
	
		$('#CommentBox').show();
		commentActive = obj.id;
	}
}

function removeHtmlCode(text) { 
	// DO NOT USE REPLACE JS FUNCTION -- HAS BUGS. split/join works like a replace. except that replace doesn't work and split/join does.
	text = text.split("&").join("&amp;"); // change & for &amp; to avoid exploits
	text = text.split("<").join("&lt;"); // same for < 
	text = text.split(">").join("&gt;"); // same for >
	return(text); // Returns the parsed text.
}

function gotfocus (target) {
	if (target.initValue == undefined) {
		target.initValue = target.value;
	}
	if (target.initValue == target.value){
		target.value = "";
	}
	className = target.className;
	className = className.split("blur");
	if (className.length == 1) {
		className += " focus";
	}else {
		className = className.join("focus");
	}
	target.className = className;
}

// depreacted
function gotblur (target) {
	if (target.value == "") {
		target.value = target.initValue;
	}
	className = target.className;
	className = className.split("focus");
	if (className.length == 1) {
		className += " blur";
	}else {
		className = className.join("blur");
	}
	target.className = className;
}

// depreacted
function autogrow (e) {
	gotfocus(e);
}

// depreacted
function SetNewSize(textarea){
	
	elem = document.getElementById('comments_input_pre');
	elem.innerHTML = removeHtmlCode(textarea.value);
	elem.innerHTML = elem.innerHTML.split("\n").join("<br />");
	if (elem.innerHTML.charAt(elem.innerHTML.length-1) == ">") { // added for carriage return add 1 char even if it's empty.
		elem.innerHTML += " ";
	}
	_height = Math.max(1, elem.offsetHeight);
	proc = document.getElementById('ProcessingBox');
	InputBox = document.getElementById('InputBox');
	textarea.style.height = _height + 'px' ;
	proc.style.padding = InputBox.offsetHeight /2 -6 + 'px 0px';
	if (textarea.value != "" && textarea.value != textarea.initValue) {
		document.getElementById('leave_comment').disabled=false;
	} else {
		document.getElementById('leave_comment').disabled=true;
		
	}
}

/*
* set everything to default
*/
function comment_reset () {

	$('#ShareBox').hide();
	$('#MessageBox').hide();
	$('#ProcessingBox').hide();
	$('.standard_actions').hide();
	$('#InputBox').show();
	$('#user_input').val(langJSComment['writeComment']);
	$('#user_input').css({height:14});
	commentActive = ""
}

/*
* then post, open the box to login 
*/
function comment_get_user_data() {
	// This is only a placeholder for the AJAX function to call for (if user logged in) and save comment in case is already authenticated.
	// when it's done, it should show one or the other outputs :
	//		SHARE for non-authenticated users,
	//		MESSAGE DISPLAY for already authenticated users.
	if ( jQuery.trim($("#user_input").val()) != "" ){	
		var heightProcessing = $('#user_input').css('height').replace('px', '') ;
		$('#ProcessingBox').css('padding', (parseInt(heightProcessing)+25)/2 +'px 0px');
		$('#ProcessingBox').show();
		$('#InputBox').hide();
		
		// if is logged in site, automatic post
		if(userSiteLogin){
			enterComment (3);
			return false;
		}
		
		// when chose dont see the name, show this msg in next steps
		if($('#user_guest').is(':checked'))
			$('.info').show();
			
		comment_get_user_data_callback();
	}
}

/*
* callback after log the user (processing box)
*/
function comment_get_user_data_callback() {
	$('#ProcessingBox').hide();
	authenticated = false;//true ; // FOR DEVELOPING PURPOSES ONLY
	
	if (authenticated) {
		// SAVE COMMENT AND DISPLAY MESSAGE.
		$('.CommentBox').hide();
		$('.message').fadeIn();
	} else {
		$('#ProcessingBox').hide();
		$('#ShareBox').fadeIn();
		
		// ASK USER TO AUTHENTICATE OR CREATE A NEW USER.
	}
}

/*
* cancel button of box to post
*/
function comment_cancel () {
	comment_reset();
	$('#CommentBox').hide();
}

/*
* navigation on the tabs
*/
function TabSelect (target) {
	$('#fieldset_info').hide();
	$('#fieldset_user_guest').hide();
	$('#fieldset_user_sendstar').hide();
	$('#fieldset_user_facebook').hide();
	
	// show or hide if name is visible or not
	if (target == "#fieldset_user_facebook" || !$('#user_guest').is(':checked') ){
		$('.info').hide();	
	}else{
		$('.info').show();
	}
	
	// clear errors
	 clearErros ()
	
	// show target
	$(target).show();
}

/*
* validate emails
*/
function validateEmailComments(elementValue){  
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    return emailPattern.test(elementValue);  
}

/*
* hide all msg of errors
*/
function clearErros () {
	$(".errorEmail").hide();
	$(".error").hide();
	$(".errorEmpty").hide();
}


/*
* save comment in the database
*
* mode = 0 User invite
* mode = 1 User sendstar
* mode = 2 User facebook
* mode = 3 User sendstar login
* mode = 4 User facebook login
*/
function enterComment (mode) {
	
	commentID			= commentActive;
	message 			= $('#user_input').val();
	userName 			= jQuery.trim($('#name').val());
	userEmail 			= jQuery.trim($('#user_email').val());
	userEmailResgitered = $('#user_email_registered').val();
	password			= $('#passwordComment').val();
	nameVisible			= ($('#user_guest').attr('checked')) ? 0 : 1;
	
	// if mode invite and dont put data show a error
	if(mode == 0 && (userName == "" || userEmail == "") && mode != 2){
		$(".errorEmpty").show();
		return false;
	}
		
	// validate email if is a invite or sendstar user
	if((mode == 0 && !validateEmailComments(userEmail)) || (mode == 1 && !validateEmailComments(userEmailResgitered))){
		$(".errorEmail").show();
		return false;
	}else{
		$(".errorEmail").hide();
	}
	 
	
	// if user inite or user sendstar or user sendstar logged yet
	if(mode == 0 || mode == 1 || mode == 3){
		$.ajax({ 
			async: true,
			type: "POST",     
			dataType: "html",
			url:  "ajax/comments/postComment.asp",
			data: ({
				mode				: mode,
				commentID			: commentID,
				message				: message,
				userName			: userName,
				nameVisible			: nameVisible,
				userEmail			: userEmail,
				userEmailResgitered	: userEmailResgitered,
				password			: password,
				userSiteLogin		: userSiteLogin
			}),	
			beforeSend: function(objeto){ 
				$('#CommentList').html("<p>"+langJSComment['loading']+"...</p>");  
			},         
			success: function(html){ 
				// user sendstar invalid
				if(html.search("userInvalid") != -1)
					$(".error").show();
				else{
					$('#ShareBox').hide();
					$('#ProcessingBox').hide();
					$('#MessageBox').fadeIn();
					$('#MessageBox').html(html);
					
					//if user sendstar set logged true in JS while dont refresh the page
					if(mode == 1){
						userSiteLogin = true;
					}
				} 
				
			}, 
			error: function(html){ 
				// if there are some error when saving show a error.
				$('#CommentList').html("<p>"+langJSComment['notCouldSave']+"</p>");
			} 
		});		
	}else if (mode == 2 ){ 
		
		// facebook mode
		
		$.ajax({ 
			async: true,
			type: "POST",     
			dataType: "html",
			url:  "ajax/comments/postComment.asp",
			data: ({
				mode				: mode,
				commentID			: commentID,
				message				: message,
				userName			: $('#facebook_name').val(),
				userLastName		: $('#facebook_lastname').val(),
				nameVisible			: 1,
				userEmail			: $('#facebook_email').val(),
				facebookId			: $('#facebook_id').val()
			}),	
			beforeSend: function(objeto){ 
				// loading msg
				$('#CommentList').html("<p>"+langJSComment['loading']+"...</p>");  
			},         
			success: function(html){ 
					// publish in wall of FB and next show message in sendstar
					publishWall();
					$('#ShareBox').hide();
					$('#MessageBox').fadeIn();
					$('#MessageBox').html(html);
			}, 
			error: function(html){ 
				// if there are some error when saving show a error.
				$('#CommentList').html("<p>"+langJSComment['notCouldSave']+"</p>");
			} 
		});	
	}
}


var offset = 3; // offset of comments to show
var firstCommentShow = 0; // number of first comment load
var nextRequest = true; // control to many click in pagintation
/*
* pagination of comment of bottom page
*/
function pagination (move) {
	// if can be a nextrequest call a function
	if(nextRequest){
		// set temporary control 
		nextRequest = false;
	
		var prevButtonOff = '<span class="off">&lt; '+langJSComment['previous']+'</span>';
		var nextButtonOff = '<span class="off">'+langJSComment['next']+' &gt;</span>';
		//depreacted
		/*$(".list_message_pagination").html(prevButtonOff + nextButtonOff);*/
	
		// next increment variables
		// prev decrease variables until 0	
		if(move == 'next'){
			offset += 1;
			firstCommentShow += 1;
		}else{
			if ((firstCommentShow-1) < 0) { return false;}
			offset = Math.max(offset-1, 3);
			firstCommentShow = Math.max(firstCommentShow-1, 0);
		}
		
		// object to know the left margin
		var $lefty = $("#CommentProductListIn");

		// offset is more than 3 and the number of first comment to show plus
		// 3 is diferen the max of comments
		if(offset > 3 && !(firstCommentShow+3 == countComments)){
		
			$.ajax({ 
				async: false,
				type: "POST",     
				dataType: "html",
				url:  "ajax/comments/displayCommentsPagination.asp",
				data: ({
					move	: move,
					offset	: offset,
					prod_id	: prod_id
				}),	
				success: function(html){
					// next append in the last of list
					// prev append in the fisrt of list
					if(move=='next') { 
						$("#CommentProductListIn").append(html);
					} else {
						$("#CommentProductListIn").prepend(html);
					}
				
				}
			});	
		}

		if (move == 'next') {
			// if is the last add a empty box in the last
			if( (firstCommentShow+3 == countComments)){
				$("#CommentProductListIn").append(
					'<div id="commentsCont_'+(countComments+1)+'" class="list_message"></div>'
					)
			}
		
			// remove the fisrt comment box
			$("#commentsCont_"+(firstCommentShow-1)).remove();
			// set the margin of container box to 0px
			$("#CommentProductListIn").attr('style', 'left:0px');

			// move animate the boxes from rigth to left
		 	$lefty.animate({
	 			 left: parseInt($lefty.css('left'),10) -333
			});
		} else {
			// if is the first add a empty box in the first
			if (firstCommentShow == 0) {
				$("#CommentProductListIn").prepend(
					'<div id="commentsCont_0" class="list_message"></div>'
					)
			}
			
			// set the margin of container box twice with to left
			$("#CommentProductListIn").attr('style', 'left:-666px');
		
			// move animated the boxes from left to rigth
		 	$lefty.animate({
	 			left: parseInt($lefty.css('left'),10) +333
			});
			
			// if not is the last comment remove the last box to show
			if (firstCommentShow+3 < countComments) {
				$("#commentsCont_"+(firstCommentShow+5)).remove();
			}
		}
		
		// set button with actions
		var prevButton = '<a href="javascript:pagination(\'prev\');">&lt; '+langJSComment['previous']+'</a>';
		var nextButton = '<a href="javascript:pagination(\'next\');">'+langJSComment['next']+' &gt;</a>';
	
		// set prev button off if is the first
		if( firstCommentShow == 0){
			prevButton = prevButtonOff;
		}
		// set next button off if is the last
		if( (firstCommentShow+3 == countComments)){
			nextButton = nextButtonOff;
		}
 		
		// print the navitagion buttons
		$(".list_message_pagination").html(prevButton + nextButton);
		
		// enable next clicks
		nextRequest = true;
	}
}

/*
* vote a comment
*/
function voteComments (idComment) {
	$.ajax({ 
		async: false,
		type: "POST",     
		dataType: "html",
		url:  "ajax/comments/voteComment.asp",
		data: ({
			idComment	: idComment
		}),	
		success: function(html){ 
			//$("#voteComment_"+idComment).hide(function(){$("#commentVotedImg_"+idComment).show()});
			$("#voteComment_"+idComment).children().attr("src","images/core/comments/comments_icon_liked_16x16.png");
			$("#voteComment_"+idComment).attr("onclick","return false");
			$("#voteComment_"+idComment).attr("href","#");
			$("#voteComment_"+idComment).attr("style","cursor:default;");
			
		}
	});		
}

$(document).ready(function() {
	
	// resize of textarea when write the comment
	$("#user_input").autoResize({
	    onResize : function() {
	        $(this).css({opacity:0.8});
	    },
	    animateCallback : function() {
	        $(this).css({opacity:1});
	    },
	    animateDuration : 300,
	    extraSpace : 0
	});
	
	// declare pause function //depreacted
	$.fn.pause = function(duration) {
	    $(this).animate({ dummy: 1 }, duration);
	    return this;
	};

	
	$("#share_menu li").mouseup(function(event){
		$("#share_menu li").removeClass('selected');
		$(this).addClass('selected');
	});
	
	var hideCommentID 		= "";
	var displayID 			= "";
	var currentId 			= "";
	
	// begin tooltips
	$("button[id*='comment_']").mouseover(function(){
		
		if  ( $(this).hasClass("empty") ) {
			return false
		}
		// clear previous interval
		clearTimeout(hideCommentID);
		
		if( commentActive != $(this).attr('id') && ( currentId != $(this).attr('id') || !$('#CommentList').is(":visible") ) ){
			// mouse over
			// show the comments
			
			position = $(this).position();
			var cssObj = {
				'left' : position.left + 20,
				'top' : position.top + 25
			}
			$('#CommentList').css(cssObj);
			$('#CommentList').show();
		
			currentId = $(this).attr('id');
			
			$.ajax({ 
					async: true,
					type: "POST",     
					dataType: "html",
					url:  "ajax/comments/displayCommentsPreview.asp",
					data: "prod_id=" + currentId,
					beforeSend: function(objeto){ 
						$('#CommentList').html("<p>"+langJSComment['loading']+"...</p>");  
					},         
					success: function(html){ 
						$("#CommentList").html(html);
					}, 
					error: function(html){ 
						$('#CommentList').html("<p>"+langJSComment['notGetComment']+"</p>");
					} 
				});	
		}			
	})
	
	$("button[id*='comment_']").mouseleave(function(){
		// mouse <del>out</del><ins>leave</ins>
		// hide the comments
		
		// clear previous interval
		clearTimeout(hideCommentID);
		
		// set the new interval
		hideCommentID = setTimeout(function(){
			currentId = ""; //restart currentId
			$('#CommentList').fadeOut();
		}, 2000);
	})
	
	$("#CommentList").mouseover(function(){
		// mouse over
		// clear the interval
		
		// clear the interval on mouseover
		clearTimeout(hideCommentID);
	})
	
	$("#CommentList").mouseleave(function(){
		// mouse out
		// hide the comments
		
		hideCommentID = setTimeout(function(){
				currentId = ""; 	//restart currentId
				$('#CommentList').fadeOut();
		}, 2000);
	})
	$('#CommentList').click(function(event) {
		event.stopPropagation();
	})
	$('#CommentBox').click(function(event) {
		event.stopPropagation();
	})
	$(document).click(function(event) { 
			currentId = ""; 	//restart currentId
			if ($('#CommentList').is(':visible')){
				$('#CommentList').fadeOut('fast');
			} else if ( (event.target.href == undefined && event.target.href == null) && (event.target.onlick == undefined && event.target.onclick == null) ){
				if ($('#InputBox').is(':visible')) {
				comment_cancel();
				}
			}
	});	
	// end tooltips	
})


