var categoryId = 0;
var module = '';

$(document).ready(function()
{
	
	$.fn.alertInputNotValidated = function(onDone) {
		return this.each(function() {
			inputObject = $(this);
			var originalColor = inputObject.css('background-color') || 'white';
			inputObject.css('background-color', '#FF9F9F');
			inputObject.animate( { backgroundColor : originalColor }, function () {
				if(onDone != undefined) { onDone(); }
			});
		});
	};
	
	var messagesToDisplay = $('.display-message-on-load');
	if(messagesToDisplay.length > 0) {
		messagesToDisplay.each(function () {
			try {
				$.gritter.add({
					title: $(this).attr('rel'),
					text: $(this).html(),
					image: '/images/growl/notice.png',
					sticky: false,
					time: 3000
				});
			} catch(e) {

			}
		});
	}

	(function($) {
		$.checkValidEmail = function(email) {
			var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
			if (filter.test(email))
				testresults=true
			else{
				testresults=false
			}
			return (testresults)
		};
	})(jQuery);
	
	
	
	$('a[rel="external"]').live('click', function(e)
	{
		window.open($(this).attr('href'));
		e.preventDefault();
	});
		
	$('a[rel="topframe"]').live('click', function(e)
	{
		window.top.location = $(this).attr('href');
		e.preventDefault();
	});
	
	// left bar popup links
	$('a[rel^="modal"]').live('click', function(e)
	{
		// width, height arguments
		var _args = $(this).attr('rel').split(',');
		var _width  = (1 in _args && _args[1]) ? parseInt(_args[1]) : 450;
		var _height = (2 in _args && _args[2]) ? parseInt(_args[2]) : 450;
		var _reload = (3 in _args && _args[3]) ? true : false;
		
		$('<iframe/>')
			.attr('id', 'modalIframe')
			.attr('src', $(this).attr('href') + '?modal=1')
			.dialog({
				'title'	 : $(this).attr('title') ? $(this).attr('title') : $(this).text(),
				'width'	 : _width,
				'height' : _height,
				'modal'	 : true,
				'resizable' : false,
				'draggable' : false,
				'position'	: ['center', 100],
				'buttons' : {
					'Submit' : function()
					{
						// disable submit button
						var _submit = $('.ui-dialog-buttonpane button').prop( 'disabled', true ).addClass('ui-state-disabled');
						
						// release hold after 2 secs
						window.setTimeout(function()
						{
							_submit.prop( 'disabled', false ).removeClass('ui-state-disabled');
						}, 2000);
						
						$(this).contents().find('form :input.submit').trigger('click');
					},
					'Cancel' : function() { $(this).dialog('close'); }
				},
				'open' : function(ev, ui)
				{
					window.modalSubmitReload = _reload;
					window.closeDialog = function() { $('#modalIframe').dialog('close'); };
					$(this).parent().find('.ui-dialog-buttonpane button').blur();
				},
				'close' : function(ev, ui)
				{
					$(this).remove();
				},
				'autoOpen' : true
			})
			.width(_width)
			.height(_height);
		
		e.preventDefault();
	});


	//hover states on the static widgets
	$('.ui-button').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
	
	
	//Disable submit button after submitting the form
	disableFormSubmitButtons();

	if ($('#top_navigation').length) {
		$('#top_navigation').animateTopMenu();
	}
	
	// load actions to any quick search boxes
	$('#quickSearch').blur(function() {
		if ($(this).val() == '') {$(this).val('Unit Search') ;}
	});
	
	$('#quickSearch').focus(function() {
		if ($(this).val() == 'Unit Search') {$(this).val('');}
	});
	
	$("#addCategoryDialog").dialog({
		resizable: false,
		height: 210,
		width: 350,
		autoOpen: false,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Save': function() { 
				$('#categoryEditForm').submit();
			},
			Cancel: function() {
					$(this).dialog('close');
			}
		}
	});
	
	$("#deleteCategoryDialog").dialog({
		resizable: false,
		height: 133,
		width: 400,
		autoOpen: false,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Yes': function() { 
				$.ajax( {
			        url: "/portal/category/delete/moduleName/" + module + "/categoryId/" + categoryId, 
			        success: function(returnData) { 					
						$('#deleteCategoryDialog').dialog('close');
						
						if (module == 'el') {
							$.get("/portal/el/view-categories/",
								function(data){
									$('#EL-autoExpire-element').after($('#el-category-box').html(data));
									initELViewCategories();	
							});
							
							var moduleType = 'Visitor type';
						} else {
							$.get("/portal/category/index/moduleName/" + module,
								function(data){
								   $('#category-box').html(data);
							});
							
							var moduleType = 'Category';
						}
					
						$.gritter.add({
							title: 'Notice:',
							text: moduleType+' was deleted successfully',
							image: '/images/growl/notice.png',
							sticky: false, 
							time: 3000
							
						});
						
						enableSubmitButtons();					
			    	}
			       }    
			    )   
			},
			
			'No': function() {
					$(this).dialog('close');
			}
		}
	});	
	

		
	$("#postNewRequestDialog").dialog({
		resizable: false,
		width: 370,
		minHeight: 460,
		autoOpen: false,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Submit': function() { 
				$('#postNewServiceRequest').submit();
			},
			'Cancel': function() { 
				$('#postNewRequestDialog').dialog('close');
			}
		}
	});	

	// START help videos
	var dialogWindow = $(".tut-vid");
	var dialogLink   = $('.tut-link');
	$.each(dialogWindow, function () {
		$(this).dialog({
			resizable : false,
			width     : 650,
			autoOpen  : false,
			modal     : true,
			overlay   : {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});	
	});
	$.each(dialogLink, function () {
		$(this).click(function () {
			var windowToOpenName = $(this).attr('rel');
			var dialogWindow = $('#' + windowToOpenName);
			dialogWindow.dialog('open');
			return false;
		});
	});
	// END help videos

});
	
