$("#projectSelector").change(function() {
  var title = $("#projectSelector").val();
  updateThumbnails(title);
  updateProjectSnapshot(title);
});

var gGallery;
$(document).ready(function() {
  var select = document.getElementById('projectSelector');
  //$("div.listOfProjectsItem").each(function() {
  for ( i = 0; i < projects.length; i++ ) {
    var txt = $(this).find("div.listOfProjectsItemTitle").text();
    var txt2 = txt.replace(/[^a-zA-Z0-9]+/g, '_');
    //select.options[select.options.length] = new Option(txt, txt);
    //$("#projectSelector").append('<option value="'+txt2+'">'+txt+'</option>');
    $("#projectSelector").append('<option value="'+i+'">'+projects[i].Title+'</option>');
  }
  
  updateFilterDropdowns();
  
  // Build thumbnails from first matching project in drop-down;
  // subsequent projects invoke a callback
  var title = $("#projectSelector option:first").val();
  updateThumbnails(title, true);
  updateProjectSnapshot(title);
   
  if ( projects.length ) {
    // We only want these styles applied when javascript is enabled
    $('div#photoGallery').css('display', 'block');
  
    // Initially set  opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li, #thumbs a.pageLink').opacityrollover({
      mouseOutOpacity:   onMouseOutOpacity,
      mouseOverOpacity:  1.0,
      fadeSpeed:         'fast',
      exemptionSelector: '.selected'
    });
    // Initialize  Advanced Galleriffic Gallery
    var gallery = $('#thumbs').galleriffic({
      delay:                     3500,
      numThumbs:                 6,
      preloadAhead:              6,
      enableTopPager:            false,
      enableBottomPager:         false,
      imageContainerSel:         '#slideshow',
      controlsContainerSel:      '#controls',
      captionContainerSel:       '#caption',
      loadingContainerSel:       '#loading',
      renderSSControls:          false,
      renderNavControls:         true,
      playLinkText:              'Play Slideshow',
      pauseLinkText:             'Pause Slideshow',
      prevLinkText:              '&lsaquo; Previous Photo',
      nextLinkText:              'Next Photo &rsaquo;',
      nextPageLinkText:          'Next &rsaquo;',
      prevPageLinkText:          '&lsaquo; Prev',
      enableKeyboardNavigation:  false,
      enableHistory:             false,
      autoStart:                 false,
      syncTransitions:           true,
      defaultTransitionDuration: 900,
      onSlideChange:             function(prevIndex, nextIndex) {
        // 'this'  refers to the gallery, which is an extension of $('#thumbs')
        this.find('ul.thumbs').children()
            .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
            .eq(nextIndex).fadeTo('fast', 1.0);
  
        // Update the photo index display
        this.$captionContainer.find('div.photo-index')
            .html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
      },
      onPageTransitionOut:       function(callback) {
        this.fadeTo('fast', 0.0, callback);
      },
      onPageTransitionIn:        function() {
        this.fadeTo('fast', 1.0);
      }
    });
    
    if ( gallery.getNumPages() > 1 ) {
      // Show  appropriate next / prev page links
      gallery.find('a.prev').show();
      gallery.find('a.next').show();
    }
  
    gallery.find('a.prev').click(function(e) {
      gallery.previousPage();
      e.preventDefault();
    });
  
    gallery.find('a.next').click(function(e) {
      gallery.nextPage();
      e.preventDefault();
    });
    
    gGallery = gallery;
  
    if ( $("#projectDetailLeft").height() > $("#projectDetailRight").height() ) {
      $("#projectDetailRight").height($("#projectDetailLeft").height());
    }
    
    $("li.thumb:nth-child(6)").find("a.thumb").css('margin-bottom', '0px');
    $("li.thumb:last").find("a.thumb").css('margin-bottom', '0px');
  } else {
    $("div#photoGalleryMain").html('<h2>No matching projects found. Please try again.</h2><p><a href="./">View all projects</a></p>');
    $("#photoGalleryThumbs").css('display', 'none');
    $("#photoGallery").css('display', 'block');
  }
});

