'use strict';

/**
 * CONSTANTS
 */
var BASE_RANDOM_NUMBER = 25,
    CUBE_SELECTOR = "#cube-wall",
    POPOVER_SELECTOR = "[data-toggle='popover']",
    SEARCH_FIELD_NAME = 'search_field',
    CUBE_SELECTOR_WRAP = '.cubes_inner_wrap',
    GRID_HEIGHT = 14,
    GRID_WIDTH = 30,
    FADE_TIME = 600,
    POPOVER_HEIGHT = 450;

$(document).ready(function(){
  detectOutdatedBrowser();

  initPlaceOfCubes();
  initGallerySlider();
  mobilePartners();
  initTip();
  initMap();
  topTip();
  initTooltipster();
  playStopVideoInModal();
  initTwentytwenty();
  scrollToTop();

  $('[data-toggle="popover"]').popover({title: "<span class=\"usr_surname\">Фондар</span><span class=\"usr_name\">Вікторія Тараневська <a href=\"#\" class=\"round_link\"><i class=\"icon icon_fb\"></i></span>", content: "<div class=\"usr_contributions\">Внесків 3</div><div class=\"usr_funds\"><div class=\"usr_funds_value\">на суму:  14 200 UAH</div></div><div class=\"usr_volunteering\">Волонтерство 2</div>", html: true, placement: "top"});
})

function scrollToTop() {
  $(window).scroll(function(){
    if ($(this).scrollTop() > 1000) {
      $('#scroller').fadeIn();
    } else {
      $('#scroller').fadeOut();
    }
  });
  $('#scroller').click(function () {
    $('body,html').animate({
        scrollTop: 0
    }, 600);
    return false;
  });
}


function initTwentytwenty() {
  $(window).load(function(){
    $(".twentytwenty-container[data-orientation!='vertical']").twentytwenty({default_offset_pct: 0.7});
  });
}

function playStopVideoInModal(){
  $('body').on('click', '.tooltipster_img', function(){
    var src = $(this).attr('href');
    $('.modal_video iframe').attr('src', src);
  })

  $(".modal").on('hidden.bs.modal', function () {
    $('.modal_video iframe').removeAttr('src');
  });

  $('body').on('click', '.modal_video .close', function(){
    $('.modal_video iframe').removeAttr('src');
  })
}

function initTooltipster(){
	if (window.matchMedia("(max-width: 991px)").matches) {
		$('.tooltipstered').tooltipster({
	    contentCloning: true,
	    trigger: 'click',
	    position: 'right',
	    interactive: true,
	    minWidth: 256,
      multiple: true
		});
		$('.grid_item').not('.last').find('.grid_item_content').on('click', function(e){
			e.preventDefault();
		})
	} else {
		$('.tooltipstered').tooltipster({
		  contentCloning: true,
	    trigger: 'hover',
	    position: 'right',
	    interactive: true,
	    minWidth: 256,
      multiple: true
		});
	}
}

function detectOutdatedBrowser(){
  outdatedBrowser({
	bgColor: '#f25648',
	color: '#ffffff',
	lowerThan: 'transform',
	languagePath: ''
  })
}

function initGallerySlider() {
  $('#gallery-2').royalSlider({
    controlNavigation: 'thumbnails',
    thumbs: {
      orientation: 'vertical',
      paddingBottom: 0,
      appendSpan: true,
      spacing: 10
    },
    transitionType:'move',
    autoScaleSlider: true,
    // autoScaleSliderWidth: 790,
    autoScaleSliderHeight: 360,
    loop: true,
    arrowsNav: false,
    keyboardNavEnabled: true
  });
}

function topTip() {
  $(window).load(function(){
		$(".show_tip").delay(1000).fadeIn(500);
		setTimeout(function(){
		  $(".show_tip").fadeOut(500);
		}, 6000);
  });
  // $(".show_tip").delay(1500).fadeIn(500);
  // setTimeout(function(){
  //   $(".show_tip").fadeOut();
  // }, 6500);
}

function initTip(){
  $('[data-toggle=tooltip]').tooltip();
}

function initMap() {
// The location of Uluru
 var uluru = {lat: 48.9161793, lng: 24.7258968};
 // The map, centered at Uluru
 var map = new google.maps.Map(
     document.getElementById('map'), {zoom: 4, center: uluru});
 // The marker, positioned at Uluru
 var marker = new google.maps.Marker({position: uluru, map: map});
}

