var UserPost;
var UserPostEdit;
var UserRegister;
var UserLogin;
var UserSearchPost;
var UserPostDelete;

/******************************************************/
/* BEGIN - All popup windows */
(function($) {
	$(document).ready(function() {
		UserPost.init();
		UserPostEdit.init();
		UserRegister.init();
		UserPostDelete.init();
		
		$("input.search_field").blur(function() {
			if ($(this).val() == "") {
				$(this).val(UserSearchPost.labels.message);
			}
		});
		$("input.search_field").focus(function() {
			if ($(this).val() == UserSearchPost.labels.message) {
				$(this).val("");
			}
		});
		$("input.search_field").trigger('blur');
		$("input#search_submit").click(function() {
			if ($("input#s").val() == UserSearchPost.labels.message) {
				$("input#s").val("");
			}
		});
		
		$("input#user_login").blur(function() {
			if ($(this).val() == "") {
				$(this).addClass("input-inactive");
				$(this).val(UserLogin.labels.username);
			}
		});
		$("input#user_login").focus(function() {
			$(this).removeClass("input-inactive");
			if ($(this).val() == UserLogin.labels.username) {
				$(this).val("");
			}
		});
		$("input#user_login").trigger('blur');
		$("input#wp-submit").click(function() {
			if ($("input#user_login").val() == UserLogin.labels.username) {
				$("input#user_login").val("");
			}
		});
		$(".register-image-terms-popup").click(function() {
			$('#dialog-register-terms').dialog('open');
		});
		
		$("#register-captcha-refresh-image").click(function() {
			$("#register-submit").attr("disabled", "true");
			$("#register-captcha-confirm").attr("value", "");
			$("#register-captcha-image").html('<img src="'+UserRegister.labels.imageLoadingURL+'" style="height:16px;width:16px;margin-top:5px;margin-left:0px;" /> '+UserRegister.labels.imageLoadingText);
			
			$.post( lal_ajaxurl, {
				'lal_action': 'register_print_captcha_image'
			}, function(response) {
				$("#register-captcha-image").html(response);
				$("#register-captcha-image").fadeIn(200);
				$("#register-submit").removeAttr("disabled");
			});
		});
		$("#register-captcha-refresh-image").trigger('click');
		
		$("select#up-category").livequery("change", function() {
			UserPost.setButtonsState(false);
			
			if ($("select#up-category").val() == "") {
				$("#up-sub-cat-zone").html("");
				UserPost.setButtonsState(true);
			} else {
				$("#up-sub-cat-zone").html('<div style="padding-top:6px;"><img src="' + UserPost.labels.loadingImageUrl + '" style="height:16px;width:16px;margin-top:5px;margin-left:0px;" /> ' + UserPost.labels.loadingText + '</div>');
				
				$.post( lal_ajaxurl, {
					'lal_action': 'load_sub_categories',
					'cat_id': $("select#up-category").val()
				}, function(response) {
					$("#up-sub-cat-zone").html(response);
					UserPost.setButtonsState(true);
				});
			}
		});
		
		$("select#upe-category").livequery("change", function() {
			UserPostEdit.setButtonsState(false);
			
			if ($("select#upe-category").val() == "") {
				$("#upe-sub-cat-zone").html("");
				UserPostEdit.setButtonsState(true);
			} else {
				$("#upe-sub-cat-zone").html('<div style="padding-top:6px;"><img src="' + UserPostEdit.labels.loadingImageUrl + '" style="height:16px;width:16px;margin-top:5px;margin-left:0px;" /> ' + UserPostEdit.labels.loadingText + '</div>');
				
				$.post( lal_ajaxurl, {
					'lal_action': 'load_sub_categories_edit',
					'cat_id': $("select#upe-category").val(),
					'sub_cat_id' : UserPostEdit.labels.childCategory
				}, function(response) {
					$("#upe-sub-cat-zone").html(response);
					
					if (UserPostEdit.labels.childCategory != '') {
						UserPostEdit.labels.childCategory = '';
					}
					UserPostEdit.setButtonsState(true);
				});
			}
		});
		
		$("img.img-cat-expandable-active").click( function() {
			var catId = $(this).parent("div").children(".menu-cat-id").val();
			var src = $("img#img-cat-expandable-"+catId).attr("src");
			
			if (src.substring(src.lastIndexOf("/")+1) == "widget-cat-expand.png") {
				$("img#img-cat-expandable-"+catId).attr("src", src.substring(0, src.lastIndexOf("/")+1)+"widget-cat-collapse.png");
				$("div#menu-cat-expandable-"+catId).animate({height:'show',opacity:'show'},'slow');
			} else {
				$("img#img-cat-expandable-"+catId).attr("src", src.substring(0, src.lastIndexOf("/")+1)+"widget-cat-expand.png");
				$("div#menu-cat-expandable-"+catId).animate({height:'hide',opacity:'hide'},'slow');
			}
		});
	});
	
	UserRegister = {
		buttonClose: null,
		labels: {},
		
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		
		init: function() {
			var buttons = {};
			buttons[this.labels.buttonClose] = this.cancel;
			
			$("#dialog-register-terms").dialog({
				bgiframe: true,
				resizable: false,
				height: 500,
				width: 700,
				modal: true,
				autoOpen: false,
				buttons: buttons
			});
			
			this.buttonClose = $(":button:contains('"+this.labels.buttonClose+"')", $("#dialog-register-terms").parent());
		},
		cancel: function() {
			$(this).dialog('close');
		}
	}
	
	UserLogin = {
		labels: {}
	}
	
	UserSearchPost = {
		labels: {}
	}
	
	UserPost = {
		fields: null,
		tips: null,
		buttonSubmit: null,
		buttonCancel: null,
		labels: {},
		
		init: function() {
			this.fields = $("#up-title, #up-post, #up-category, #up-sub-category");
			this.tips = $("#up-validate-tips");
			
			var buttons = {};
			buttons[this.labels.buttonSubmit] = this.submit;
			buttons[this.labels.buttonCancel] = this.cancel;
			
			$("#up-dialog").dialog({
				bgiframe: true,
				resizable: false,
				height: "auto",
				width: 700,
				modal: true,
				autoOpen: false,
				buttons: buttons,
				close: function() {
					UserPost.resetDialog();
				}
			});
			
			this.buttonSubmit = $(":button:contains('"+this.labels.buttonSubmit+"')", $("#up-dialog").parent());
			this.buttonCancel = $(":button:contains('"+this.labels.buttonCancel+"')", $("#up-dialog").parent());
			
			$('.up-get-popup').click(function() {
				$('#up-dialog').dialog('open');
			});
		},
		
		processingState: function(state) {
			UserPost.setButtonsState(!state);
			
			if (state) {
				$("#up-form-zone").hide();
				$("#up-results-zone").html("<img src=\"" + UserPost.labels.loadingImageUrl + "\" width=\"16\" height=\"16\" style=\"margin-bottom: -3px;\" /> "+UserPost.labels.processingMessage).show();
			} else {
				$("#up-results-zone").html("").hide();
				$("#up-form-zone").show();
			}
		},
		
		submit: function() {
			var formValid = true;
			
			UserPost.fields = $("#up-title, #up-post, #up-category, #up-sub-category");
			UserPost.fields.removeClass('ui-state-error');
			
			if (!checkLength($('#up-title'), 1)) {
				updateTips(UserPost.tips, UserPost.labels.errorTitleMissing, formValid);
				formValid = false;
			}
			
			if (!checkLength($('#up-post'), 1)) {
				updateTips(UserPost.tips, UserPost.labels.errorMessageMissing, formValid);
				formValid = false;
			}
			
			if (!checkLength($('#up-category'), 1)) {
				updateTips(UserPost.tips, UserPost.labels.errorCatMissing, formValid);
				formValid = false;
			} else {
				if (!($('#up-no-subcat').length)) {
					if (!checkLength($('#up-sub-category'), 1)) {
						updateTips(UserPost.tips, UserPost.labels.errorSubCatMissing, formValid);
						formValid = false;
					}
				}
			}
			
			if (formValid) {
				UserPost.processingState(true);
				$('#up-form').submit();
			}
		},
		
		cancel: function() {
			if (!($('#up-new-post').length)) {
				$(this).dialog('close');
			} else {
				$(this).dialog('close');
				$(location).attr('href', $('#up-new-post').val());
			}
		},
		
		resetDialog: function() {
			UserPost.fields.val("");
			UserPost.tips.html("");
			UserPost.fields.removeClass('ui-state-error');
			$("#up-sub-cat-zone").html("");
		},
		
		setButtonsState: function(state) {
			setDialogButtonState(this.buttonSubmit, state);
			setDialogButtonState(this.buttonCancel, state);
		},
		
		setModeClose: function(activate_result) {
			if (activate_result) {
				$("#up-form-zone").hide();
				$("#up-results-zone").show();
			} else {
				$("#up-form-zone").show();
				$("#up-results-zone").hide();
			}
			
			UserPost.buttonSubmit.hide();
			setDialogButtonState(UserPost.buttonCancel, true);
		}
	}
	
	UserPostEdit = {
		fields: null,
		tips: null,
		buttonSubmit: null,
		buttonCancel: null,
		labels: {},
		
		init: function() {
			if ($('#upe-title').length != 0) {
				this.fields = $("#upe-title, #upe-post, #upe-category, #upe-sub-category");
				this.tips = $("#upe-validate-tips");
				
				var buttons = {};
				buttons[this.labels.buttonSubmit] = this.submit;
				buttons[this.labels.buttonCancel] = this.cancel;
				
				$("#upe-dialog").dialog({
					bgiframe: true,
					resizable: false,
					height: "auto",
					width: 700,
					modal: true,
					autoOpen: false,
					buttons: buttons,
					close: function() {
						UserPostEdit.resetDialog();
					}
				});
				
				this.buttonSubmit = $(":button:contains('"+this.labels.buttonSubmit+"')", $("#upe-dialog").parent());
				this.buttonCancel = $(":button:contains('"+this.labels.buttonCancel+"')", $("#upe-dialog").parent());
				
				$('.upe-get-popup').click(function() {
					$('#upe-dialog').dialog('open');
					
					UserPostEdit.processingLoadingState(true);
					
					$.post( lal_ajaxurl, {
						'lal_action': 'load_edit_post',
						'post_id': UserPostEdit.labels.postId
					}, function(response) {
						$("#upe-title").val(response.post_title);
						$("#upe-post").val(response.post_content);
						
						$("#upe-category").attr('value',UserPostEdit.labels.parentCategory)
						
						$("select#upe-category").trigger("change");
						
						UserPostEdit.processingLoadingState(false);
					},'json');
				});
			}
		},
		
		processingState: function(state) {
			UserPostEdit.setButtonsState(!state);
			
			if (state) {
				$("#upe-form-zone").hide();
				$("#upe-results-zone").html("<img src=\"" + UserPostEdit.labels.loadingImageUrl + "\" width=\"16\" height=\"16\" style=\"margin-bottom: -3px;\" /> "+UserPostEdit.labels.processingMessage).show();
			} else {
				$("#upe-results-zone").html("").hide();
				$("#upe-form-zone").show();
			}
		},
		
		processingLoadingState: function(state) {
			UserPostEdit.setButtonsState(!state);
			
			if (state) {
				$("#upe-form-zone").hide();
				$("#upe-results-zone").html("<img src=\"" + UserPostEdit.labels.loadingImageUrl + "\" width=\"16\" height=\"16\" style=\"margin-bottom: -3px;\" /> "+UserPostEdit.labels.processingMessageLoading).show();
			} else {
				$("#upe-results-zone").html("").hide();
				$("#upe-form-zone").show();
			}
		},
		
		submit: function() {
			var formValid = true;
			
			UserPostEdit.fields = $("#upe-title, #upe-post, #upe-category, #upe-sub-category");
			UserPostEdit.fields.removeClass('ui-state-error');
			
			if (!checkLength($('#upe-title'), 1)) {
				updateTips(UserPostEdit.tips, UserPostEdit.labels.errorTitleMissing, formValid);
				formValid = false;
			}
			
			if (!checkLength($('#upe-post'), 1)) {
				updateTips(UserPostEdit.tips, UserPostEdit.labels.errorMessageMissing, formValid);
				formValid = false;
			}
			
			if (!checkLength($('#upe-category'), 1)) {
				updateTips(UserPostEdit.tips, UserPostEdit.labels.errorCatMissing, formValid);
				formValid = false;
			} else {
				if (!($('#upe-no-subcat').length)) {
					if (!checkLength($('#upe-sub-category'), 1)) {
						updateTips(UserPostEdit.tips, UserPostEdit.labels.errorSubCatMissing, formValid);
						formValid = false;
					}
				}
			}
			
			if (formValid) {
				UserPostEdit.processingState(true);
				$('#upe-form').submit();
			}
		},
		
		cancel: function() {
			if (!($('#upe-new-post').length)) {
				$(this).dialog('close');
			} else {
				$(this).dialog('close');
				$(location).attr('href', $('#upe-new-post').val());
			}
		},
		
		resetDialog: function() {
			UserPostEdit.fields.val("");
			UserPostEdit.tips.html("");
			UserPostEdit.fields.removeClass('ui-state-error');
			$("#upe-sub-cat-zone").html("");
		},
		
		setButtonsState: function(state) {
			setDialogButtonState(this.buttonSubmit, state);
			setDialogButtonState(this.buttonCancel, state);
		},
		
		setModeClose: function(activate_result) {
			if (activate_result) {
				$("#upe-form-zone").hide();
				$("#upe-results-zone").show();
			} else {
				$("#upe-form-zone").show();
				$("#upe-results-zone").hide();
			}
			
			UserPostEdit.buttonSubmit.hide();
			setDialogButtonState(UserPostEdit.buttonCancel, true);
		}
	}

	UserPostDelete = {
		buttonSubmit: null,
		buttonCancel: null,
		labels: {},
		
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		
		init: function() {
			var buttons = {};
			buttons[this.labels.buttonSubmit] = this.submit;
			buttons[this.labels.buttonCancel] = this.cancel;
			
			$("#upd-dialog").dialog({
				bgiframe: true,
				resizable: false,
				height: "auto",
				width: 400,
				modal: true,
				autoOpen: false,
				buttons: buttons
			});
			
			this.buttonSubmit = $(":button:contains('"+this.labels.buttonSubmit+"')", $("#upd-dialog").parent());
			this.buttonCancel = $(":button:contains('"+this.labels.buttonCancel+"')", $("#upd-dialog").parent());
			
			$('.upd-get-popup').click(function() {
				$('#upd-dialog').dialog('open');
			});
		},
		submit: function() {
			UserPostDelete.processingState(true);
			
			$.post( lal_ajaxurl, {
				'lal_action': 'delete_user_post',
				'post_id' : UserPostEdit.labels.postId
			}, function(response) {
				window.location.replace(UserPostDelete.labels.home);
			});
		},
		cancel: function() {
			$(this).dialog('close');
		},
		setButtonsState: function(state) {
			setDialogButtonState(this.buttonSubmit, state);
			setDialogButtonState(this.buttonCancel, state);
		},
		processingState: function(state) {
			UserPostDelete.setButtonsState(!state);
			
			if (state) {
				$("#upd-form-zone").hide();
				$("#upd-results-zone").html("<img src=\"" + UserPostDelete.labels.loadingImageUrl + "\" width=\"16\" height=\"16\" style=\"margin-bottom: -3px;\" /> "+UserPostDelete.labels.processingMessage).show();
			} else {
				$("#upd-results-zone").html("").hide();
				$("#upd-form-zone").show();
			}
		}
	}
	
})(jQuery);
/* END - All popup windows */
/******************************************************/

