var Search =
{
    //  {{{ properties

    catSelected: false,
    subCatSelected: false,

    //  }}}
    //  {{{ init()

	init: function()
	{
        $(".t-list-link").bind("click", function(){
            var href = $(this).attr('href');
            $(this).attr('href', href + '&pageOffset=' + window.pageYOffset);
        });

		$('.search-result-item')
            .mouseover(Search.highlightMember)
            .mouseout(Search.lowlightMember)
            .click(Search.goToMember);

		//	Stop the propagation so the goToMember function won't
		//	be called when these links are clicked.
		$('.search-result-email, .search-result-website, .search-result-directions')
			.click(function(event) {
				event.stopPropagation();
			});

		$("select[name='category_id']").change(Search.populateMemberSubType);
		$("select[name='region_id']").change(Search.repopulateCategories);

        Search.setGET();
		Search.repopulateCategories();
		Search.populateMemberSubType();
	},

    //  }}}
    //  {{{ setGET()

    setGET: function()
    {
        var get=(""+location.search).substring(1).split("&");
        window.location.GET = new Array();
        for (var i in get) {
            var temp = get[i].split("=");
            window.location.GET[temp[0]] = temp.splice(1, temp.length-1).join("=");
        }
    },

    //  }}}
    //  {{{ highlightMember()

	highlightMember: function(event)
	{
		if ($(this).find("a[title='More Info']").is('a')) {
			$(this).addClass('search-result-item-on');
		}
	},

    //  }}}
    //  {{{ lowlightMember()

	lowlightMember: function(event)
	{
		if ($(this).find("a[title='More Info']").is('a')) {
			$(this).removeClass('search-result-item-on');
		}
	},

    //  }}}
    //  {{{ goToMember()

	goToMember: function(event)
	{
		var link = $(this).find("a.moreInfo");
		if (link.is('a')) {
			document.location.href = link.attr('href');
		}
	},

    //  }}}
    //  {{{ repopulateCategories()

    /**
     * repopulate the sub category box based on the the value
     * selected in the region box
     *
     * if no region was selected, then get all main categories available
     *
     * if a region was selected, then get all main categories available in that
     * region.
     */
    repopulateCategories: function(event)
    {
    	// Get currently selected "Region"
        if ($("[name='region_id']").is("select")) {
            var region = $("select[name='region_id'] option:selected").val();
        } else {
            var region = $("input[name='region_id']").val();
        }

        // Get currently selected "Member Type" (category)
		var catList = $("select[name='category_id']");

		// Clear category list
		$("select[name='category_id'], select[name='sub_category_id']")
            .empty()
            .append('<option value="">-- Select --</option>');

		var usedValues = [];
		var options = [];
		var cats = [];

    	// If we have the RegionCats data (json)
		if (window.RegionCats != undefined) {
            var RegionCats = window.RegionCats;
			
			// If no region is selected
			if (region == '') {
                // For each region
				$.each(RegionCats, function(id, obj) {
					// If that region has categories in RegionCats
					if (RegionCats[id]) {
						// Add each of those categories
						$.each(RegionCats[id], function(i, j) {
							if (!usedValues[i]) {
								usedValues[i] = true;
								cats[mainCats[i]] = i;
								options.push(mainCats[i]);
							}
						});
					}
				});
				
			// Otherwise do this for the selected region
			} else {
				// For each category in this region 
				$.each(RegionCats[region], function(id, obj) {
					// Add the category
					cats[mainCats[id]] = id;
					options.push(mainCats[id]);
				});
			}
			
        } // if RegionCats
		
		options.sort();
		if (options.length == 0) {
			catList.append('<option value="">-- Select --</option>');
		}
		$.each(options, function(idx, itm) {
			catList.append('<option value="'+cats[itm]+'">'+itm+'</option>');
		});

        //  If only one option is available, default to have it selected.
		var catListOptions = catList.children('option');
        if (catListOptions.length == 2) {
            $("select[name='category_id'] option:last")
				.attr('selected', 'selected');
            //  need to repopulate the sub cats, b/c we already know what
            //  the selected cat is.
            Search.populateMemberSubType(false);
        }

        //  Figure out wich category we need to set as the selected value
        var category_id = window.location.GET['category_id'];
        if (!isNaN(parseInt(category_id))) {
            if (!Search.catSelected) {
                Search.catSelected = true;
                $("select[name='category_id'] option[value='"+category_id+"']").attr('selected', 'selected');
            }
        }
    },

    //  }}}
    //  {{{ populateMemberSubType()

    /**
     * repopulate the sub category box based on the the value
     * selected in the main category box
     *
     * if no region was selected, then get all sub categories available
     * under the main category selected
     *
     * if a region was selected, then get all sub categories available in that
     * region under the main category selected.
     */
    populateMemberSubType: function(event)
    {
        //var region = $("select[name='region_id'] option:selected").val();
        if ($("[name='region_id']").is("select")) {
            var region = $("select[name='region_id'] option:selected").val();
        } else {
            var region = $("input[name='region_id']").val();
        }
        var cat  = $("select[name='category_id'] option:selected").val();
		var subList = $("select[name='sub_category_id']");

		// Clear sub-category list
        subList.empty()
               .append('<option value="">-- Select --</option>');

        var usedValues = [];
		var options = [];
		var subCats = [];
		
		// If we have RegionCats data (json)
    	if (window.RegionCats != undefined) {

    		// If no region is selected
	        if (region == '') {
	        	// for each region
        		$.each(RegionCats, function(id, obj) {
        			// If that region has categories in RegionCats
        			if (RegionCats[id]) {
        				// If this category has any sub-cats
        				if(RegionCats[id][cat]) {
	        				// Add each of those categories
							$.each(RegionCats[id][cat], function(i, j) {
								if (!usedValues[i]) {
									usedValues[i] = true;
									subCats[j] = i;
									options.push(j);
								} 
							});
        				}
        			}
				});
        	// Otherwise do this for the selected region
	        } else {
				// For each sub-category in selected category in region
				$.each(RegionCats[region][cat], function(i, j) {
					if (!usedValues[i]) {
						usedValues[i] = true;
						subCats[j] = i;
						options.push(j);
					}
				});
	        }
    		
    	}
    
    
		options.sort();
		if (options.length == 0) {
			subList.append('<option value="">-- Select --</option>');
		}
		$.each(options, function(idx, itm) {
			subList.append('<option value="'+subCats[itm]+'">'+itm+'</option>');
		});

        //  If only one option is available, default to have it selected.
		var subListOptions = subList.children('option');
        if (subListOptions.length == 2) {
            $("select[name='sub_category_id'] option:last-child")
                .attr('selected', 'selected');
        }

        //  Figure out which sub category we need to set as the selected value
        var sub_category_id = window.location.GET['sub_category_id'];
        if (parseInt(sub_category_id) != 'NaN') {
            if (!Search.subCatSelected && event != false) {
                Search.subCatSelected = true;
                $("select[name='sub_category_id'] option[value='"+sub_category_id+"']").attr('selected', 'selected');
            }
        }
    }

    //  }}}
};

$(document).ready(Search.init);