// function initMap(){
// 	if ($('#map').length) {
// 		var map = new GMaps({
// 	  el: '#map',
// 	  lat: -12.043333,
// 	  lng: -77.028333,
// 	  zoomControl : true,
// 	  zoomControlOpt: {
// 		  style : 'SMALL',
// 		  position: 'TOP_LEFT'
// 	  },
// 	  panControl : false,
// 	  streetViewControl : false,
// 	  mapTypeControl: false,
// 	  overviewMapControl: false
// 	  });
// 	}
// }

function mobilePartners() {
  var checkWidth = $(window).width();

  if (window.matchMedia("(min-width: 768px)").matches) {
		$("#owl-demo").trigger('destroy.owl.carousel');
		$("#owl-demo").removeClass('owl-carousel');
  } else {
		$("#owl-demo").addClass('owl-carousel');
		$("#owl-demo").owlCarousel({
		  items: 1,
		  loop: true
		});
  }
}


$(window).resize(function() {
  mobilePartners();
  initTooltipster();
  initDraggable();
});

/**
 * @function initPlaceOfCubes - function for drawing cubes(images) on place(some element)
 */
function initPlaceOfCubes() {
  $.ajax({
    url: "builder_users_squares",
    method: "GET"
  }).done(function (data) {
    var sourceData = data;
    var baseHeight = getCubeBaseHeight(sourceData);

    initAutocomplete(sourceData, SEARCH_FIELD_NAME);
    searchFounder();
    var html = generateCubeHTML(sourceData, baseHeight);
    $(CUBE_SELECTOR).html(html);
	  var promise = new Promise(function(resolve, reject) {
      $.getJSON('js/json/cube_diff.json', function (data) {
        _.map($('.cell:not(.empty)'), function(item, i) {
          var correct_height,
            fault = Number(data[String($(item).data('folder'))]);
          correct_height = roundedToNumber(fault, GRID_HEIGHT) + GRID_HEIGHT/2 - fault;
          $(item).css('margin-top', correct_height + 'px');
        });
        setTimeout(function(){resolve(data);}, 200)
      });
    });
    promise.then(function(){
        if (gratitudeCubeElement.id) {
          centralizeContainer($(CUBE_SELECTOR), gratitudeCubeElement.get().position(), gratitudeCubeElement.get().width());
        }
    });
    initPopover($(POPOVER_SELECTOR));
    initFreewall(CUBE_SELECTOR, baseHeight);
    initDraggable($(CUBE_SELECTOR));
  }).fail(function (msg) {
    console.error(msg);
  });
}

/**
 * @function gratitudeCube - service for managing popup (gratitude)
 */
var gratitudeCubeElement = {
  element: null,
  id: null,
  get: function() {
    this.element = $('[data-id=' + this.id + ']');
    return this.element;
  },
  set: function(id) {
    this.id = id;
  }
};


/**
 * @function initFreewall - function for initialization
 * @param cubeSelector - container, where is drawing cubes
 * @param sourceData - {Array}, array of cube's object
 */
function initFreewall(cubeSelector, baseHeight) {
  var wall = new Freewall(cubeSelector);
  wall.reset({
    selector: '.cell',
    animate: true,
    /*draggable: true,*/
    gutterY: 0,
    gutterX: 0,
    cellW: function(){},
    cellH: function(){},
    //bottomToTop: true,
    onResize: function () {
      /*wall.fitWidth();*/
      var height = $(cubeSelector).height();
      wall.fitHeight(height);
    }
  });
  // for scroll bar appear;
  $(window).trigger("resize");
}

/**
 * @function getCubeBaseHeight - function for getting max height of cube block
 * @param sourceData - {Array}, array of cube's object
 */
function getCubeBaseHeight(sourceData) {
  var height = _.max(_.map(sourceData, function (item) {
        return item.height || GRID_HEIGHT*5;
      })) + getRandomNumber();
    height = roundedToNumber(height, GRID_HEIGHT);
    return height;
}

/**
 * @function getCubeWidth - function for getting max height of cube block
 * @param width - {Int}, width of cube block
 */
function getCubeWidth(width) {
  var resultWidth = roundedToNumber((width + getRandomNumber()), GRID_WIDTH);
    return resultWidth;
}