/****************************************/
/* BEGIN - Shared functions for widgets */
function checkLength(otext, min) {
	if ( otext.val().length < min ) {
		otext.addClass('ui-state-error');
		return false;
	} else {
		return true;
	}
}

function updateTips(otips, text, clear) {
	otips.show();
	if (clear)
		otips.html(text).effect("highlight", {}, 1500);
	else
		otips.html(otips.html() + "<br />" + text);
}

function check_regexp(textField, regularExpr) {
	if ( !(regularExpr.test(textField.val())) ) {
		textField.addClass('ui-state-error');
		return false;
	} else {
		return true;
	}
}

function setDialogButtonState(button, state) {
	button.show();
	if (state) {
		button.addClass('ui-state-default');
		button.removeClass('ui-state-disabled');
		button.removeClass('ui-state-hover');
		button.removeAttr('disabled');
	} else {
		button.removeClass('ui-state-default');
		button.addClass('ui-state-disabled');
		button.addClass('ui-state-hover');
		button.attr('disabled', 'disabled');
	}
}
/* END - Shared functions for widgets */
/**************************************/

/***************************************************/
/*             BEGIN GOOGLE ANALYTICS              */
/***************************************************/
function getGoogleAnalyticsAccount() {
	var location = window.location.toString();
	
	if(location.indexOf("laltruiste.ca") > 0 && location.indexOf("laltruiste.ca") < 14)
	{
		return "UA-10646999-4";
	}
	
	return "";
}

