$(function () {
    // Japan drop down option.
    $('#locationFilters form').submit(function (e) {
        var countryValue = $('select[name=Country]').val();
        var japanOptionValue = $('select[name=Country] option').filter(function () {
            return $(this).text() == 'Japan';
        }).val();

        // Japan is selected, execute special option.
        if (countryValue == japanOptionValue) {
            e.preventDefault();

            window.open('http://www.2xu.jp/dealer/', 'japan2xuwindow', "toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1");
        }
    });

    // Location filters.
    $('#locationFilters select').change(function () {
        // Define elements.
        $currDropdown = $(this)
        $nextDropdown = $currDropdown.parents('.fieldRow').next('.fieldRow').find('select');

        var selectedValue = $currDropdown.val();
        //alert(selectedValue);

        // If it's a legitimate value, attempt to populate next drop down if found.
        if (selectedValue.length > 0 && $nextDropdown.length) {
            // Populate menu.
            $.ajax(
			{
			    url: rootFolder + '/ajax/getSubRegions.asp',
			    data:
				{
				    id: selectedValue
				},

			    type: 'POST',
			    dataType: 'html',

			    success: function (html) {
			        $newItems = $(html).find('option');

			        // Remove all non-default valued items from next drop down.
			        $nextDropdown.find('option[value!=\'\']').remove();

			        // Add new items and select default value.
			        $nextDropdown.append($newItems);
			        $nextDropdown.val(['']);
			    }
			});
        }
    });

    // Range filters.
    $('#rangeFilters input').click(function () {
        $.ajax(
		{
		    url: rootFolder + '/ajax/getSubRegions.asp',
		    data:
			{
			    id: selectedValue
			},

		    type: 'POST',
		    dataType: 'html',

		    success: function (html) {
		        $newItems = $(html).find('option');

		        // Remove all non-default valued items from next drop down.
		        $nextDropdown.find('option[value!=\'\']').remove();

		        // Add new items and select default value.
		        $nextDropdown.append($newItems);
		        $nextDropdown.val(['']);
		    }
		});
    });
});
