/*
 * Interact.js
 * Common interactive functions
 */


/*
 * rateItem
 * @returns - string "success" of "fail" outcome after subitting the vote
 * Checks for existing cookie and that the user is logged in before progressing
 *
 * @params:
 * rating - the actual rating value
 * assocTypeId - association type (basket, story, image etc)
 * assocId - the associationId of the thing we are rating (basketId, storyId, yourSayId)
 * skipLogin -
 *		Only passed in when the callback function is happy they are logged in.
 *		will mean we don't check they are logged in twice
 * @globalparam: ysCookieName
 */
function rateItem(rating, assocTypeId, assocId, skipLogin) {

	//**************************************************************
	// KNOWN ISSUE WITH LOGIN RATINGS
	// if they are NOT logged in when they first vote, the popup
	// login form opens and all works fine, but the initial call to
	// rate has returned a fail (from the if (!userLoggedIn) check).
	// you don't have to be logged in for ratings on anything yet
	// so have left this for now.
	//***************************************************************

	if (typeof(window.loginRatings) !== "boolean") window.loginRatings = true;
	checkLogin = window.loginRatings;

	if (checkLogin) {
		// true
		if (!skipLogin || skipLogin!=true) {

			// check if they are logged in
			var userLoggedIn = $.isUserLoggedIn( function() {
				// on successful login, call this function again skipping the login procedure
				rateItem(rating, assocTypeId, assocId, true);
			});
			if( !userLoggedIn ) {
				return "fail";
			}

		}
		theURL = "/rate/" + rating + "/" + getCookie(ysCookieName) + "/" + assocTypeId + "/" + assocId + "/";
	} else {
		if (getCookie(ysCookieName)) {
			// pass in user id if we have it
			theURL = "/rate/" + rating + "/" + getCookie(ysCookieName) + "/" + assocTypeId + "/" + assocId + "/";
		} else {
			// false - don't pass in the userId
			theURL = "/rate/site/" + rating + "/" + siteId + "/" + assocTypeId + "/" + assocId + "/";
		}
	}

	allowRating = 1;
	cookieData = "";
	outcome = "Sorry. There was a problem casting your vote. Please try again";

	// see if we have an existing cookie for this association type.
	if (getCookie("rating_" + assocTypeId)) {

		// we've got the cookie - check if assocId is already in there - if it is, they have already votes
		cookieData = getCookie("rating_" + assocTypeId);
		if (cookieData && checkPreviousRating(cookieData, assocId) == 1) {
			allowRating = 0;
			outcome = "We already have your vote. Thanks";
		}

	}

	if (allowRating == 1) {

		$.ajax({
			type: "GET",
			url: theURL,
			dataType: "html",
			complete: function(response) {
				var data = response.responseText;
				if (data.match("success")) {
					// prepend the new vote to the cookie value
					cookieValue = assocId + ":" +rating + "#" + cookieData;
					setCookie("rating_" + assocTypeId, cookieValue, 365);
					outcome = "success";
				} else if (data.match("already voted")) {
					var dataVars = data.split(":");
					// prepend the vote to the cookie value again...
					var rId = dataVars[1];
					cookieValue = assocId + ":" + rId + "#" + cookieData;
					setCookie("rating_" + assocTypeId, cookieValue, 365);
					outcome = "already voted:"+rId;
				} else if (data.match("fail")) {
					outcome = "Sorry. There was a problem casting your vote";
				}
			},
			async:false
		});

	}
	return outcome;

}

/*
 * checkPreviousRating
 * @returns - the rating value of the assocId if found
 * @params:
 * cookieData - the string value of the cookie
 * assocId - the associationId of the thing we are rating
 *
 */
function checkPreviousRating(cookieData, assocId) {

	ratedValue = null;
	if (cookieData && assocId) {
		// split the cookie data out - string should be "assocId:rating#assocId:rating#" etc
		prevRatingsArr = cookieData.split('#');
		// loop through each value pair until we match ours
		for(var i=0; i < prevRatingsArr.length; i++) {
			ratedItemArr = prevRatingsArr[i].split(":");
			ratedItem = ratedItemArr[0];
			if (ratedItem == assocId) {
				// we've found one - there for they have already voted
				ratedValue = ratedItemArr[1];
				break;
			}
		}
	}
	return ratedValue;
}


/*
 * renderRatings
 * @params:
 *	ratings
 *	allowedOpts - optional. expects an array of rate types you want to display
 *				- e.g. "Stonker","Stinker" will mean "Maybe" is ignored
 */
