$(document).ready(function() {
	//never cache ajax content
	$.ajaxSetup({ cache: false });

	//hide the ajax processing message
	$('#ajax').hide();
	
	//setup default responders for showing msgs while processing the ajax queue
	$('#ajax').ajaxStart(function() {
		if ($(window).width() < 768) {
			$('#ajax').find('.ajax-overlay').css({
				width: $(window).width()+'px',
				height: ((window.innerHeight)?window.innerHeight:$(window).height())+'px'				
			});
			$('#ajax').css({ top: $('body').scrollTop()+'px' }).show();
		} else {
			$('#ajax').fadeIn('slow');
		}
	}).ajaxStop(function() {
		if ($(window).width() < 768) {
			$('#ajax').stop(true, true).hide();
		} else {
			$('#ajax').fadeOut('fast');
		}		
	});
	
	//scroll the ajax overlay with the window on mobile
	$(window).scroll(function() {
		if ($(window).width() < 768) {
			$('#ajax:visible').find('.ajax-overlay').css({
				width: $(window).width()+'px',
				height: ((window.innerHeight)?window.innerHeight:$(window).height())+'px'				
			});
			$('#ajax').css({ top: $('body').scrollTop()+'px' });
		}
	});
	
	//create a numeric enforcer
	$('input.numeric').live('keydown', function (e) { 
		var key = e.charCode || e.keyCode || 0;
		// allow backspace, tab, delete, arrows, period, negative, numbers and keypad numbers ONLY
		return (
			key == 8 || 
			key == 9 ||
			key == 46 ||
			(key >= 37 && key <= 40) ||
			(key >= 48 && key <= 57) ||
			(key >= 96 && key <= 105) ||
			key == 109 ||
			key == 110 ||
			key == 189 ||
			key == 190			
		);
	});

	//setup report inbox
	$('#reportsInbox .reportsInbox-toggle').live('click', function() {
		reportsToggle();
	});
	
	//setup pnav accordion
	$('#accordion').accordion({ autoHeight: false });

	//switch the layout when resizing the window
	$(window).resize(adjustLayout);
	
	//run the resize at startup to make sure we update if already on a mobile device
	adjustLayout();
	
	//rebuild autocomplete features for mobile
	mobileAutocomplete();
});

/* MOBILE LAYOUT REARRANGE ON RESIZE / ORIENTATION CHANGE ================== */

var adjustLayout = function() {
	if ($(window).width() < 768) {
		//if small move the global nav to the footer and company info to the end of the footer
		$('#gnav').insertBefore($('#fnav'));
		$('#companyInfo').insertAfter($('#fnav'));		
	} else {
		//if large move the global nav to the header and company info to the start of the footer
		$('#gnav').appendTo($('#header .eightcol'));
		$('#companyInfo').appendTo($('#footer .eightcol:first-child'));
	}
}

/* AUTOCOMPLETE FUNCTIONS ================================================== */

var autocompleteClick = function() {
	if ($(this).hasClass('run')) {
		$(this).blur();
		runMobileAutocomplete($(this));
	} else {
		var _this = this;
		$('input.mobileSuggest').remove();
		$('<input/>', { type:'button', value:'Search' })
			.addClass('mobileSuggest')
			.click(function() {
				runMobileAutocomplete($(_this));
			})
			.insertAfter($(this));
	}
	return false;
}

var runMobileAutocomplete = function(src) {
	var parent = $(src);
	
	if (parent.hasClass('run')) {
		parent
			.val('')
			.trigger('autocompleteselect', {item: null})
			.trigger('autocompletechange', {item: null});
	}
	
	if (parent.val().length >= 2 || parent.hasClass('run')) {
		if (parent.hasClass('multiAutoComplete')) {
			var url = parent.attr('source');
		} else {
			var url = parent.autocomplete('option', 'source');
		}
		$.get(url, { term: parent.val() }, function(data, status, xhr) {
			var obj = $.parseJSON(data);			
			if (obj && obj.length) {				
				var newSelect = $('<select />')
					.addClass('mobileSuggest')
					.css({ display:($(window).width() < 768)?'block':'inline' });

				newSelect.append($('<option />', { value: '', text: obj.length + ' Matches' }));
				_(obj).each(function(rec, i) {
					newSelect
						.append(
							$('<option />', { value: rec.label, text: rec.label })
								.data('ui', rec)
						);
				});
				
				parent.hide();
				$('input.mobileSuggest').remove();
				
				newSelect
					.change(function() {
						parent
							.trigger('autocompleteselect', {item: $(this).find('option:selected').eq(0).data('ui')})
							.trigger('autocompletechange', {item: $(this).find('option:selected').eq(0).data('ui')})
							.val($(this).val())
							.show();
						$('.mobileSuggest').remove();
					})
					.insertAfter(parent)
					.click();
			}
		});
	} else {
		$('.mobileSuggest').remove();
		showDialog('Please enter 2 or more characters.', 'notice');
	}

	return false;
}

