$(document).ready(function(){
    
  // Initialise cookie
  $.Jookie.Initialise("consciousconsumers", -1);
    
  // Cafe Details pages
  if ($("#cafe-page").length) {
    setUpGoogleMapForCafeDetailsPage();
  }

  // Join as cafe / supplier pages
  tidyUpCreateBusiness();
  
  // Tidy up form errors
  if ($("div.form-errors").length) {
    tidyUpFormErrors();
  }

  showCorrectSearchFields();

  // Terms & Conditions tickbox
  $("#tandc-text").hide();
  $("#tandc-link").click(function() {
    $("#tandc-text").slideDown();
  });

  // When city field changes
  $("#metadata_field_select_2395").change(function() { 

    // Find out which city is selected
    var city = $(this).find("option:selected").attr("value").substring(0,3);
  
    // Show correct suburbs for this city
    // These will be the ones with the correct 3 letter prefix on the option value
    $("#metadata_field_select_2396 option").removeAttr("disabled");
    $("#metadata_field_select_2396 option").not("option[value^='" + city + "']").attr("disabled","disabled");
    $("#metadata_field_select_2396 option:first").show().removeAttr("disabled").attr("selected", "selected");

    // If the city chosen does not have any suburbs (other than itself), populate the (required) suburb field with the name of the town and then hide the suburb field.
    // This needs to be done as the suburb field is required.
    if (city == "cam" || city == "rag") {
      $("#metadata_field_select_2396 option[value^='" + city + "']").attr("selected", "selected");
      $("#metadata_field_select_2396").parent("div").slideUp();
    } else {
      $("#metadata_field_select_2396").parent("div").slideDown();
    }

  });

  setUpFindCafesAndSupplierLinks();
  
  // Pages with a search box
  if ($("#search-column").length) {
    repopulateSearchForm();
    tidyUpSearchForm();
    doActionsOnSearchSubmit();
    tidyUpSearchResults();
  }
  
  // Add zebra striping
  if ($("#search-results").length) {
    $("#search-results ul li:odd").addClass("odd");
  }
  
  // Dynamically load feature box based on previous searches
  if ($("#content-feature-box-wrapper, #right-column-feature-box-wrapper").length) {
    loadFeatureBox();
  }
  
  // Login form slidedown
  if ($(".create-form").length) {
    $("#create-form-login-link").click(function() {
      $("#create-form-login").slideDown();
      return false;
    });
  }

  // Photo Gallery
  $("#photoGallery a.galleryImage").fancybox(
    {'titlePosition' : 'over',
    'onComplete' : function() {
      $("#fancybox-wrap").hover(function() {
        $("#fancybox-title").fadeIn();
      }, function() {
        $("#fancybox-title").fadeOut();
      });
    }
  }); 

  // When user changes the sort option, also change the ascending / descending selector
  $('#search_page_2406_sort_by').change(function() {

    // Find which option has been selected
    var selectedValue = $(this).find('option:selected').attr('value');
 //   $('#search_page2406_sort_direction option').removeAttr('selected');

    if (selectedValue == '0') {
      $('#search_page_2406_sort_direction option[value="1"]').attr('selected', 'selected');
    } else {
      $('#search_page_2406_sort_direction option[value="0"]').attr('selected', 'selected');
    }
  });
  
});



// Setting up the Google Map
function setUpGoogleMapForCafeDetailsPage() {

  var contentString = $("").text();

  var lat = $("#latitude").text();
  var lng = $("#longitude").text();
  var latlng = new google.maps.LatLng(lat, lng);
  var myOptions = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("google-map"), myOptions);

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });

  var marker = new google.maps.Marker({
    position: latlng,
    map: map
   // title: contentString
  }); 

  infowindow.open(map,marker);

} // end setUpGoogleMapForCafeDetailsPage