function renderRatings(ratings, allowedOpts, showTxt) {

	rateHtml = "";
	// loop through each rating option
	$.each(ratings, function(r,rate){

		if (rate.type) {
			canProgress = 0;
			// allowedOpts is passed in, then check that this rate.type is allowed
			if (!allowedOpts) {
				canProgress = 1;
			} else if ($.inArray(rate.type, allowedOpts) > -1) {
				canProgress = 1;
			}

			if (canProgress == 1) {
				rateHtml += '<li>';
					aClass = "";
					//  check if they have already voted on this ysc
					if (prevRate != null) {
						// already voted on this ysc
						if (rate.type.toLowerCase() == 'recommend') {
							// disable if voted (recommend is only option)
							aClass = 'disabled'; // grey out the ones they didn't vote for
						} else if (prevRate == r) {
							aClass = ''; // this is the one they voted for
						} else {
							aClass = 'disabled'; // grey out the ones they didn't vote for
						}
						aTitle = 'Thanks! We already have your vote';
					} else {
						// allow vote
						aClass = 'enabled';
						aTitle = 'Vote Now!';
					}
					rateHtml += '<a onclick="return false;" href="#" ratingId="' + r + '" title="'+ aTitle +'" class="'+rate.type.toLowerCase()+' '+ aClass + ' tooltip">';
					if (showTxt && showTxt == true) rateHtml += rate.type;
					rateHtml += ' (<span>' + rate.total + '</span>)' + '</a>';
				rateHtml += '</li>';
			}
		}
	});
	return rateHtml;

}

/*
 * loadComments
 * This should be totally  generic / reuseable by anything
 * @globalParams: expect to be declared on the page
 *    var assocType - associationTypeId (basket, story etc)
 *    var assocId - assocationId (basketId, storyId etc)
 *    var siteUserId
 *    var numPerPage - how many comments per page
 *    var ignoreYscId - if set we will have shown a featured comment - so ignore it
 *
 * @params:
 *   ysListType - either byAssoc, byUser or byYscId - will determine which API we call
 *   pageNo - (will be yscId if ysListType = byYscId)
 *   outDivId - the div to populate with comments
 *   renderFunc - the function name for rendering each ysc.
 *   dispRatings - true/false will be passed into both
 */
