﻿/************************************** Splendid *************************************
* Created By:		Steve Doggett
* Creation Date:	25th November 2008
* Edited ----------------------------------------------------------------------------
*      By:              On:  
* Description -----------------------------------------------------------------------
*      This file gives the search functionality contained within ctlSearchForm.ascx
*      Uses the JQuery plugin.
*
*      Functions:
*          showAdvProjectSearch()			// Opens the advanced search and disables the single keyword search at the top
*          cancelAdvProjectSearch()			// Closes the advanced search and enables the single keyword search. Also empties the values in the advanced search    
*          getCategories()					// Called to get the list of types for a chosen category
*          getSubCats()                     // Called to create the 3rd drop down
*          AddSearchLocationSubmit()        // Adds the location to the page and hides the input box.
*          ChangeSearchLocation()           // Removes the chosen location and displays the input box
*          swapSearchTabs()                 // Changes the Supplier/Project tabs on the search
*          setNumResults()                  // Updates the number of results per page and submits the search form again.
*          
**************************************************************************************/

/********************************** Global Variables *********************************/
var returnedCats = null;
var CurrentSearchData = "";
var CurrentSearchLocation = "";


$(document).ready(function() {
    /****
    * This stuff initialises the location auto complete search box.
    ****/

    function formatItem(row) {
        return row[0] + " (<strong>id: " + row[1] + "</strong>)";
    }

    function formatResult(row) {
        return row[0].replace(/(<.+?>)/gi, '');
    }

    $("#searchForLocation").autocomplete("/WebServices/locationsearch.aspx", {
        minChars: 3,
        delay: 500,
        width: 400,
        max: 200,
        selectFirst: false
    });

    $("#searchForLocation").result(function(event, data, formatted) {
        if (data) {
            CurrentSearchLocation = data[0];
            CurrentSearchData = data[1];
            AddSearchLocationSubmit();
        }
    });
});

/************************************* Functions *************************************/

/****
 * Opens the advanced search and disables the single keyword search at the top
 ****/
function showAdvProjectSearch() {
    $('#advSearchLink').slideUp('slow', function() {
        $('#SearchKeywords1').val($('#SearchKeywords').val());
        $('#SearchKeywords').val('');
        $('#advSearchOptions').slideDown('slow');
        $('#keywordLabel').fadeTo('slow', 0.2);
        $('#btnGo').fadeTo('slow', 0.2);
        $('#searchKeywords').attr('disabled', 'disabled');
    });
}

/****
 * Closes the advanced search and enables the single keyword search. Also empties the values in the advanced search
 ****/
function cancelAdvProjectSearch(){
    $('#advSearchOptions').slideUp('slow', function() {
        $('#SearchKeywords').val($('#SearchKeywords1').val());
        $('#SearchKeywords1').val('');
        $('#advSearchLink').slideDown('slow');
        $('#keywordLabel').fadeTo('slow', 1);
        $('#btnGo').fadeTo('slow', 1);
        $('#searchKeywords').attr('disabled', '');
        $('#hidServiceID').val('0');
        $('#hidCategoryID').val('0');
        $('#hidSubCategoryID').val('0');
        $('#locationid').val('0');
        $('#showLoc').hide();
        $('#setLoc').show();

        $('#SearchKeywords').unbind('click');
    });
}

/****
* Called to get the list of types for a chosen category
* Called by the onchange event of the first service drop down.
****/
function getCategories(ID) {
	// Don't do anything without an ID
	if (ID == '')
		return;

	// Go get the JSON from the server
	$.getJSON("/webservices/servicesearch.aspx", { action: 'category', id: ID }, function(json) {
		// Keep a global copy of the JSON as it's used to create the 3rd drop down.
		returnedCats = json;

		// Create the second drop down from the returned JSON
		$("#CategoryID").children().remove();
		var options = '<option value="">All</option>';
		for (var i = 0; i < returnedCats.data.length; i++) {
			options += '<option value="' + returnedCats.data[i].id + '">' + returnedCats.data[i].name + '</option>';
		}
		// Add the options to the drop down and show the drop down and it's label
		$("#CategoryID").append(options);

		$("#SubCategoryID").children().remove();
		$("#SubCategoryID").append('<option value="">Select a type</option>');
	});


}

