var pulldowns;
var stores_list;
var stores_per_page = 16;
var page = 0;
var column_target_element = "listings_columns";


function changeCountry() {
  selected_country = $('country').value;
  if (selected_country == "Canada")
  {
    Element.addClassName($('state'), "inactive");
    stores_list = new Array();
    writeListingColumns();
    updateDistribution('Canada');
  } else {
    updateStatePulldown(selected_country);
    updateListings();
  }
}

function handleListings(request) {
  // alert(request.responseText);
  // var json = eval('(' +request.responseText+ ')');
  var json_obj = eval('(' +request.responseText+ ')');
  stores_list = json_obj['Stores'];
  // writeListingColumns(json['Stores'], "listings_columns");
  writeListingColumns();
  updateDistribution(json_obj['Distribution Zone']);
}

function next_page() {
  page = page+1;
  writeListingColumns()
}
  
function prev_page() {
  page = page-1;
  writeListingColumns()
}

function updateDistribution(zone) {
  $A(document.getElementsByClassName("distribution_zone")).each(function(div) {
    Element.addClassName(div, "inactive");
  });
  Element.removeClassName($(zone), "inactive");
}

function updateListings() {
  // var selected_country = $('country').options[$('country').selectedIndex].value;
  var selected_country = $('country').value;
  var url = "/data/store_list.php?country=";
  url    += encodeURIComponent(selected_country);
  var state = $('state').value;
  if (state) {
    url    += '&state=' + encodeURIComponent(state);
  }
  new Ajax.Request(url, {
    method: 'get',
    onComplete: handleListings
  });
}

function updateStatePulldown(selected_country) {
  var states_list = pulldowns[selected_country];
  $('state').innerHTML = "";
  if (states_list.length == 0) {
    Element.addClassName($('state'), "inactive"); 
  } else {
    Element.removeClassName($('state'), "inactive");
  }
  
  $A(states_list).each(function(state) {
    var new_option = document.createElement("option");
    new_option.setAttribute('value', state['value']);
    var option_text = document.createTextNode(state['name']);
    new_option.appendChild(option_text);
    $('state').appendChild(new_option)
  });
}

function writeListingColumns() {
  target_element = $(column_target_element);
  if (stores_list.length > stores_per_page) {
    var page_links = new Array();
    var range_begin = page*stores_per_page;
    var range_end   = (page+1)*stores_per_page;
    list = stores_list.slice(range_begin, range_end);
    if (page > 0) {
      page_links[page_links.length] = "<a href='javascript:prev_page();'>previous</a>";
    }
    if (stores_list.length >= range_end) {
        page_links[page_links.length] = "<a href='javascript:next_page();'>next</a>";
    }
  } else {
    list = stores_list;
  }
  var stores_count = list.length;
  target_element = $(target_element);
/*    
  var col1_count = Math.ceil(stores_count/3);
  var col2_count = Math.ceil((stores_count-col1_count)/2);
  var col3_count = stores_count-col1_count-col2_count;
*/
  var col1_count = Math.ceil(stores_count/2);
  var col2_count = stores_count-col1_count;
  
  var makeColumn = function(col_list, id) {
    var col = document.createElement("div");
    col.setAttribute('id', id);
    var html = "";
    col_list.each(function(store, idx) {
      html += '<div class="store_listing">';
      html += '<div class="store_name">' +store['Store Name']+ '</div>';
      html += '<div class="street_address">' +store['Street Address']+ '</div>';
      html += '<div class="city_state_zip">' +store['City']+ 
/*          ' ' +store['State']+ '' +store['Postal Code']+ */'</div>';
      html += '<div class="phone">' +store['Telephone']+ '</div>';
      html += '</div>';
    });
    col.innerHTML = html;
    return col;
  };
  
  var col_container = document.createElement("div");
  col_container.setAttribute('id', 'col_container');

  col_container.appendChild(makeColumn(list.slice(0,col1_count), "col1"));
/*    
  col_container.appendChild(makeColumn(list.slice(col1_count,col1_count+col2_count), "col2"));
  col_container.appendChild(makeColumn(list.slice(col1_count+col2_count), "col3"));
*/
  col_container.appendChild(makeColumn(list.slice(col1_count), "col2"));
  
  target_element.innerHTML = '';
  target_element.appendChild(col_container);
  
  if (page_links != undefined && page_links.length > 0) {
    var page_links_div = document.createElement("div");
    page_links_div.setAttribute('id', 'page_links');
    page_links_div.innerHTML = page_links.join(' | ');
    var br = document.createElement("br");
    br.setAttribute('clear', 'all');
  target_element.appendChild(br);
  target_element.appendChild(page_links_div);
  }
}


function init() {
  pulldowns   = eval('(' +$("pulldowns").innerHTML+ ')');
  var cnt     = $("json").innerHTML;
  var stores  = eval('(' +cnt+ ')');
  stores_list = stores['Stores'];
  writeListingColumns();
  util.addEventListener($("country"), "change", changeCountry);
  util.addEventListener($("state"), "change", updateListings);
  updateDistribution(stores['Distribution Zone']);
}