// 
//  buylocal.js - Contains functions mapped to page elements which make up the public user interface for buylocal
//  For example, click events for buttons and UI flair.
//  buylocal
//  
//  Created by Jay Roberts <jay@designhammer.com>
// 


// Here's where it all begins...
$(document).ready(function(){
	if (GBrowserIsCompatible()) {
	   
	   // Google Map
   	map = new GMap2(document.getElementById("gmap"));
      // map.setMapType(G_HYBRID_MAP);
		map.addControl(new GSmallMapControl());
   	map.setCenter(new GLatLng(-79.0341650, 35.9296810)); // Chapel Hill
		map.enableScrollWheelZoom(); 

		// Marker boundary information, used to center and zoom the map to contain a set of markers
		bounds = new GLatLngBounds();

		geocoder = new GClientGeocoder();
		
		// Marker Info Window Options
		info_window_options = new Object();
		info_window_options.maxWidth = 550;

      markers = new Array();

		// Stores information about the last search so if we need the same results again, due to ui mode switching, we don't have to redo the search
      search_pane = new Object();
      search_pane.term = get_search_term();
      search_pane.page = get_page_from_url();
      search_pane.category = get_category_from_url();
      search_pane.org_id = get_org_id_from_url();
      search_pane.markup = '<div class="dh-search-list-panel"><div class="dh-search-list-container"><ul class="main"><li><a class="category-link" href="#">Search: </a><ul class="sublist"><li class="no-results">No results </li></ul></li></ul></div></div>';

      // Keeps track of the number of running processes, used to show a busy indicator
      busy_count = 0;

      switch ($('body').attr('id')) {
         case 'search':
            search_pane.markup = $('div#dh-categories-list').html();
            
            if (search_pane.term != '') {
               do_search_map_only(search_pane.term, search_pane.page);
            } else {
               center_map();
            }
            break;
         case 'category':
            center_map();
            // Load map markers
            show_category_map(search_pane.category, search_pane.page);
            break;
         case 'single':
            search_pane.markup = $('div#dh-categories-list').html();
            show_single_org(search_pane.org_id);
            break;
      }

 	}

   //
   // UI Events - Events mapped to html elements
   //
	$('#org-search-button').click(function(){
		var term = $('#org-search-term').val();
		do_search(term);
		return false;
	});

	$('#dh-nav-menu ul li#search-nav a').click(function(){
	   $('#dh-nav-menu ul li').removeClass('active');
	   $('#dh-nav-menu ul li#search-nav').addClass('active');
	   load_search_pane(search_pane.term);

	   return false;
	});
	
   $('#org-search-term').focus(function(){
      $('#dh-nav-menu ul li').removeClass('active');
      $('#dh-nav-menu ul li#search-nav').addClass('active');
      load_search_pane(search_pane.term);
      
      return false;
   });

	$('#dh-nav-menu ul li#category-nav a').click(function(){
	   $('#dh-nav-menu ul li').removeClass('active');
	   $('#dh-nav-menu ul li#category-nav').addClass('active');
	   load_category_pane();
	   
	   return false;
	});
	
	$('#busy-on').click(function() {
	   alert('On Clicked');
	   busy_icon_on();
	});

	$('#busy-off').click(function() {
	   alert('Off Clicked');
	   busy_icon_off();
	});
	
   bind_category_menu_click_events();
   bind_category_back_click_events();

});

//
// Functions
//

function get_search_term() {
   var path_array = window.location.pathname.split('/');
   
   if ($('body').attr('id') == 'search') { // Get it from the url
      var path_array = window.location.pathname.split('/');
      if (typeof(path_array[2]) != 'undefined') {
         return path_array[2];
      } else {
         return $('#org-search-term').val();
      }
   } else { // Get it from the search box
      return $('#org-search-term').val();
   }
}