/****
* Called to create the 3rd drop down
* Called by the onchange event of the second service drop down.
****/
function getSubCats(ID) {
	// Already hacve the data from the last JSON call, so select the right data and create the third drop down
	for (var i = 0; i < returnedCats.data.length; i++) {
		if (parseInt(returnedCats.data[i].id) == parseInt(ID)) {
			$("#SubCategoryID").children().remove();

			var options = '<option value="">All</option>';
			for (var j = 0; j < returnedCats.data[i].subCats.length; j++) {
				options += '<option value="' + returnedCats.data[i].subCats[j].id + '">' + returnedCats.data[i].subCats[j].name + '</option>';
			}
			// Add the options to the drop down and show the drop down and it's label
			$("#SubCategoryID").append(options);
		}
	}
}

/****
* Adds the location to the page and hides the input box.
****/
function AddSearchLocationSubmit() {
    var aryLocationData;
    $('#searchForLocation').val('');
    aryLocationData = CurrentSearchData.split(":");
    $('#locationid').val(aryLocationData[aryLocationData.length - 1]);

    var output = ''
               + '<p>'
               + '  <label>Location:</label>'
               + '  <span style="padding-top:5px; display:block; float:left; width:350px">' + CurrentSearchLocation + '</span>'
               + '  &nbsp;<a href="Javascript:ChangeSearchLocation()" style="position:relative; margin:-14px 0 0 20px; display:block; float:left;">Change</a>'
               + '</p>';

    $('#setLoc').fadeOut('fast', function() {
        $('#showLoc').children().remove();
        $('#showLoc').append(output).fadeIn('fast');
    });
};

/****
* Removes the chosen location and displays the input box
****/
function ChangeSearchLocation() {
    $('#showLoc').fadeOut('fast', function() {
        $('#setLoc').fadeIn('fast');
        $('#locationid').val('');
    });
};

/****
* Adds the service to the page and hides the input box.
****/
function AddSearchServiceSubmit(catName) {
    var output = ''
               + '<p>'
               + '  <label>Service:</label>'
               + '  <span style="padding-top:5px; display:block; float:left; width:350px">' + catName + '</span>'
               + '  &nbsp;<a href="Javascript:ChangeSearchService()" style="position:relative; margin:-14px 0 0 20px; display:block; float:left;">Change</a>'
               + '</p>';

    $('#setService').fadeOut('fast', function() {
        $('#showService').children().remove();
        $('#showService').append(output).fadeIn('fast');
    });
};

/****
* Removes the chosen location and displays the input box
****/
function ChangeSearchService() {
    $('#showService').fadeOut('fast', function() {
        $('#setService').fadeIn('fast');

        $('#hidServiceID').val('0');
        $('#hidCategoryID').val('0');
        $('#hidSubCategoryID').val('0');
    });
};

/****
 * Changes the Supplier/Project tabs on the search
 ****/
function swapSearchTabs( which )
{
    switch( which.toLowerCase() ){
        case 'suppsearchtab':
            $('#projSearchTab').removeClass('selected');
            $('#suppSearchTab').addClass('selected');
            $('#HomeSearchType').val('1');
            $('#frmSiteSearch').attr('action', '/supplier-search/');
            break;
        case 'projsearchtab':
            $('#suppSearchTab').removeClass('selected');
            $('#projSearchTab').addClass('selected');
            $('#HomeSearchType').val('2');
            $('#frmSiteSearch').attr('action', '/project-search/');
            break;
        case 'lbbsearchtab':
            $('#suppSearchTab').removeClass('selected');
            $('#lbbSearchTab').addClass('selected');
            $('#HomeSearchType').val('3');
            $('#LBBOnly').val('1');
            $('#frmSiteSearch').attr('action', '/supplier-search/');
            break;
    }
}

/****
 * Updates the number of results per page and submits the search form again.
 ****/
function setNumResults(num) {
    $('#numResults').val(num);
    $('#pageNum').val(1); 
    $('#suppSearchForm').submit();
}

/****
* Changes the sort by value
****/
function changeSortBy(num) {
    $('#sortBy').val(num);
    $('#pageNum').val(1);
    $('#suppSearchForm').submit();
}

/****
* Changes the sort by value
****/
function setLBBOnly() {
    if ($("#chkLBBOnly:checked").length == 1)
        $('#lbbOnly').val("1");
    else
        $('#lbbOnly').val("0");
    $('#pageNum').val(1);
    $('#suppSearchForm').submit();
}

/****
 * Updates the current page number
 ****/
function updatePage(pageNum) {
    $('#pageNum').val(pageNum);
    $('#suppSearchForm').submit();
}