/**
 * Initialize entry log categories
 */
function initELViewCategories()
{
	$('.folder').mouseover(function() {
		$('.edit-icons-' + $(this).attr("ref")).show();			 
	});	

	$('.folder').mouseout(function() {		
		$('.edit-icons-' + $(this).attr("ref")).hide();		 
	});	

	$('.add-el-category, .edit-el-ategory').click(function() {
		id = $(this).attr("rel");
		var title = (id != 0) ? 'Edit Visitor Type' : 'Add Visitor Type';		
		addCategoryDialog(id, title, 'el');
	});	
	
	$('.delete-el-ategory').click(function() {
		id = $(this).attr("rel");
		deleteElCategoryDialog(id, 'el');
	});	
}

function showNewRequestDialog(id, title)
{
	postNewRequestDialog(0, title);
}

function postNewRequestDialog(mrId, newTitle)
{
	$('#postNewRequestDialog').dialog('open');
	if(!newTitle)
		title = 'Add a Service Request';		
	$("#postNewRequestDialog").dialog({ title: newTitle ? newTitle : title });	
	$.ajax( {
	        url: "/portal/mr/submit/mrId/" + mrId, 
	        success: function(returnData) { 
		        $('#postNewRequestDialog').html(returnData);		           
	    	}
	       }
	    )    
}

function submitServiceRequest(data)
{
	if (!data.success)  {
		var errors = '';

		jQuery.each(data.fail, function() {
			errors += this.message + '<br />';
		}
		);
	
		$('#mrError').html('<p class="ui-state-error form_error" style="display: block;"> ' + errors + ' </p>');

		enableSubmitButtons();
	} else {
		$('#mrError').html('');
		enableSubmitButtons();
		$('#postNewRequestDialog').dialog('close');	
			
		window.location.reload();
	}
}

/**
 * Unit search
 */
function unitSearch()
{	
	$("input.unit").autocomplete({
	    source: "/portal/units/search"
	});
}

/**
 * Unit search
 */
function unitSearch()
{	
	$("input.unit").autocomplete({
	    source: "/portal/units/search"
	});
}



// disable all submit buttons on dialogs function
function disableSubmitButtons() {
	var dialogButtons = $('.ui-dialog-buttonpane').find('button:first');

	dialogButtons.each(function () {
		$(this).prop('disabled', 'true');
		$(this).addClass('ui-state-disabled');
	});
}

// enable all submit buttons on dialogs function
function enableSubmitButtons() {
	var dialogButtons = $('.ui-dialog-buttonpane').find('button:first');

	dialogButtons.each(function () {
		$(this).removeClass('ui-state-disabled');
		$(this).prop('disabled', '');
	});
}



function addCategoryDialog(id, title, type) 
{
	categoryId = id;
	
	$('#addCategoryDialog').dialog('open');
	$("#addCategoryDialog").dialog({ title: title });	
	$.ajax( {
        url: "/portal/category/edit/moduleName/" + type + "/categoryId/" + categoryId, 
        success: function(returnData) { 
	        $('#addCategoryDialog').html(returnData);		   
    	}
       }
    )  
}