// Updates thumb nails based on selected project (by  title)
// use Gallerific's built-in removeImage() and  appendImage() functions to do this
function updateThumbnails(title, init) {
  if ( init ) {
    $("ul.thumbs").empty();
  } else {
    while ( gGallery.data.length ) {
      gGallery.removeImageByIndex(gGallery.data.length - 1);
    }
  }
  
  if ( projects.length ) {
    $.each(projects[title].images, function(i, val) {
      if ( projects[title].images ) {
        var html = '<li class="thumb">';
        html += '<a class="thumb" href="' + val + '?w=480&h=322&padded=true" title="' + title + '">';
        html += '<img src="' + val + '?w=150&h=113" alt="' + title + '" /></a>';
        html += '</li>';
        if ( init ) {
          $("ul.thumbs").append(html);
        } else {
          gGallery.appendImage(html);
        }
      }
    });
  }  
  if ( !init ) {
    gGallery.gotoIndex(0, false, true);
  }
}

function updateProjectSnapshot(title) {
  if ( typeof(projects[title]) != 'undefined' ) {
    $("#projectNumber span").text(projects[title].Project);
    var html = $("div.listOfProjectsItemTitle:contains('"+projects[title].Title+"')").parent().find(".divEditDeleteControls").html();
    if ( html ) {
      $("#projectDetails .inner span.editdel").remove();
      $("#projectDetails .inner strong").after('<span class="editdel">&nbsp;&nbsp;' + html + '</span>');
    }
    if ( projects[title].WoodType ) {
      $("#projectWoodType").text(projects[title].WoodType);
      $("#projectWoodType").show();
    } else {
      $("#projectWoodType").hide();
    }
    if ( projects[title].FinishingOption )  {
      $("#projectFinishing").text(projects[title].FinishingOption);
      $("#projectFinishing").show();
    } else {
      $("#projectFinishing").hide();
    }
    if ( projects[title].BottleCapacity)  {
      $("#projectCapacity span").text(projects[title].BottleCapacity);
      $("#projectCapacity").show();
    } else {
      $("#projectCapacity").hide();
    }
    if ( projects[title].InteriorFurnishing) {
      $("#projectFurnishing").text(projects[title].InteriorFurnishing);
      $("#projectFurnishing").show();
    } else {
      $("#projectFurnishing").hide();
    }
    if ( projects[title].CellarLocation)  {
      $("#projectLocation span").text(projects[title].CellarLocation);
      $("#projectLocation").show();
    } else {
      $("#projectLocation").hide();
    }
    $("#projectDetailRight").html('');
    if ( projects[title].Skus ) {
      var tmp = projects[title].Skus.split(',');
      $.each(tmp, function(i, val) {
        val = $.trim(val);
        var html = '<div class="productThumb">';
        //html += '<a href="' + storeDomain + '/Impact3StoreService/AddToCart.aspx?mainProduct=' + val + '">';
        html += '<a href="' + storeDomain + '/Impact3StoreService/AddToWishlist.aspx?quickaddsku=' + val + '">';
        html += '<img src="' + storeDomain + '/Images/products/' + val + '_S.jpg" width="60" height="81" alt="' + val + '" title="' + val + '" /><br />';
        html += '<img src="/gallery-button-add.gif" width="31" height="22" alt="Add" style="padding: 5px 0;" />';
        html += '</a>';
        html += '</div>';
        $("#projectDetailRight").append(html);
      });
      $("#projectDetailRight").append('<div class="clear"></div>');
      $("#projectDetailRight").css("border-left", "solid 1px #ccc");
    }
  
    if ( $("#projectDetailLeft").height() > $("#projectDetailRight").height() ) {
      $("#projectDetailRight").height($("#projectDetailLeft").height());
    }
    
    // Adjust overall height of content container, so we don't spill out over the bottom
    var heights = $("#contentInner > h1").height() + $("#projectFilters").height() + $("#matchingProjects").height() + $(".divAddControl").height();
    heights += $(".slideshow-container").height();
    heights += $("#projectDetails").height();
    if ( heights > $("#contentInner").height() ) {
      $("#contentInner").height(heights + 17);
    }
  }
}