function gaFilterSpecialCharacters(text) {
	return text.replace(/&#[0-9]*;/g, ""); //Remove the encoded characters. Per example: &#10;
}

function gaBuildTrackingCodesMap() {
	var codesMap = {};
	/*
	codesMap['REGISTER'] = {link:'/register/'};
	codesMap['LOGIN'] = {link:'/login/'};
	codesMap['LOGIN_SUCCESS'] = {link:'/login-success/'};
	codesMap['SEARCH_ENDECA'] = {link:'/Search-Endeca/?kw={1}/'};
	*/
	return codesMap;
}

function gaBuildTrackerLink() {
	if (buildTrackerLink.arguments.length > 0) {
		var args = buildTrackerLink.arguments;
		var codesMap = gaBuildTrackingCodesMap();
		var code = args[0];
		gaTrackerLink = codesMap[code].link;
		
		for(var i=1; i<args.length; i++) {
			gaTrackerLink = gaTrackerLink.replace("{" + i + "}", gaFilterSpecialCharacters(args[i]));
		}
	}
}

function gaCallAsyncTrackerLink() {
	if (callTrackerLinkAsync.arguments.length > 0) {
		var args = callTrackerLinkAsync.arguments;
		var codesMap = gaBuildTrackingCodesMap();
		var code = args[0];
		gaLocalTrackerLink = codesMap[code].link;
		
		for(var i=1; i<args.length; i++) {
			gaLocalTrackerLink = gaLocalTrackerLink.replace("{" + i + "}", gaFilterSpecialCharacters(args[i]));
		}
		
		gaPageTracker._trackPageview(gaLocalTrackerLink);
		
		// DEBUG
		//alert("async : " + gaLocalTrackerLink);
	}
}

function gaTrackPage() {
	gaPageTracker._trackPageview(gaTrackerLink);
	
	// DEBUG
	//alert("sync : " + gaTrackerLink);
}
/***************************************************/
/*             END GOOGLE ANALYTICS                */
/***************************************************/