// Populate Latitude and Longtitude
function populateLatLong() {

  var geocoder = null;
  var street = $("#metadata_field_text_2394_value").attr("value");
  var suburb = $("#metadata_field_select_2396 option:selected").text();
  var city = $("#metadata_field_select_2395 option:selected").text();
  var address = street + ", " + suburb + ", " +  city;

  geocoder = new google.maps.Geocoder();
  geocoder.geocode({ 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
  
  
        // Set hidden latitude and longitude metadata fields
        $("#metadata_field_text_221_value").attr("value", results[0].geometry.location.lat());
        $("#metadata_field_text_222_value").attr("value", results[0].geometry.location.lng());
      }
    }

    // If form passes javaScript validation, click the real submit button
    if (createBusinessFormValidation()) {
      $("#sq_commit_button").click();
    }

  });

} // end of populateLatLong() 


function showCorrectSearchFields() {

  // When the user selects Cafes or Suppliers from the 'search-type' search field,
  // either show the city field or the supply-to field.

  // Initially hide the supply-to field
  $("#supply-to").hide();
   toggleSearchFormFields();
  
  $("#search-type input").change(function() {
    toggleSearchFormFields();
  });
 
} // end showCorrectSearchFields



function toggleSearchFormFields() {

  selectedType = $("#search-type input:checked").attr("value");
  
  if (selectedType == "Cafe") {
    $("#search-city").show();
    $("#supply-to").hide();
  } else {
    $("#search-city").hide();
    $("#supply-to").show();
  };

} // end showCityOrRegionsServed


function doActionsOnSearchSubmit() {

  // Store search field data in cookie.
  // Also, clear unused search fields on submit.
  $("#search-button input").click(function() {
  
    // Retrieve search field values from form and set them in the cookie
    var businessType = $("#search-type input:checked").attr("value");
    $.Jookie.Set("consciousconsumers", "businessType", businessType);

    var city = $("#search-city option:selected").attr("value");
    $.Jookie.Set("consciousconsumers", "city", city);
    
    var regionsServed = $("#supply-to option:selected").attr("value");
    $.Jookie.Set("consciousconsumers", "regionsServed", regionsServed);
    
    var badge = $("#search-badges option:selected").attr("value");
    $.Jookie.Set("consciousconsumers", "badge", badge);

    // Clear unused search fields.
    // i.e. if Cafe is selected as the type, the supply-to field should be cleared
    // and if Supplier is selected as the type, the city field should be cleared
    if (businessType == "Cafe") {
      $("#supply-to option:selected").removeAttr("selected");
      $.Jookie.Set("consciousconsumers", "regionsServed", "");
    } else {
      $("#search-city option:selected").removeAttr("selected");
      $.Jookie.Set("consciousconsumers", "city", "");
    }

  });

} // end doActionsOnSearchSubmit



function tidyUpSearchForm() {

  // Change the text of the search-type radio button labels so that they read 'Cafes' and 'Suppliers to cafes'
  // instead of 'Cafe' and 'Supplier'
  $("label[for='queries_type_query_Cafe']").text("Cafes");
  $("label[for='queries_type_query_Supplier']").text("Suppliers to cafes");

  // Restrict which cities are shown in the City dropdown field. Remove unwanted options.
   $("#queries_city_query option[value='ragRaglan'], #queries_city_query option[value='camCambridge']").remove();


  // Change the text for the default option for the Supply To field
  $("#queries_regionsserved_query option[value='']").text("Any New Zealand region");

} // end tidyUpSearchForm




function repopulateSearchForm() {

  // We only need to repopulte the badges and the supply-to (regionsServed) fields.
  // These are hardcoded on the search form (so that they appear as a dropdown rather than tickboxes).
  // The values of the other fields are brought through correctly by Matrix.
  $.Jookie.Initialise("consciousconsumers", -1);

  var regionsServed = $.Jookie.Get("consciousconsumers", "regionsServed");
  $("#supply-to option[value=" + regionsServed + "]").attr("selected", "selected");

  var badge = $.Jookie.Get("consciousconsumers", "badge");
  $("#search-badges option[value=" + badge + "]").attr("selected", "selected");

} // end repopulateSearchForm