// Attempts to parse the page number from the current url and returns it. Returns 1 if no page found.
function get_page_from_url() {
   var path_array = window.location.pathname.split('/');
   var last_segment = path_array[path_array.length - 1]; 
   var second_to_last_segment = path_array[path_array.length - 2]; 
   
   switch($('body').attr('id')) {
      case 'search':
         if (last_num = parseInt(last_segment)) {
            return last_num;
         } else {
            return 1;
         }
         break;

      case 'category':
         if ((last_num = parseInt(last_segment)) && (second_num = parseInt(second_to_last_segment))) { // Two trailing digits, last one is the page number
               return last_num;
         } else if (last_num) { // One trailing digit, it's the category id
               return last_num;
         } else  { // No digits in the last 2 url segments
            return 1;
         }
         break;
   }
}

// Attempts to parse the org_id from the current url
function get_org_id_from_url() {
   var path_array = window.location.pathname.split('/');
   var last_segment = path_array[path_array.length - 1]; 
   
   if ($('body').attr('id') == 'single') {
      if (org_id = parseInt(last_segment)) {
         return org_id;
      } else {
         return false;
      }
   }
}

// Attempts to parse the category id from the current url
function get_category_from_url() {
   var path_array = window.location.pathname.split('/');
   var last_segment = path_array[path_array.length - 1]; 
   var second_to_last_segment = path_array[path_array.length - 2]; 
   
   if ($('body').attr('id') == 'category') {
      if (last_num = parseInt(last_segment)) {
         if (second_num = parseInt(second_to_last_segment)) { // Two trailing digits, first one is the category id
            return second_num;
         } else { // Only one trailing digit
            return last_num;
         }
      } else {
         return 1;
      }
   } else {
      return 1;
   }
   
}


// Perform a search of the supplied term
function do_search(term, page) {
   if (typeof(page) == 'undefined') {
      search_pane.page = 1;
   } else {
      search_pane.page = page;
   }
   
   reset_map();

   increase_busy_count();
   $.getJSON('/organization/search/' + term + '/' + search_pane.page, function(orgs) {
      if (orgs != null) {
         // Add markers
   		$.each(orgs, function(i, org){
   			add_org_marker_and_show_all(org);
   		});
      }
      
      load_search_pane(term, orgs);
      show_detail_list_by_search(term);
		
      decrease_busy_count();
	});
}

// Perform a search of the supplied term and only updates the map
function do_search_map_only(term, page) {
   if (typeof(page) == 'undefined') {
      page = 1;
   }
   
   reset_map();

   increase_busy_count();
   $.getJSON('/organization/search/' + term + '/' + page, function(orgs) {
      // Add markers
		$.each(orgs, function(i, org){
			add_org_marker_and_show_all(org);
		});
      decrease_busy_count();
	});
}

// Clears the map and shows a single organization based on the supplied organization id
function show_single_org(org_id) {
   reset_map();

   increase_busy_count();
 	$.getJSON('/organization/get/' + org_id, function(org) {
		add_org_marker_and_pan(org);
      decrease_busy_count();
	});  
}

// Adds an organization marker to the map
function add_org(org_id) {
   increase_busy_count();
 	$.getJSON('/organization/get/' + org_id, function(org) {
		add_org_marker_and_show_all(org);
      decrease_busy_count();
	});  
}


// Attaches a click event to category menu links. Loads the appropriate menu and slides it into place preventing a page refresh
function bind_category_menu_click_events() {
   $('a.category-link').click(function() {
      var link = $(this).attr('href') + '/html';

      // Load menu markup
      increase_busy_count();
      $.get(link, function(markup) {
         $('div#dh-categories-list').append(markup);

         // Slide first child of div#dh-categories-list left
         increase_busy_count();
         $('.dh-category-list-panel:first-child').animate(
            {"marginLeft": "-=250px"},
            500, function(){
               $('.dh-category-list-panel:first-child').remove();         
               decrease_busy_count();
            });

         // We've added new links so we need to make sure the navigation functions are bound to them
         bind_category_menu_click_events();
         bind_category_back_click_events();

         decrease_busy_count();
      });
      
      // Load map markers
      show_category_map($(this).attr('rel'), 1);
      
      // Load detail list
      show_detail_list_by_category($(this).attr('rel'));
      
      return false;
   });
   
   $('a.organization-link').click(function() {
      increase_busy_count();
      var org_id = $(this).attr('rel');
      
    	$.getJSON('/organization/get/' + org_id, function(org) {
    	   var markup = get_info_window_markup(org);
    	   bind_organization_link_click(org_id, markup);
         
         decrease_busy_count();
   	});
   	
      return false;
   });
   
}