var mobileAutocomplete = function() {
	if (isMobile) {
		//change all autocompletes to select boxes
		$('input.suggest').hide();
		$('input[autocomplete]')
			.autocomplete('disable')			
			.unbind('blur')
			.unbind('click')
			.unbind('focus')
			.unbind('keydown')
			.unbind('keypress')
			.unbind('remove')
			.bind('click', autocompleteClick);
			
		//make form load an integrated section at the top of the form, instead of an overlay
		if ($(window).width() < 768) {
			$('.loadOverlay').each(function(i, elm) {
				$(this).insertAfter($(this).closest('.formContainer').find('.formTools .loadBtn'));
			});
		}
			
		//additional work on form clear to remove extra mobile suggest elements
		$('.formTools').find('.loadBtn, .saveBtn, .clearBtn, .deleteBtn')
			.unbind('click.mobileautocomplete')
			.bind('click.mobileautocomplete', function() {
				$(this).closest('div.formContainer').find('input[autocomplete]').show();
				$(this).closest('div.formContainer').find('.mobileSuggest').remove();
			});			

		//additional work on tab clear to remove extra mobile suggest elements
		$('.formBtns input[value="Clear"]')
			.unbind('click.mobileautocomplete')
			.bind('click.mobileautocomplete', function() {
				$(this).closest('div.formContainer').find('input[autocomplete]').show();
				$(this).closest('div.formContainer').find('.mobileSuggest').remove();
			});
	}
}

/* REFRESH FUNCTIONS ======================================================= */

function eventsLoad(widget, widgetPkey, today) {
	$.post('/widgets/events.php', { submit: true, widget_pkey: widgetPkey, today: today }, function(data) {
		//widget.find(settings.contentSelector).html(data);
		$(widget).find('.widget-content').html(data);
	});	
}

/* HELPER FUNCTIONS ======================================================== */

//add a chainable jQuery function to apply input masks
jQuery.fn.applyMasks = function() {
	//apply all masks on the form
	this.find('input[mask]').each(function(i, elm) {
		jQuery(elm).mask(jQuery(elm).attr('mask'));
	});
	
	return this;
}

//add a javascript string trim
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

// a class to provide GUIDs, GUID.generate() anywhere in the code to access
var GUID = new function() {
	this.s4 = function() {
		return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	};
	this.generate = function() {
		return (this.s4()+this.s4()+"-"+this.s4()+"-"+this.s4()+"-"+this.s4()+"-"+this.s4()+this.s4()+this.s4());
	}
};

// simple function to handle google analytic tracking
var gaTrack = function(page) {
	try {
		pageTracker._trackPageview(page);
	} catch(err) {}
} 

/* SCHEDULED STATUS / REFRESH UPDATES ====================================== */

var reportsOpen = function() {
	//reportsRefresh();
	if ($(window).width() < 768) {
		$('body').animate({ scrollTop: 0 }, 'slow', function() {
			$('#reportsInbox').slideDown();
		});		
	} else {
		if ($('#reportsInbox:visible').length == 0) {
			$('#reportsInbox').css({ width: '230px' }).show(); 
			$('#reportsInbox .reportsInbox-toggle').click();
		} else if ($('#reportsInbox .reportsInbox-content:visible').length == 0) {
			$('#reportsInbox .reportsInbox-toggle').click();
		}
	}
}

var reportsClose = function() {
	if ($(window).width() < 768) {
		$('#reportsInbox').slideUp();
	} else {
		if ($('#reportsInbox:visible').length == 1) {
			$('#reportsInbox').fadeOut('slow', function() {
				$('#reportsInbox .reportsInbox-content').hide();
				$('#reportsInbox').css({ width: '230px' });
			});
		}
	}
}