function updateFilterDropdowns() {
  var woodTypes = [], finishOptions =  [], bottles = [], furnish = [], location = [];

  // We only want to show filters for actual data...
  var url = document.URL.replace('http://www.winecellarinnovations.com', '');
  pixelsilk2.getListItems({
    path: url,
    fields: ["WoodType", "FinishingOption", "BottleCapacity", "InteriorFurnishing2", "CellarLocation"],
    filters: [],
    filterrel: "",
    sorts: [],
    pagesize: "1000",
    page: "1"
  }, function(json) {
    for ( var i = 0; i < json.length; i++ ) {
      woodTypes.push(json[i].WoodType);
      finishOptions.push(json[i].FinishingOption);
      bottles.push(json[i].BottleCapacity);
      var tmp = json[i].InteriorFurnishing2;
      tmp = tmp.split(',');
      for ( var j = 0; j < tmp.length; j++ ) {
        if ( $.trim(tmp[j]) ) {
          furnish.push($.trim(tmp[j]));
        }
      }
      location.push(json[i].CellarLocation);
    }
    woodTypes = woodTypes.unique();
    woodTypes.sort();
    finishOptions =  finishOptions.unique();
    finishOptions.sort();
    bottles.sort(sortNumber);
    //bottles.sort();
    furnish = furnish.unique();
    furnish.sort();
    location = location.unique();
    location.sort();

    var select = document.getElementById('filter1');
    $.each(woodTypes, function(i, val) {
      if ( document.URL.indexOf(val) > -1 ) {
        select.options[select.options.length] = new Option(val, 'WoodType,eq,' + val, true, true);
      } else {
        select.options[select.options.length] = new Option(val, 'WoodType,eq,' + val);
      }
    });

    var select = document.getElementById('filter2');
    $.each(finishOptions, function(i, val) {
      if ( document.URL.indexOf(val) > -1 ) {
        select.options[select.options.length] = new Option(val, 'FinishingOption,eq,' + val, true, true);
      } else {
        select.options[select.options.length] = new Option(val, 'FinishingOption,eq,' + val);
      }
    });

    var select = document.getElementById('filter3');
    $.each(bottles, function(i, val) {
      if ( document.URL.indexOf(val) > -1 ) {
        select.options[select.options.length] = new Option(val, 'BottleCapacity,eq,' + val, true, true);
      } else {
        select.options[select.options.length] = new Option(val, 'BottleCapacity,eq,' + val);
      }
    });

    var select = document.getElementById('furnishFilter');
    $.each(furnish, function(i, val) {
      if ( document.URL.indexOf(val) > -1 ) {
        select.options[select.options.length] = new Option(val, val, true, true);
      } else {
        select.options[select.options.length] = new Option(val, val);
      }
    });
    $("form#projectFilters").submit(function() {
      // Remove any extra hidden fields this may have added
      if ( tmp = $("#numFilters").val() ) {
        for ( i = 0; i < tmp; i++ ) {
          $('#filter' + (i + 5)).remove();
        }
        $("#numFilters").remove();
      }
      var i = 0;
      $("#furnishFilter option:selected").each(function() {
        i++;
        $("form#projectFilters").append('<input type="hidden" name="filter' + (i+4) + '" id="filter' + (i+4) + '" value="InteriorFurnishing2,contains,' + $(this).val() + '" />');
      });
      $("form#projectFilters").append('<input type="hidden" name="numFilters" id="numFilters" value="' + i + '" />');
      var tmp = '';
    });

    var select = document.getElementById('filter4');
    $.each(location, function(i, val) {
      if ( document.URL.indexOf(val) > -1 ) {
        select.options[select.options.length] = new Option(val, 'CellarLocation,eq,' +  val, true, true);
      } else {
        select.options[select.options.length] = new Option(val, 'CellarLocation,eq,'  + val);
      }
    });

  });
}

function sortNumber(a,b) {
  return a - b;
}
