﻿$(document).ready(function() {
  var $vp = jQuery('.version-picker');
  var product = $vp.data('product');
  var versionListUrl = '';
  var $select = jQuery('select', $vp);

  if (product !== undefined) {
    var file = 'vp.json'

    versionListUrl = '/docscdn/' + product + '/config/' + file;
  }

  if (!versionListUrl) {
    return;
  }

  jQuery.ajax({
    url:      versionListUrl,
    complete:  function(data) {
      addVpOptions(data, $select);
      $select.on('change', openVersion)
      $vp.on('mouseover', disableVersions)
    }
  });
})

// Open selected version.
function openVersion() {
  var optionValue = jQuery(this).val();
  if (optionValue != "") {
      window.location.href = optionValue;
  }
}

// Disable unavailable versions based on file existence.
function disableVersions(){
  var $vp = jQuery(this);

  if ($vp.hasClass('processed')) {
    return;
  }
  $vp.addClass('processed');

  // iterate over options in vp
  var $list = jQuery('option', $vp);

  $list.each(function() {
    var $option = jQuery(this);
    var url = $option.val(); // url is stored in value attribute
    var last = url.substr(-1);

    if (last !== 'l' && last !== 'm' && last !== '/') {
      url += '/';
    }
    UrlExists(url, $option);
  });
}

// Fill Vp options and select current one.
function addVpOptions(data, $select) {
  var versions = data.responseJSON;

  if (!Array.isArray(versions)) {
    return;
  }

  var currentPage = window.location.pathname.split('/');
  var currentVersion = currentPage[3];
  currentPage.splice(1,3);
  var endPage = currentPage.join('/');

  jQuery.each(versions, function(i, item){
    $select.append(jQuery('<option>', {
      value: item.path + endPage,
      text: item.label,
      selected: item.path.indexOf(currentVersion) > -1
    }));
  });
}

// check if url exists for given version
function UrlExists(url, $option) {
  jQuery.ajax({
    url:      url,
    dataType: 'text',
    type:     'HEAD',
    complete:  function(data){
      $option.attr('disabled', data.status !== 200);
    }
  });
}