var reportsToggle = function() {
	if ($('#reportsInbox .reportsInbox-content:visible').length) {
		$('#reportsInbox .reportsInbox-content').slideUp(function() {
			$('#reportsInbox').animate({ width:'230px'}, 'fast');
		});						
	} else {
		$('#reportsInbox').animate({ width:'100%'}, 'fast', function() {
			$('#reportsInbox .reportsInbox-content').slideDown();
		});			
	}
}

var reportsRefresh = function(delay) {
	var d = 0;
	if (typeof(delay) != 'undefined') {
		d = delay;
	}
	
	setTimeout(function() {
		var isVisible = $('#reportsInbox .reportsInbox-content:visible').length;
		$.ajax({
			url: '/reports.php',
			global: false,
			success: function(data, status, xhr) {
				$('#reportsInbox').html(data);				
				if (isVisible) {
					$('#reportsInbox .reportsInbox-content').show();
				}
				
				$('.reportsInboxTableStack').remove();
				if ($(window).width() < 768) {
					$('#reportsInbox h1').insertBefore($('#reportsInbox .reportsInbox-close'));		

					$('#reportsInbox table.grid').each(function(i, grid) {
						$(grid).hide();
						
						//convert widget tables into stacks on the fly
						var newTable = $('<table/>')
							.css({ width: '100%' })
							.addClass('reportsInboxTableStack')
							.insertAfter($(grid));
						
						//loop over each row in the master table
						$(grid).find('tbody tr').each(function(i, row) {
							var newTr = $('<tr/>')
								.appendTo(newTable);
							var newTd = $('<td/>')
								.css({ padding: '10px 0px', borderBottom: '1px solid #ccc' })
								.appendTo(newTr);						
								
							//loop over reach cell in the master table
							$(row).find('td').each(function(i, cell) {
								newTd.append('<strong>' + $(grid).find('thead th').eq(i).html() + ':</strong> ' + $(cell).html()+'<br/>');
							});					
						});					
					});			
				} else {
					$('#reportsInbox h1').insertAfter($('#reportsInbox .reportsInbox-refresh'));
					
					$('#reportsInbox table.grid').each(function(i, grid) {
						$(grid).show();
					});
				}
			}
		});
	}, d);
}
reportsRefresh();

var reportsDelete = function(pkey) {
	$.get('/reports/_report_delete.php', { pkey: pkey }, function(data, status, xhr) {
		reportsRefresh();
	});
}

var reportsPollPkeys = [];
var reportsPoll = function(check) {
	if (!doPolls) { return; }
	
	if (check) {
		$.ajax({
			url: '/_queries/report_inbox_poll.php',
			global: false,
			success: function(data, status, xhr) {
				var obj = $.parseJSON(data);
				if (obj && obj.length) {
					var notify = false;
					_(obj).each(function(rec) {
						if (_.indexOf(reportsPollPkeys, rec.pkey) == -1) {
							notify = true;
							reportsPollPkeys.push(rec.pkey);
						}
					});
					if (notify) {
						reportsRefresh();
						if ($(window).width() < 768) {
							showDialog('New reports are available.');
						} else {
							if ($('#reportsInbox:visible').length == 0) {							
								$('#reportsInbox').css({ width: '230px' }).slideDown().effect('shake', { direction:'left', distance: 5, times: 3 }, 300); 
							}
						}
					}
				}
			}
		});
	}
	
	setTimeout(function() {
		reportsPoll(true);
	}, 60000); // 1 min
}
//wait 5 seconds before running it the first time
setTimeout(function() { reportsPoll(true); }, 5000);

var systemPoll = function(check) {
	if (!doPolls) { return; }
	
	if (check) {
		$.ajax({
			url: '/_queries/system_poll.php',
			global: false,
			success: function(data, status, xhr) {
				var obj = $.parseJSON(data);
				if (obj && obj.length == 1) {
					if (obj[0].seedware_web_status == 0) {
						location.href = '/logout.php';						
					}
				}
			}
		});
	}
	
	setTimeout(function() {
		systemPoll(true);
	}, 900000); //15 min
};
systemPoll(false);
