/**
 * Common JS
 *
 * @author veselka.ua
 * @version 0.2
 * @modify 16-03-2018
 */


var commonEvents = (function ($)
{

	/**
	 * Navbar
	 */
	$.runNavbarEvents = {


		/**
		 * Navbar
		 */
		nav: '#stick-menu',


		/**
		 * Offset
		 */
		origOffsetY: 0,


		/**
		 * Init
		 */
		init: function ()
		{
			var _this = this;
			/* Scroll */
			this.origOffsetY = $(this.nav).offset().top;
			this.stickMenu();
			$(window).scroll(function(e)
			{
				_this.stickMenu();
			});
		},


		/**
		 * Stick menu
		 */
		stickMenu: function()
		{
			if( $(window).width() < 767 )
			{
				//return true;
			}
			//var urlRelative = $('#navbar-logo').attr('src');
			//var cond = urlRelative.split('navbar_logo');

			if( $(window).scrollTop() >= this.origOffsetY )
			{
				if( !$(this.nav).hasClass('navbar-fixed-top') )
				{
					$(this.nav).addClass('navbar-fixed-top');
				}
				//$('header.affix-add').addClass('header-affix-margin-top');
				$('.logo-wrap').removeClass('hidden');
				$('.social-wrap').addClass('hidden');
				$('.phone-wrap').removeClass('hidden');
				$('.logo-phone-wrap').addClass('hidden');
				$('.phone-btn-wrap').removeClass('hidden');
				$('.email-btn-wrap').removeClass('hidden');
				$('#menu-top').addClass('navbar-right');
				// body position
				//$('body').css('position','initial');
			}
			else
			{
				if( $(this.nav).hasClass('navbar-fixed-top') )
				{
					$(this.nav).removeClass('navbar-fixed-top');
				}
				//$('header.affix-add').removeClass('header-affix-margin-top');
				$('.logo-wrap').addClass('hidden');
				$('.social-wrap').removeClass('hidden');
				$('.phone-wrap').addClass('hidden');
				$('.logo-phone-wrap').removeClass('hidden');
				$('.phone-btn-wrap').addClass('hidden');
				$('.email-btn-wrap').addClass('hidden');
				$('#menu-top').removeClass('navbar-right');
				// body position
				//$('body').css('position','relative');
			}
		},

	};



	/**
	 * Affix
	 */
	$.runAffixEvents = {


		/**
		 * Display width
		 */
		width: '',


		/**
		 * Init
		 */
		init: function ()
		{
			var _this = this;

			// Width
			$( window ).load( function()
			{
				_this.width = window.innerWidth;

				// Affix
				_this.affixLoad();
			});


			// Resize
			$( window ).resize( function()
			{
				if( _this.width == '' )
				{
					_this.width = window.innerWidth;
					return;
				}
				// Only width
				if( _this.width != window.innerWidth )
				{
					// Distroy affix (if exists)
					_this.affixDestroy();
					// Affix
					_this.affixLoad();
					// New width
					_this.width = window.innerWidth;
				}
			});

		},


		/**
		 * Affix load
		 */
		affixLoad: function()
		{
			if( $('.menu-affix').length == 0 )
			{
				return false;
			}

			if( this.width < 992 && $('aside').length )
			{
				return false;
			}
			if( this.width < 768 && $('.product-thumbnail').length )
			{
				return false;
			}
			if( $('#content').outerHeight() < $('.menu-affix').outerHeight() )
			{
				return false;
			}

			var offsetTop = 0;
			$.each( $('.affix-add'), function( i, v )
			{
				offsetTop = offsetTop + $(this).outerHeight();
				//console.log($(this).outerHeight());
			});
			if( $('.navbar').data('correction') != undefined )
			{
				offsetTop = offsetTop + parseInt($('.navbar').data('correction'));
			}

			var offsetBottom = 0;
			$.each( $('.affix-sub'), function( i, v )
			{

				offsetBottom = offsetBottom + $(this).outerHeight();
			});
			// Поправк отступа
			offsetBottom = offsetBottom + 72;
			offsetTop = offsetTop + 10;
			// Поправка для това
			if( $('.product-thumbnail').length )
			{
				offsetBottom = offsetBottom - 13;
				offsetTop = offsetTop - 30;
			}

			// Set affix
			$('.menu-affix').affix({
				offset: {
					top: offsetTop,
					bottom: offsetBottom,
				}
			});
			$(window).on('resize', function()
			{
				$('.menu-affix').scrollspy('refresh');
			});
		},


		/**
		 * Affix destroy
		 */
		affixDestroy: function()
		{
			// Distroy affix (if exists)
			$(window).off('.affix');
			$('.menu-affix').removeData('bs.affix').removeClass('affix affix-top affix-bottom');
		},

	};



	/**
	 * Phones popover
	 */
	$.runPopoverEvents = {


		/**
		 * Popover
		 */
		popover: {
			btnId:			'#phones-popover',
			selectorName:	'contact-phones-popover',
			container:		'#masthead-shopping',
		},


		/**
		 * Init
		 */
		init: function ()
		{
			var _this = this;

			// Width
			$( window ).load( function()
			{
				// Phones popover
				_this.popoverPhonesActions();
			});
		},


		/**
		 * Phones popover
		 */
		popoverPhonesActions: function()
		{
			var _this = this;
			// Show popover
			$(this.popover.btnId).popover({
				animation:false,
				container: this.popover.container,
				placement:'bottom',
				html:true,
				template:'<div id="'+this.popover.selectorName+'" class="popover" role="tooltip" style=""><div class="popover-content"></div></div>',
			});
			// Popouver paddings
			var currentId;
			$(this.popover.btnId).on('shown.bs.popover', function ()
			{
				currentId = '#'+$(this).attr('aria-describedby');
				var left = $(_this.popover.btnId).offset().left-15+'px';
				var top = $(_this.popover.btnId).offset().top-15+'px';
				if( window.innerWidth > 768 )
				{
					$(currentId).css('left',left);
				}
				$(currentId).css('top',top);
			});
			// Hide on click outside, trigger='focus' not working
			$('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 )
				{
					$(_this.popover.btnId).popover('hide');
				}
			});
			// BUGFIX: double click
			$(this.popover.btnId).on('hidden.bs.popover', function (e)
			{
				$(e.target).data('bs.popover').inState.click = false;
			});
		},
	};



	/**
	 * Search highlighting
	 */
	$.highlighting = {

		/**
		 * Takes in an array of consecutive TextNodes and returns a document fragment with `word` highlighted
		 *
		 * @argument array nodes
		 * @argument string word
		 */
		highlight_text_nodes: function(nodes, word)
		{
			if (!nodes.length)
			{
				return;
			}

			var text = '';

			// Concatenate the consecutive nodes to get the actual text
			for (var i = 0; i < nodes.length; i++)
			{
				text += nodes[i].textContent;
			}

			var fragment = document.createDocumentFragment();

			while (true)
			{
				// Tweak this if you want to change the highlighting behavior
				var index = text.toLowerCase().indexOf(word.toLowerCase());

				if (index === -1)
				{
					break;
				}

				// Split the text into [before, match, after]
				var before = text.slice(0, index);
				var match = text.slice(index, index + word.length);
				text = text.slice(index + word.length);

				// Create the <mark>
				var mark = document.createElement('mark');
				mark.className = 'found';
				mark.appendChild(document.createTextNode(match));

				// Append it to the fragment
				fragment.appendChild(document.createTextNode(before));
				fragment.appendChild(mark);
			}

			// If we have leftover text, just append it to the end
			if (text.length)
			{
				fragment.appendChild(document.createTextNode(text));
			}

			// Replace the nodes with the fragment
			nodes[0].parentNode.insertBefore(fragment, nodes[0]);

			for (var i = 0; i < nodes.length; i++)
			{
				var node = nodes[nodes.length - i - 1];
				node.parentNode.removeChild(node);
			}
		},


		/**
		 * Highlights all instances of `word` in `node` and its children
		 *
		 * @argument link node
		 * @argument string word
		 */
		mark: function(node, word)
		{
			var children = node.childNodes;
			var current_run = [];

			for (var i = 0; i < children.length; i++)
			{
				var child = children[i];

				if (child.nodeType === Node.TEXT_NODE)
				{
					// Keep track of consecutive text nodes
					current_run.push(child);
				}
				else
				{
					// If we hit a regular element, highlight what we have and start over
					this.highlight_text_nodes(current_run, word);
					current_run = [];

					// Ignore text inside of our <mark>
					if (child.nodeType === Node.ELEMENT_NODE && child.className !== 'found')
					{
						this.highlight(child, word);
					}
				}
			}

			// Just in case we have only text nodes as children
			if( current_run.length )
			{
				this.highlight_text_nodes(current_run, word);
			}
		},


		/*
		 * Removes all highlighted <mark>s from the given node
		 *
		 * @argument link node
		 */
		unmark: function(node)
		{
			var marks = [].slice.call(node.querySelectorAll('mark.found'));

			for (var i = 0; i < marks.length; i++)
			{
				var mark = marks[i];
				// Replace each <mark> with just a text node of its contents
				mark.parentNode.replaceChild(document.createTextNode(mark.childNodes[0].textContent), mark);
			}
		},

	
	};



	/**
	 * Common ajax 
	 *
	 * 1. Write session data (save)
	 * 2. Load ajax data
	 * 3. Erase session data
	 *
	 */
	$.common =
	{
		/**
		 * Verification codes
		 */
		proof:
		{
			// Common
			dataSave:		'166c4ec6b541f604df0c3f70ecca17ad',
			dataErase:		'201194fc0c1fd8f5301498ed9ab5ba80',
			dataLoad:		'a944ce16dbe7ab9224fcb2b6305013ee',
			loadAnswer:		'7c7d65d534452cf0568a6ee80ee77244',
			// Calculator
			preinstalled:	'42fc715079818c5414af490a2f239a1f',
			allInclusive:	'45839ae6dd57bd439fcbf95baf631632',
			// Shopping cart
			cartList:		'8387e75558297875d1712d63b725940d',
			cartToDb:		'c0cb24a8b6c42bcae45775eb72bc6f38',
			encryptedId:	'd8babccce0cb156c01e70983c1da8b2c',
		},


		/**
		 * Objects links
		 */
		obj:
		{
			control:		{},
			calculator:		{},
			cart:			{},
		},


////////////////////////////// WRAP METHODS //////////////////////////////


		/**
		 * Write session data (save)
		 *
		 * @argument string client
		 */
		writeSessionData: function(client)
		{
			// Undefined?
			if( typeof client == 'undefined' ) {
				return;
			}

			// Data cunstruct
			var data = {};
			data.proof = this.proof.dataSave;
			data[client] = this.obj[client][client];
			//console.log(data);
			// Ajax
			this.sendAndReturnResponse(client, data);
		},


		/**
		 * Load current ajax data
		 *
		 * @argument string client
		 */
		loadDeferredAjaxData: function(client)
		{
			// Undefined?
			if( typeof client == 'undefined' ) {
				return;
			}

			var _this = this;
			// Data cunstruct
			var data = {};
			data.proof = this.proof.dataLoad;
			// Ajax
			this.sendAndWriteData(client, client, data);
		},


		/**
		 * Erase session data
		 *
		 * @argument string client
		 */
		eraseSessionData: function(client)
		{
			// Undefined?
			if( typeof client == 'undefined' ) {
				return;
			}

			// Data cunstruct
			var data = {};
			data.proof = this.proof.dataErase;
			// Ajax
			this.sendAndReturnResponse(client, data);
		},


////////////////////////////// PRIVATE METHODS //////////////////////////////



		/**
		 * Send ajax and return response
		 *
		 * @argument string client
		 * @argument object data
		 * @argument bool flag
		 */
		sendAndReturnResponse: function(client, data, flag)
		{
			// Undefined?
			if( typeof client == 'undefined' ) {
				return;
			}

			var _this = this;
			// Check flag
			if( typeof flag == 'undefined' )
			{
				flag = false;
			}
			//console.log(data);
			// Ajax
			this.obj[client].deferred.push(
				$.ajax({
					url: this.obj[client].ajaxFile,
					type: 'POST',
					dataType: 'json',
					data: data,
					success: function(response, code)
					{
						//console.log(flag);console.log(client);
						//console.log(response);//console.log(code);
						if( flag )
						{
							_this.obj[client]['ajaxData'] = response;
						}
					},
					error: function(response, code)
					{
						console.log(code+' '+response);
					}
				})
			);
		},


		/**
		 * Send ajax data trow deffered and write result to property
		 *
		 * @argument string client
		 * @argument string prorertyToWrite
		 * @argument object data
		 */
		sendAndWriteData: function(client, prorertyToWrite, data)
		{
			// Undefined?
			if( typeof client == 'undefined' ) {
				return;
			}

			var _this = this;
			// Ajax
			this.obj[client].deferred.push(
				$.ajax({
					url: this.obj[client].ajaxFile,
					type: 'POST',
					dataType: 'json',
					data: data,
					//async: false,
					success: function(response, code)
					{
						if( response.proof != _this.proof.loadAnswer )
						{
							return;
						}
						//response.proof = null;
						delete response.proof;
						$.each( response, function( index, data )
						{
							if( index != 'proof' && data != '' )
							{
								_this.obj[client][prorertyToWrite][index] = data;
							}
						});
						//console.log(this.control);
					},
					error: function(response, code)
					{
						console.log(response);
					}
				})
			);
		},


	};




})(jQuery);


$(document).ready(function()
{
	// Navbar
	if( $('#stick-menu').length > 0 )
	{
		$.runNavbarEvents.init();
	}
	// Affix
	if( $('aside').length || $('.product-thumbnail').length )
	{
		$.runAffixEvents.init();
	}
	// Shopping popover
	if( $('#masthead-shopping').length > 0 )
	{
		$.runPopoverEvents.init();
	}
});