function loadComments(ysListType, pageNo, outDivId, renderFnc, showReplies, hbxCall, ignoreYscId) {

	// check our function is actually a function and we have outDivId / pageNo
	if (typeof(window[renderFnc]) === "function" && outDivId && pageNo) {

		$('#'+outDivId).html('<img src="/shared/images/loading-wheel.gif" alt="Loading" class="loading-wheel" />');

		if (typeof(ignoreYscId) == "undefined") {
			ignoreYscId = -1;
		}

		// do we fetch it with or without replies?
		if (typeof(showReplies) == "undefined" || typeof(showReplies) != "boolean" || showReplies == false) {
			showReplies = 0;
		} else {
			showReplies = 1;
		}

		if (ysListType == "byUser" && siteUserId) {
			jsonUrl = "/yoursay/commentList/byUser/"+pageNo+"/"+numPerPage+"/"+siteUserId+"/"+showReplies;
		} else if (ysListType=="byAssoc" && ysAssocType && ysAssocId) {
			jsonUrl = "/yoursay/commentList/byAssoc/"+pageNo+"/"+numPerPage+"/"+ysAssocId+"/"+ ysAssocType+"/"+showReplies;
		} else if (ysListType=="byYscId" && pageNo) {
			// see comment above. pageNo = yscId
			jsonUrl = "/yoursay/commentList/byYsc/"+pageNo+"/"+showReplies;
		}

		if (!jsonUrl) {
			return;
		} else {

			$.getJSON(jsonUrl, function(data) {

				$('#'+outDivId).html(""); // clear out the loading animation

				if (data.count == 0) {
					if (pageNo == 1) {
						// first page - but no comments
						$('#'+outDivId).html("<p>Be the first to post a comment on this story!</p>");
					} else {
						// used pagination links, no more comments to display
						$('#'+outDivId).html("Sorry! We don't have any more comments to display.");
					}

					//HB: hack for PF1 until we sort out SHAKIRA count
					// hide the next link if we didn't find any comments, no point showing it
					if (typeof(siteId) != "undefined") {
						$(".base-pagination li").find('a[pn='+(pageNo+1)+']').hide();
					}


				} else {

					// 9 = ys comment association
					ratingAssocId = 9;

					// see if we have a cookie containing previous ratings
					prevRatingData = (getCookie('rating_'+ratingAssocId)) ? getCookie('rating_'+ratingAssocId) : "";

					// loop through each "ysc" and render
					$.each(data.ysc, function(i,ysc){
						if (ysc.id != ignoreYscId) {
							$('#'+outDivId).append( window[renderFnc](ysc, showReplies) );
						}
					})

					// Now Activate Ratings
					$('#'+outDivId +' ul li a.enabled').click(function() {

						rValue = $(this).attr('ratingId');
						yscId = $(this).closest('ul').attr('yscId');
						rOutcome = rateItem(rValue, ratingAssocId, yscId);
						if (rOutcome == "success") {

							// disabled all links for this ysc
							$(this).closest('ul').find('li a').
								attr('title','We already have your vote. Thanks').
								removeClass('enabled').
								addClass('disabled').
								unbind('click');

							// remove disabled from this specific link (so it's not grey anymore)
							$(this).removeClass('disabled').attr('title','We already have your vote. Thanks');

							// increment the number of votes
							$(this).find('span').text( parseInt($(this).find('span').text()) + 1 );

						} else if (rOutcome.match("already voted")) {

							// they've already voted - disabled all links for this ysc
							$(this).closest('ul').find('li a').
								attr('title','We already have your vote. Thanks').
								removeClass('enabled').
								addClass('disabled').
								unbind('click');

							var outcomeVars = rOutcome.split(":");
							var rId = outcomeVars[1];
							// remove disabled from previously voted link (so it's not grey anymore)
							$(this).closest('ul').find('li a[ratingId=\''+rId+'\']').removeClass('disabled');

						} else {

							// something went wrong - let them know
							$(this).closest("ul").find("li a").attr('title',rOutcome);

						}
						return false;

					})

					// Activate reply to links - load in the form on click
					if (typeof(window["renderCommentReplyForm"]) === "function") {

						$('#'+outDivId +' .comment-links a.comment-reply').toggle(
							function() {
								yscId = $(this).closest('div.comment').attr('yscId');
								if ( $(this).parents('div.comment').find('form.reply-form').length != 0 ) {
									// form has already been outputted - just show it
									$(this).parents('div.comment').find('form.reply-form').show('slow');
								} else {
									renderCommentReplyForm(yscId, $(this).parents('div.comment'), true, false);
								}
							},
							function() {
								$(this).parents('div.comment').find('form.reply-form').hide('normal');
							}
						).click(function() {
							return false;
						})

					}

					// call tooltip (if exists) to get the hoverovers working
					if (typeof(window["tooltip"]) === "function") {
						tooltip();
					}

					// HBX - if we want to log it, and the function exists
					if (hbxCall == true && typeof(window["_hbPageView"] === "function")) {
						myPN = hbx.pn + " - User Comments Page " + pageNo;
						myMLC= hbx.mlc + "/User Comments Page " + pageNo;
						//alert(myPN+ "\n" + myMLC);
						_hbPageView(myPN, myMLC);
					}

				} // end if count
			});

		} // end jsonUrl

	} else {
		// we don't know where to dump out the comments or how - don't try
	} // end outDivId
}

/*
 * renderCommentReplyForm
 * @params
 * yscId
 * theDiv - should be a handle on the div that we will be writing into e.g. $(this).parents('div.comment')
 * needsLogin - true/false determinds if we check for login or not - different resource called if false
 * skipLogin -
 *		Only passed in when the callback function is happy they are logged in.
 *		will mean we don't check they are logged in twice
 */
