$(document).ready(function() {
//	------------------------------------------------
	var _busyLoadingCategory = false;
	var _busyLoadingCity = false;
	var data_cat = null;
	var data_city = null;

	function clearOnStart()
	{
		$('.suggestlist').remove();
		$('#suggestcity').remove();
		$('#suggesttype').remove();
		return false;
	}
	/************************
	 * Get category name
	 ***********************/	
	$('#categoryinput').focus(function(){

		$('body').unbind('click');

		if(_busyLoadingCategory == true)
		{
			return false;
		}
		else
		{
			_busyLoadingCategory = true;
		}

		clearOnStart();
		$('#categoryinput').addClass("focusinput");
		$('#cityinput').removeClass('focusinput');

		//apply ajax images
		$("#categoryinput").attr("class", "autocomplete_busy") ;

		if(data_cat == null)
		{	
			var sendURL = '/json/categories';
			$.ajax({
				url: sendURL,
				data: '',
				dataType: 'json',
				type: 'post',
				timeout: (15 * 1000),
				success: function (e) {
				if(e.status == "ok")
				{

					//find out x pos #businesstype
					var divTop = $('#businesstype').offset().top;
					var divLeft = $('#businesstype').offset().left;
					var divHeight = $('#businesstype').height();
					var divWidth = $('#businesstype input').width();

					if(e.total < 10)
					{
						$('#businesstype').append('<div id="suggesttype" style=";position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px;">');
					}else{
						$('#businesstype').append('<div id="suggesttype" style=";position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px; height:120px; overflow: auto;">');
					}

					jQuery.each(e.data, function(i, obj) {
						$('#suggesttype').append('<div class="suggestlist" style="width:'+(divWidth-10)+'px">'+obj.type+'</div>');
					});

					$('#categoryinput').attr("class","focusinput");

					//get first child and make it active
					$('.suggestlist:first-child').attr("id","suggestlist_first_item");

					$(".suggestlist").click(function(e){
						$("#categoryinput").val($(this).text());
						$('#categoryinput').attr("class","focusinput");
						$('.suggestlist').remove();
						$('#suggesttype').remove();

						if( jQuery.trim($('#cityinput').val()).length > 2)
						{
							searchNow();
						}
						return false;
					});
					$(".suggestlist").mouseover(function(e){ 
						$(this).attr("class","current_item");
						return false;
					});
					$(".suggestlist").mouseout(function(e){ 
						$(this).attr("class","suggestlist");			
						return false;
					});
					data_cat = e;
					_busyLoadingCategory = false;
				}
				else{}
			},
			error: function( objAJAXRequest, strError ){
				_busyLoadingCategory = false;
				alert("Connection timeout.Please try again later");	
			}
			});

		}
		else
		{
			//find out x pos #businesstype
			var divTop = $('#businesstype').offset().top;
			var divLeft = $('#businesstype').offset().left;
			var divHeight = $('#businesstype').height();
			var divWidth = $('#businesstype input').width();

			if(data_cat.total < 10)
			{
				$('#businesstype').append('<div id="suggesttype" style=";position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px;">');
			}else{
				$('#businesstype').append('<div id="suggesttype" style=";position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px; height:120px; overflow: auto;">');
			}

			jQuery.each(data_cat.data, function(i, obj) {
				$('#suggesttype').append('<div class="suggestlist" style="width:'+(divWidth-10)+'px">'+obj.type+'</div>');
			});

			$('#categoryinput').attr("class","focusinput");

			//get first child and make it active
			$('.suggestlist:first-child').attr("id","suggestlist_first_item");

			$(".suggestlist").click(function(e){
				$("#categoryinput").val($(this).text());
				$('#categoryinput').attr("class","focusinput");
				$('.suggestlist').remove();
				$('#suggesttype').remove();

				if( jQuery.trim($('#cityinput').val()).length > 2)
				{
					searchNow();
				}
				return false;
			});
			$(".suggestlist").mouseover(function(e){ 
				$(this).attr("class","current_item");
				return false;
			});
			$(".suggestlist").mouseout(function(e){ 
				$(this).attr("class","suggestlist");			
				return false;
			});

			$('#categoryinput').focus();
			_busyLoadingCategory = false;

		}

		setTimeout( function() 
				{ 
			$('body').click(function (e){
				clearOnStart();
				$('#categoryinput').blur();
			});
				}, 200); 

		return false;
	});

	$('#categoryinput').blur(function(){
		$('#categoryinput').removeClass("focusinput");
		return false;
	});


	/************************
	 * Get cities name
	 ***********************/

	$('#cityinput').focus(function(){

		$('body').unbind('click');

		if(_busyLoadingCity == true)
		{
			return false;
		}
		else
		{
			_busyLoadingCity = true;
		}

		clearOnStart();
		$('#cityinput').addClass("focusinput");
		$('#categoryinput').removeClass('focusinput');

		//apply ajax images
		$("#cityinput").attr("class", "autocomplete_busy") ;

		if(data_city == null)
		{
			var sendURL = '/json/cities/';
			$.ajax({
				url: sendURL,
				data: '',
				dataType: 'json',
				type: 'post',
				timeout: (15 * 1000),
				success: function (e) {
				if(e.status == "ok")
				{
					data_city = e;

					//find out x pos #businesstype
					var divTop = $('#businesscity').offset().top;
					var divLeft = $('#businesscity').offset().left;
					var divHeight = $('#businesscity').height();
					var divWidth = $('#businesscity input').width();

					if(e.total < 10)                                                                                                                                                                        
					{                                                                                                                                                                                       
						$('#businesscity').append('<div id="suggestcity" style="z-index:100; position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px;">');                              
					}else{                                                                                                                                                                                  
						$('#businesscity').append('<div id="suggestcity" style="z-index:100; position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px; height:120px; overflow: auto;">');
					}                                                                                                                                                                                       


					jQuery.each(e.data, function(i, obj) {
						$('#suggestcity').append('<div class="suggestlist" style="width:'+(divWidth-10)+'px">'+obj.city+'</div>');
					});

					$('#cityinput').attr("class","focusinput");

					//get first child and make it active
					$('.suggestlist:first-child').attr("id","suggestlist_first_item");

					$(".suggestlist").click(function(e){
						$("#cityinput").val($(this).text());
						$('#cityinput').attr("class","focusinput");
						$('.suggestlist').remove();
						$('#suggestcity').remove();
						if( jQuery.trim($('#categoryinput').val()).length > 2)
						{
							searchNow();
						}
						return false;
					});
					$(".suggestlist").mouseover(function(e){ 
						$(this).attr("class","current_item");
						return false;
					});
					$(".suggestlist").mouseout(function(e){ 
						$(this).attr("class","suggestlist");			
						return false;
					});

					_busyLoadingCity = false;
				}
				else{}
			},
			error: function( objAJAXRequest, strError ){
				_busyLoadingCity = false;
				alert("Connection timeout.Please try again later");	
			}
			});
		}
		else
		{
			//find out x pos #businesstype
			var divTop = $('#businesscity').offset().top;
			var divLeft = $('#businesscity').offset().left;
			var divHeight = $('#businesscity').height();
			var divWidth = $('#businesscity input').width();

			if(data_city.total < 10)                                                                                                                                                                        
			{                                                                                                                                                                                       
				$('#businesscity').append('<div id="suggestcity" style="z-index:100; position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px;">');                              
			}else{                                                                                                                                                                                  
				$('#businesscity').append('<div id="suggestcity" style="z-index:100; position:absolute; top:'+(divTop+divHeight)+'px; left:'+divLeft+'px; width:'+divWidth+'px; height:120px; overflow: auto;">');
			}                                                                                                                                                                                       


			jQuery.each(data_city.data, function(i, obj) {
				$('#suggestcity').append('<div class="suggestlist" style="width:'+(divWidth-10)+'px">'+obj.city+'</div>');
			});

			$('#cityinput').attr("class","focusinput");

			//get first child and make it active
			$('.suggestlist:first-child').attr("id","suggestlist_first_item");

			$(".suggestlist").click(function(e){
				$("#cityinput").val($(this).text());
				$('#cityinput').attr("class","focusinput");
				$('.suggestlist').remove();
				$('#suggestcity').remove();
				if( jQuery.trim($('#categoryinput').val()).length > 2)
				{
					searchNow();
				}
				return false;
			});
			$(".suggestlist").mouseover(function(e){ 
				$(this).attr("class","current_item");
				return false;
			});
			$(".suggestlist").mouseout(function(e){ 
				$(this).attr("class","suggestlist");			
				return false;
			});

			_busyLoadingCity = false;
		}

		setTimeout( function() 
				{ 
			$('body').click(function (e){
				clearOnStart();
			});
				}, 200); 

		return false;
	});

	$('#cityinput').blur(function(){
		$('#cityinput').attr("class","formInput");
		return false;
	});


	/**
	 * get contacts from db and print out info
	 */
	function getContacts(data, parent)
	{
		var BusinessInfo = $(parent).find('.BusinessInfo');
		var BusinessContacts = $(parent).find('.BusinessContacts');
		var searchURL = '/json/contacts/businessID/'+data

		$.ajax({
			url: searchURL,
			data: '',
			dataType: 'json',
			type: 'post',
			timeout: (10 * 1000),
			success: function (e) {
			if(e.status == "ok")
			{
				jQuery.each(e.data, function(i, obj) {
					$(BusinessContacts).append('<p><b>'+obj.type+':</b> '+obj.contactdata+'</p>');
				});

			}
			else
			{
			}

			$(BusinessContacts).removeClass('ajaxbusy');
			$(BusinessContacts).find('p:first').hide();

			return false;
		},
		error: function( objAJAXRequest, strError ){
			alert("Connection timeout?.Please try again later");	
		}
		});
	}

	function getMap(data, parent)
	{
		var BusinessInfo = $(parent).find('.BusinessInfo');
		var businessName = $(parent).find('h1').text();
		var businessAddress = $(parent).find('h2').text();
		var lat = $(BusinessInfo).attr('lat');
		var lng = $(BusinessInfo).attr('lng');			
		var googlemapDiv = "googlemap_" + $(BusinessInfo).attr('businessID');
		//$(parent).find('#'+googlemapDiv).addClass('googlemap');

		//Display google map
		var map = new GMap2(document.getElementById(googlemapDiv));
		var point = new GLatLng(lat, lng);			
		map.setCenter(point, 16);
		var marker = new GMarker(point);
		map.addOverlay(marker);
		
		var customUI = map.getDefaultUI();
        // Remove MapType.G_HYBRID_MAP
        //customUI.maptypes.hybrid = false;
        map.setUI(customUI);

		var info ="<b>"+businessName+"</b><br />"+businessAddress;

		GEvent.addListener(marker, "click", function() {
			map.openInfoWindowHtml(point, info);
		});

		marker.openInfoWindowHtml(info);		

		//map.addControl(new GSmallMapControl());			
		$(parent).find('div:last').removeClass('ajaxbusy');
	}



	function searchNow(page)
	{
		if( jQuery.trim($('#categoryinput').val()).length < 2 ||
				jQuery.trim($('#cityinput').val()).length < 2)
		{
			alert('Please fill in the form again');
			return false;
		}

//        $.getScript('/js/login.js', function(){
//            login.init();
//        });

		// DISPLAY AJAX BUSY STATUS
		$('#info').remove();
		$('#searchingStatus p').remove();
		$('#searchingStatus').append('<p class="ajaxbusy">Searching...</p>');
		$('#cityinput').attr("class","formInput");

		var category = $('#categoryinput').val().toLowerCase();
		var city = $('#cityinput').val();
		if(page != null && page < 2){
			var searchURL = '/public/'+encodeURI(city)+'/'+category;
		}
		else{
			var searchURL = '/public/'+encodeURI(city)+'/'+category+'/'+page;
		}


		var www = "http://"+window.location.host;

		$.ajax({
			url: searchURL,
			data: '',
			dataType: 'json',
			type: 'post',
			timeout: (10 * 1000),
			success: function (e) {
			if(e.status == "ok")
			{
				$('.searchresults').remove();
				$('p.paging').remove();

				jQuery.each(e.data, function(i, obj) {

					var directLink = www+'/'+category+'/'+obj.businessID;

					//html template
					var info = '<div class="searchresults">'+
					'<div businessID="'+obj.businessID+'" lat="'+obj.lat+'" lng="'+obj.lng+'" class="BusinessInfo"></div>'+
					'<div class="info_column">'+
					'<h1>'+obj.businessName+'</h1>'+
					'<h2>'+obj.businessAddress+', '+obj.city+'</h2>'+
					'<div class="ExtendInfo" style="display:none">'+									
					'<div class="BusinessContacts ajaxbusy">'+
					'<p>Loading data...</p>'+
					'</div>'+
					'<p>'+obj.businessDescription+'</p>'+
					'<p  style="font-size:10px; margin:5px 0 0 0"><br/><b>Link:</b> <input class="directLink" type="text" class="directLink" value="'+directLink+'" style="width:200px; border:none; font-size:11px;"/>'+
					'<br/><b>Review:</b> <a href="'+directLink+'" title="Login now and write your review">Write a review about this '+obj.type.toLowerCase()+'</a>'+
					'</p>'+
					'</div>'+
					'</div>'+
					'<div class="map_column collapse" id="googlemap_'+obj.businessID+'">Loading map...</div>'+
					'</div>';												

					$('#main_content').append(info);
					if(obj.rate > 0)
					{
						var rate = rateCount(obj.rate);
						$('.searchresults:last').find('h1').after('<div class="searchRating rating'+rate+'"><a href="'+directLink+'" title="click here to read reviews">'+obj.reviews+' votes</a></div>');								
					}
				});

				//ERASE AJAX BUSY STATUS
				$('#searchingStatus p').remove();
				if(e.pages < 2)
				{
					if(e.perpage < e.total)
					{
						$('#searchingStatus').append('<p class="resultInfo">Results: 1-'+e.perpage+' of '+e.total+'</p>');
					}
					else
					{
						$('#searchingStatus').append('<p class="resultInfo">Results: 1-'+e.total+' of '+e.total+'</p>');
					}
				}
				else //display paging
				{
					var startFrom = e.perpage*(e.page-1)+1;
					if(e.page == e.pages)
					{
						var endTo = e.total;
					}
					else
					{
						var endTo = e.perpage*e.page;
					}

					$('#searchingStatus').append('<p class="resultInfo">Results: '+startFrom+'-'+endTo+' of '+e.total+'</p>');

					$('#searchingStatus').append('<p class="paging">Page: </p>');
					for(var i=1; i<= e.pages; i++)
					{
						if(e.page == i)
						{
							$('#searchingStatus').find('p.paging').append(i);
						}
						else
						{
							$('#searchingStatus').find('p.paging').append('<a href="#page'+i+'" title="Go to page'+i+'">'+i+'</a>');
						}
					}

					//copy paging to the bottom					
					$('.searchresults:last').after($('#searchingStatus').find('p.paging').clone());

					//clickable paging
					$('p.paging a').click(function(e){
						$('p.paging').remove();
						searchNow($(this).text());
						return false;
					});
				}



				// WHEN USER PRESS MORE/LESS INFO DIV
				$(".BusinessInfo").click(function(e){
					var ExtendInfoDiv = $(this).parent().find('.ExtendInfo');
					var MapDiv = $(this).parent().find('.map_column');
					var directLink = $(this).parent().find('.info_column input.directLink');

					if($(ExtendInfoDiv).css('display') == "none")
					{
						$(ExtendInfoDiv).css('display','block');
						$(MapDiv).removeClass('collapse');
						$(MapDiv).addClass('expanded');								

						$(this).parent().attr('class', 'searchresults hide');

						//	GET CONTACTS WHEN USER CLICK HERE
						var BusinessInfo = $(this).parent().find('.BusinessInfo');
						var businessID = $(BusinessInfo).attr('businessID');

						//Only load data when call first time
						if($(this).parent().find('.BusinessContacts p').length < 2  )
						{
							getContacts( businessID,$(this).parent());
							getMap( businessID,$(this).parent());
						}

					}
					else
					{
						$(ExtendInfoDiv).css('display','none');
						$(MapDiv).removeClass('expanded');
						$(MapDiv).addClass('collapse');


						$(this).parent().attr('class', 'searchresults searchHover expand');
					}

					$(directLink).click(function(e){
						$(this).select();
					});

				});

				// CHANGE COLOR WHEN MOUSEOVER/MOUSEOUT RESULT
				$('.searchresults').mouseover(function(e){
					if( $(this).attr('class') != "searchresults hide")
					{
						$(this).removeClass('hide');
						$(this).addClass('searchHover');
						$(this).addClass('expand');
						//$(this).attr('class', 'searchresults searchHover expand');		
					}
				});
				$('.searchresults').mouseout(function(e){
					if( $(this).attr('class') != "searchresults hide")
					{
						$(this).removeClass('searchHover');
						$(this).removeClass('expand');
						$(this).removeClass('hide');
						//$(this).attr('class','searchresults');
					}
				});

				return false;
			}
			else
			{
				//ERASE AJAX BUSY STATUS
				$('#searchingStatus p').remove();
				$('#searchingStatus').append('<p>Results: '+e.total+'</p>');
				$('.searchresults').remove();

				return false;
			}
		},
		error: function( objAJAXRequest, strError ){
			alert("Connection timeout?.Please try again later");	
		}
		});
		return false;
	}

	function rateCount(rate)
	{
		//rate = parseFloat(rate);
		if(rate < 1.3)
		{
			return 1; // 1 star
		}
		else if(rate > 1.30 && rate < 1.75)
		{
			return 15; // 1.5 star
		}
		else if(rate > 1.75 && rate < 2.3)
		{
			return 2;	// 2 stars
		}
		else if(rate > 2.3 && rate < 2.75)
		{
			return 25; //2.5 stars
		}
		else if(rate > 2.75 && rate < 3.3)
		{
			return 3; 	// 3 stars
		}
		else if(rate > 3.3 && rate < 3.75)
		{
			return 35;
		}
		else if(rate > 3.75 && rate < 4.3)
		{
			return 4;
		}
		else if(rate > 4.3 && rate < 4.75)
		{
			return 45;
		}
		else return 5;
	}

//	------------------------------------------------
});
