var SEARCH_BOX_DEFAULT_TEXT = 'Enter the keywords:';

var AJAX_PENDING_TIMER;
var CURRENT_PAGE = 1;
var CURRENT_LIMIT = 10;

function init_search() {

	var sTextBox   = $("#search_val");
    var CountryDropBox   = $("#country_val");
    var CityDropBox   = $("#city_val");
    var BranchDropBox   = $("#branch_val");
	sTextBox.focus(function() {
		if(this.value == SEARCH_BOX_DEFAULT_TEXT) {
			this.value = '';
		}
	});
	sTextBox.blur(function() {
		if(this.value == '') {
			this.value = SEARCH_BOX_DEFAULT_TEXT;
		}
	});
	sTextBox.blur();


	sTextBox.keyup(function() {
		var q = $("#search_val").val();
		if( q == SEARCH_BOX_DEFAULT_TEXT) {
			HideLiveSearch();
		}
		else {
            
            if (q.length <= 2 && q.length > 0) {
                return;
            }
        
			clearTimeout(AJAX_PENDING_TIMER);
			CURRENT_PAGE = 1;
			AJAX_PENDING_TIMER = setTimeout("PerformLiveSearch()",500);
		}
		
	});
    
    CountryDropBox.change(function() {
         
         	$.ajax({
		url: '/ajax_files/search.php',
		data: {
            country: $("#country_val").val()
            },
		type:       'GET',
		timeout:    '5000',
		dataType:   'json',
		beforeSend: function() {
			var options = '<option value="">Loading...</option>';
            $('#city_val option').remove();
            $("#city_val").html(options);
		},
		complete: function() {
			
		},
		success: function(j) {
            var add_text = ($('#country_val option:selected').text());
                        
            $('#city_val option').remove();
                   var options = '<option value="">All Cities in ' + add_text + '</option>';
               for (var i = 0; i < j['populate'].length; i++)
            {
            options += '<option value="' + j['populate'][i].optionValue + '">' + j['populate'][i].optionDisplay + '</option>';
            }

            $("#city_val").html(options);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
            var options = '<option value="">All Cities</option>';
            $('#city_val option').remove();
            $("#city_val").html(options);
		}
	});
         
                
        clearTimeout(AJAX_PENDING_TIMER);
        CURRENT_PAGE = 1;
        AJAX_PENDING_TIMER = setTimeout("PerformLiveSearch()",500);
    });
    
    CityDropBox.change(function() {
        clearTimeout(AJAX_PENDING_TIMER);
        CURRENT_PAGE = 1;
        AJAX_PENDING_TIMER = setTimeout("PerformLiveSearch()",500);
    });
    
    BranchDropBox.change(function() {
        clearTimeout(AJAX_PENDING_TIMER);
        CURRENT_PAGE = 1;
        AJAX_PENDING_TIMER = setTimeout("PerformLiveSearch()",500);
    });
	
	$("#livesearch_result_close_link").click(function() {
        //Reset Countries
        CountryDropBox.find('option:first').attr('selected', 'selected').parent('select');
        
        //Reset Cities
        var reset_options = '<option value="">All Cities</option>';
            $('#city_val option').remove();
            $("#city_val").html(reset_options);
        
        //Reset Branches
        BranchDropBox.find('option:first').attr('selected', 'selected').parent('select');
        
        //Reset Keywords
        sTextBox.val(SEARCH_BOX_DEFAULT_TEXT);
        
        //Hide results
        HideLiveSearch();
	});
}

function NextPage(p) {
	if(p['has_next']) {
		AJAX_IS_RUNNING = false;
		CURRENT_PAGE++;
		PerformLiveSearch();
	}
}
function PrevPage(p) {
	if(p['has_prev']) {
		AJAX_IS_RUNNING = false;
		CURRENT_PAGE--;
		PerformLiveSearch();
	}
}

function ShowLoaders() {
	$('#ajaxloader').fadeIn('fast');

	if( $('#livesearch').css('display') == 'block' ) {
		var h = $('#livesearch').height() - 5;
		var w = $('#livesearch').width() - 45;
		$('#loader_div').width(w);
		$('#loader_div').height(h);
		$('#loader_div p').css('margin-top',(h/2)+20);
		$('#loader_div').fadeIn('fast');
	}
}

function HideLoaders() {
	$('#ajaxloader').fadeOut('fast');
	$('#loader_div').hide();
}