function renderCommentReplyForm(yscId, theDiv, needsLogin, skipLogin) {

	if (needsLogin) {
		// true
		if (!skipLogin || skipLogin!=true) {

			// check if they are logged in
			var userLoggedIn = $.isUserLoggedIn( function() {
				// on successful login, call this function again skipping the login procedure
				renderCommentReplyForm(yscId, theDiv, needsLogin, true);
			});
			if( !userLoggedIn ) {
				return "fail";
			}

		}

	}

	// append the form to the comment div
	replyForm = '<form class="reply-form" id="replyForm'+yscId+'" method="post" action="#" onSubmit="return false;">';
		//replyForm += '<div method="post" type="hidden">';
			replyForm += '<input value="'+yscId+'" name="assocId" type="hidden">';
			replyForm += '<input value="9" name="assocTypeId" type="hidden">';
			replyForm += '<textarea name="ysComment" class="comment-textarea" cols="46" rows="5">Write a comment...</textarea>';
			replyForm += '<div class="add-comment-btn">';
				replyForm += '<input value="Post Reply" style="margin-right: 10px;" align="left" type="submit">';
				replyForm += '<a href="#" class="close">Close</a>';
			replyForm += '</div>';
			replyForm += '<p class="comment-message"></p>';
		//replyForm += '</div>';
	replyForm += '</form><!--reply-form-->';

	$(theDiv).append(replyForm);


	$(theDiv).find('form').show('slow');
	$(theDiv).find('form').find('a.close').click(function() {
		$(this).parents('form').hide('slow');
		return false;
	});
	$(theDiv).find('form').find('textarea.comment-textarea').click(function() {
		clearBox(this);
	});
	$(theDiv).find('form').submit(function() {
		postYourSayComment($(this), true, false);
		return false;
	});


	//return replyForm;

}

function postYourSayComment(myForm, needsLogin, skipLogin) {

	// myForm should be a handle on the form

	// empty and hide the message box
	$(myForm).find(".comment-message").hide().html("");

	ysComment = $(myForm).find("textarea[name='ysComment']").val();
	errMsg = null;
	if (ysComment.match("Write a comment...") || ysComment == null) {
		errMsg = "Please write your comment";
	} else if (ysComment.length > 1900) {
		errMsg = "Your message is too long. You have entered "+ysComment.length+" characters, you are only allowed up to 1900";
	}

	if (errMsg) {
		$(myForm).find(".comment-message").html(errMsg).fadeIn(500).addClass("submitted error");
		return false;
	}

	if (needsLogin) {
		// true
		if (!skipLogin || skipLogin!=true) {

			// check if they are logged in
			var userLoggedIn = $.isUserLoggedIn( function() {
				// on successful login, call this function again skipping the login procedure
				postYourSayComment(myForm, needsLogin, true);
			});
			if( !userLoggedIn ) {
				return false;
			}

		}

	}

	theURL = '/yoursay/commentProcess';
	postData = {
			siteUserId:		getCookie(ysCookieName),
			assocTypeId:	$(myForm).find("input[name='assocTypeId']").val(),
			assocId:		$(myForm).find("input[name='assocId']").val(),
			ysComment:		$(myForm).find("textarea[name='ysComment']").val(),
			callingPage:	$(myForm).find("input[name='callingPage']").val()
	};
	$.ajax({
		type: 'POST',
		data: postData,
		dataType: 'json',
		url: theURL,
		success: function(data) {
			if (data.result == 'OK') {
				// SUCCESS!
				$(myForm).find(".comment-message")
					.html("<b>Thank You!</b>  Your comment has been submitted for approval.")
					.fadeIn(500, function() {
						$(this).fadeOut(5000);
						//$(this).hide("slide", { direction: "up" }, 5000)
					})
					.addClass("submitted")
					.removeClass("error");

				// reset and hide the form
				$(myForm).find("textarea[name='ysComment']").val("Write a comment...");
			} else {
				// FAIL
				$(myForm).find(".comment-message")
					.html("<b>Sorry!</b>  There seems to be a problem submitting your comment.  Please contact our Service Desk.")
					.fadeIn(500)
					.addClass("submitted error");
			}
		},
		async:false
	});

	return false;

}

var processed = false;
function submitQuiz(myForm, needsLogin, skipLogin) {

	if (needsLogin) {
		// true
		if (!skipLogin || skipLogin!=true) {

			// check if they are logged in
			var userLoggedIn = $.isUserLoggedIn( function() {
				// on successful login, call this function again skipping the login procedure
				submitQuiz(myForm, needsLogin, true);
			});
			if(!userLoggedIn) {
				return false;
			}
		}
	}

	var numQuestions = $(myForm).find("input[name='numQuestions']").val();
	var userOptions = new Array();
	var emptyQuestions = "";
	for (var i=0; i<numQuestions; i++) {
		// pass through questionId/optionId in array
		var questionId =  $(myForm).find("input[name='questionId_"+i+"']").val();
		var optionId =  $(myForm).find("input[name='quiz_opt_"+i+"']:checked").val();
		if (!optionId) {
			if (emptyQuestions.length > 0) {
				emptyQuestions += ", ";
			}
			emptyQuestions += i+1;
		} else {
			userOptions[i.toString()] = questionId+":"+optionId;
		}
	}
	if (emptyQuestions.length > 0) {
		$("#quiz-fail-msg").html("You have not answered the following questions: " + emptyQuestions).fadeIn(500);
		return false;
	} else {
		theURL = '/quiz/quizProcess';
		postData = {
				siteUserId:			getCookie(ysCookieName),
				'userOptions[]':	userOptions,
				questionGroupId:	$(myForm).find("input[name='questionGroupId']").val()
		};
		var result = false;
		$.ajax({
			type: 'POST',
			data: postData,
			url: theURL,
			dataType: 'html',
			complete: function(response) {
				console.log(response);
				var resp = response.responseText;
				if (resp.match('fail')) {
					// failed to update db
					result = false;
				} else {
					// successfully updated db
					result = true;
				}
			},
			async:false
		});
		processed = true;
		if (skipLogin && result) {
			$(myForm).trigger("submit");
		}
	}
}