/**
 * @function roundedToNumber - function for rounding to some(optional) number
 * @param currentNumber - {Int}, number for rounding
 * @param roundedNumber - {Int}, number to round
 */
function roundedToNumber(currentNumber, roundedNumber) {
    var resultWidth = Math.ceil(currentNumber/roundedNumber) * roundedNumber;
    return resultWidth;
}

/**
 * @function initDraggable - function for initialization draggable property
 * @param selector - {JQuery Object}, selector using for draggable
 */
function initDraggable() {
  $(CUBE_SELECTOR).draggable({
    drag: function(event, ui) {
      var additionalLimit = 150,
          customHeight = getCustomHeight(additionalLimit),
          customWidth = getCustomWidth(additionalLimit);

      // if (ui.position.top > additionalLimit) {
      //   ui.position.top = additionalLimit;
      // }
      // if (ui.position.top - customHeight <= 0) {
      //   ui.position.top = customHeight;
      // }
      // if (ui.position.left > additionalLimit) {
      //   ui.position.left = additionalLimit;
      // }
      // if (ui.position.left - customWidth <= 0) {
      //   ui.position.left = customWidth;
      // }
    },
      stop: function(event, ui) {
          var top = roundedToNumber(ui.position.top, GRID_HEIGHT),
              left = roundedToNumber(ui.position.left, GRID_WIDTH);
          $(CUBE_SELECTOR).animate({ 'left': left + 'px', 'top': top + 'px' }, FADE_TIME);
      },
    scroll: false,
    cursor: 'move'});

  function getCustomWidth(additionalLimit) {
    return $(CUBE_SELECTOR_WRAP).width() - $(CUBE_SELECTOR).width() - additionalLimit;
  }

  function getCustomHeight(additionalLimit) {
    return $(CUBE_SELECTOR_WRAP).height() - $(CUBE_SELECTOR).height() - additionalLimit;
  }
}

/**
 * @function getRandomNumber - function for generating random int number
 * @param number - {Number}, not required
 */
function getRandomNumber(number) {
  number = number || BASE_RANDOM_NUMBER;
  return number * Math.random() << 0;
}

/**
 * @function initPopover - function for initialization popover
 * @param selector - {JQuery Object}, popover selector
 */
function initPopover(selector) {
  selector.each(function () {
    var $elem = $(this);
    $elem.popover({
      placement: 'top auto',
      html: true,
      container: $elem
    });
  });
  
  selector.on('show.bs.popover', function () {
    var minTop = getCssValueByInt($(CUBE_SELECTOR).parent(), 'margin-top'),
      popoverHeight = GRID_HEIGHT*10;
    if ($(this).offset().top - minTop < popoverHeight) {
      $(CUBE_SELECTOR).animate({ 'top': popoverHeight + 'px'}, FADE_TIME);
    }
  });

  selector.on('shown.bs.popover', function () {
    $('.default_tip').addClass('hidden_tip');
    var id = $(this).parents('.cell').attr('data-id');
    ($(CUBE_SELECTOR).find('.cell[data-id]:not([data-id='+id+'])')).find(POPOVER_SELECTOR).popover('hide');
  });

  $('body').on('click', function (e) {
    //did not click a popover toggle, or icon in popover toggle, or popover
    if ($(e.target).data('toggle') !== 'popover'
        && $(e.target).parents('[data-toggle="popover"]').length === 0
        && $(e.target).parents('.popover.in').length === 0) {
      $('[data-toggle="popover"]').popover('hide');
    }
  });
}

/**
 * @function generateCubeHTML - function for generating html for cube map
 * @param sourceData - {Array}, array of cube's object
 * @param baseHeight - {Int}, height of all cubes
 */
