var askFriends = {
	init : function(config) {

        askFriends.errorMessage = config.errorMessage;
        askFriends.askContentLoader = $('#' + config.askContentLoaderId);
		askFriends.selectClass = config.selectClass;
		askFriends.currentProductId = config.productId;
		askFriends.askFriendsContent = $('#' + config.askFriendsContentId);
		askFriends.repliesContent = $('#' + config.repliesContentId);
		askFriends.askFriendsTab = $('#' + config.askFriendsTabId);
		askFriends.repliesTab = $('#' + config.repliesTabId);
		askFriends.repliesContainer = $('#' + config.repliesContainerId);
		askFriends.errorContainerId = config.errorContainerId;
		askFriends.errorRepliesContainer = $('#' + config.errorRepliesContainerId);
		askFriends.errorContainer = false;
		
		askFriends.thumbsWhoBoughtContainerId = config.thumbsWhoBoughtContainerId;
		askFriends.allRadioId = config.allRadioId;
		askFriends.whoBoughtRadioId = config.whoBoughtRadioId;
		askFriends.askContentTextareaId = config.askContentTextareaId;
		askFriends.selectAllButtonId = config.selectAllId;
		askFriends.selectWhoBoughtButtonId = config.selectNoneId;
		askFriends.askButtonId = config.askButtonId;

		askFriends.repliesTabInitialized = false;
		askFriends.askTabInitialized = false;
		askFriends.friendsWhoBoughtData = new Object();
		askFriends.askAll = true;
		askFriends.defaultMessage = config.defaultMessage;
		askFriends.noPostsMessageContainer = $('#'+config.noPostsMessageId);
		this.selectAll()
		askFriends.canClick = true;

		askFriends.askFriendsTab.bind('click', askFriends.askFriendsTabOpen);		
		askFriends.repliesTab.bind('click', askFriends.repliesTabOpen);
//                askFriends.getMessages();
	},

        getMessages: function() {
            askFriends.repliesContainer.html('');
            $.ajax({
				type :"GET",
				url :window.location.href.replace(/#/gi, ''),
				data :"view_wall_posts=1&product_id="+askFriends.currentProductId,
				dataType :'json',
				success : function(response) {
					if (response.status == 'success') {
						askFriends.stopLoading();
						if (response.messages.length > 0)
						{
                                                        
                                                        askFriends.getCountReplies(response.messages);
							askFriends.repliesBuildContent(response.messages);
                                                        
						}
						else
						{
							askFriends.repliesContainer.hide();
							askFriends.noPostsMessageContainer.show();
						}

					} else {
						alert(askFriends.errorMessage);
						askFriends.stopLoading();
						askFriends.repliesTabInitialized = false;
					}
					askFriends.canClick = true;
				},
				error : function() {
					alert(askFriends.errorMessage);
					askFriends.stopLoading();
					askFriends.repliesTabInitialized = false;
					askFriends.canClick = true;
				}
			});
        },

        getCountReplies: function(messages) {
                var count = 0;
                for (var k = 0; k < messages.length; k++)
		{
                        if (messages[k]['comments'])
                        {
                                count = count + messages[k]['comments']['count'];
                        }
                }
                if (count > 0)
                {
                        $('#repliesLink').html('');
                        $('#repliesTab').html('');
                        $('#repliesTab').append('(' + count + ')');
                        $('#repliesLink').append('(' + count + ')');
                }
        },

	repliesTabOpen: function() {
		askFriends.repliesTab.addClass('active');
		askFriends.askFriendsTab.removeClass('active');
		askFriends.repliesContent.show();
		askFriends.askFriendsContent.hide();
		if (askFriends.errorContainer != false)
			askFriends.errorContainer.hide();
		askFriends.errorRepliesContainer.hide();
		if (!askFriends.repliesTabInitialized)
		{
			if (!askFriends.canClick)
			{
				return false;
			}
			askFriends.canClick = false;
			askFriends.repliesTabInitialized = true;
			askFriends.repliesContainer.hide();		
			askFriends.repliesContainer.html('');
			askFriends.noPostsMessageContainer.hide();
			askFriends.startLoading();
			askFriends.getMessages();
                        askFriends.repliesContainer.show();
		}
	},
	repliesBuildContent: function(messages) {
		for (var k = 0; k < messages.length; k++)
		{
			var data = new Array();
			if (messages[k]['id'])
			{
				data['id'] = messages[k]['from']['id'];
				data['name'] = messages[k]['from']['name'];
				data['message'] = messages[k]['message'];
				data['message_id'] = messages[k]['id'];
				data['created_time'] = messages[k]['created_time'];
				var templateEngine = new xtTemplate({
					'template'	: $('#wall-post-template').html(),
					'tv'		: data
				})
				var html = templateEngine.parse()
				askFriends.repliesContainer.append(html);
				if (messages[k]['comments'])
				{
                                    alert(messages[k]['comments']['count']);
					$('#arrow' + data['message_id']).show();
					for (var i = 0; i < messages[k]['comments']['count']; i++)
					{
						if (messages[k]['comments']['data'] && messages[k]['comments']['data'][i]['id'])
						{
							var commentData = new Array();
							commentData['id'] = messages[k]['comments']['data'][i]['from']['id'];
							commentData['name'] = messages[k]['comments']['data'][i]['from']['name'];
							commentData['message'] = messages[k]['comments']['data'][i]['message'];
							commentData['message_id'] = messages[k]['comments']['data'][i]['id'];
							commentData['created_time'] = messages[k]['comments']['data'][i]['created_time'];
							var templateEngine = new xtTemplate({
								'template'	: $('#wall-post-comment-template').html(),
								'tv'		: commentData
							})
							var html = templateEngine.parse()
							$('#comments'+messages[k]['id']).append(html);
						}
					}
				}
			}
		}
		askFriends.repliesContainer.show();
	},
	askFriendsTabOpen: function() {
		askFriends.repliesTab.removeClass('active');
		askFriends.askFriendsTab.addClass('active');
		askFriends.repliesContent.hide();
		askFriends.askFriendsContent.show();
		if (askFriends.errorContainer != false)
			askFriends.errorContainer.hide();
		askFriends.errorRepliesContainer.hide();
		if (!askFriends.askTabInitialized)
		{
			if (!askFriends.canClick)
			{
				return false;
			}
			askFriends.canClick = false;
			askFriends.askTabInitialized = true;
			askFriends.askFriendsContent.html('');
			askFriends.startLoading();
			$.ajax({
				type :"GET",
				url :window.location.href.replace(/#/gi, ''),
				data :"ajax_get_friends_with_same_purchase_html=1&product_id="+askFriends.currentProductId,
				dataType :'json',
				success : function(response) {
					if (response.status == 'success')
					{
						askFriends.askFriendsContent.append(response.html);

						askFriends.thumbsWhoBoughtContainer = $('#' + askFriends.thumbsWhoBoughtContainerId);
						askFriends.allRadio = $('#' + askFriends.allRadioId);
						askFriends.whoBoughtRadio = $('#' + askFriends.whoBoughtRadioId);
						askFriends.askContentTextarea = $('#' + askFriends.askContentTextareaId);
						askFriends.selectAllButton = $('#' + askFriends.selectAllButtonId);
						askFriends.selectWhoBoughtButton = $('#' + askFriends.selectWhoBoughtButtonId);
						askFriends.askButton = $('#' + askFriends.askButtonId);
						askFriends.errorContainer = $('#' + askFriends.errorContainerId);

						askFriends.askButton.bind('click', function() {
							if (askFriends.errorContainer != false)
								askFriends.errorContainer.hide();
							askFriends.errorRepliesContainer.hide();
							askFriends.clickFunction();
							return false;
						});

						askFriends.allRadio.bind('click', function() {
							if (askFriends.errorContainer != false)
								askFriends.errorContainer.hide();
							askFriends.errorRepliesContainer.hide();
							askFriends.selectAll();
							//return false;
						});

						askFriends.whoBoughtRadio.bind('click', function() {
							if (askFriends.errorContainer != false)
								askFriends.errorContainer.hide();
							askFriends.errorRepliesContainer.hide();
							askFriends.selectWhoBought();
							//return false;
						});
						
						askFriends.stopLoading();
						//askFriends.askTabInitialized = false;

						var friends = askFriends.thumbsWhoBoughtContainer.children();
						for ( var thumb = 0; thumb < friends.length; thumb++ ) {
							if (friends[thumb].nodeName == 'div' || friends[thumb].nodeName == 'DIV')
							{
								$('#' + friends[thumb].id).bind('click', {id : friends[thumb].id}, function(event){
									if (askFriends.errorContainer != false)
										askFriends.errorContainer.hide();
									askFriends.errorRepliesContainer.hide();
									askFriends.thumbWhoBoughtSelect(event.data.id);
									
								});

								$('#' + friends[thumb].id).hover(
									function () {
										$(this).addClass("ask-friends-hover");
									},
									function () {
										$(this).removeClass("ask-friends-hover");
									}
								);

								askFriends.friendsWhoBoughtData[friends[thumb].id] = true;
							}
						}
						askFriends.selectAll();
					} 
					else
					{
						alert(response.message);
						askFriends.stopLoading();
						askFriends.askTabInitialized = false;
					}
					askFriends.canClick = true;
				},
				error : function() {
					alert(askFriends.errorMessage);
					askFriends.stopLoading();
					askFriends.askTabInitialized = false;
					askFriends.canClick = true;
				}
			});
		}
		else
		{
			askFriends.selectAll();
			askFriends.allRadio.attr({"checked": "checked"});
			askFriends.whoBoughtRadio.removeAttr("checked");
		}
	},
	
	clickFunction : function() {
		var msg = askFriends.validateData();
		if (!msg) {
			askFriends.errorContainer.html($('#ask-friends-no-message-container').html());
			askFriends.errorContainer.show();
			return false;
		}
		if (msg.length > 255)
		{
			askFriends.errorContainer.html($('#ask-friends-bad-message-container').html());
			askFriends.errorContainer.show();
			return false;
		}
		var ids = askFriends.getIdList();
		if (!ids) {
			askFriends.errorContainer.html($('#ask-friends-no-friends-selected-container').html());
			askFriends.errorContainer.show();
			return false;
		}
		askFriends.sendAskMessage(msg, ids);
	},

	selectAll : function() {
		if (askFriends.thumbsWhoBoughtContainer)
		{
			askFriends.thumbsWhoBoughtContainer.css('visibility', 'hidden');
			askFriends.thumbsWhoBoughtContainer.css('height', '60px');
			askFriends.askAll = true;
		}
	},

	selectWhoBought : function() {
		if (askFriends.thumbsWhoBoughtContainer)
		{
			askFriends.thumbsWhoBoughtContainer.css('visibility', 'visible');
			askFriends.thumbsWhoBoughtContainer.css('height', '138px');
			askFriends.askAll = false;
			var thumbs = askFriends.thumbsWhoBoughtContainer.children();
			for ( var thumb = 0; thumb < thumbs.length; thumb++) {
				if (!$('#' + thumbs[thumb].id).hasClass(askFriends.selectClass)) {
					 $('#' + thumbs[thumb].id).addClass(askFriends.selectClass);
					 $('#ch' + thumbs[thumb].id).attr("checked", "checked");
				}
			}
			for ( var key in askFriends.friendsWhoBoughtData) {
				askFriends.friendsWhoBoughtData[key] = true;
			}
		}
	},

	selectNone : function() {
		askFriends.thumbsWhoBoughtContainer.css('visibility', 'hidden');
		askFriends.askAll = true;
		var thumbs = askFriends.thumbsWhoBoughtContainer.children();
		for ( var thumb = 0; thumb < thumbs.length; thumb++) {			
			if ($('#' + thumbs[thumb].id).hasClass(askFriends.selectClass)) {
				$('#' + thumbs[thumb].id).removeClass(askFriends.selectClass);
			}
		}
		for ( var key in askFriends.friendsWhoBoughtData) {
			askFriends.friendsWhoBoughtData[key] = false;
		}
	},

	thumbWhoBoughtSelect : function(id) {
		$('#' + id).toggleClass(askFriends.selectClass);
		if (askFriends.friendsWhoBoughtData[id])
		{
			askFriends.friendsWhoBoughtData[id] = false;
			$('#ch' + id).removeAttr("checked");
		}
		else
		{
			askFriends.friendsWhoBoughtData[id] = true;
			$('#ch' + id).attr("checked", "checked");
		}
	},

	startLoading : function() {
		askFriends.askContentLoader.show()
	},

	stopLoading : function() {
		askFriends.askContentLoader.hide()
	},

	validateData : function() {
		var str = askFriends.askContentTextarea.val();
		var check = str.replace(/(^\s+)|(\s+$)/g, "");
		if (check.length == 0) {
			return false;
		} else {
			return str;			
		}
	},

	getIdList : function() {
		if (askFriends.askAll)
		{
			return 'everyone';
		}
		var result = new Array();
		for ( var key in askFriends.friendsWhoBoughtData) {
			if (askFriends.friendsWhoBoughtData[key]) {
				result.push(key);
			}
		}
		if (result.length == 0) {
			return false;
		} 
		else {
			return result.join(',');
		}
	},

	sendAskMessage : function(msg, ids) {
		if (!askFriends.canClick)
		{
			return false;
		}
		askFriends.startLoading();
		askFriends.canClick = false;
		if (askFriends.errorContainer != false)
			askFriends.errorContainer.hide();
		askFriends.errorRepliesContainer.hide();
		//msg = msg.replace(/(<([^>]+)>)/ig,"");
		var sendingData = {ask_your_friends: 1, message: escape(msg), friends: ids, products_id: askFriends.currentProductId};
		$.ajax( {
			type :"POST",
			url : window.location.href.replace(/#/gi, ''),
			data : sendingData,
			dataType :'json',
			success : function(response) {
				if (response.status == 'success') {
					askFriends.stopLoading();
					askFriends.selectNone();
					askFriends.askContentTextarea.val('');
					askFriends.repliesTabInitialized = false;
					askFriends.canClick = true;
					askFriends.repliesTabOpen();
				} else {
					askFriends.errorContainer.html($('#ask-friends-error-container').html());
					askFriends.errorContainer.show();
					askFriends.stopLoading();
					askFriends.canClick = true;
				}
			},
			error : function() {
				askFriends.errorContainer.html($('#ask-friends-error-container').html());
				askFriends.errorContainer.show();
				askFriends.stopLoading();
				askFriends.canClick = true;
			}
		});
		return false
	},
	
	sendComment: function (message_id) {
		var message = $('#wallpostmessage_comment_text'+message_id).val();
		message = $.trim(message);
		if (message.length > 0 && message.length < 255)
		{
			if (askFriends.errorContainer != false)
				askFriends.errorContainer.hide();
			askFriends.errorRepliesContainer.hide();
			$('#comment_button'+message_id).addClass('disabled');
			$('#comment_loader'+message_id).show();
			$('#wallpostmessage_comment_text'+message_id).attr({"disabled" : "disabled"});
			var sendingData = {wallpostcomment: 1, message: escape(message), post_id: message_id};
			$.ajax( {
				type :"GET",
				url :window.location.href.replace(/#/gi, ''),
				data : sendingData,
				dataType :'json',
				success : function(response) {
					if (response.status == 'success') {
						var commentData = new Array();
						commentData['id'] = response.facebook_uid;
						commentData['name'] = response.facebook_name;
						commentData['message'] = response.message;
						commentData['message_id'] = response.comment_id;
						commentData['created_time'] = response.created_time;
						var templateEngine = new xtTemplate({
							'template'	: $('#wall-post-comment-template').html(),
							'tv'		: commentData
						})
						var html = templateEngine.parse();
						$('#comments'+message_id).append(html);
						$('#arrow' + message_id).show();
                                                askFriends.incRepliesCount();
					}
					else 
					{
						askFriends.errorRepliesContainer.html($('#ask-friends-error-container').html());
						askFriends.errorRepliesContainer.show();
					}
					$('#comment_loader'+message_id).hide();
					$('#wallpostmessage_comment_text'+message_id).val(askFriends.defaultMessage);
					$('#wallpostmessage_comment_text'+message_id).removeClass('active');
					$('#wallpostmessage_comment_text'+message_id).removeAttr("disabled");
				},
				error : function() {
					askFriends.errorRepliesContainer.html($('#ask-friends-error-container').html());
					askFriends.errorRepliesContainer.show();
					$('#comment_loader'+message_id).hide();
					$('#wallpostmessage_comment_text'+message_id).val(askFriends.defaultMessage);
					$('#wallpostmessage_comment_text'+message_id).removeClass('active');
					$('#wallpostmessage_comment_text'+message_id).removeAttr("disabled");
				}
			});
		}
		else
		{
			askFriends.errorRepliesContainer.html($('#ask-friends-bad-message-container').html());
			askFriends.errorRepliesContainer.show();
		}
	},

        incRepliesCount: function () {
            var countString = $('#repliesTab').html();
            strLength = countString.length;
            if (strLength > 0)
            {
                    count = countString.substring(1, (strLength - 1));
            }
            else
            {
                    count = 0;
            }
            count++;
            $('#repliesTab').html('');
            $('#repliesLink').html('');
            $('#repliesTab').append('(' + count + ')');
            $('#repliesLink').append('(' + count + ')');

        },

	showCommentButton: function (obj) {
		var commentButton = $('#'+ obj.id.replace(/wallpostmessage_comment_text/gi, 'comment_button'));
		if ($(obj).val() == askFriends.defaultMessage)
		{
			$(obj).val('');
		}
		$(commentButton).removeClass('disabled');
		$(obj).addClass('active');
	},
	hideCommentButton: function (obj) {
		var commentButton = $('#'+obj.id.replace(/wallpostmessage_comment_text/gi, 'comment_button'));
		if ($(obj).val() == '')
		{
			$(obj).val(askFriends.defaultMessage);
			$(commentButton).addClass('disabled');
			$(obj).removeClass('active');
		}		
	}
}
