﻿// when a user changes the sort by field
function OnChangeSort(destinationUrl, paramName, sortBy)
{
	var paramIndex = destinationUrl.indexOf(paramName);
	
	// trim out old sortby value
	var paternSort = /&sortBy=(\w+\b)/;
	var paternSort2 = /sortBy=(\w+\b)/;
	
	destinationUrl = destinationUrl.replace(paternSort, '');
	destinationUrl = destinationUrl.replace(paternSort2, '');
	
	// remove any paging logic, as sorting should start over
	var paternPage = /&page=(\w+\b)/;
	var paternPage2 = /page=(\w+\b)/;
	destinationUrl = destinationUrl.replace(paternPage, '');
	destinationUrl = destinationUrl.replace(paternPage2, '');
	
	if (destinationUrl.indexOf('?') != -1)
	{
		window.location.href = destinationUrl + '&' + paramName + '=' + sortBy;
	}
	else
	{
		window.location.href = destinationUrl + '?' + paramName + '=' + sortBy;
	}
	
	return false;
}

// when a user initiates a keyword search
function OnSearchKeyword(destinationUrl, paramName, textBoxId)
{
	var txtInput = $(textBoxId);
	var txtValue = txtInput.value;
	var paramIndex = destinationUrl.indexOf(paramName);
	
	// make sure they're not searching for the default text
	var isDefaultText = (Object.isUndefined(txtInput.defaultText))	? false : (txtValue == txtInput.defaultText);
	if(txtValue == '' || isDefaultText){
		alert('Please enter your search criteria.');
		return false;
	}
	
	// trim out old sortby value
	if (paramIndex != -1)
	{
		destinationUrl = destinationUrl.substring(0, paramIndex - 1); // also remove & or ?
	}
	
	if (destinationUrl.indexOf('?') != -1)
	{
		window.location.href = destinationUrl + '&' + paramName + '=' + encodeURIComponent(txtValue);
	}
	else
	{
		window.location.href = destinationUrl + '?' + paramName + '=' +  encodeURIComponent(txtValue);
	}
	
	return false;	 
}
