/**
 * Get the Code IGniter Base URL
 */
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
   }
}

/**
 * Function to show the Error and Advertising message
 * The object is the message to show
 * @param {Object} message
 */
function showMessageError(message){
	if($("#messageErrorAlt").css("display") == "none"){
		   $("#messageErrorAlt").fadeIn("fast");
		   $("#messageErrorAlt").text(message);
		   setTimeout("hideMessageError()",5000);
	}
}

function hideMessageError(){
       $("#messageErrorAlt").fadeOut("fast");
}

/* Function to route the click on the textbox to the click on the upload*/
$(document).ready(function(event){
    
    if($.browser.mozilla){
        $('#uploaderGroup').css('z-index','3');
        $('#uploaderGroup').bind("change", function() {
            $('#fakeUploadLogo').val($('#uploaderGroup').val());
        });
    }
    
    $('#fakeUploadLogo').click(clickFakeUploadLogo);
})

function clickFakeUploadLogo(){
    $('#uploaderGroup').click();
    $('#uploaderGroup').bind("change", function() {
        $('#fakeUploadLogo').val($('#uploaderGroup').val());
    });
}

/*======================================================= GRoups Section =================================================================*/

$(document).ready(function(event){
	assignEventSendMessageToGroup();
	assignEventSendJoinPetitionToGroup();
	assignEventAcceptMemberJoinPetition();
	assignEventCancelMemberJoinPetition();
	assignEventSelectFriendForInvitation();
	assignEventLeaveGroup();
});

function assignEventSendMessageToGroup(){
	$("span[id^=sendMessageToGroup]").click(function(event){
		
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec($(this).attr('id'));
		var id = matches[0];
		$('#activeGroup').val(id);
		
		$('#messageBox').jqm({
			ajax : getBaseURL() + 'groups/showMessageSenderGroup',
			modal : true,
			onShow : function(dialog){
				dialog.w.fadeIn('slow');
			},
			onClose : function(dialog){
				dialog.w.fadeOut('slow');
				dialog.o.remove();
			},
			onLoad : loadEventDialogSendMessageToGroup
		});
		
		$('#messageBox').jqmShow();
	});
}

function loadEventDialogSendMessageToGroup(dialog){
	cancelSendMessageToGroup(dialog);
	acceptSendMessageToGroup(dialog);
}

function cancelSendMessageToGroup(dialog){
	$("#btnCancelSendMessageToGroup",dialog.w).click(function(event){
		dialog.w.jqmHide();
	});
}

function acceptSendMessageToGroup(dialog){
	$('#btnSendMessageToGroup',dialog.w).click(function(event){
		$.ajax({
			data : 'groupId=' + $('#activeGroup').val() + '&message=' + $('#txtMessage',dialog.w).val(),
			dataType : 'html',
			type : 'post',
			url : getBaseURL() + 'groups/sendMessageToGroup',
			success : function(data){
				dialog.w.jqmHide();
			}
		});
	})
}

function assignEventSendJoinPetitionToGroup(){
	$('span[id^=sendJoinPetitionToGroup]').click(function(event){
		
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec($(this).attr('id'));
		var id = matches[0];
		
		$.ajax({
			dataType : 'html',
			type : 'post',
			url : getBaseURL() + 'groups/sendJoinPetition',
			data : 'groupId=' + id,
			success : function(data){
				if(data == "false"){
					return;
				}
				
				$('#toolBoxGroup'+id).css('text-align','right');
				$('#toolBoxGroup'+id).html('<span class="fakeLink" id="sendMessageToGroup'+id+'">Send Message</span>');
				showMessageError("Your join petition has been sent to the owner of " + data);
			}
		});
		
	});
}

function assignEventAcceptMemberJoinPetition(){
	
	$('img[id^=acceptPetition]').click(function(event){
		
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec($(this).attr('id'));
		var id = matches[0];
		var groupId = $('#groupId').val();
		
		
		$.ajax({
			data : 'groupId='+groupId+'&userId='+id,
			dataType : 'json',
			type : 'post',
			url : getBaseURL() + 'groups/confirmMemberPetition',
			success : function(data){
				
				$('#userMember'+id).fadeOut('fast',function(){
					$('#userMember'+id).remove();
				});
				
				showMessageError("Now "+data.userName+" is part of " + data.groupName);
			}
			
		})
	})
}

function assignEventCancelMemberJoinPetition(){
	
	$('img[id^=cancelPetition]').click(function(event){
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec($(this).attr('id'));
		var id = matches[0];
		var groupId = $('#groupId').val();
		
		
		$.ajax({
			data : 'groupId='+groupId+'&userId='+id,
			dataType : 'html',
			type : 'post',
			url : getBaseURL() + 'groups/cancelMemberPetition',
			success : function(data){
				
				$('#userMember'+id).fadeOut('fast',function(){
					$('#userMember'+id).remove();
				});
			}
		})
	})
}

function assignEventSelectFriendForInvitation(){
	
	events = {
		selected : function(event, ui){
			var regularExpression = new RegExp('(\\d)+');
			var matches = regularExpression.exec(ui.selected.getAttribute('id'));
			
			if(matches != null){
				var id = matches[0];
				$('#friendsSelected').append('<input type="hidden" name="friendsSelected[]" value="'+id+'" />');
			}
		},
		unselecting : function(event, ui){
			var regularExpression = new RegExp('(\\d)+');
			var matches = regularExpression.exec(ui.unselecting.getAttribute('id'));
			var id = matches[0];
			$('input[value='+id+']').remove();
		}
	}

if (document.getElementById("selectableFriend")) {
	$('#selectableFriend').selectable(events);
}
}

$(document).ready(function(event){
	$('#txtEmails').val('Write emails separated by commas.')
	.css('color','#bbb').css('text-decoration','italic').click(function(event){
		if($(this).val() == 'Write emails separated by commas.')
			$(this).val('').css('color','#000').css('text-decoration','none');
	});

});

function assignEventLeaveGroup(){
	$('span[id^=leaveGroup]').click(function(event){
		
		var regularExpression = new RegExp('(\\d)+');
		var matches = regularExpression.exec($(this).attr('id'));
		var id = matches[0];
		
		if(confirm('Do you want to leave this group?')){
			$.ajax({
				url : getBaseURL() + 'groups/leaveGroup',
				dataType : 'html',
				type : 'post',
				data : 'groupId=' + id,
				success : function(data){
					$('#'+id).fadeOut('fast',function(){
						$(this).empty();
					})
					
					showMessageError('You have left ' + data);
				}
			});
		}
	});
}