function generateCubeHTML(sourceData, baseHeight) {
  var baseWidth = 2*GRID_WIDTH,
    additionalArray,
    gratitudeElement,
    emptyElement,
    width,
    html = '',
    iWeight,
    iHeight,
    source,
    countCubes = getCountOfCubes();
  if (sourceData.length < countCubes) {
    additionalArray = new Array(countCubes-sourceData.length);
    sourceData = _(sourceData).concat(additionalArray);
  }
  //generate random array
  sourceData = _.shuffle(sourceData);
  gratitudeElement =
    "<div class='cell' style='width: {width}px; height: {height}px;' data-id='{id}' data-folder='{folder_name}'>" +
    "<div style='display: inline-block; position: relative; '>" +
    "<div class='default_tip' style='position: absolute; bottom: calc(100% + 20px); left: {iHalfWeight}px; z-index: 999'> " +
    "<div class='default_tip_content'> " +
    "<div class='default_tip_title'>{gratitude_title} </div> <div class='default_tip_text'>{gratitude_phrase}</div> " +
    "<div class='vertical_soc {gratitude_share} '> " +
    "<a href=\"{link_share_facebook}\" class='circle_link soc_btn_fb hidden_link_share_facebook'><span><i class='icon icon_fb'></i></span> <i class='icon icon_right_arrow_lg'></i></a> " +
    "<a href=\"{link_share_twitter}\" class='circle_link soc_btn_tw hidden_link_share_twitter'><span><i class='icon icon_tw'></i></span> <i class='icon icon_right_arrow_lg'></i></a> " +
    "<a href=\"{link_share_google}\" class='circle_link soc_btn_google hidden_link_share_google'><span><i class='icon icon_google'></i></span> <i class='icon icon_right_arrow_lg'></i></a> " +
    "</div> " +
    "</div> " +
    "</div>" +
    "<div data-toggle='popover' " +
    "title='<span class=\"usr_surname\">{role}</span>" +
    "<span class=\"usr_name\">{name} " +
    "<a href=\"{facebook}\" class=\"round_link\"><i class=\"icon icon_fb\"></i></a>" +
    "</span>' " +
    "data-content='<div class=\"usr_contributions\">{contributions_title} {contributions_value}</div>" +
    "<div class=\"usr_funds\">{funds_title}<div class=\"usr_funds_value\">{funds_value} {funds_currency}</div>" +
    "</div>' " +
    "class='usr-info'>" +
    "<img width='{iWeight}' height='{iHeight}' src='{source}' alt=''/>" +
    "</div>" +
    "</div>" +
    "</div>";
  emptyElement = "<div class='cell empty' style='height: " + baseHeight + "px; width: " + baseWidth + "px;' ></div>";
  _.map(sourceData, function (item) {
    if (!Boolean(item)) {
      html += emptyElement;
      return;
    }
    var fullElement = getElement(item.info.links.facebook);
    iHeight = item.height;
    iWeight = item.width;
    width = getCubeWidth(iWeight );
    source = item.source || ''; //set default image
    if (item.id == item.user_donate) {
      gratitudeCubeElement.set(item.user_donate);
      fullElement = gratitudeElement
        .replace(/\{gratitude_title\}/, item.title)
        .replace(/\{gratitude_phrase\}/, item.phrase)
        .replace(/\{gratitude_share\}/, getGratitudeShareClass(item.is_share))
    }

    //customize social network links
    _.map(item.info.links, function(link, social) {
      var socialReg = new RegExp('\{' + social + '\}');
      fullElement = fullElement.replace(socialReg, link);
    });

    //customize social network links by sharing
    _.map(item.socials, function(link, social) {
      var socialReg = new RegExp('\{' + social + '\}'),
        socialRegClassName = 'hidden_' + social;
      if ($.trim(link).length != 0) {
        fullElement = fullElement
          .replace(socialReg, link)
          .replace(socialRegClassName, '');
      }
    });

    html += fullElement
        .replace(/\{id\}/, item.id)
        .replace(/\{folder_name\}/, item.folder_name)
        .replace(/\{height\}/, baseHeight)
        .replace(/\{width\}/, width)
        .replace(/\{iHeight\}/g, iHeight)
        .replace(/\{iHalfWeight\}/, -35 + iWeight/2)
        .replace(/\{iWeight\}/, iWeight)
        .replace(/\{source\}/, source)
        .replace(/\{name\}/, item.info.name)
        .replace(/\{role\}/, item.info.role)
        .replace(/\{contributions_title\}/, item.info.contributions.title)
        .replace(/\{contributions_value\}/, item.info.contributions.value)
        .replace(/\{funds_title\}/, item.info.funds.title)
        .replace(/\{funds_value\}/, item.info.funds.value)
        .replace(/\{funds_currency\}/, item.info.funds.currency);

  });

  return html;
}

