$(document).ready(function(){
	
       //var dataArray = {'city': city, 'state': state, 'categoryid': category_id, 'categorylevel': category_level, 'numperpage': 10};
       //showContent(dataArray);

    $('div.page_num').find('a').click(function(){
	        newdata = {'city': city, 'state': state, 'categoryid': category_id, 'categorylevel': category_level, 'numperpage': 10, 'start': $(this).attr('rel')};
     	showContent(newdata);
     	return false;
	});
	
	
	//ajax call to add favourite business
	   $('a.add_clipboard').click(function(){
	      $.getJSON($(this).attr('href'), function(data){
	         loadClipBoard();
	   });
	   return false;
	});
	
	
       //mapdata = data['companies'];
       //enlarge the image on hover
       $('img.enlarge').hover(
          function(){

          	  var src = $(this).attr('src');
          	  var newsrc = src.replace(imagepath, imagepath_large);

          	  $(this).next().attr('src', newsrc);
          	  var offset = $(this).offset();

          	  $(this).next().css('position', 'absolute').css('top', offset.top - 220)
          	                         .css('left', offset.left + 100)
          	                         .css('display', 'block')
          	                         .css('width', '400px').css('height', '300px')
          	                         .css('z-index', 500)
          	                         .css('border', '1px solid black');
          },
          
          function(){
          	  $(this).next().removeClass('hover_show').css('display', 'none').css('z-index', -1);

          }
       );
	//setup category
	//setupCategory(category_level, data);
	
});

function showContent(dataArray){
	
	    $('#searchcontent').addClass('ajax_loading');
	    $('li.nave_g').remove();
	    $.ajax({
	   	 url: searchUrl, 
	   	 cache: false,
	   	 data: dataArray,
	   	 dataType: "json",
	     success: function(data){
	     
	     $('#searchcontent').removeClass('ajax_loading');
  
	     if (data.success == true && data.totalnumber != 0) {
             $('div.page_all').html(showNum(data['totalnumber'], data['start'], data.numperpage));
             $('div.page_num').html(paginate(data['totalnumber'], data['start'],data.numperpage));
	     	
	         var content = "";
	         for(var i = 0; i < data['companies'].length; i++){
	            	//replace space with dash in company name
	     	    var companyName = data['companies'][i]['company_name'].replace(/\s/g, '-');
	     	    
	     	    content += '<li class="rlt_list_blc">';
	     	    content += '<div class="biz_block"><a href="/'+ currentCity + '/view/'+ companyName + '-' + data['companies'][i]['ID']
	     	             +'/ " class="biz_tit_link">';
	     	    if(data['companies'][i]['image'] == undefined)
	     		    content += '<img src="/img/no_img_defalt.gif" alt="no image" class="no_img" />';
                else
	     	       content += '<img  src="'+ imagepath + data['companies'][i]['image'] +  '" alt="image" class="no_img enlarge" />';
	     	 
	     	    content += '</a><img style="display:none" />';
	     	    content += '<div class="biz_info">';
	     	      //output the start function 
                var width = outputStar(data['companies'][i]['rate']);
                var category_name = replaceDash(data['companies'][i]['description']);
                
	     	    //according to the rate, calculate the width for star
	     	    content += '<div class="rate"><div class="rate_star"  id = "rate" ><span style="width:' + width + 'px "></span></div>' + data['companies'][i]['rate'] + '/5 (' + data['companies'][i]['num_of_rate'] + ' reviews)';	
	     	    content += '</div>';
	     	
	     	    content +='<a href="/'+ currentCity + '/view/'+ companyName + '-' + data['companies'][i]['ID']
	     	             +'/ " class="biz_tit_link">' + data['companies'][i]['company_name'] +'</a><br />';
	     	    	     	 
	     	    content += '<p class="biz_cat">Category: ';
                content += '<a href="/' + currentCity + '/category-'+ category_name + '-' + data['companies'][i]['cid'] + '-' + '4' + '">' + data['companies'][i]['description']+ '</a>';
	            content +=  '</p>';
	            content += '<p>';
	            content += data['companies'][i]['address'] + ' ' + data['companies'][i]['city'] + ' ' + data['companies'][i]['state'] + ' ' + data['companies'][i]['postal_code'];
	     	    content += '</p>';
	     	    
	     	    content +='<p>';
	     	    if (data['companies'][i]['phone_number'] != null)
	     	       content += '(phone)' + data['companies'][i]['phone_number'];

	     	    
	     	    if (data['companies'][i]['fax_number'] != null)
	     	       content += ' (fax)' + data['companies'][i]['fax_number'];
	     	    
	     	    content +='</p>';
	     	    if (data['companies'][i]['url'] != null)
	     	       content += '<p><a href="' + data['companies'][i]['url'] + '" target="_blank" >' + outputurl(data['companies'][i]['url']) + '</p>';
	     	       

	     	    content += 
                       '</div></div><div class="biz_link">' + 
                       '<a href="/'+ currentCity + '/view/'+ companyName + '-' + data['companies'][i]['ID'] + '-write " class="wrt_rev">write review</a>' +       
                       '<a href="/business/addclipboard?businessid=' + data['companies'][i]['ID'] +  '" class="add_clipboard">add to clipboard</a>' +     
                       '<a href="/business/contactbusiness?businessid=' + data['companies'][i]['ID'] +  '" class="contact_business">contact business</a>' + 
                       '</div>';
                  	   
	     	    content += '</li>'; 
	      }
	     
	       $('#searchcontent').html(content);
	       $('div.page_num').find('a').click(function(){
	       	        newdata = {'city': city, 'state': state, 'categoryid': category_id, 'categorylevel': category_level, 'numperpage': 10, 'start': $(this).attr('rel')};
                 	showContent(newdata);
                 	return false;
            });
            

            //ajax call to add favourite business
	           $('a.add_clipboard').click(function(){
	              $.getJSON($(this).attr('href'), function(data){
	                 loadClipBoard();
	           });
	           return false;
	        });
	       
	       //setup category
	        setupCategory(category_level, data);
	        
	       //enlarge the image on hover
	        $('img.enlarge').hover(
	           function(){
	           	  var src = $(this).attr('src');
	           	  var newsrc = src.replace(imagepath, imagepath_large);

	           	  $(this).parent().next().attr('src', newsrc);
	           	  var offset = $(this).offset();

	           	  $(this).parent().next().css('position', 'absolute').css('top', offset.top + $(this).height())
	           	                         .css('left', offset.left - $(this).width())
	           	                         .css('display', 'block')
	           	                         .css('width', '400px').css('height', '300px')
	           	                         .css('z-index', 500)
	           	                         .css('border', '1px solid black');
	           },
	           
	           function(){
	           	  $(this).parent().next().removeClass('hover_show').css('display', 'none').css('z-index', -1);

	           }
	        );
	     }
	     
	     else $('#searchcontent').html('<h2>Sorry, no record has been found</h2>');
	   },
	     error: function() {
            alert("Failed to connect server");
        }
     
	 });
	
   }