function deleteCategoryDialog(id, type)
{
	categoryId = id;
	module = type;
	
	$('#deleteCategoryDialog').dialog({title: 'Delete category'});
	$('#deleteCategoryDialog').html('Are you sure you want to delete this category?');
	$('#deleteCategoryDialog').dialog('open');
}

function deleteElCategoryDialog(id, type)
{
	categoryId = id;
	module = type;
	
	$('#deleteCategoryDialog').dialog({title: 'Delete visitor type'});
	$('#deleteCategoryDialog').html('Are you sure you want to delete this visitor type?');
	$('#deleteCategoryDialog').dialog('open');
}

function submitEditCategory(data) {
	if (!data.success)  {
		var errors = '';

		jQuery.each(data.fail, function() {
			errors += this.message + '<br />';
		});
	
		$('#category-error').html('<p class="ui-state-error form_error" style="display: block;"> ' + errors + ' </p>');

		enableSubmitButtons();
	} else { 
		$('#addCategoryDialog').dialog('close');
		
		if (data.module == 'el') {
			$.get("/portal/el/view-categories/",
				function(data){
					$('#EL-autoExpire-element').after($('#el-category-box').html(data));	
					initELViewCategories();
			});
		} else {
			$.get("/portal/category/index/moduleName/" + data.module,
				function(data){
				   $('#category-box').html(data);
			});	
		}
			
		
		$.gritter.add({
			title: 'Notice:',
			text: data.message,
			image: '/images/growl/notice.png',
			sticky: false, 
			time: 3000
			
		});
		
		enableSubmitButtons();
	}
}

function highlightTableRow()
{
	$('input:checkbox').click(function() {
		var isChecked =  $(this).is(':checked');

		if (isChecked == true) {
			$('input:checkbox:checked').parents("tr").addClass('highlight');
		} else {
			$('input:checkbox:not(:checked)').parents("tr").removeClass('highlight');
		}
	});
}

/**
* Initialize table data details (expandable row in a table)
*/
function initTableDataDetails()
{
	$('table.has-details td').not('table.has-details td.details, table.has-details td.info').attr('style', 'border-bottom: 0px;')

	//Slide down/up of content details
	$('table.has-details td').not('table.has-details td.not-clickable').click(function () { 
		var $this = $(this);
		
		$this.parent().find('td').attr('style', 'border-bottom: 0px; cursor: default; background-color: #FFFFFF;')
		$this.parent().next().find('div.details-data').slideToggle('slow', toggleRow);
		
		function toggleRow()
		{
			if ($this.parent().next().find('div.details-data').is(":visible") == true) {
				$this.parent().find('td').attr('style', 'border-bottom: 0px; cursor: default;');
			} else {
				$this.parent().find('td').attr('style', 'border-bottom: 0px; cursor: pointer;');
				$this.parent().find('td.details').attr('style', 'border-bottom: 0px; cursor: default;');
			}	
		}	
	});
}

/**
 * Replace plain URLs with links
 */
function linkify(text) 
{
    if (text) {
        text = text.replace(
            /(https?\:\/\/)|(www\.)?(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '" target="_blank">' + url + '</a>';
            }
        );
    }
    
    return text;
}

/**
 * Disable form submit buttons
 */
function disableFormSubmitButtons()
{
	$('form').submit(function() {
		$('input[type=submit]', this).attr('disabled', 'disabled').addClass('ui-state-disabled');
	});
}

/**
 * Enable form submit buttons
 */
function enableFormSubmitButtons()
{
	$('input[type=submit]').attr('disabled', false).removeClass('ui-state-disabled');
}

String.prototype.stripslashes = function()
{
	return this.replace(/\\'/g,'\'')
		.replace(/\\"/g,'"')
			.replace(/\\\\/g,'\\')
				.replace(/\\0/g,'\0');
};


	function showNotice(text_p) {
		$.gritter.add({
			title: 'Notice:',
			text: text_p,
			image: '/images/growl/notice.png',
			sticky: false,
			time: 3000
		});
	}


(function($) {
	$.fn.watermark = function(c, t) {
		var e = function(e) {
			var i = $(this);
			if (!i.val()) {
				var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
				i.replaceWith($c);
				$c.focus(function() {
					$c.replaceWith(i); setTimeout(function() {i.focus();}, 1);
				})
				.change(function(e) {
					i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
				})
				.closest('form').submit(function() {
					$c.replaceWith(i);
				});
			}
		};
		return $(this).live('blur change', e).change();
	};
})(jQuery);