function loadFeatureBox() {

  // Dynamically load the featured business box using JavaScript.
  // The type and badge fields from previous searches are used to display a feature box which matches these fields.
  // If no matching cafe or business is found, the No Results display format displays a generic feature box.
  
  // Get field values from cookie
  var businessType = $.Jookie.Get("consciousconsumers", "businessType");
  var badge = $.Jookie.Get("consciousconsumers", "badge");
  var city = $.Jookie.Get("consciousconsumers", "city");
  var regionsServed = $.Jookie.Get("consciousconsumers", "regionsServed");

  // Check that fields are not undefined
  if (typeof badge == "undefined") {
    badge = "";
  }
  if (typeof city == "undefined") {
    city = "";
  }
  if (typeof regionsServed == "undefined") {
    regionsServed = "";
  }
  
  // The feature box may be in the right column or in the content area
  var featuredDOMId;
  var baseUrl;
  if ($("#content-feature-box-wrapper").length) {
    featuredDOMId = "#content-feature-box-wrapper";
    baseUrl = "http://www.consciousconsumers.org.nz/js/display-random-business-content-area/_nocache";
  } else if ($("#right-column-feature-box-wrapper").length) {
    featuredDOMId = "#right-column-feature-box-wrapper";
    baseUrl = "http://www.consciousconsumers.org.nz/js/display-random-business/_nocache";
  }
  
  if (typeof featuredDOMId != "undefined") {
    var url = baseUrl + "?type=" + businessType + "&badge=" + badge + "&city=" + city + "&regionsServed=" + regionsServed;
    $(featuredDOMId).load(url);
  }

} // end loadFeatureBox



function tidyUpSearchResults() {

  // If only one page of results, remove the text which says 'Displaying page 1 of 1'.
  if ($("#total-pages-number").text() == "1") {
    $("#current-page-sentence").remove();
  }

  // Tidy up search results navigation - remove unwanted next/prev links, and the whole search results nav if there is only one page
  if ($("#results-list-pagination").length) {
    // Strip the text (previous/next) that are not links
    $("#results-list-pagination").contents().not($("#results-list-pagination").children()).remove();

    if (!$("#results-list-pagination a").length) {
      $("#results-list-pagination").remove();
    }
  }

} // end tidyUpSearchResults



function tidyUpCreateBusiness() {

  // Actions to perform when user clicks dummy submit button
  // First add cafe page
  if ($("#page_asset_builder_2442").length){
    $("#create-business-button input").click(function() {
      // When page is submitted, get latitude and longitude coordinates for the physical address.
      // Inside the callback for this function is the JavaScript form validation.
      populateLatLong();     
    });
  }
  
  // Then add supplier page
  if ($("#page_asset_builder_2483").length){
    $("#create-business-button input").click(function() {
      
      // If form passes javaScript validation, click the real submit button
      if (createBusinessFormValidation()) {
        $("#sq_commit_button").click();
      }
      
    });
  }
  
  // Show only certain "supply to" checkboxes.
  // First hide them all.
  $("#supply-to-checkboxes li").hide();

  // Show selected regions. The values in this array must be identical to the metadata keys on CC.RegionsServed.
  var checkboxesToShow = ['auckland','waikato','wellington'];
  
  // Loop through checkboxesToShow array, showing only these checkboxes (and associated labels and lis).  
  for (var i=0; i < checkboxesToShow.length; i++) {
    $("#supply-to-checkboxes li input[id*='" + checkboxesToShow[i] + "']").parent("li").show();
  }
  
  // Change text on City and Suburb dropdown boxes
  $("#metadata_field_select_2395 option[value='']").text("-- Eligible towns & cities --");
  $("#metadata_field_select_2396 option[value='']").text("-- Eligible suburbs --");

} // end tidyUpCreateBusiness