function setupCategory(category_level, data){
  //set the forum category 
  var level = parseInt(category_level);
  if (level == 4) level--;
           
  var categorylink = "";
  
  for (var j = 0; j <= level; j++){
  	 var categoryName = "";
  	 if (data['companies'][0]['level' + j +  '_des'].length > 15)
  	    categoryName = data['companies'][0]['level' + j +  '_des'].substring(0, 14) + "...";
  	 else 
  	    categoryName = data['companies'][0]['level' + j +  '_des'];
  	 
  	 var aCategory = replaceDash(data['companies'][0]['level' + j +  '_des']);
     categorylink += '<li class="nave_g"><a title="' + data['companies'][0]['level' + j +  '_des'] + '" href="/' + currentCity + '/category-' + aCategory + '-' + data['companies'][0]['level'+j] + '-' + j + '">' + categoryName + '</a>';
              
    if (j != level)
     categorylink += '></li>';
  }
         
  $('div.nav > ul').append(categorylink);
  
}
//output the number of items in format : "	Showing 1-10 total 100
function showNum(total, start, numperpage){
	start = parseInt(start);
	numperpage = parseInt(numperpage);
	total = parseInt(total);
	if (total >  start + numperpage)
	  var end = start + numperpage;
	else end = total;
	
	var showbar = "Showing " + (start + 1) + "-" + end + " of " + total;
	
	return showbar;
}

function paginate(total, start, numperpage){
	start = parseInt(start);
	numperpage = parseInt(numperpage);
	total = parseInt(total);
	//get total number of pages
	var pages = Math.ceil(total / numperpage);
	var link = "";
	var currentpage = (start / numperpage) + 1; 
	var half = Math.ceil(numperpage /2);
    var upper_limit = pages - numperpage;
    var start = currentpage>half ?Math.max(Math.min(currentpage-half, upper_limit), 1):1;
    var end = currentpage>half?Math.min(currentpage+half, pages):Math.min(numperpage, pages);
    var url = window.location;
    
    //output the page link
	if (currentpage != 1)
	  link += '<a rel="'+ (currentpage - 2) * numperpage +'">Previous</a>'
	else
	  link += 'Previous';

	for(var i = start; i <= end; i++){
      if (currentpage == i)
      	link += "<b> " + i + " </b>";
      else
        link += '<a id = "#' + (i - 1) * numperpage +'" rel="'+ ((i - 1) * numperpage) +'"> ' + i + ' </a>';
	}
	
	if (currentpage != pages)
	  link += '<a rel="'+ (currentpage) * numperpage +'"> Next </a>';
	else 
	  link += 'Next';
	  
    return link;
}