function submitCompetition(myForm, needsLogin, skipLogin) {
	if (needsLogin) {
		// true
		if (!skipLogin || skipLogin!=true) {
			// check if they are logged in
			var userLoggedIn = $.isUserLoggedIn( function() {
				// on successful login, call this function again skipping the login procedure
				submitCompetition(myForm, needsLogin, true);
			});
			if(!userLoggedIn) {
				return false;
			}
		}
	}

	var numQuestions = $(myForm).find("input[name='numQs']").val();
	var optInTypeId =  $(myForm).find("input[name='contactOptIn']:checked").val();
	var phoneNumber = $(myForm).find("input[name='phoneNumber']").val();
	var userOptions = new Array();
	var emptyQuestions = "";

	for (var i=0; i<numQuestions; i++) {
		// pass through questionId/optionId in array
		var questionId =  $(myForm).find("input[name='questionId_"+i+"']").val();
		var optionId =  $(myForm).find("input[name='opt"+i+"']:checked").val();
		var answerText =  $(myForm).find("input[name='answer"+i+"']").val();
		if (!optionId && answerText==undefined) {
			if (emptyQuestions.length > 0) {
				emptyQuestions += ", ";
			}
			emptyQuestions += i+1;
		} else {
			if (answerText==undefined) {
				userOptions[i.toString()] = questionId+":"+optionId+":o";
			} else {
				userOptions[i.toString()] = questionId+":"+answerText+":a";
			}
		}
	}
	if (emptyQuestions.length > 0) {
		$("#comp-msg").html("<b> You have not answered the question </b>").fadeIn(500);
		return false;
	} else if (!phoneNumber || phoneNumber.length <= 10) {
		$("#comp-msg").html("<b> You have not entered a contact number </b>").fadeIn(500);
		return false;
	} else {
		theURL = '/competitions/process';
		postData = {
				siteUserId:			getCookie(ysCookieName),
				'userOptions[]':	userOptions,
                optInTypeId:		optInTypeId,
				phoneNumber:		phoneNumber,
				questionGroupId:	$(myForm).find("input[name='questionGroupId']").val(),
                competitionId:		$(myForm).find("input[name='competitionId']").val()
		};
		var result = false;
		$.ajax({
			type: 'POST',
			data: postData,
			url: theURL,
			dataType: 'html',
			complete: function(response) {

				var resp = response.responseText;

				if (resp.match('OK')) {
					// SUCCESS!
					$("#competition-form").html("<h2>Thank You! Your competition entry has been submitted.</h2>");
				} else if (resp.match('already entered')) {
					// user has already entered. remove submit button
					$("#competition-form").html("<h2>You have already entered this competition.</h2>")
				} else {
					//uncaught failure
					$(myForm).find("#comp-msg")
							.html("<b>Sorry!</b>  There seems to be a problem submitting your competition entry.  Please contact our Service Desk.")
							.fadeIn(500)
							.addClass("submitted error");
				}
			},
			async:false
		});
	}
    return false;
}

function updateDetails(needsLogin, skipLogin) {
	// check user is logged in before opening the settings
	if (needsLogin) {
		// true
		if (!skipLogin || skipLogin!=true) {

			// check if they are logged in
			var userLoggedIn = $.isUserLoggedIn( function() {
				// on successful login, call this function again skipping the login procedure
				updateDetails(needsLogin, true);
			});
			if(!userLoggedIn) {
				return false;
			}
		}
	}
	tb_show(null,'/edit-profile/'+getCookie(ysCookieName)+'?height=310&width=350',null);
}