function createBusinessFormValidation() {

  // On join a cafe page, check that at least one display material has been chosen
  var errorText = "";

  // Check that the display material has been completed successfully (if it is on the form)
  if ($("#display-material").length) {

    var dispMaterial = false;
  
    $("#display-material select").each(function(index) {
      if ($(this).find("option:selected").attr("value") != "") {
        dispMaterial = true;
      }
    });
    
    if (!dispMaterial) {
      errorText += "You must choose at least one Display Material\n\n";
    }
  }

  // Check if Terms and Conditions checkbox has been ticked.
  if ($("#tandcs:checked").length == 0) {
    errorText += "You must agree to the Terms and Conditions\n\n";
  }
  
  if (errorText.length) {
    alert(errorText);
    return false;
  } else {
    return true;
  }

}  // end createBusinessFormValidation


function setUpFindCafesAndSupplierLinks() {

  // Set cookie values when the Find Cafes or Find Suppliers menu nav links are clicked
  // This will ensure the correct feature box shows in the right column on the search page
  $("a[href*='find-cafes']").click(function() {
  
    // If there are any query string parameters in the link, use these to set values in the cookie.
    var url = $(this).attr("href");
    var queryString = getQueryString(url);

    // Set businessType and reset all other fields in the cookie
    $.Jookie.Set("consciousconsumers", "businessType", "Cafe");
    $.Jookie.Set("consciousconsumers", "city", getQueryStringValue(queryString, 'queries_city_query'));
    $.Jookie.Set("consciousconsumers", "regionsServed", "");
    $.Jookie.Set("consciousconsumers", "badge", getQueryStringValue(queryString, 'queries_badges_query'));

  });

  $("a[href*='find-suppliers']").click(function() {
  
    // If there are any query string parameters in the link, use these to set values in the cookie.
    var url = $(this).attr("href");
    var queryString = getQueryString(url);

    // Set businessType and reset all other fields in the cookie
    $.Jookie.Set("consciousconsumers", "businessType", "Supplier");
    $.Jookie.Set("consciousconsumers", "city", "");
    $.Jookie.Set("consciousconsumers", "regionsServed", getQueryStringValue(queryString, 'queries_regionsserved_query'));
    $.Jookie.Set("consciousconsumers", "badge", getQueryStringValue(queryString, 'queries_badges_query'));

  });

} // end setUpFindCafesAndSupplierLinks



function tidyUpFormErrors() {

  // Some Matrix errors come through on the forms when some fields are filled in.
  // Doesn't seem to be any way of stopping these from coming through from Matrix, so we'll hide them.
  $("div.form-errors li:contains('SYS'), div.form-errors li:contains('CORE')").each(function() {
  
    if ($(this).text().indexOf('SYS0073') > 0) {
      $(this).remove();
    }
    if ($(this).text().indexOf('SYS0017') > 0) {
      $(this).text("Your password and confirmation passwords don't match");
    }
    if ($(this).text().indexOf('CORE0220') > 0) {
      $(this).text("Your password needs to be at least 6 characters long");
    }
  
  });

} // end tidyUpFormErrors



function getQueryString(url) {

  var queryString = "";
  var queryStringPos = url.indexOf("?");
  if (queryStringPos > 0) {
    queryString = url.substring(queryStringPos + 1);
  }
  return queryString;

} // end getQueryString



function getQueryStringValue(queryString, qsKey) {

  var queryStringArr = queryString.split("&");
  var qsValue = "";
  for (var i = 0; i < queryStringArr.length; i++) {
    var keyValuePairArr = queryStringArr[i].split("=");
    if (keyValuePairArr[0] == qsKey) {
      qsValue = keyValuePairArr[1]
    }
  }
  return qsValue;

}  // end getQueryStringValue
