﻿(function($)
{
	jQuery.fn.populate = function(settings)
	{
		var config =
		{
			"requestType": "GET",
			"begin": 0,
			"end": 19,
			"currentPage": 0,
			"cache": false,
			"paginationSelector": "div.pagination",
			"jobTitleSelector": "div#jobTitle",
			"jobDescriptionSelector": "div#description",
			"jobQualificationsSelector": "div#qualifications",
			"sortHandler": "postDateDescending",
			"scrollToTop": true,
			"searchQueryFilterURL": "/careers/layouts/searchquerybyfilter.aspx",
			"jsonRequestURL": "/careers/layouts/JSONRequest.aspx",
			"videoMarkupURL": "/careers/Layouts/VideoMarkup.aspx",
			"enableSort": true
		};

		if(settings)
		{
			jQuery.extend(config, settings);
		}
		
		this.each(function()
		{
			// Assign object reference
			obj = jQuery(this);
			
			// Scroll the window to the top
			if(config.scrollToTop == true)
			{
				window.scroll(0, 0);
			}
			
			if(config.cache == false)
			{
				// Build from the filters
				queryString = buildQueryString(jQuery.filters);
				
				// If the hidden query input exists, update its value with the queryString value we just built
				if(jQuery("input.query").length > 0)
				{
					jQuery("input.query").val(queryString);
				}

				// Get the data set.
				jQuery.ajax(
				{
					type: config.requestType,
					url: config.searchQueryFilterURL,
					dataType: "json",
					data: queryString,
					beforeSend: function()
					{
					    obj.html("<div class=\"loadingDiv\"><div><img src=\"/~/media/Careers/Images/Icons/ajax-loader-teal.ashx\" alt=\"Loading...\" title=\"Loading...\" border=\"0\" /></div><b>Loading</b></div>");
					},
					success: function(data, textStatus)
					{
						if(config.enableSort == true)
						{
							// Get the resource and sort it
							switch(config.sortHandler)
							{
								case "postDateAscending":
									jQuery.dataResource = data.sort(postDateAscending);
								break;
								
								case "jobTitleAscending":
									jQuery.dataResource = data.sort(jobTitleAscending);
								break;
								
								case "jobTitleDescending":
									jQuery.dataResource = data.sort(jobTitleDescending);
								break;
								
								case "locationAscending":
									jQuery.dataResource = data.sort(locationAscending);
								break;
								
								case "locationDescending":
									jQuery.dataResource = data.sort(locationDescending);
								break;
								
								case "organizationNameAscending":
									jQuery.dataResource = data.sort(organizationNameAscending);
								break;
								
								case "organizationNameDescending":
									jQuery.dataResource = data.sort(organizationNameDescending);
								break;
								
								default:
									jQuery.dataResource = data.sort(postDateDescending);
								break;
							}
						}
						else
						{
							jQuery.dataResource = data;
						}
						
						// Set up searching within type
						var searchingWithinText = new String();
						
						// Check to see if the filter has a free text value entered. This will be the first thing to be tracked.
						if(jQuery.filters.Free_Text != undefined)
						{
							// Append the free text value
							searchingWithinText += "<b>Query:</b> <span id=\"currentQueryString\">" + urldecodeSpecialChars(jQuery.filters.Free_Text) + "</span>&nbsp;&nbsp;&nbsp;";
						}
						
						// Deal with the Region
						if(jQuery.filters.Region != "All" && jQuery.filters.Region != undefined)
						{
							searchingWithinText += "<b>Region:</b> <span id=\"regionString\">" + urldecodeSpecialChars(jQuery.filters.Region) + "</span>&nbsp;&nbsp;&nbsp;";
						}
						
						// Selectively declare the location
						if(typeof(jQuery.filters.Location) != "object")
						{
							searchingWithinText += "<b>Location:</b> <span id=\"locationString\">" + urldecodeSpecialChars(jQuery.filters.Location) + "</span>&nbsp;&nbsp;&nbsp;";
						}
						else if((jQuery.filters.Country == undefined && jQuery.filters.StateProvinceCode == undefined && jQuery.filters.City == undefined))
						{
							searchingWithinText += "<b>Location:</b> <span id=\"locationString\">All Countries</span>&nbsp;&nbsp;&nbsp;";
						}
						else if(jQuery.filters.Country == undefined && (jQuery.filters.StateProvinceCode != undefined || jQuery.filters.City != undefined))
						{
							// Set region label to North America
							searchingWithinText += "<b>Region:</b> <span id=\"regionString\">North America</span>&nbsp;&nbsp;&nbsp;";
							
							// Various city/state hooks...
							if(jQuery.filters.City != undefined)
							{
								// Append the city to begin with
								searchingWithinText += "<b>Location:</b> <span id=\"locationString\">" + urldecodeSpecialChars(jQuery.filters.City);
								
								// Add the state code if it's defined
								if(jQuery.filters.StateProvinceCode != undefined)
								{
									searchingWithinText += ", " + urldecodeSpecialChars(jQuery.filters.StateProvinceCode);
								}
								
								// Add the separator
								searchingWithinText += "</span>&nbsp;&nbsp;&nbsp;";
							}
							else if(jQuery.filters.City == undefined && jQuery.filters.StateProvinceCode != undefined)
							{
								searchingWithinText += "<b>Location:</b> <span id=\"locationString\">" + urldecodeSpecialChars(jQuery.filters.StateProvinceCode) + "</span>&nbsp;&nbsp;&nbsp;";
							}
							else
							{
								searchingWithinText += "<b>Location:</b> <span id=\"locationString\">Nationwide</span>&nbsp;&nbsp;&nbsp;";
							}
						}
						else
						{
							searchingWithinText += "<b>Location:</b> <span id=\"locationString\">" + urldecodeSpecialChars(jQuery.filters.Country) + "</span>&nbsp;&nbsp;&nbsp;";
						}
						
						// Time to loop through the rest of the filters!
						for(var x in jQuery.filters)
						{
							// Make sure we're not dealing with the previous fields we've dealt with before
							if(x != "Free_Text" && x != "Country" && x != "City" && x != "StateProvinceCode" && x != "Location" && x != "Region")
							{
								// Begin a temporary string
								var tempSearchString = new String();
								
								// Check the type of this index. If it's an array/object, we'll cycle through that as needed
								if(typeof(jQuery.filters[x]) == "object")
								{
									// If this object doesn't have an "All" value of true, let's loop through it. Otherwise we're just going to leave it be.
									if(jQuery.filters[x].All != true)
									{
										// Begin the string
										tempSearchString = "<b>" + x.replace("_", " ") + "</b>: ";
										
										// We'll need to cycle through this object's children
										for(var y in jQuery.filters[x])
										{
											// If this selection is turned on...
											if(jQuery.filters[x][y] == true)
											{
												tempSearchString += y + ", ";
											}
										}
										
										// Truncate the last comma/space if it exists
										if(tempSearchString.substr((tempSearchString.length - 2), 2) == ", ")
										{
											tempSearchString = tempSearchString.substr(0, (tempSearchString.length - 2)) + "&nbsp;&nbsp;&nbsp;";
										}
										
										// Add the temp search string to the master text
										searchingWithinText += tempSearchString;
									}
								}
								else if(typeof(jQuery.filters[x]) == "string")
								{
									// If the value isn't "All", go ahead and append it to our string
									if(jQuery.filters[x] != "All")
									{
										searchingWithinText += "<b>" + x.replace("_", " ") + "</b>: " + jQuery.filters[x] + "&nbsp;&nbsp;&nbsp;";
									}
								}
							}
						}
						
						// Populate the free text span
						jQuery("div.searchTerms").html(urldecodeSpecialChars(searchingWithinText));
						
						// Print the data to the results table
						printData(config.populateMode);
						
						// Print special video related markup
						if(jQuery.dataResource.length > 0)
						{
							// Get the related markup
							jQuery.ajax(
							{
								type: config.requestType,
								url: config.videoMarkupURL,
								dataType: "html",
								data:
								{
									id: jQuery.dataResource[0].CN
								},
								success: function(data, textStatus)
								{
								    if(data != "false")
								    {
									    // Remove the old ourBusinesses div...
									    jQuery("div.ourBusinesses").remove();
    									
									    // Add the new one
									    jQuery("div#custom-doc").after(data);
									}
								}
							});
						}
					}
				});
			}
			else
			{
				if(config.enableSort == true)
				{
					switch(config.sortHandler)
					{
						case "postDateAscending":
							jQuery.dataResource = jQuery.dataResource.sort(postDateAscending);
						break;
						
						case "jobTitleAscending":
							jQuery.dataResource = jQuery.dataResource.sort(jobTitleAscending);
						break;
						
						case "jobTitleDescending":
							jQuery.dataResource = jQuery.dataResource.sort(jobTitleDescending);
						break;
						
						case "locationAscending":
							jQuery.dataResource = jQuery.dataResource.sort(locationAscending);
						break;
						
						case "locationDescending":
							jQuery.dataResource = jQuery.dataResource.sort(locationDescending);
						break;
						
						case "organizationNameAscending":
							jQuery.dataResource = jQuery.dataResource.sort(organizationNameAscending);
						break;
						
						case "organizationNameDescending":
							jQuery.dataResource = jQuery.dataResource.sort(organizationNameDescending);
						break;
						
						default:
							jQuery.dataResource = jQuery.dataResource.sort(postDateDescending);
						break;
					}
				}
				
				// Print the data to the results table
				printData(config.populateMode);
			}
			
			function printData(mode)
			{
				// Unbind all previously bound events
				jQuery("div.resultText, a.saveJob, a.findSimilarJobs").unbind();
				
				// Initialize results markup string
				var resultsString = new String();
				
				// Fill up the table
				for(var i = config.begin; i < config.end; i++)
				{
					// Only print results if its array index exists.
					if(jQuery.dataResource[i] != undefined)
					{
						// Begin this pass
						resultsString += "<div class=\"searchResult\">";
						resultsString += "<div class=\"resultText\">";
						
						// Determine if we need to print the save icon
						if(jQuery.dataResource[i].Sv == "True")
						{
							resultsString += "<img class=\"saveIcon\" src=\"/~/media/Careers/Images/Icons/icon_savedjobs.ashx\" alt=\"Saved\" title=\"Saved\" border=\"0\" />&nbsp;";
						}
						
						resultsString += "<a class=\"jobTitle\" href=\"" + jQuery.dataResource[i].URL + "\">" + jQuery.dataResource[i].T + " <i>(" + jQuery.dataResource[i].CN + ")</i>" + "</a><br />";
						resultsString += "<span class=\"jobData\">";
						
						// Shift string handler
						if(jQuery.dataResource[i].S == "")
						{
							resultsString += "Unknown Shift";
						}
						else
						{
							resultsString += jQuery.dataResource[i].S;
						}
						
						resultsString += " ";
						
						// City string handler
						if(jQuery.dataResource[i].Ci == "" || jQuery.dataResource[i].Ci == "null" || jQuery.dataResource[i].Ci == undefined)
						{
							// Nothing
						}
						else
						{
							resultsString += jQuery.dataResource[i].Ci + ", ";
						}
						
						// State/Province string handler
						if(jQuery.dataResource[i].SP == "" || jQuery.dataResource[i].SP == "null" || jQuery.dataResource[i].SP == undefined)
						{
							// Nothing
						}
						else
						{
							resultsString += jQuery.dataResource[i].SP;
						}
						
						// Finish up the resultsString for this pass
						resultsString += "</span>";
						resultsString += "<br />";
						resultsString += "<span class=\"jobPostedOn\">Job Posting: " + jQuery.dataResource[i].ODE + "</span>";
						resultsString += "</div>";
						resultsString += "<div class=\"quickLookIcon\">";
						resultsString += "Quick Look";
						resultsString += "<div class=\"quickLook " + jQuery.dataResource[i].CN + "\">";
						resultsString += "<div class=\"leftCap\">";
						resultsString += "<div class=\"jobTitle\"><a class=\"jobTitle\" href=\"" + jQuery.dataResource[i].URL + "\">" + jQuery.dataResource[i].T + "</a></div>";
						resultsString += "<div class=\"jobCreationDate\">Posted " + jQuery.dataResource[i].ODE + "</div>";
						resultsString += "<div class=\"separatorRule\"></div>";
						resultsString += "<div>";
						resultsString += "<div class=\"jobLocation\">";
						resultsString += "<b>Region:</b> " + jQuery.dataResource[i].R;
						resultsString += "<br />";
						
						if(jQuery.dataResource[i].C != "" && jQuery.dataResource[i].C != "null" && jQuery.dataResource[i].C != undefined)
						{
							resultsString += "<b>Country:</b> " + jQuery.dataResource[i].C;
						}
						
						resultsString += "</div>";
						resultsString += "<div class=\"jobLocation\">";
						
						if(jQuery.dataResource[i].SP != "" && jQuery.dataResource[i].SP != "null" && jQuery.dataResource[i].SP != undefined)
						{
							resultsString += "<b>State/Province:</b> " + jQuery.dataResource[i].SP + "<br />";
						}
						
						if(jQuery.dataResource[i].Ci != "" && jQuery.dataResource[i].Ci != "null" && jQuery.dataResource[i].Ci != undefined)
						{
							resultsString += "<b>City:</b> " + jQuery.dataResource[i].Ci;
						}
						
						resultsString += "</div>";
						resultsString += "</div>";
						resultsString += "<p class=\"jobDescription\">Loading...</p>";
						resultsString += "<img src=\"/~/Media/Careers/Images/Icons/icon_arrow_whitebkg.ashx\" width=\"8\" height\"7\" />&nbsp;<a href=\"" + jQuery.dataResource[i].URL + "\">Learn More</a><br />";
						resultsString += "<div class=\"separatorRule\"></div>";
						resultsString += "<div class=\"clickToApply\"><a href=\"" + jQuery.dataResource[i].AURL + "\" onclick=\"javascript:pageTracker._link(this.href);return false;\"><img src=\"/~/media/Careers/Images/Buttons/btn_clickheretoapply_teal.ashx\" alt=\"Click here to Apply\" title=\"Click here to Apply\" width=\"172\" height=\"24\" border=\"0\" /></a></div>";
						
						// Only show this if the job hasn't been saved.
						if(jQuery.dataResource[i].Sv == "False")
						{
							resultsString += "<img src=\"/~/Media/Careers/Images/Icons/icon_arrow_whitebkg.ashx\" width=\"8\" height\"7\" />&nbsp;<a class=\"saveJob\" href=\"javascript:void(0);\">Save This Job</a><br />";
						}
						
						resultsString += "<img src=\"/~/Media/Careers/Images/Icons/icon_arrow_whitebkg.ashx\" width=\"8\" height\"7\" />&nbsp;<a class=\"findSimilarJobs\" href=\"javascript:void(0);\">Search for Similar Jobs</a><br />";
						resultsString += "<span class=\"jobFunction\" style=\"display: none;\">" + jQuery.dataResource[i].F + "|" + jQuery.dataResource[i].SPC + "</span>";
						resultsString += "</div>";
						resultsString += "<div class=\"rightCap\">&nbsp;</div>";
						resultsString += "</div>";
						resultsString += "</div>";
						resultsString += "</div>";
					}
				}
				
				// Populate target element
				obj.html(resultsString);
				
				// Bind mouseover events for the quick look elements
				jQuery("div.quickLookIcon").mouseenter(function()
				{
					// Show the quicklook.
					jQuery(this).children("div.quickLook").show();
					
					// Get the quicklook class
					var quickLookClass = jQuery(this).children("div.quickLook").attr("class");
					
					// Split the class string
					var quickLookClassArr = quickLookClass.split(" ");
					
					// Get the contest number
					var contestNumber = quickLookClassArr[1];
					
					if(jQuery(this).children("div.quickLook").children("div.leftCap").children("p.jobDescription").text() == "Loading...")
					{
						// Get the quicklook description
						jQuery.ajax(
						{
							type: "GET",
							url: "/careers/layouts/searchquerybyfilter.aspx",
							dataType: "json",
							data: "Quicklook=true&Contest%20Number=" + contestNumber,
							success: function(data, textStatus)
							{
								// Populate the description
								jQuery("div." + contestNumber).children("div.leftCap").children("p.jobDescription").html(data[0].SDe);
							}
						});
					}
				}).mouseleave(function()
				{
					jQuery(this).children("div.quickLook").hide();
				});
				
				// Bind our Save Job and Search Similar Jobs events
				jQuery("a.saveJob").click(function()
				{
					// Get the class number of the quicklook tooltip.
					var elementClassString = jQuery(this).parent("div.leftCap").parent("div.quickLook").attr("class");
					
					// Split the string into an array
					var elementClassArr = elementClassString.split(" ");
					
					// Save the job
					jQuery.ajax(
					{
						type: "GET",
						url: config.jsonRequestURL,
						dataType: "text",
						data: "SaveJob=true&Contest%20Number=" + elementClassArr[1],
						success: function(data, textStatus)
						{
							if(data == "true")
							{
								// Insert the saved jobs icon
								jQuery("div." + elementClassArr[1]).parent("div.quickLookIcon").prev("div.resultText").prepend("<img class=\"saveIcon\" src=\"/~/media/Careers/Images/Icons/icon_savedjobs.ashx\" alt=\"Saved\" title=\"Saved\" border=\"0\" />&nbsp;");
								jQuery("div." + elementClassArr[1]).children("div.leftCap").children("a.saveJob").unbind().text("Job Saved!");
								
								// Increment the saved jobs count
								var savedJobCount = Number(jQuery("strong#savedJobContent").text());
								savedJobCount++;
								jQuery("strong#savedJobContent").text(savedJobCount);
							}
						}
					});
				});
				
				jQuery("a.findSimilarJobs").click(function()
				{
					// Get the jobFunction text
					var functionText = jQuery(this).parent("div.leftCap").children("span.jobFunction").html();
					
					// Split the text into an array
					var functionTextArr = functionText.split("|");
					
					// Manually build filters
					jQuery.filters.StateProvinceCode = functionTextArr[1];
					
					// Delete the city filter if it exists
					if(jQuery.filters.City != undefined)
					{
						delete jQuery.filters.City;
					}
					
					// Blank out the job filter
					jQuery.filters.Job_Field = {};
					
					// Establish the job filter for the similar job search
					jQuery.filters.Job_Field[functionTextArr[0]] = true;
					
					// We need to make sure this gets checked and logged in our session
					var checkBoxQueryString = "Job%20Field=" + urlencodeSpecialChars(functionTextArr[0]);
					
					// Blank out all checkboxes in the job field filters div
					jQuery("div.Job_Field input[type=checkbox]").attr("checked", false);
					
					// Check to see if this checkbox exists on the non modal level
					if(jQuery("input[value=" + functionTextArr[0] + "]").length > 0)
					{
						jQuery("input[value=" + functionTextArr[0] + "]").attr("checked", true);
					}
					
					// Run populate
					jQuery("div#resultsTable").populate();
					
				});
				
				// Populate the pagination
				jQuery(config.paginationSelector).paginate({currentPage: config.currentPage});
				
				// Run bgiframe on the quicklook floating layers if we're in IE6.
				if(jQuery.browser.msie == true && jQuery.browser.version == "6.0")
				{
					jQuery("div.quickLook div.leftCap").bgiframe();
				}
			}
		});
		
		return this;
	};
})(jQuery);