/**
 * 
 */
	// Ajax Search Request
	$(document).ready(function() {

		/* Get Industries */
		$.get('/jobs/ajaxServer.php?action=getIndustries', function(data) {
			$.each(data.cla, function(index) {
				industryType = $(this)[0];
//				if ((industryType.id == 54039) || (industryType.parent == 54039)) {
					if (industryType.parent == "0") {
						industryOptGroup = $('<optgroup>');
						industryOptGroup.attr('label', industryType.displayName);
						industryOptGroup.attr('value', industryType.id);
						$(industryOptGroup).append('<option value="' + industryType.id + '">All ' + industryType.displayName + ' Jobs</option>');
						$(industryOptGroup).append('<option disabled="disabled">-----</option>');
						$('#indId,#hjindId').append(industryOptGroup);
					} else {
						industryOpt = $('<option>' + industryType.displayName + '</option>');
						industryOpt.attr('value', industryType.id);
						$('optgroup[value=' + industryType.parent + ']').append(industryOpt);
					}
//				}
			});
			// Re-arrange order
			$('#indId').prepend($('#indId optgroup[value=54072]'));
			$('#hjindId').prepend($('#hjindId optgroup[value=54072]'));
			$('#indId').prepend($('#indId optgroup[value=54215]'));
			$('#hjindId').prepend($('#hjindId optgroup[value=54215]'));
			$('#indId, #hjindId').prepend('<option value="">All Positions</option>');
//			$('#indId').selectmenu();
			$('#indId-button').click(function() { $('#indId-menu').css('width',''); });
			dropdownReady('industries');

			window.setTimeout(function(){$('#indId, #hjindId').val('')}, 500);

			if (typeof(indIdDef) != 'undefined') {
				$('#indId, #hjindId').val(indIdDef);
			}
		});
	
		/* Get Locations */
		$.get('/jobs/ajaxServer.php?action=getLocations', function(data) {
			$('#locId,#hjlocId').append('<option value="">All Locations</option>');
			$.each(data.loc, function(index) {
				loc = $(this)[0];
				if (loc.parent == "0") {
					locOptGroup = $('<optgroup>');
					locOptGroup.attr('label', loc.displayName);
					locOptGroup.attr('value', loc.id);
					$(locOptGroup).append('<option value="' + loc.id + '">All ' + loc.displayName + ' Jobs</option>');
					$(locOptGroup).append('<option disabled="disabled">-----</option>');
					$('#locId,#hjlocId').append(locOptGroup);
				} else {
					locOpt = $('<option>' + loc.displayName + '</option>');
					locOpt.attr('value', loc.id);
					$('optgroup[value=' + loc.parent + ']').append(locOpt);
				}
			});
			if (typeof(locIdDef) != 'undefined') {
				$('#locId,#hjlocId').val(locIdDef);
			}
//			$('#locId').selectmenu();
			$('#locId-button').click(function() { $('#locId-menu').css('width',''); });
			dropdownReady('locations');
		})
	
		/* Get Work Types */
		$.get('/jobs/ajaxServer.php?action=getWorktypes', function(data) {
			$('#wtId, #hjwtId').append('<option value="">All Types</option>');
			$.each(data.wor, function(index) {
				workType = $(this)[0];
				if (workType.id != 54460) {
					workTypeOpt = $('<option>' + workType.displayName + '</option>');
					workTypeOpt.attr('value', workType.id);
					$('#wtId, #hjwtId').append(workTypeOpt);
				}
			});
			if (typeof(wtIdDef) != 'undefined') {
				$('#wtId, #hjwtId').val(wtIdDef);
			}
//			$('#wtId').selectmenu();
			$('#wtId-button').click(function() { $('#wtId-menu').css('width',''); });
			dropdownReady('worktypes');
		});

		/* Populate keyword field */
		if (typeof(keyDef) != 'undefined') {
			$('#keywords').val(keyDef);
		}

		// Subscribe Buttons
		$('.jobalertsbutton').click(function() {
			$('#jobAlertsDialog').dialog('open');
		});
		
		$('.getjobupdates').click(function() {
			$('#jobAlertsDialog').dialog('open');
		});

		// Clickable RSS feed url in job alerts dialog
		$('.rssFeedUrl').click(function(){
			window.location.href = $(this).val();
		});

		$('#jobAlertsDialog').dialog({
			modal: true,
			resizable:true,
			autoOpen:false,
			buttons: {
				'Subscribe': function() {
					var self = $(this);
					var form = $(this).find('form');

					$.ajax({
						url: form.attr('action'),
						async:false,
						data:form.serialize(),
						type: (form.attr('method')),
						dataType: 'json',
						success: function(data) {
							if (data.result == true) {
								alert('Subscription Successful!');
								self.dialog('close');
							} else {
								alert("Request Failed!\nReason: " + data.message);
							}
						}
					});
				}
			},
			width: '500px'
		});

		$('.emailthisjob').click(function() {
			$('#sendToFriendDialog').dialog('open');
		});
		
		$('#sendToFriendDialog').dialog({
			modal: true,
			resizable:true,
			autoOpen:false,
			buttons: {
				'Send to Friend': function() {
					self = $(this);
					form = $(this).find('form');

					if ((/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(form.find('#friend_email').val())) &&
							(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(form.find('#user_email').val()))) {
						$.ajax({
							url: form.attr('action'),
							async:false,
							data:form.serialize(),
							type: (form.attr('method')),
							dataType: 'json',
							success: function(data) {
								if (data.result == true) {
									alert('Send to friend Successful!');
									self.dialog('close');
								} else {
									alert('Send to friend Failed! Please check your details are correct!');
								}
							}
						});
					} else {
						alert('Please check the email addresses are valid!');
					}
				}
			},
			width: '525px'
		});
	});

	function uriSafe(str) {
		if (typeof(str) == 'string') {
			return encodeURIComponent(str.replace(/&amp;/gi, 'and').replace(/&/gi, 'and').replace(/#/gi, ' ')).replace(/%2F/gi, '/');
		} else {
			return '';
		}
	}

	readyDropdowns = {
			locations: false,
			worktypes: false,
			industries: false
		}
	function dropdownReady(name) {
		switch (name) {
			case 'locations':
				readyDropdowns.locations = true;
				break;
			case 'worktypes':
				readyDropdowns.worktypes = true;
				break;
			case 'industries':
				readyDropdowns.industries = true;
				break;
			default:
				// return ready status
				if (readyDropdowns.locations && readyDropdowns.worktypes && readyDropdowns.industries) {
					return true;
				} else {
					return false;
				}
				break;
		}

		if (readyDropdowns.locations && readyDropdowns.worktypes && readyDropdowns.industries) {
			/* Search Jobs Button */

			$('.searchforjobsbutton').click(function() {
				// If on job search results page then refresh job search results view
				if ($('#jobSearchResults').size()) {
					// Reset Page Numbers
					currentPage = 0;
					resultsPerPage = 0;
					paginationGen = false;
					// Call Search
					searchJobs();
				} else { // If on any other page, then take to search results page

					// Grab all drop down values
					selectedIndLabel	= $('#indId option:selected').text();
					selectedIndValue	= $('#indId').val();
					selectedLocLabel	= $('#locId option:selected').text();
					selectedLocValue	= $('#locId').val();
					selectedWtLabel		= $('#wtId option:selected').text();
					selectedWtValue		= $('#wtId').val();

					// build search URL
					searchUrl = '/hot-jobs/';
					searchUrl += ($('#indId').val() ? 'Industry/' + uriSafe(selectedIndLabel) + '/' + selectedIndValue + '/':'');
					searchUrl += ($('#locId').val() ? 'Location/' + uriSafe(selectedLocLabel) + '/' + selectedLocValue + '/':'');
					searchUrl += ($('#wtId').val() ? 'WorkType/' + uriSafe(selectedWtLabel) + '/' + selectedWtValue + '/':'');
					if ($('#keywords').val() == "Enter Keywords") {
						$('#keywords').val('');
					}
					searchUrl += ($('#keywords').val() ? 'Keywords/' + uriSafe($('#keywords').val()) + '/':'');

					document.location = searchUrl;
				}
			});

			// Back button search
			if (typeof($.deparam.fragment().locId) != 'undefined') {
				$('#indId').val(fragments.indId);
				$('#locId').val(fragments.locId);
				$('#wtId').val(fragments.wtId);
				$('#keywords').val(fragments.keywords);
				currentPage = parseInt(fragments.currentPage);
				paginationGen = false;
				searchJobs();
			}
		}
	}