// Attaches a click event to category list "Back" links. Loads the appropriate menu and slides it into place preventing a page refresh
function bind_category_back_click_events() {
   $('a.category-list-back').click(function() {
      var link = $(this).attr('href') + '/html';

      // Load menu markup
      increase_busy_count();
      $.get(link, function(markup) {
         $('div#dh-categories-list').prepend(markup);
         
         $('.dh-category-list-panel:first-child').attr('style', 'margin-left: -250px;');

         // Slide first child of div#dh-categories-list left
         increase_busy_count();
         $('.dh-category-list-panel:first-child').animate(
            {"marginLeft": "+=250px"},
            500, function(){
               $('.dh-category-list-panel:last-child').remove();         
               decrease_busy_count();
            });
         
         // We've added new links so we need to make sure the navigation funcitons are bound to them
         bind_category_menu_click_events();
         bind_category_back_click_events();

         decrease_busy_count();
      });
      
      // Load map markers
      show_category_map($(this).attr('rel'), 1);
      
      // Load detail list
      show_detail_list_by_category($(this).attr('rel'));
      
      return false;
      
   });
}

// Adds a click event to an organization link in the category list pane that pens the info window for the matching marker
function bind_organization_link_click(org_id, markup) {
   $('.organization-link[rel="' + org_id + '"]').click(function() {
      markers[org_id].openInfoWindowHtml(markup, info_window_options);
   });
}

function load_search_pane(term, orgs) {
   $('div#dh-categories-list').empty();
   if (term != search_pane.term) { // This is a new search
      var link = '/search/category_list_markup/' + term + '/' + search_pane.page;

      increase_busy_count();
      $.get(link, function(markup) {
         search_pane.markup = markup;
         $('div#dh-categories-list').prepend(search_pane.markup);
         bind_category_menu_click_events();
         decrease_busy_count();
      });
   } else {
      $('div#dh-categories-list').prepend(search_pane.markup);
   }
}



function load_category_pane() {
   $('div#dh-categories-list').empty();

   var link = $('#category-nav').attr('val');
   
   if (typeof(link) == 'undefined') {
      link = '/category/list/1/html';
   }
   
   // Load menu markup
   increase_busy_count();
   $.get(link, function(markup) {
      $('div#dh-categories-list').prepend(markup);
      
      // We've added new links so we need to make sure the navigation funcitons are bound to them
      bind_category_menu_click_events();
      bind_category_back_click_events();
      decrease_busy_count();
   });
}


function show_detail_list_by_search(term) {
   var link = '/search/details_markup/' + term;

   increase_busy_count();
   $.get(link, function(markup) {
      $('div#dh-detail-box-outer-wrapper').remove();
      $('div#dh-org-results-outer-wrapper').after(markup);
      decrease_busy_count();
   });
}


function show_detail_list_by_category(cat_id) {
   var link = '/category/details_markup/' + cat_id;

   increase_busy_count();
   $.get(link, function(markup) {
      $('div#dh-detail-box-outer-wrapper').remove();
      $('div#dh-org-results-outer-wrapper').after(markup);
      decrease_busy_count();
   });
}

function show_category_map(cat_id, page){
   increase_busy_count();
   reset_map();
   $.getJSON('/organization/category/' + cat_id + '/' + page, function(orgs) {
      // Add markers
		$.each(orgs, function(i, org){
			add_org_marker_and_show_all(org);
		});
      decrease_busy_count();
	});
}

// Busy Icon functions
function increase_busy_count() {
   var prev_val = busy_count;
   busy_count++;
   if (prev_val == 0) {
      busy_icon_on();
   }
}

function decrease_busy_count() {
   if (busy_count != 0) {
      busy_count--;
   }
   if (busy_count == 0) {
      busy_icon_off();
   }
}

function busy_icon_on() {
   $('li.busy-icon').addClass('spinning');
}

function busy_icon_off() {
   $('li.busy-icon').removeClass('spinning');
}