function getCountOfCubes() {
  var countViaWidth = $(CUBE_SELECTOR).width()/60 >> 0,
    countViaHeight = $(CUBE_SELECTOR).height()/38 >> 0,
    baseCount = countViaHeight * countViaWidth;
  return baseCount;
}

function getElement(fbLink) {
  fbLink = Boolean(fbLink) ? "<a href=\"{facebook}\" class=\"round_link\"><i class=\"icon icon_fb\"></i></a>" : '';
  return "<div class='cell' style='width: {width}px; height: {height}px;' data-id='{id}' data-folder='{folder_name}'>" +
    "<div style='display: inline-block;'>" +
    "<div data-toggle='popover' data-trigger='hover' " +
    "title='<span class=\"usr_surname\">{role}</span>" +
    "<span class=\"usr_name\">{name} " +
    fbLink +
    "</span>' " +
    "data-content='<div class=\"usr_contributions\">{contributions_title} {contributions_value}</div>" +
    "<div class=\"usr_funds\">{funds_title}<div class=\"usr_funds_value\">{funds_value} {funds_currency}</div>" +
    "</div>' " +
    "class='usr-info'>" +
    "<img width='{iWeight}' height='{iHeight}' src='{source}' alt=''/>" +
    "</div>" +
    "</div>" +
    "</div>";
}

function getGratitudeShareClass(isShare) {
  var className = '';
  if (!isShare) {
    className = 'hidden_share';
  }
  return className;
}

/**
 * @function initAutocomplete - function for initialization auto complete by input
 * @param data - {Array}, array of cube's object
 * @param selector - {JQuery Object}, input selector
 */
function initAutocomplete(data, selector) {
  data = data || [];
  var input = document.getElementById(selector);
  var listByNameFounders = _.map(data, function(item, i) {
    return {
      value: item.info.name,
      data: item
    };
  });

  $('#' + selector).autocomplete({
    lookup: listByNameFounders,
    onSelect: function (suggestion) {
      if (window.currentSuggestion == suggestion.data.id) {
        return;
      }
      window.currentSuggestion = suggestion.data.id;
      var element = $('[data-id=' + suggestion.data.id + ']'),
          scrollingContainer = $(CUBE_SELECTOR),
          position = element.position();
        centralizeContainer(scrollingContainer, position, element.width());
      setTimeout(function () {
        //hide popovers except selected
        (scrollingContainer.find('.cell[data-id]:not([data-id=' + suggestion.data.id + '])')).find(POPOVER_SELECTOR).popover('hide');
      }, 0);

      setTimeout(function () {
        //show selected item (popover)
        element.find(POPOVER_SELECTOR).popover('show');
      }, FADE_TIME);
    },
    onSearchComplete: function (query, suggestion) {
      window.suggestion = suggestion;
      if (window.query !== query) {
        window.query = query;
        window.currentSuggestion = -1;
      }
    }
  });
}

/**
 * @function getCssValueByInt - function for getting value (value type like number) and parse it into Int type
 * @param selector - {JQuery Object}, selector
 */
function  getCssValueByInt(selector, property) {
  return parseInt(selector.css(property));
}

/**
 * @function centralizeContainer - function for centralizing container
 * @param container - {JQuery Object}, selector
 * @param position - {Object}, which consists keys "left" and "top"
 */
function centralizeContainer(container, position, correctWidth) {
    correctWidth = correctWidth || 0;
    var top = roundedToNumber((getCssValueByInt(container.parent(), 'margin-top') + POPOVER_HEIGHT - parseInt(position.top)), GRID_HEIGHT),
        left = roundedToNumber((container.width()/2 - correctWidth - parseInt(position.left)), GRID_WIDTH);
    container.animate({ 'left': left + 'px', 'top': top + 'px' }, FADE_TIME);

}

/**
 * @function searchFounder - function for searching by founder name
 */
function searchFounder() {
  $('.search_btn').on('click', function() {
    searching();
  });

  $('#' + SEARCH_FIELD_NAME).keypress(function(event) {
    if(event.which == 13) {
      _.map($('.autocomplete-suggestion'), function(item) {
        if ($('#' + SEARCH_FIELD_NAME).val() === $(item).text()) {
          $(item).trigger('click');
        }
      });
      searching();
    }
  });
  function searching() {
    window.currentSuggestion = -1;
    $('#' + SEARCH_FIELD_NAME).focus();
  }
}