var AJAX_IS_RUNNING = false;
function PerformLiveSearch() {

	if(AJAX_IS_RUNNING == true) {
		return;
	}

    if ( ($("#search_val").val() == SEARCH_BOX_DEFAULT_TEXT || $("#search_val").val() =='') && $("#city_val").val()=='' && $("#country_val").val()=='' && $("#branch_val").val()=='') {
        HideLiveSearch();
        return;
    }

	var query       = $("#search_val");
	var q_val       = (query.val() && query.val() != SEARCH_BOX_DEFAULT_TEXT) ? query.val() : '';
    var country     = $("#country_val");
    var country_val = (country.val() && country.val() != 0) ? country.val() : '';
    var city        = $("#city_val");
    var city_val    = (city.val() && city.val() != 0) ? city.val() : '';
    var branch      = $("#branch_val");
    var branch_val  = (branch.val() && branch.val() != 0) ? branch.val() : '';
    
	AJAX_IS_RUNNING = true;

	$.ajax({
		url: '/ajax_files/search.php',
		data: {
			query: q_val,
            country: country_val,
            city: city_val,
            branch: branch_val,
			output: 'json',
			page: CURRENT_PAGE,
			limit: CURRENT_LIMIT
		},
		type:       'GET',
		timeout:    '5000',
		dataType:   'json',
		beforeSend: function() {
			// Before send request
			// Show the loader
			AJAX_IS_RUNNING = true;
			ShowLoaders();
		},
		complete: function() {
			// When Sent request
			// Hide the loader
			AJAX_IS_RUNNING = false;
			HideLoaders();
		},
		success: function(data, textStatus) {
            AJAX_IS_RUNNING = false;
			HideLoaders();
			$('#livesearch').slideDown();

			// clear the results
			//$("#search_results").remove();
            $(".livesearch_results dd").remove();
            
			var resultsNav = $('.livesearch_results dt');
            if (data['results'].length) {
				// add the new results (in reverse since the
				// append inserts right after the header and not
				// at the end of the result list
				var current = resultsNav;
                if (data['results'][0]['error']) {
                    current.after('<dd id=""><div class="error">' + data['results'][0]['error'] + '</div></dd>');
                    $('.livesearch_navbody').slideUp();
                    AJAX_IS_RUNNING = false;
                    HideLoaders();
                    return false;
                }
                
				for(i = data['results'].length; i > 0; i--) {
					current.after(
						DisplayResult(data['results'][i-1])
					);
                    $('.livesearch_navbody').slideDown();
				}
			}
			else {
                resultsNav.after('<div class="error">No events found with these search terms</div>');
			}

			// Pagination at the bottom of LiveSearch panel
			Pagination(data['paging'],".livesearch_navbody");

		},
		
		// We're gonna hide everything when get error
		error: function(XMLHttpRequest, textStatus, errorThrown) {
            AJAX_IS_RUNNING = false;
			HideLoaders();
			HideLiveSearch();
		}
	});

}

function DisplayResult(row) {
	var output = '<dd id="">';
	output += '<a href="' + row['url'] + '">';
	output += '<span class = "title_holder">' + row['title'] + '</span>';
    output += '<span class="locations_holder"><span class = "country_holder">' + row['country'] + '</span>' + '<span class="separator">|</span>' + '<span class = "city_holder">' + row['city'] + '</span></span>';
    output += '<div class="clearfix">&nbsp;</div>'
	output += '</a></dd>';
	return output;
}
function Pagination(p,selector) {
	$(selector + " *").remove();
   
	if(p['start_idx'] != undefined && p['has_next']===true) {
		var html = '<span class="livesearch_legend">' + p['start_idx'] + ' - ' + p['end_idx'] + ' of ' + p['total'] + ' Results</span>';
		if (p['has_next']===true) {
            html += '<a class="livesearch_next" href="javascript:void(0);" title="Next '+CURRENT_LIMIT+' Results"><em></em></a>';
		}
        if (p['has_prev']===true) {
            html += '<a class="livesearch_prev" href="javascript:void(0);" title="Previous '+CURRENT_LIMIT+' Results"><em></em></a>';
		}
        html += '<div class="clearfix">&nbsp;</div>';

		$(selector).append(html);
	}
	else {
		var html = '<span class="livesearch_legend">' + p['start_idx'] + ' - ' + p['end_idx'] + ' of ' + p['total'] + ' Results</span>';
		if (p['has_prev']===true) {
            html += '<a class="livesearch_prev" href="javascript:void(0);" title="Previous '+CURRENT_LIMIT+' Results"><em></em></a>';
		}
        html += '<div class="clearfix">&nbsp;</div>';

		$(selector).append(html);
	}

	$(selector + " .livesearch_next").click(function() {
		NextPage(p);
	});
	$(selector + " .livesearch_prev").click(function() {
		PrevPage(p);
	});

}

function HideLiveSearch() {
	$('#livesearch').slideUp();
	$('#ajaxloader').fadeOut('fast');
}

$(document).ready(function() {
	//fix the width of cities
    
    $('#city_val').attr('style','width: 150px');
    
    init_search();
    
    $("form").bind("keypress", function(e) {
             if (e.keyCode == 13) {
                 return false;
        }
    });
});
