/* merit.js for MeritBuilder
Author: MIZ
Version 1.1 
*/

/* Init on document load */
$(function(){ 
	
	
	/* ADDITION FORM VALIDATION */
	jQuery.validator.addMethod("alphanumeric", function(value, element) {
		return this.optional(element) || /^\w+$/i.test(value);
	}, "Letters, numbers, spaces or underscores only please");  

	/* GENERAL MERIT CONTROLLER */
	// $('.details').hide();
	// $('.merit > .deleteBtn, .merit > .printBtn, .merit > .displayBtn, .merit > .resendBtn, .merit img.meritImage').hide();
	// 
	//     $(".merit").hover(
	// 	function () {
	//         	$(this)
	//         		.find('.deleteBtn,.printBtn,.displayBtn,.resendBtn').toggle();
	// 	}, 
	// 	function () {
	//         	$(this)
	//         		.find('.deleteBtn,.printBtn,.displayBtn,.resendBtn').toggle();
	//       	}
	//     );


	$('.detailMerit, .sent').click(function(){
		var x = $(this).is('.active');
		if (x) {
			$(this)
				.removeClass('active').addClass('inactive')
				.siblings('.details').toggle('fast')
				.parent().find('.meritImage').fadeIn('fast');
				
		} else {
			$(this)
				.removeClass('inactive').addClass('active')
				.siblings('.details').toggle('fast')
				.parent().find('.meritImage').fadeOut('fast');

		}
		
		return false;
	}) 
	
	
	
	// $('.topMeritInfo').click(function(){
	// 	var x = $(this).siblings().find('.detailMerit').is('.active');
	// 	if (x) {
	// 		$(this)
	// 			.removeClass('active').addClass('inactive')
	// 			.siblings('.details').toggle('fast')
	// 			.parent().find('.meritImage').fadeIn('fast');
	// 			
	// 	} else {
	// 		$(this)
	// 			.removeClass('inactive').addClass('active')
	// 			.siblings('.details').toggle('fast')
	// 			.parent().find('.meritImage').fadeOut('fast');
	// 
	// 	}
	// 	
	// 	return false;
	// })   
	



	
	
	
	
	// RESEND MERIT
	$('.resendMerit').click(function(){
		var meritID = $.ListLast($(this).attr('id'), '-');
		$.fn.deleteConfirmation({
			message : 'Are you sure you want to resend this merit?', 
			onClickYes : function(){
				$.ajax({
					type: 'POST',
					url: '/ajax/resendMerit',
					dataType: 'json',
					data: {meritID:meritID}, 
					success: function(obj){
						if(parseInt(obj.status) == 1) {
							$.unblockUI(); 
							$.fn.flashMessage({
								message: obj.msg
							})
						}
					}
				});
				
				
			}
		});
	});
	
	
	//PRINT MERIT
	$('.printMerit').click(function(){
		alert('printMerit');
	
	})
	
    $(".newFile").makeAsyncUploader({
        upload_url: 'http://' + location.host + '/ajax/uploadSWF/', 
        flash_url: '/javascripts/swfupload.swf',
        button_image_url: '/images/blankButton.png',
        file_types: '*.jpg; *.gif; *.png; *.doc; *.pdf; *.xls; *.zip',
        button_text: '<div align="center"><font face="Arial" size="12">Upload File</font></div>'
    });
	
	
	// DELETE MERIT
	$('.deleteMerit').click(function(){
		var mRow = $(this).parent().parent();
		var nRow = $(mRow).next().eq(1);
		var meritID = $.ListLast($(this).attr('id'), '-');
		$.fn.deleteConfirmation({
			message : 'Are you sure you want to delete this merit?', 
			onClickYes : function(){
				$.ajax({
					type: 'POST',
					url: '/ajax/meritReceiveDestroy',
					dataType: 'json',
					data: {meritID:meritID}, 
					success: function(obj){
						// if(parseInt(obj.status) == 1) {
							$(mRow).fadeOut('fast').remove();
							$(nRow).remove('slow');
							$.unblockUI(); 
							$.fn.flashMessage({
								message: obj.msg
							})
						// }
					}
				});
				
				
			}
		});
	});          
	

	// ASSIGN MERIT TO PROFILE 
	$('.merit2Profile').click(function(){
		var control = this;
		var main = $(control).attr('id');
		var meritId = $.ListFirst(main, '-');
		var profileId = $.ListLast(main, '-');
		$.ajax({
			type: 'POST',
			url: '/ajax/processIMP',
			dataType: 'json',
			data: {meritID:meritId, profileID:profileId}, 
			beforeSend : function() {
				$(control).attr('disabled', true);
			}, 
			success: function(obj){
				if (parseInt(obj.value) == 1) {
					$(control).attr('checked', 'checked');
				} else {
					$(control).removeAttr('checked');
				}
				$('.merit2Profile').removeAttr('disabled');
				return true;
			}
		});
		
	});
	
	
	
	
	// 
	// // Toggle merit / achivement visible 
	// $('.toggleVisible').click(function(){
	// 	var control = this;
	// 	// var main = $(control).attr('id');
	// 	var meritId = $(this).atrr('id');
	// 	$.ajax({
	// 		type: 'POST',
	// 		url: '/ajax/toggleVisible',
	// 		dataType: 'json',
	// 		data: {meritID:meritId, profileID:profileId}, 
	// 		beforeSend : function() {
	// 			$(control).attr('disabled', true);
	// 		}, 
	// 		success: function(obj){
	// 			if (parseInt(obj.value) == 1) {
	// 				$(control).attr('checked', 'checked');
	// 			} else {
	// 				$(control).removeAttr('checked');
	// 			}
	// 			$('.merit2Profile').removeAttr('disabled');
	// 			return true;
	// 		}
	// 	});
	// 	
	// });
	// 
	// 
	
	
	
	
   
	/* ACTION : SENT */	
	$('#showSuspend').click(function(){
		//$('#meritsPending').show();
		$('#meritsActive,#meritEmpty,#msgPending').fadeOut('fast');
		$('#meritsSuspend').fadeIn('fast');
		return false;
	})
	

	$('.deleteBtnSent').click(function(){
		var mRow = $(this).parent().parents().eq(0);
		var nRow = $(mRow).next().eq(0);
		var meritID = $.ListLast($(this).attr('id'), '-');
		
		$.fn.deleteConfirmation({
			message : 'Are you sure you want to delete merit?', 
			onClickYes : function(){
				$.ajax({
					type: 'POST',
					url: '/ajax/meritSentDestroy',
					dataType: 'json',
					data: {meritID:meritID}, 
					success: function(obj){
						if(parseInt(obj.status) == 1) {
							$(mRow).fadeOut('fast').remove();
							$(nRow).remove();
							$.unblockUI(); 
							$.fn.flashMessage({
								msg: obj.msg
							})
						}
					}
				});
				
				
			}
		});
		
		
	});
	
	$('.verifyBtn').click(function(){
		var mRow = $(this).parent().parents().eq(0);
		var nRow = $(mRow).next().eq(0);
		var meritID = $.ListLast($(this).attr('id'), '-');
		
		$.ajax({
			type: 'POST',
			url: '/ajax/meritVerify',
			dataType: 'json',
			data: {meritID:meritID}, 
			success: function(obj){
				if(parseInt(obj.status) == 1) {
					$(mRow).fadeOut('fast').remove();
					$.unblockUI(); 
					$.fn.flashMessage({
						msg: obj.msg
					})
				}
			}
		});
		
	});
	
	
	// PROFILE-UPDATE
    $('#editProfile').ajaxForm({
        dataType: 'json',
        success: function(obj){
			$.fn.flashMessage(obj)
        }
    });    
	
	// PROFILE-IMAGE
	var x = $('.fileProperty').val();
	    $('.imageProfile').makeAsyncUploader({
	        upload_url: '/ajax/fileUpload', 
	        flash_url: '/javascripts/swfupload.swf',
	        button_image_url: '/images/blankButton.png',
	        file_types: '*.jpg; *.gif; *.png',
	        post_params: {
	        	username:$.ListGetAt(x, 1, '|'),
	        	profileID:$.ListGetAt(x, 2, '|')
	        	}
	    });
	
	
	// PROFILE-DELETE
	$('.profileDelete').click(function(main){
		xMain = main.target;
		$.fn.deleteConfirmation({
			message : 'Are you sure you want to delete this tag?', 
			onClickYes : function(){
				var id = $.ListLast($(xMain).attr('id'), '-');
				$.ajax({
					type: 'GET',
					url: '/profile/destroy/' + id,
					dataType: 'html',
					success: function(html){
						self.location.href = '/profile/index';
					}
				});
			}
		});
	})
	
	// PROFILE-LOCK & UNLOCK
	
	var profileLock = $('.profileLock').is('.active');
	if (profileLock) {
		$('.urlProfile.active,.rssProfile.active').hide();
	} else {
		$('.urlProfile.inactive,.rssProfile.inactive').hide();
	}
	
	
	$('.profileLock').click(function(main){
		var x = $(this).is('.active');
		var id = $.ListLast($(this).attr('id'), '-');
		var href = '/profile/updateStatus';
		$.ajax({
			type: 'POST',
			url: href,
			data: { id: id, newstatus: ((x == true)?"1":"0")  }, 
			dataType: 'json',
			beforeSend: function(){
				$(main.target)
					.attr('disabled', 'disabled')
					.css({opacity:0.25});
			},
			success: function(response){
				if (x) {
					$(main.target)
						.removeClass('active').addClass('inactive');
					$('.urlProfile.active,.rssProfile.active').show();
					$('.urlProfile.inactive,.rssProfile.inactive').hide();

				} else {
					$(main.target)
						.removeClass('inactive').addClass('active')

					$('.urlProfile.inactive,.rssProfile.inactive').show();
					$('.urlProfile.active,.rssProfile.active').hide();
					
				}				
				$(main.target)
					.removeAttr('disabled')
					.css({opacity:1.0});
				$.fn.flashMessage(response)	
			}
		});
		return false;
	})

	// PROFILE NEW
	$("#profileNew").validate({
		errorClass: 'formError',
		errorLabelContainer: $('div.profileError').css({color:'red'}), 
		submitHandler: function(form) {
			jQuery(form).ajaxSubmit({
		        success: function(obj){
					$.fn.flashMessage(obj);
					if($.trim(obj.messageStatus).toLowerCase() == 'pass') {
						var x = '#sidebarInterior ul.menu li';
						var y = $(x).length - 2;
						var ori = $(x).eq(y);
						$(ori).clone().appendTo($(ori))
						$(x + ' a').eq(y+1).attr('href', '/profile/edit/' + obj.id).text(obj.label);
					}
		        },
		        dataType: 'json', 
		        resetForm: true
			});
			return false;
		} 
	});
	
	
	// ACCOUNT-IMAGE
	var x = $('#fileProperty').val();
	    $('#imageAccount').makeAsyncUploader({
	        upload_url: '/ajax/fileAccount', 
	        flash_url: '/javascripts/swfupload.swf',
	        button_image_url: '/images/blankButton.png',
	        file_types: '*.jpg; *.gif; *.png', 
	        post_params: {
	        	username:$.ListGetAt(x, 1, '|'),
	        	accountID:$.ListGetAt(x, 2, '|')
	        	}
	    });

	// REGISTER - FREE
	$('form[name=newAccountFree]').validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.next() );
		}, 
		errorClass : 'errorValidation',
		meta: 'validate',
		messages: {
			username: {
				required: 'Please enter your username.',
				remote: jQuery.format("Username {0} is already taken, please enter a different username."), 
				minlength: "Your username must consist of at least 3 characters"
			}, 
			email: {
				required: 'Please enter your email.',
				email: 'Please enter valid email.', 
				remote: jQuery.format("Email {0} is already used.")	
			}, 
			captcha: {
				required: 'Please enter captcha code.',
				remote: 'Invalid captcha code.'
			}
		} 
		
	});
	$('form[name=newAccountFree] #username').keyup($.fn.specialChar);
	
	
	
	
	// SEND MERIT (HOME)
	$.validator.addMethod("emailCheck", function(value) {
		return value !== "example@domain.com";
	}, "Please don't enter example@domain.com as email address.");


	$("#sendMerit").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.next() );
		}, 
		messages: {
			toIdentificationInfo: {
				required: 'Please enter your email.',
				email: 'Please enter valid email.'
			}, 
			messagebody : {
				required: 'Your missing your merit!'
			}
		}, 
		rules: {
			toIdentificationInfo : 'emailCheck'
		}, 
		errorClass : 'errorValidation',
		meta: 'validate'
	});


	$('#sendMerit #email').focus(function(){
		var text = 'example@domain.com';
		if ($(this).val() == text) {
			$(this).val('');
		}
	});
	$('#sendMerit #email').blur(function(){
		var text = 'example@domain.com';
		if ($(this).val() == '') {
			$(this).val(text);
		}
	});

	$('#addAchievement').validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.next() );
		}, 
		errorClass : 'errorValidation',
		meta: 'validate'
	});

	// GENERAL ACTION 






});