
//  1 - Include Plugins
//  2 - Loader
//  3 - Main Navigation Dropdown
//  4 - Input Field
//  5 - Top Header Active Background Apply Color
//  6 - Go To Top Button
//  7 - AFFIX
//  8 - Smooth Scroll Page
//  9 - Modal Box
// 10 - Tabs
// 11 - Left Right Slide
// 12 - Fancy Scrollbar
// 13 - Left Menu
// 14 - Add/Delete Rows
// 15 - Popup Gallery
// 16 - Item Carousel
// 17 - Counter
// 18 - Rating
// 19 - My Tabs Style
// 20 - LazyLoad Images
// 21 - Get Creditcart Type
// 22 - YouTube API
// 23 - Full Screen Toggle


/***** 1 - Include Plugins*/
window.as_html_preload();

window.afterReady.push(function(){
	if ($(".ZipCodeMsk").length) $(".ZipCodeMsk").mask("99999");
	if ($(".StateCodeMsk").length) $(".StateCodeMsk").mask("AA");
	if ($(".PhnNmbrMsk").length) $(".PhnNmbrMsk").mask("9999999999");
	if ($(".DateMsk").length) $(".DateMsk").mask("99/99/9999");
	if ($(".VisaCardNumberMsk").length) $(".VisaCardNumberMsk").mask("9999-9999-9999-9999");
	if ($(".AccountNumberMsk").length) $(".AccountNumberMsk").mask("999999999");
	if ($(".SocialSecurityNumber").length) $(".SocialSecurityNumber").mask("999-99-9999");
	
	if ($(".SocialSecurityNumber").length) $(".SocialSecurityNumber").mask("999-99-9999");
	
	if ($(".credit_card_expiration").length) $('[name="credit_card_expiration"]').mask("99/9999");
	if ($(".credit_card_number").length) $('[name="credit_card_number"]').each(function(e,c){
		
		changeCardImg(e);
	});
	
});

window.afterReady.push(function(){
	if ($('[as_dev_signature]').length) {
		$('[as_dev_signature]').as_signature();
	}
});

window.afterReady.push(function(){
	$('.datePicker').each(function(){

		var input = $(this).find('input');
		var span = $(this).find('.input-group-append');
		span.prop('data-target',input[0]).prop('data-target',input[0]).data('target',input[0])
		$(this).prop('data-target',input[0]).prop('data-target',input[0]).data('target',input[0])

		input.datetimepicker({
			format: 'L'
		});
	});

	$('.timePicker').each(function(){

		var input = $(this).find('input');
		var span = $(this).find('.input-group-append');
		span.prop('data-target',input[0]).prop('data-target',input[0]).data('target',input[0])
		$(this).prop('data-target',input[0]).prop('data-target',input[0]).data('target',input[0])

		input.datetimepicker({
			format: 'LT'
		});
	});

	$('.dateTimePicker').each(function(){

		var input = $(this).find('input');
		var span = $(this).find('.input-group-append');
		span.prop('data-target',input[0]).prop('data-target',input[0]).data('target',input[0])
		$(this).prop('data-target',input[0]).prop('data-target',input[0]).data('target',input[0])

		input.datetimepicker();
	});
	//$('.dateTimePicker').asdevtestPicker();

});

window.fn_fn_include_file = {};
window.fn_include_file = function(e, as_fn)
{
	try
	{
		//console.log(e);
		var fn_name = e.toString().split(' ');
		//console.log(JSON.stringify(e) + '_line _ 85');
		//console.log(as_fn.toString() + '_line _ 86');
		//console.log(as_fn.toString());
		//console.log(fn_name + '_line _ 88');
		fn_name = (fn_name[1])?fn_name[1]:fn_name[0];
		fn_name = fn_name.split(').');
		fn_name = (fn_name[1])?fn_name[1]:fn_name[0];
		fn_name = fn_name.split('.');
		fn_name = (fn_name[1])?fn_name[1]:fn_name[0];
		
		if( $.trim(e.toString().indexOf('ReferenceError:')) !== '-1' && $.trim(e.toString().indexOf('variable:')) !== '-1' )
		{
			fn_name = e.toString().split('variable:');
			//console.log(fn_name);
			fn_name = $.trim(fn_name[1]);
			
		}
		
		if($.trim(fn_name) === 'undefined' || typeof(fn_name) === 'undefined' )
		{
			fn_name = e.toString().split('...');
			fn_name = fn_name[1];
			fn_name = fn_name.split(').');
			fn_name = (fn_name[1])?fn_name[1]:fn_name[0];
			fn_name = fn_name.split('.');
			fn_name = (fn_name[1])?fn_name[1]:fn_name[0];
			//console.log(fn_name + '_line _ 109');
		}
		
	}catch(e){console.log(e.toString());}
	
	try
	{
		if($.trim(fn_name) === '\'undefined\'' || $.trim(fn_name) === '\'null\'')
		{
			var as_fn_list = ['marqueeInit','slider','easyZoom','starrr','datetimepicker','mask','Inputmask','inputmask','as_signature','autocomplete','mentionsInput'];
			for(var i=0;as_fn_list.length>i;i++)
			{
				//console.log(as_fn_list[i]);
				//console.log(as_fn.toString().indexOf(as_fn_list[i]) !== -1);
				if(as_fn.toString().indexOf(as_fn_list[i]) !== -1 )
				{
					window.fn_include_file(as_fn_list[i],as_fn);
					return;
					break;
				}
			}
		}
	}catch(e){console.log(e.toString()+ '_line _ 159');}
	
	try
	{
		switch(fn_name)
		{
			case 'marqueeInit':
				console.log(window.imgPath + 'plugins/scrolling/crawler.js');
				include_file(window.imgPath + 'plugins/scrolling/crawler.js',as_fn);
				/*window.fn_fn_include_file['marqueeInit'] = setInterval(function(as_fn){
					try
					{
						console.log(as_fn);
						as_fn();
						clearInterval(window.fn_fn_include_file['marqueeInit']);
					}catch(e){}
				},200,as_fn);*/
			break;

			case 'slider':
				include_file(window.imgPath + 'plugins/jquery-ui-1.12.1/jquery-ui.css');
				include_file(window.imgPath + 'plugins/jquery-ui-1.12.1/jquery-ui.js',as_fn);
			break;

			case 'easyZoom':
				include_file(window.imgPath + 'plugins/easyzoom/easyzoom.js',as_fn);
			break;

			case 'starrr':
				include_file(window.imgPath + 'plugins/rating/like-rating.js',as_fn);
			break;

			case 'datetimepicker':
				include_file(window.imgPath + 'plugins/bootstrap-datepicker/moment-with-locales.min.js',function(){
					include_file(window.imgPath + 'plugins/bootstrap-datepicker/moment-timezone-with-data-2012-2022.min.js',function(){
						include_file(window.imgPath + 'plugins/bootstrap-datepicker/bootstrap-datetimepicker.js',as_fn);
					});
				});
				
				include_file(window.imgPath + 'plugins/bootstrap-datepicker/bootstrap-datetimepicker.css');
				

				/*window.fn_fn_include_file['datetimepicker'] = setInterval(function(as_fn){
					try
					{
						console.log(as_fn);
						as_fn();
						clearInterval(window.fn_fn_include_file['datetimepicker']);
					}catch(e){}
				},200,as_fn);*/
			break;

			case 'Mask':
			case 'mask':
				console.log('Mask');
				include_file(window.imgPath + 'plugins/inputmasked/jquery.maskedinput.js',as_fn);
			break;
			
			//case 'resizeCanvas':
			case 'as_signature':
				include_file(window.imgPath + 'plugins/signature_pad/signature_pad.umd.js');
				include_file(window.imgPath + 'plugins/signature_pad/app.js',as_fn);
			break;
			
			case 'mentionsInput':
				include_file(window.imgPath + 'plugins/mentionsInput/jquery.mentionsInput.css');
				
				include_file(window.imgPath + 'plugins/mentionsInput/underscore-min.js',function(){
					include_file(window.imgPath + 'plugins/mentionsInput/jquery.elastic.js',function(){
						include_file(window.imgPath + 'plugins/mentionsInput/jquery.mentionsInput.js',as_fn);
					});
				});
			break;

			default:
				console.log(fn_name);
				return;
			break;
		}
		as_fn();
	}catch(e){/*fn_include_file(e,as_fn);*/}
};


window.html_lodded_files = {};
function include_file (file, callback, file_type ){
	var xf = file;
	xf = xf.split('?');
	xf = xf[0];
	xf = xf.split('.');
	xf = xf[xf.length-1];
	xf = xf.toLowerCase();
	
	xf = (file_type)?file_type.toLowerCase():xf;

	if (window.html_lodded_files[file])
	{
	}else
	{
		window.html_lodded_files[file] = true;
		//console.log(xf);
		
		switch(xf)
		{
			case 'css':
				
				var script = document.createElement( "link" )
				//script.type = "text/javascript";
				
				if(script.readyState) {  //IE
					script.onreadystatechange = function() {
						if ( script.readyState === "loaded" || script.readyState === "complete" ) {
							script.onreadystatechange = null;
							try{callback();}catch(e){}
						}
					};
				} else {  //Others
					script.onload = function() {
						try{callback();}catch(e){}
					};
				}
				
				/*$('head').append('<link rel="stylesheet" href="' + file +  '" rel="preload">');*/
				script.rel = "stylesheet";
				script.href = file;
			break;
			
			case 'js':
				
				var script = document.createElement( "script" )
				//script.type = "text/javascript";
				
				if(script.readyState) {  //IE
					script.onreadystatechange = function() {
						if ( script.readyState === "loaded" || script.readyState === "complete" ) {
							script.onreadystatechange = null;
							try{callback();}catch(e){}
						}
					};
				} else {  //Others
					script.onload = function() {
						try{callback();}catch(e){}
					};
				}
				
				
				/*$('head').append('<script src="' + file +  '"></script>');*/
				script.type = "text/javascript";
				script.src = file;
			break;
		}
		
		document.getElementsByTagName( "head" )[0].appendChild( script );
		
	}
};

if(false)
{
	include_file(window.imgPath + 'plugins/bootstrap-select/bootstrap-select.min.css');
	include_file(window.imgPath + 'plugins/bootstrap-select/bootstrap-select.min.js');
	include_file(window.imgPath + 'plugins/scrolling/crawler.js');

	include_file(window.imgPath + 'plugins/bootstrap-datepicker/moment-with-locales.min.js');
	include_file(window.imgPath + 'plugins/bootstrap-datepicker/moment-timezone-with-data-2012-2022.min.js');
	include_file(window.imgPath + 'plugins/bootstrap-datepicker/bootstrap-datetimepicker.css');
	include_file(window.imgPath + 'plugins/bootstrap-datepicker/bootstrap-datetimepicker.js');

	include_file(window.imgPath + 'plugins/easyzoom/easyzoom.js');
	
	include_file(window.imgPath + 'plugins/range-slider/multirange.css');
	include_file(window.imgPath + 'plugins/range-slider/multirange.js');
};

$('.SelectStyle').each(function(){
	include_file(window.imgPath + 'plugins/bootstrap-select/bootstrap-select.min.css');
	include_file(window.imgPath + 'plugins/bootstrap-select/bootstrap-select.min.js');
});



//***** 2 - Loader
$( document ).ready(function() {
	if (typeof(window.afterReady) !== 'undefined')
	{
		for(k in window.afterReady)
		{
			try{window.afterReady[k]();}catch(e){fn_include_file(e,window.afterReady[k]);}
		}
	}
	window.afterReady = [];
	setTimeout(function(){
		$('#loader-wrapper').fadeOut('fast');
	}, 500);
});

//console.log(window.afterLoad[5]);
$(window).on('load',function() {
	if (typeof(window.afterLoad) !== 'undefined')
	{
	    //console.log( window.afterLoad );
		for(k in window.afterLoad)
		{
		    if (typeof window.afterLoad[k] === 'function')
		    try{window.afterLoad[k]();}catch(e){fn_include_file(e,window.afterLoad[k]);}
		}
	}
	//window.afterLoad = [];
});

$(document).on('click focusin','.date input',function() {
	setTimeout(function(ele){
		old_val = ele.value;
		if($(ele).closest('.date').find('.bootstrap-datetimepicker-widget').length)
		{
			
		}else
		{
			$(ele).closest('.date').find('[data-toggle]').trigger('click');
		}
		if($.trim(old_val)==='') ele.value='';
	},10,this);
});
$(document).on('blur focusout','.date input',function() {
	setTimeout(function(ele){
		
		if($(ele).closest('.date').find('.bootstrap-datetimepicker-widget').length)
		{
			$(ele).closest('.date').find('[data-toggle]').trigger('click');
		}
		
	},10,this);
});



//***** 3 - Main Navigation Dropdown
$(function() {
	var nav_bar_dropdown_set_timeout = 0;
	$('.navbar-nav .dropdown, .navbar-nav .dropdown-submenu').mouseenter(function(e) {
		clearTimeout(this.mouseTimeOut);
		ele = this;
		if($(ele).parent().hasClass('nohover'))
		{
			return;
		}
		//console.log($(ele).find('.dropdown-toggle').first()[0]);
		if(!$(ele).hasClass('show')) $(ele).find('.dropdown-toggle').first().trigger('click');
	}).mouseleave(function(e) {
		clearTimeout(this.mouseTimeOut);
		this.mouseTimeOut = setTimeout(function(ele){
			
			if($(ele).parent().hasClass('nohover'))
			{
				return;
			}
			//console.log($(ele).find('.dropdown-toggle').first()[0]);
			if($(ele).hasClass('show')) $(ele).find('.dropdown-toggle').first().trigger('click');
			
		},500,this);
	});

	$("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {
		event.preventDefault();
		event.stopPropagation();
		$(this).parent().toggleClass("show");
		$(this).siblings().toggleClass("show");
	});
	
	$(".stop_toggle[data-toggle='dropdown']").on("click", function(event) {
		event.preventDefault();
		event.stopPropagation();
		$(this).parent().toggleClass("show");
		$(this).siblings().toggleClass("show");
	});
});

var dd_obj = {
    jq_win :jQuery(window),
    jq_doc :jQuery(document),
  };
  function selfCalc(ele) {
    var $this = jQuery(ele),
        $dd_menu = $this.children(".dropdown-menu"), 
        ddOffset = $this.offset(),
        ddMenu_posTop = dd_obj.jq_win.outerHeight(true ) - (($this.outerHeight(true ) + ddOffset.top + $dd_menu.outerHeight(true )) - dd_obj.jq_doc.scrollTop());
        ddMenu_posRight = dd_obj.jq_win.outerWidth(true ) - (($this.outerWidth(true ) + ddOffset.left + $dd_menu.outerWidth(true )) - dd_obj.jq_doc.scrollLeft());

    (ddMenu_posTop <= 0) ? $this.addClass("dropup") : $this.removeClass("dropup"); 
    (ddMenu_posRight <= 0) ? $this.find('.dropdown-menu').addClass("dropdown-menu-right") : $this.find('.dropdown-menu').removeClass("dropdown-menu-right");
  }
  jQuery('body').on("shown.bs.dropdown", ".dropdown", function () {
    var self = this;
    selfCalc(self)
    dd_obj.jq_win.on('resize.custDd scroll.custDd mousewheel.custDd',function() {
      selfCalc(self)
    })
  }).on("hidden.bs.dropdown", ".dropdown", function() {
      // there is no need to keep the window event after dropdown has closed, 
      // still if we keep the event then there is no use
      dd_obj.jq_win.off('resize.custDd scroll.custDd mousewheel.custDd')
  });

$(document).on('click','[data-target="#navbarContent"],[data-is_mobile_menu="true"]',function(){
	//console.log('Clicked');
	var aria_expanded = $(this).attr('aria-expanded');
	//console.log(aria_expanded);
	
	$('.navbar [aria-expanded="true"]').not(this).trigger('click');
	
	if($.trim(aria_expanded) === 'true')
	{
		$('html').addClass('is_mobile_menu');
	}else
	{
		$('html').removeClass('is_mobile_menu');
	}
});


//***** 4 - Input Field
window.ele_valid_chk = function(ele)
{
	if($.trim(ele.value) === '')
	{
		$(ele).removeClass('not_empty');
		$(ele).closest('.dropdown').removeClass('not_empty');
	}else
	{
		$(ele).addClass('not_empty');
		$(ele).closest('.dropdown').addClass('not_empty');
	}
};

$('.FieldWrapp input, .FieldWrapp textarea, .SelectStyle select').each(function(index, element) {
    window.ele_valid_chk(element);
});

$(document).on('click focus focusin focusout blur change keypress keyup keydown','.FieldWrapp input, .FieldWrapp textarea, .SelectStyle select',function(){
	window.ele_valid_chk(this);
});

$('.FieldWrapp input, .FieldWrapp textarea, .SelectStyle select').each(function(){
	window.ele_valid_chk(this);
});



//***** 5 - Top Header Active Background Apply Color
	// ** https://stackoverflow.com/questions/28266651/change-header-background-colour-when-page-scrolls
	// ** http://jsfiddle.net/634d6vgq/2/
	
$(window).on("scroll", function() {
	var topFixPosition = $("#TopHead").data('fix_top')?$("#TopHead").data('fix_top'):$("#TopHead").attr('data-fix_top');
	if(topFixPosition)
	{
	}else
	{
		topFixPosition = 0;
	}
	if($(window).scrollTop() > topFixPosition) {
		$("#TopHead").addClass("th_active").trigger('classChange');
	} else {
		//remove the background property so it comes transparent again (defined in your css)
	   $("#TopHead").removeClass("th_active").trigger('classChange');
	}
});

$("#TopHead").height($("#TopHead").children().first().height());


$(document).on('classChange','#TopHead',function(e){
	
	if($(e.target).hasClass('th_active'))
	{
		
	}else
	{
		$(e.target).height($($(e.target).children()[0]).height())
	}
	
});


//***** 6 - Go To Top Button
$(window).scroll(function(){
	var totalH = $(window).height();
	if( $(window).scrollTop() > (totalH/2) ){
		$('.topBtn').fadeIn();
	}else{
		$('.topBtn').fadeOut();
	}
	$('#set_window_scroll_position').val($(window).scrollTop());
});

$('.topBtn').unbind('click');
$('.topBtn').click(function(e){
	e.preventDefault();
	//$(window).scrollTop(0);
	
	
	$('html, body').animate({
          scrollTop: 0
        },1000);
});



//***** 7 - AFFIX
+function ($) {
  'use strict';

  // AFFIX CLASS DEFINITION
  // ======================

  var Affix = function (element, options) {
    this.options = $.extend({}, Affix.DEFAULTS, options)

    this.$target = $(this.options.target)
      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this));

    this.$element     = $(element),
    this.affixed      = null,
    this.unpin        = null,
    this.pinnedOffset = null,

    this.checkPosition()
  };

  Affix.VERSION  = '3.3.7',

  Affix.RESET    = 'affix affix-top affix-bottom';

  Affix.DEFAULTS = {
    offset: 0,
    target: window
  };

  Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
    var scrollTop    = this.$target.scrollTop()
    var position     = this.$element.offset()
    var targetHeight = this.$target.height()

    if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false

    if (this.affixed == 'bottom') {
      if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
      return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
    }

    var initializing   = this.affixed == null
    var colliderTop    = initializing ? scrollTop : position.top
    var colliderHeight = initializing ? targetHeight : height

    if (offsetTop != null && scrollTop <= offsetTop) return 'top'
    if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'

    return false
  };

  Affix.prototype.getPinnedOffset = function () {
    if (this.pinnedOffset) return this.pinnedOffset;
    this.$element.removeClass(Affix.RESET).addClass('affix');
    var scrollTop = this.$target.scrollTop();
    var position  = this.$element.offset();
    return (this.pinnedOffset = position.top - scrollTop);
  };

  Affix.prototype.checkPositionWithEventLoop = function () {
    setTimeout($.proxy(this.checkPosition, this), 1)
  };

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var height       = this.$element.height()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom
    var scrollHeight = Math.max($(document).height(), $(document.body).height())

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

    var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)

    if (this.affixed != affix) {
      if (this.unpin != null) this.$element.css('top', '')

      var affixType = 'affix' + (affix ? '-' + affix : '')
      var e         = $.Event(affixType + '.bs.affix')

      this.$element.trigger(e)

      if (e.isDefaultPrevented()) return

      this.affixed = affix
      this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

      this.$element
        .removeClass(Affix.RESET)
        .addClass(affixType)
        .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
    }

    if (affix == 'bottom') {
      this.$element.offset({
        top: scrollHeight - height - offsetBottom
      })
    }
  };


  // AFFIX PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.affix')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  };

  var old = $.fn.affix;

  $.fn.affix             = Plugin,
  $.fn.affix.Constructor = Affix,


  // AFFIX NO CONFLICT
  // =================

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  };


  // AFFIX DATA-API
  // ==============

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
      var data = $spy.data()

      data.offset = data.offset || {};

      if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom;
      if (data.offsetTop    != null) data.offset.top    = data.offsetTop;

      Plugin.call($spy, data)
    });
  });

}(jQuery);
// AFFIX END!



//***** 8 - Smooth Scroll Page
$('.goto').click(function(event) {
	// On-page links
	if (
		location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
		&& 
		location.hostname == this.hostname
	) {
	// Figure out element to scroll to
	var target = $(this.hash);

	target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
	// Does a scroll target exist?

	if (target.length) {
		// Only prevent default if animation is actually gonna happen
		event.preventDefault();
		event.stopPropagation();
		
		if($('body').hasClass('is_touch_screen'))
		{
			$('[data-target="#navbarContent"]').trigger('click');
		}

		$('html, body').animate({
		scrollTop: target.offset().top - 0
		}, 1000, function() {
			// Callback after animation
			// Must change focus!
				$(event.target).parent().parent().children().not($(event.target).parent()).removeClass('active');
				$(event.target).parent().addClass('active');
				
				var $target = $(target);
				$target.focus();
				if ($target.is(":focus")) { // Checking if the target was focused
				return false;
				} else {
				$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
				$target.focus(); // Set focus again
				};
			});
		}
	}
});



//***** 9 - Modal Box
$('.boostrap_modal_open').click(function(event){
	event.preventDefault();
	event.stopPropagation();
	$(this).closest('*[role=dialog]').trigger('click.dismiss.bs.modal').delay(1500);
	var hash = this.hash
	window.setTimeout(function(hash){
		$(hash).modal('show');
	},500,hash);
});



//***** 10 - Tabs
(function($) {

  'use strict';

  $(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
    var $target = $(e.target);
    var $tabs = $target.closest('.nav-tabs-responsive');
    var $current = $target.closest('li');
	var $parent = $current.closest('li.dropdown');
		$current = $parent.length > 0 ? $parent : $current;
	var $next = $current.next();
    var $prev = $current.prev();
	var updateDropdownMenu = function($el, position){
      $el
      	.find('.dropdown-menu')
        .removeClass('pull-xs-left pull-xs-center pull-xs-right')
      	.addClass( 'pull-xs-' + position );
    };

    $tabs.find('>li').removeClass('next prev active');
    $current.addClass('active');
	$prev.addClass('prev');
    $next.addClass('next');
    
    updateDropdownMenu( $prev, 'left' );
    updateDropdownMenu( $current, 'center' );
    updateDropdownMenu( $next, 'right' );
  });

})(jQuery);



//***** 11 - Left Right Slide
$(document).on('click',".slide_left_right",function () {
	  var ele = $(this).data('ele')?$(this).data('ele'):$(this).attr('data-ele');
	  $(ele).animate({width: "toggle"});
	  
	  //$(".WrappClose").parent().not(ele).find(".WrappClose").trigger('click');
	  
	  //$(this).show("slide", { direction: slide }, 1000);
});
$(document).on('click',".WrappClose",function () {
	$('[data-ele="#' + $(this).parent()[0].id + '"]').trigger('click');
});



//***** 12 - Fancy Scrollbar
/*include_file(window.imgPath + 'plugins/nicescroll/jquery.nicescroll.min.js')
setTimeout(function(){
	$(".").niceScroll({
		cursorcolor: "#000",
		cursorborderradius: "0",
		cursorborder: "0 solid #fff",
		cursorwidth: "12px",
		zindex: "999999",
		scrollspeed: 100,
		cursoropacitymin:0,
	});

},200);*/



//***** 13 - Left Menu
$(document).on('click','.SidebarToggle',function(){
	$(this).parent().toggleClass('active');
	if($(this).find('button i').hasClass('fa-close'))
	{
		$(this).find('button i').addClass('fa-bars').removeClass('fa-close');
	}else
	{
		$(this).find('button i').addClass('fa-close').removeClass('fa-bars');
	}
});



//***** 14 - Add/Delete Rows
$(document).on('click','.addRow',function(){
	var prent = $(this).closest('.AdRmvRowBtn').parent();
	var row;
	var clone;
	switch(prent[0].localName.toLowerCase())
	{
		case 'div':
			row = prent.closest('.row');
			clone = row.clone();
		break;
		
		default:
		break;
	}
	row.after(clone);
	setOrderAddRow(row);
	$(this).trigger('as.addrow');
});

$(document).on('click','.delRow',function(){
	var prent = $(this).closest('.AdRmvRowBtn').parent();
	var row;
	var clone;
	switch(prent[0].localName.toLowerCase())
	{
		case 'div':
			row = prent.closest('.row');
			clone = row.clone();
		break;
		
		default:
		break;
	}
	
	var limit = 0;
	limit = row.parent().data('limit')?row.parent().data('limit'):row.parent().attr('data-limit');
	limit = (limit)?limit:1;
	
	if(row.parent().children().length>limit)
	{
		if (confirm("Are you sure you want to delete this?") )
		{
			row.remove();
		}
	}
	setOrderAddRow(row);
	row.parent().trigger('as.deleterow');
});

function setOrderAddRow(ele)
{
	$(ele).parent().children().each(function(e){
		//console.log(this);
		var id = '';
		$(this).find('*[data-name]').each(function(){
			$(this).prop('name',$(this).data('name').replace('{COUNT}',e));
			id = $(this).data('name').replace('{COUNT}',e);
			id = id.replace(new RegExp("\\]\\[","gm"),'_').replace(new RegExp("\\[","gm"),'_').replace(new RegExp("\\]","gm"),'');
			//console.log(id);
			$(this).prop('id',id);
			
			try
			{
				var lable;
				lable = $(this).closest('label');
				
				
				if (lable.length)
				{
				}else
				{
					lable = $(this).parent().find('label');
				}
				
				
				if (lable && lable[0] && lable[0].localName.toLowerCase() === 'label')
				{
					lable.prop('for',id).attr('for',id);
				}
				
			}catch(e){}
			
		});
	});
}
$($('.delRow').closest('.AdRmvRowBtn').parent().closest('.row')[0]).each(function(){
	//var table = $(this).closest('tbody');
	setOrderAddRow(this);
});



//***** 15 - Popup Gallery
$.fn.as_gallery = function()
{
	$('.ImgPopup').remove();
	$('body').append('<div class="ImgPopup"><div class="Close"><img src="'+imgPath+'images/icons/close.svg" alt="Close"></div><div class="LrgImg"><table><tr><td height="700"><img src="'+imgPath+'images/img_notfound.jpg" alt="notfound"><div class="ImgPopupTitle">My Test Title</div><div class="ImgPopupCaption">My Test Caption</div></td></tr></table></div><div class="Direction"><a href="#" class="Prv"><img src="'+imgPath+'images/icons/prev.svg" class="Previous"></a><a href="#" class="Nxt"><img src="'+imgPath+'images/icons/next.svg" class="Next"></a></div></div>');
	
	this.as_ga_next = function()
	{
		var r = this.show_wraper();
		for(var i = 0;this[this.index_gallery].imgaes.length>i;i++)
		{
			if(r[0].this_img === this[this.index_gallery].imgaes[i])
			{
				if(this[this.index_gallery].imgaes[i+1])
				{
					this.as_ga_open(this[this.index_gallery].imgaes[i+1]);
					break;
				}
			}
		}
	};

	this.as_ga_prev = function()
	{
		var r = this.show_wraper();
		for(var i = this[this.index_gallery].imgaes.length;0<i;i--)
		{
			if(r[0].this_img === this[this.index_gallery].imgaes[i])
			{
				if(this[this.index_gallery].imgaes[i-1])
				{
					this.as_ga_open(this[this.index_gallery].imgaes[i-1]);
					break;
				}
			}
		}
	};

	this.as_ga_open = function(ele)
	{
		$('.ImgPopup')[0].this_obj = this;
		$('.ImgPopup')[0].this_img = ele;
		$('.ImgPopup').show();
		$('.ImgPopup').find('.LrgImg img').attr('src',ele.img_src);
		$('.ImgPopup').find('.LrgImg img').closest('td').height(parseInt($(window).height()) - 100);
		
		var title = $(ele).data('title')?$(ele).data('title'):$(ele).attr('data-title');
		var caption = $(ele).data('caption')?$(ele).data('caption'):$(ele).attr('data-caption');
		console.log(title);
		
		$('.ImgPopup').find('.LrgImg').find('.ImgPopupTitle,.ImgPopupCaption').hide();
		
		if(title)
		{
			$('.ImgPopup').find('.LrgImg').find('.ImgPopupTitle').html(title).show();
		}
		
		if(caption)
		{
			$('.ImgPopup').find('.LrgImg').find('.ImgPopupCaption').html(caption).show();
		}
	};

	this.as_ga_close = function()
	{
		var r = this.show_wraper();
		r.hide();
	};

	var as_ga_init = function(obj)
	{
		var imgaes = [];
		
			
		if(obj[0].localName.toLowerCase() === 'img')
		{
			var src = obj.data('src')?obj.data('src'):obj.attr('data-src');
			if(!src)
			{
				src = obj[0].src;
			}
			
			obj[0].img_src = src;
			obj[0].this_obj = this_obj;
			obj[0].count_position = 0;
			imgaes.push(obj[0]);
			//obj.css({'background-image':"url('"+src+"')"});

			obj.click(function(e){
				console.log(this);
				e.preventDefault();
				this.this_obj.as_ga_open(this);
				this.this_obj.index_gallery = $( ".GalleryWrapper" ).index( $(this).closest('.GalleryWrapper') )
			});

			$('.ImgPopup').find('.Direction').hide();

		}else
		{
			$('.ImgPopup').find('.Direction').show();
			obj.find('.row>div .Image').each(function(c){
				var src = $(this).data('src')?$(this).data('src'):$(this).attr('data-src');
				if(!src)
				{
					src = obj[0].src;
				}
				var full_src = $(this).data('full')?$(this).data('full'):$(this).attr('data-full');
				if(!full_src)
				{
					full_src = obj[0].src;
				}
				this.img_src = full_src;
				this.count_position = c;
				this.this_obj = this_obj;
				$(this).css({'background-image':"url('"+src+"')"});
				$(this).height($(this).width());
				//console.log("url('"+src+"');");
				imgaes.push(this);
			});
			obj[0].imgaes = imgaes;
			
			obj.find('.row>div .Image').off('click');
			obj.find('.row>div .Image').unbind('click');
			obj.find('.row>div .Image').click(function(e){
				//console.log(this);
				e.preventDefault();
				this.this_obj.as_ga_open(this);
				this.this_obj.index_gallery = $( ".GalleryWrapper" ).index( $(this).closest('.GalleryWrapper') )
				
			});

		}
		
		
		$('.ImgPopup .Direction .Prv').off('click');
		$('.ImgPopup .Direction .Prv').unbind('click');
		$('.ImgPopup .Direction .Prv').click(function(e){
			this.this_obj = $(this).closest('.ImgPopup')[0].this_obj;
			e.preventDefault();
			this.this_obj.as_ga_prev(this);
			
		});

		$('.ImgPopup .Direction .Nxt').off('click');
		$('.ImgPopup .Direction .Nxt').unbind('click');
		$('.ImgPopup .Direction .Nxt').click(function(e){
			this.this_obj = $(this).closest('.ImgPopup')[0].this_obj;
			e.preventDefault();
			this.this_obj.as_ga_next(this);
		});

		$(document).off('click','.ImgPopup .Close');
		$(document).unbind('click','.ImgPopup .Close');
		$(document).on('click','.ImgPopup .Close',function(e){
			this.this_obj = $(this).closest('.ImgPopup')[0].this_obj;
			e.preventDefault();
			this.this_obj.as_ga_close(this);
		});

	};

	this.show_wraper = function()
	{
		return $('.ImgPopup');
	};

	var this_obj = this;
	$(this).each(function(){
		as_ga_init($(this));
		$(this).addClass('as_gallery_loaded');
	});

	if(window.as_gallery_loaded) clearTimeout(window.as_gallery_loaded);
	
	window.as_gallery_loaded = setTimeout(function(){
		$(window).resize(function(){
			$('.as_gallery_loaded').as_gallery();
		})
	},200);

};
if ($('.GalleryWrapper,[single_popup]').length) $('.GalleryWrapper,[single_popup]').as_gallery();


//***** 16 - Item Carousel
$.fn.as_crasole = function()
{
	var init = function(eele)
	{
		eele[0].ele = eele.find('>div:not(.as_controls_btn_wrap)');
		eele[0].sub_ele = eele.find('>div>div');
		eele[0].asdir = eele.data('asdir')?eele.data('asdir'):eele.attr('data-asdir');
		
		eele[0].ele_first_visible = 1;
		
		eele[0].ele_data_screen = eele.data('screen')?eele.data('screen'):eele.attr('data-screen');
		
		if (!eele[0].asdir)
		{
			eele[0].asdir = 'v';
		}
		
		if ($(document).width()<=eele[0].ele_data_screen)
		{
			console.log('Screetn 500');
			eele[0].org_asdir = (eele[0].org_asdir)?eele[0].org_asdir:eele[0].asdir;
			eele[0].asdir = 'v';
		}else
		{
			eele[0].org_asdir = (eele[0].org_asdir)?eele[0].org_asdir:eele[0].asdir;
			eele[0].asdir = eele[0].org_asdir;
		}
		
		
		eele.attr('data-asdir',eele[0].asdir).prop('data-asdir',eele[0].asdir).data('asdir',eele[0].asdir);
		eele[0].asdir =  eele[0].asdir.toLowerCase();
		
		switch(eele[0].asdir)
		{
			case 'h':
				if(eele[0].top_position)
				{
				}else
				{
					eele[0].top_position = 0;
				}
				
				//console.log(this.sub_ele.children());
				var v = $(eele[0].sub_ele.children()[0]).outerHeight(true);
				
				var t_size = 0;
				
				eele[0].sub_ele.children().each(function(){
					t_size = t_size + $(this).outerHeight(true);
				});
			break;
			
			default:
				if(eele[0].left_position)
				{
				}else
				{
					eele[0].left_position = 0;
				}
				
				//console.log(this.sub_ele.children());
				var v = $(eele[0].sub_ele.children()[0]).outerWidth(true );
				
				var t_size = 0;
				
				eele[0].sub_ele.children().each(function(){
					t_size = t_size + $(this).outerWidth(true );
				});
			break;
		}
		
	};
	
	var next = function(e)
	{
		var ele = $(this).closest('.as_carousel_init');
		if(ele.length)
		{
		}else
		{
			ele = $($(this).closest('.as_controls_btn_wrap').data('ele')?$(this).closest('.as_controls_btn_wrap').data('ele'):$(this).closest('.as_controls_btn_wrap').attr('data-ele'));
		}
		
		if($.trim(ele[0].asdir) === 'h')
		{
			if(ele[0].top_position)
			{
			}else
			{
				ele[0].top_position = 0;
			}
			
			//console.log(this.sub_ele.children());
			var v = $(ele[0].sub_ele.children()[ele[0].ele_first_visible-1]).outerHeight(true);
			
			ele[0].siteOutterMarging = ele.outerHeight(true) - ele.height();
			
			var t_size = 0;
			
			ele[0].sub_ele.children().each(function(){
				t_size = t_size + $(this).outerHeight(true);
			});
			
			
			//console.log(t_size - this.ele[0].left_position);
			
			if(t_size - ele[0].top_position - ele[0].siteOutterMarging <= ele.height())
			{
				return;
			}
			
			ele[0].ele_first_visible = ele[0].ele_first_visible + 1;
			
			var top_position = ele[0].top_position + v;
			
			
			ele[0].top_position = top_position;
			
			$(ele[0].ele).animate({
				top: '-'+ (ele[0].top_position ) +'px'
			});
		}else
		{
			if(ele[0].left_position)
			{
			}else
			{
				ele[0].left_position = 0;
			}
			
			//console.log(this.sub_ele.children());
			var v = $(ele[0].sub_ele.children()[0]).outerWidth(true );
			
			ele[0].siteOutterMarging = ele.outerWidth(true ) - ele.width();
			
			var t_size = 0;
			
			ele[0].sub_ele.children().each(function(){
				t_size = t_size + $(this).outerWidth(true );
			});
			
			
			//console.log(t_size - this.ele[0].left_position);
			
			console.log(  't_size: ' + t_size + '  left_position:' + ele[0].left_position + '  siteOutterMarging:' + ele[0].siteOutterMarging + '  width:' + ele.width() );
			
			console.log(  t_size - ele[0].left_position - ele[0].siteOutterMarging  );
			console.log(  ele.outerWidth(true ) );
			
			if(t_size - ele[0].left_position - ele[0].siteOutterMarging <= ele.width())
			{
				return;
			}
			
			var left_position = ele[0].left_position + v;
			
			
			ele[0].left_position = left_position;
			
			$(ele[0].ele).animate({
				left: '-'+ (ele[0].left_position ) +'px'
			});
		}
	};
	
	var prev = function(eele)
	{
		var ele = $(this).closest('.as_carousel_init');
		
		if(ele.length)
		{
		}else
		{
			ele = $($(this).closest('.as_controls_btn_wrap').data('ele')?$(this).closest('.as_controls_btn_wrap').data('ele'):$(this).closest('.as_controls_btn_wrap').attr('data-ele'));
		}
		
		
		if($.trim(ele[0].asdir) === 'h')
		{
			if(ele[0].top_position)
			{
			}else
			{
				ele[0].top_position = 0;
			}
			
			//console.log(this.sub_ele.children());
			var v = $(ele[0].sub_ele.children()[ele[0].ele_first_visible-1]).outerHeight(true);
			
			console.log(ele.outerHeight(true));
			
			ele[0].siteOutterMarging = ele.outerHeight(true) - ele.height();
			
			
			var top_position = ele[0].top_position - v;
			
			//console.log(t_size - this.ele[0].left_position);
			
			if(ele[0].top_position - ele[0].siteOutterMarging <=0)
			{
				console.log(ele[0].top_position - ele[0].siteOutterMarging);
				console.log(ele[0].siteOutterMarging);
				console.log(ele[0].top_position);
				return;
			}
			
			ele[0].ele_first_visible = ele[0].ele_first_visible - 1;
			
			ele[0].top_position = top_position;
			
			$(ele[0].ele).animate({
				top: '-'+ (ele[0].top_position) +'px'
			});
		}else
		{
			if(ele[0].left_position)
			{
			}else
			{
				ele[0].left_position = 0;
			}
			
			//console.log(this.sub_ele.children());
			var v = $(ele[0].sub_ele.children()[0]).outerWidth(true );
			
			var t_size = 0;
			
			ele[0].sub_ele.children().each(function(){
				t_size = t_size + $(this).outerWidth(true );
			});
			
			
			var left_position = ele[0].left_position - v;
			
			//console.log(t_size - this.ele[0].left_position);
			
			if(ele[0].left_position - ele[0].siteOutterMarging <=0)
			{
				return;
			}
			
			ele[0].left_position = left_position;
			
			$(ele[0].ele).animate({
				left: '-'+ (ele[0].left_position ) +'px'
			});
		}
	};
	
	$(this).each(function(){
		init($(this));
		console.log(this.id);
		$(this).addClass('as_carousel_init');
		$(this).find('.btn-floating[data-slide="next"]').on('click',next);
		$(this).find('.btn-floating[data-slide="prev"]').on('click',prev);
		
		$('[data-ele="#'+this.id+'"]').find('.btn-floating[data-slide="next"]').on('click',next);
		$('[data-ele="#'+this.id+'"]').find('.btn-floating[data-slide="prev"]').on('click',prev);
		
	});
};

if ($('.as_carousel').length) $('.as_carousel').as_crasole();

if(false)
{
$(document).on('click','.btn-floating[data-slide="next"]',function(){
	var ele = $(this).closest('.as_controls_btn_wrap').data('ele')?$(this).closest('.as_controls_btn_wrap').data('ele'):$(this).closest('.as_controls_btn_wrap').attr('data-ele');
	
	if(this.ele)
	{
	}else
	{
		this.ele = $(ele+'>div:not(.as_controls_btn_wrap)');
		this.sub_ele = $(ele+'>div>div');
	}
	
	if(this.ele[0].left_position)
	{
	}else
	{
		this.ele[0].left_position = 0;
	}
	
	//console.log(this.sub_ele.children());
	var v = $(this.sub_ele.children()[0]).outerWidth(true );
	
	var t_size = 0;
	
	this.sub_ele.children().each(function(){
		t_size = t_size + $(this).outerWidth(true );
	});
	
	
	var left_position = this.ele[0].left_position + v;
	
	//console.log(t_size - this.ele[0].left_position);
	
	if(t_size - this.ele[0].left_position - 30 <= $(this.ele).width())
	{
		return;
	}
	
	this.ele[0].left_position = left_position;
	
	$(this.ele).animate({
		left: '-'+ this.ele[0].left_position +'px'
	});
});

$(document).on('click','.btn-floating[data-slide="prev"]',function(){
	var ele = $(this).closest('.as_controls_btn_wrap').data('ele')?$(this).closest('.as_controls_btn_wrap').data('ele'):$(this).closest('.as_controls_btn_wrap').attr('data-ele');
	
	if(this.ele)
	{
	}else
	{
		this.ele = $(ele+'>div:not(.as_controls_btn_wrap)');
		this.sub_ele = $(ele+'>div>div');
	}
	
	if(this.ele[0].left_position)
	{
	}else
	{
		this.ele[0].left_position = 0;
	}
	
	//console.log(this.sub_ele.children());
	var v = $(this.sub_ele.children()[0]).outerWidth(true );
	
	var t_size = 0;
	
	this.sub_ele.children().each(function(){
		t_size = t_size + $(this).outerWidth(true );
	});
	
	
	var left_position = this.ele[0].left_position - v;
	
	
	if(this.ele[0].left_position - 30 <=0)
	{
		return;
	}
	
	console.log(this.ele[0].left_position);
	this.ele[0].left_position = left_position;
	
	$(this.ele).animate({
		left: '-'+ this.ele[0].left_position +'px'
	});
});
}



//***** 17 - Counter
(function ( $ ) {
$.fn.asFixCounter = function(){
	$('.counter-count').each(function (c,ele) {
		var counter_count = $(ele).text();
		if(ele.counter_count)
		{
		}else
		{
			ele.counter_count = counter_count;
		}
		
		var isElementInView = Utils.isElementInView($(ele), false);
		if (isElementInView)
		{
			if(!$(ele).hasClass('loded'))
			{
				$(ele).addClass('loded').finish().stop();
				$(ele).prop('Counter',0).animate({
					Counter: this.counter_count
				}, {
					duration: 2000,
					easing: 'swing',
					step: function (now) {
						$(ele).text(Math.ceil(now).toLocaleString());
					},
					complete:function(){
						$(this).text(Math.ceil(this.counter_count).toLocaleString());
					}
				});
			}
		}else
		{
			$(ele).not('only_one_time').removeClass('loded');
		}
	});
};
}( jQuery ));
$(window).scroll(function(){
	//console.log(checkVisible($('.counter-count')[0]));
	$('.counter-count').asFixCounter();
});



//***** 18 - Rating
window.afterLoad.push(function(){
	if ($('.as_ratable').length)
	{
		//$('.as_ratable').starrr();
		$('.as_ratable').starrr({
		  change: function(e, value){
			//console.log(e.target);
			var ratingText = $(e.target).data('ratingText')?$(e.target).data('ratingText'):$(e.target).attr('data-ratingText');
			if($(e.target).next().hasClass('starrr-count'))
			{
			}else
			{
				$(e.target).after(ratingText);
			}
			value = (value)?value:0;
			if (true) {
			  //$('.starrr-count').show();
			  $(e.target).next().find('.choice').text(value);
			} else {
			  //$('.starrr-count').hide();
			}
		  }
		});
		$('.as_ratable').each(function(){
			var ratingText = $(this).data('ratingText')?$(this).data('ratingText'):$(this).attr('data-ratingText');
			var ratingValue = $(this).data('rating')?$(this).data('rating'):$(this).attr('data-rating');
			ratingValue = (ratingValue)?ratingValue:0;
			
			if(!ratingText)
			{
				ratingText = "<span class='starrr-count'><span class='choice'></span> rating.</span>";
			}
			
			if($(this).next().hasClass('starrr-count'))
			{
			}else
			{
				console.log(ratingText);
				$(this).after(ratingText);
			}
			
			$(this).next().find('.choice').text(ratingValue);
			
		});
	}
});



//***** 19 - My Tabs Style
jQuery.fn.INICSOL_Tabs = function() {

	$(this).each(function(){
		var elements = '0';
		var tabs = [];
		tabs.push($('<div></div>')[0]);
		
		$(this).children().each(function(e){
			//console.log($(this).data('inicsol-tab'));

			var tab_ele = $(this).data('inicsol-tab');
			$(tab_ele).addClass('desktop_only');

			$(this).click(function(){
				hideAll(elements,tabs);
				var tab_ele2 = $(this).data('inicsol-tab');
				activeEle($(this)[0],tab_ele2);
			});
			elements = elements + ',' + tab_ele;
			console.log(elements);
			tabs.push($(this)[0]);
		});
		hideAll(elements,tabs);
		init(elements,tabs);
	});

	function hideAll(elements,tabs)
	{
		$(elements).hide();
		$(tabs).find('a').removeClass('Active');
		$(tabs).find('.mobile_only').remove();
	}

	function activeEle(tab,ele)
	{
		console.log(ele);
		$(tab).append("<div class=\"mobile_only\">" + $(ele).html() + "</div>");
		$(ele).show();
		$(tab).find('a').addClass('Active');
	}

	function init(elements,tabs)
	{
		split_ele = elements.split(',');
		console.log(tabs);
		activeEle(tabs[1],split_ele[1]);
	}

};

if ($('.MyTabStyle>ul').length) $('.MyTabStyle>ul').INICSOL_Tabs();

function openTab(selector){
  $(selector).tab('show') ;
}



//***** 20 - LazyLoad Images
$('[data-src]').addClass('lazy').attr('src','images/img.png');
$('[data-src][data-size]').each(function(){
	var data_size = $(this).data('size')?$(this).data('size'):$(this).attr('data-size');
	data_size = data_size.split('x');
	console.log(data_size);
	var ratio = data_size[1] / data_size[0];
	$(this).height(parseInt(ratio * $(this).width()));
});

function Utils() {

};

Utils.prototype = {
	constructor: Utils,
	isElementInView: function (element, fullyInView) {
		var pageTop = $(window).scrollTop();
		var pageBottom = pageTop + $(window).height();
		var elementTop = $(element).offset().top;
		var elementBottom = elementTop + $(element).height();

		if (fullyInView === true) {
			return ((pageTop < elementTop) && (pageBottom > elementBottom));
		} else {
			return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
		}
	}
};

var Utils = new Utils();

var lazyloadThrottleTimeout;

function lazyload () {
	var lazyloadImages = $(".lazy");
	if(lazyloadThrottleTimeout) {
		clearTimeout(lazyloadThrottleTimeout);
	}    

	lazyloadThrottleTimeout = setTimeout(function() {
		var scrollTop = $(window).scrollTop();//window.pageYOffset;
		lazyloadImages.each(function(c,img){

			var isElementInView = Utils.isElementInView($(img), false);
			var show_src = $(img).data('src')?$(img).data('src'):$(img).attr('data-src');//img.dataset.src;
			var src_obj = {};
			var src_viewport = [];
			var cur_w =  $( window ).width();
			
			$(img.attributes).each(function(c,e){
				if(e.name.substring(0,12) === 'data-src-max')
				{
					src_viewport.push(e.name.substring(13));
					src_obj[e.name.substring(13)] = e.value;
					//console.log(e.name.substring(0,12));
				}
			});
			
			src_viewport.reverse();
			
			//console.log(src_obj,src_viewport);
			
			
			if(src_viewport.length)
			{
				for(var i=0;src_viewport.length>i;i++)
				{
					if(cur_w<=src_viewport[i])
					{
						show_src = src_obj[src_viewport[i]];
						break;
						//console.log(src_obj[src_viewport[i]]);
					}
				}
			}
			
			if(isElementInView)
			{
				if(img.localName.toLowerCase() === 'img')
				{
					img.src = show_src;
					$(img).removeClass('lazy');
				}else
				{
					$(img).css('background-image',"url( '"+show_src+"' )");
					$(img).removeClass('lazy');
				}
				
				lazyloadfn(img);
			}
		});
		/*if(lazyloadImages.length == 0)
		{
			document.removeEventListener("scroll", lazyload);
			window.removeEventListener("resize", lazyload);
			window.removeEventListener("orientationChange", lazyload);
		}*/
		try
		{
			$('.home-portfolio').masonry('layout');
		}catch(e)
		{
		}
	}, 20);
};
/*document.addEventListener("DOMContentLoaded", function() {
	document.addEventListener("scroll", lazyload);
	window.addEventListener("resize", lazyload);
	window.addEventListener("orientationChange", lazyload);
});

document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);*/

$(document).on('DOMContentLoaded', lazyload);
$(document).on('scroll', lazyload);
$(window).on('resize', lazyload);
$(window).on('orientationChange', lazyload);

$(window).on('resize',function(){
	
	$('[data-src]').addClass('lazy');
	
});

$(document).on('hover','.lazy', lazyload)

//setInterval(lazyload,200);

$("img").one("load", function() {
  try
	{
		$('.home-portfolio').masonry('layout');
	}catch(e)
	{
	}
	lazyload();
}).each(function() {
  if(this.complete) {
     try
	{
		$('.home-portfolio').masonry('layout');
	}catch(e)
	{
	}
  }
  lazyload();
});

(function($){
    $.fn.imgLoad = function(callback) {
        return this.each(function() {
            if (callback) {
                if (this.complete || $(this).height() > 0) {
                    callback.apply(this);
                }
                else {
                    $(this).on('load', function(){
                        callback.apply(this);
                    });
                }
            }
        });
    };
	
})(jQuery);

window.lazyloadfn = function(img)
{
	$(img).closest('[data-lazyloadfn]').each(function(){
		
		$(this).find('.lazy').imgLoad(function(ele){this.isloaded =true;});
		
		if(this.id && $.trim(this.id)!=='')
		{
		}else
		{
			this.id = 'lazyloadfn_' + Math.round(new Date().getTime() + (Math.random() * 100));
		}
		
		if(window['lazyloadfn_' + this.id]) clearInterval(window['lazyloadfn_' + this.id]);
		
		window['lazyloadfn_' + this.id] = setInterval(function(id,images,main){
			
			var is_as_loaded = true;
			
			images.each(function(c,im){
				if(im.isloaded)
				{
				}else
				{
					is_as_loaded = false;
				}
			});
			
			if(is_as_loaded)
			{
				clearInterval(window[id]);
				console.log('All images loaded.');
				var callback_fn = $(main).data('lazyloadfn')?$(main).data('lazyloadfn'):$(main).attr('data-lazyloadfn');
				console.log(callback_fn);
				try{window[callback_fn](id,images,main);}catch(e){fn_include_file(e,window[callback_fn]);}
			}
			
		},200,'lazyloadfn_' + this.id, $(this).find('.lazy'),this);
	});
};
//////////////////////////////////////////////// END!



//***** 21 - Get Creditcart Type
window.GetCardType = function (number)
{
    // visa
    var re = new RegExp("^4");
    if (number.match(re) != null)
        return "Visa";

    // Mastercard
	//|2(22[1-9]|[3-6][0-9]{2}|7[0-2][0-9])
    re = new RegExp("^(5[1-5]|2(22[0-9]|[3-6]([0-9]{2})|7[0-1][0-9]|720))");
    if (number.match(re) != null)
        return "Mastercard";

    // AMEX
    re = new RegExp("^3[47]");
    if (number.match(re) != null)
        return "AMEX";

    // Discover
    re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
    if (number.match(re) != null)
        return "Discover";

    // Diners
    re = new RegExp("^36");
    if (number.match(re) != null)
        return "Diners";

    // Diners - Carte Blanche
    re = new RegExp("^30[0-5]");
    if (number.match(re) != null)
        return "Diners - Carte Blanche";

    // JCB
    re = new RegExp("^35(2[89]|[3-8][0-9])");
    if (number.match(re) != null)
        return "JCB";

    // Visa Electron
    re = new RegExp("^(4026|417500|4508|4844|491(3|7))");
    if (number.match(re) != null)
        return "Visa Electron";

    return "";
};


$(document).on('keyup','[name="cc_exp"]',function(){
	$(this).mask("99/9999");
});


$(document).on('blur','[name="cc_exp"]',function(){
	$(this).mask("99/9999");
});

function changeCardImg(ele)
{
	$('#Visa_card_img,#Mastercard_card_img,#Discover_card_img,#AMEX_card_img').removeClass('active');
	$('#'+GetCardType(ele.value)+'_card_img').addClass('active');
	
	if (GetCardType(ele.value) === 'AMEX' )
	{
		$(ele).mask("9999-999999-99999");
		$('[name="cc_cvv"],[name="ccv2"]').mask("9999");
	}else
	{
		$(ele).mask("9999-9999-9999-9999");
		$('[name="cc_cvv"],[name="ccv2"]').mask("999");
	}
};

$(document).on('input change keyup','[name="credit_card_number"]',function(){
	changeCardImg(this);
});


//***** 22 - YouTube API
+function ($) {
  'use strict';
	var AS_YouTube = function (element, options) {
		console.log('Test');
		this.options = $.extend({}, AS_YouTube.DEFAULTS, options);
		this.$element     = $(element);
		//this.$element.addClass('fa');
		
		
		if(AS_YouTube.interval)
		{
		}else
		{
			this.get_api();
			AS_YouTube.interval = true;
		}
		
		this.as_interval = setInterval(function(obj){
			try
			{
				console.log(YT);
				if(YT.Player)
				{
					clearInterval(obj.as_interval);
					obj.init();
					console.log('YouTube API Loadded.');
				}
			}catch(e){console.log(e);}
		},20,this);
		
	};
	
	AS_YouTube.DEFAULTS = {
		'controls': 0,
		'showinfo': 0,
		'rel': 0,
		'enablejsapi':1,
		'loop': 1,
		'color':'white',
		'disablekb':1,
		'iv_load_policy':3,
	};

	AS_YouTube.interval = null;

	AS_YouTube.onresize = function(){
		alert('Test');
		this.init();
	};

	AS_YouTube.prototype.get_api = function()
	{
		window["YTConfig"] = window.location.protocol + '//' + window.location.hostname;
		var tag = document.createElement('script');
		tag.src = "https://youtube.com/iframe_api";
		tag.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
		tag.loop = 1;
		var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
	};
	
	AS_YouTube.prototype.init = function()
	{
		var ele = this.$element;
		console.log(ele);
		ele.off('onresize',ele.onresize);
		ele.on('onresize',ele.onresize);
		ele.on('onresize',ele.onresize);
		var dimensions = ele.data('dimensions')?ele.data('dimensions'):ele.attr('data-dimensions');
		//console.log(dimensions);
		try
		{
			dimensions = dimensions.toLowerCase();
			
		}catch(e){
			dimensions = ele.width() + 'x' + ele.parent().height();
		}

		dimensions = dimensions.split('x');

		var videoId = ele.data('vidid')?ele.data('vidid'):ele.attr('data-vidid');

		ele.html('<div></div>');
		var vid_ele = ele.find('div');

		
		/*var h = ele.parent().height();
		var w = ele.parent().width();
		var ratio_h = h / w;
		var ratio_w = w / h;*/

		var vid_w_org = parseInt(dimensions[0]);
		var vid_h_org = parseInt(dimensions[1]);

		var ratio = vid_h_org / vid_w_org;
		console.log(ratio);

		var w = ele.width();
		var h = w * ratio;
		
		var setheight = ele.data('setheight')?ele.data('setheight'):ele.attr('data-setheight');
		if(setheight) ele.height(h);
		
		


		var vid_w = w;
		var vid_h = h;
		/*
		var vid_ratio_h = vid_h_org / vid_w_org;
		var vid_ratio_w = vid_w_org / vid_h_org;
		
		//var vid_w = vid_w_org * ratio_w;
		var vid_w = w;
		var vid_h = (w * vid_ratio_h);
		
		if(h>vid_h)
		{
			vid_w = h * vid_ratio_w;
			vid_h = h;
			console.log('Testes');
		}
		
		var top = parseInt(vid_h) - h;
		var left = parseInt(vid_w) - w;
		
		if(top>1)
		{
			top = parseInt(top / 2) + 60;
		}else
		{
			top = 60;
		}
		
		if(left>1)
		{
			left = parseInt(left / 2);
		}else
		{
			left = 0;
		}
		ele.css({'left':'-'+left+'px','top':'-'+top+'px'});
		//vid_h = vid_h * vid_ratio_h;
		
		
		var ratio_w = vid_w / vid_h;
		*/
		
		var isautoplay = ele.attr('autoplay')?ele.attr('autoplay'):0;
		
		if ($.trim(isautoplay)==='' || isautoplay)
		{
			isautoplay = 1;
		}
		
		var controls = ele.attr('controls')?ele.attr('controls'):0;
		
		if ($.trim(controls)==='' || controls)
		{
			controls = 1;
		}
		
		console.log(isautoplay);
		
		var host_name = window.location.protocol + '//' + window.location.hostname;
		
		this.$element[0].player = new YT.Player(vid_ele[0], {
			width: parseInt(vid_w),
			height: parseInt(vid_h) + 150,
			videoId: videoId,
			'origin': host_name, 
			playerVars: {
				'controls': controls,
				//'hl':'123',
				'playsinline':1,
				'showinfo': 0,
				'autoplay': isautoplay,
				'rel': 0,
				'enablejsapi':1,
				'loop': 1,
				'color':'transparent',
				'disablekb':1,
				'modestbranding':1,
				'iv_load_policy':3,
				'host': host_name,
				'origin': host_name, 
			},
			events: {
				'onReady': onPlayerReady,
				'onStateChange': onPlayerStateChange
			}
		});
	};

	function Plugin(option) {
		return this.each(function () {
			var options = typeof option == 'object' && option;
			new AS_YouTube(this, options)
		});
	};
	
	var old = $.fn.as_youtube;
	
	$.fn.as_youtube   = Plugin;
	$.fn.as_youtube.Constructor = AS_YouTube;
	
	
	// AS_YouTube NO CONFLICT
	// =================
	
	$.fn.as_youtube.noConflict = function () {
		$.fn.as_youtube = old;
		return this
	};
}(jQuery);

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
	//console.log(event.target);
	event.target.setLoop(1);
	
	if ($(event.target.h).parent().attr('mute'))
	{
		event.target.mute();
	}
	
	//event.target.playVideo();
	console.log('curetn yt ele');
	
	if ($(event.target.h).parent().attr('autoplay'))
	{
		console.log('IS autoplay curetn yt ele');
		event.target.mute();
		event.target.playVideo();
	}
	
	console.log('API loaded');
	$(event.target).trigger('youtube_ready');
	setTimeout(function(){$('.carousel').trigger('slide.bs.carousel');},200);
}

// 5. The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
	//console.log(event.target);
	if(event.data)
	{
		$('.slide_video_wrap').each(function(c,e){
			if(e.player === event.target)
				$(e).css('visibility','visible');
		});
	}
	
	console.log(event.data);
	
	if(event.data === 0)
	{
		event.target.mute();
		event.target.playVideo();
	}
	/*if(event.data === 0)
	{
		event.target.mute();
		event.target.playVideo();
	}*/
	/*if (event.data == YT.PlayerState.PLAYING && !done) {
	setTimeout(stopVideo, 6000);
	done = true;
	}*/
}
function stopVideo() {
	player.stopVideo();
}

$(window).on('resize',function(event){
	$('.as_youtube').as_youtube();
});

$('.carousel').on('slide.bs.carousel',function(event){
	var $slides = $(this).find('.carousel-inner .carousel-item');
	
	if(typeof(event.to) === 'undefined')
	{
		$slides.each(function(c,e){
			if($(e).hasClass('active'))
			{
				event.to = c;
			}
		});
	}
	
	try
	{
		$slides.each(function(c,e){
			//console.log($(e).find('.slide_video_wrap')[0].player);
			if($slides === $slides [event.to])
			{
			}else
			{
				if($(e).find('.slide_video_wrap').length)
				$(e).find('.slide_video_wrap')[0].player.pauseVideo();
			}
		});
		
		if($($slides[event.to]).find('.slide_video_wrap').length)
		$($slides[event.to]).find('.slide_video_wrap').css('visibility','visible')[0].player.playVideo();
	}catch(e){console.log(e)}
});



//***** 23 - Full Screen Toggle
function toggleFullScreen(elem) {
    // ## The below if statement seems to work better ## if ((document.fullScreenElement && document.fullScreenElement !== null) || (document.msfullscreenElement && document.msfullscreenElement !== null) || (!document.mozFullScreen && !document.webkitIsFullScreen)) {
    if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) || (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) || (document.mozFullScreen !== undefined && !document.mozFullScreen) || (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {
        if (elem.requestFullScreen) {
            elem.requestFullScreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullScreen) {
            elem.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        } else if (elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
        }
		$(elem).addClass('isFullScreen');
    } else {
        if (document.cancelFullScreen) {
            document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
		$(elem).removeClass('isFullScreen');
    }
};

$.fn.as_accordion = function(){
	function as_show_all (ele){
		//console.log(ele.find(".card"));
		ele.find(".card").each(function(){
			//aria-expanded="true"
			$(this).find('[aria-expanded]').attr('aria-expanded','true').prop('aria-expanded','true').removeClass('collapsed');
			$(this).find('[aria-labelledby]').addClass('show');
		});
	}

	function as_hide_all (ele){
		//console.log(ele.find(".card"));
		ele.find(".card").each(function(){
			$(this).find('[aria-expanded]').attr('aria-expanded','false').prop('aria-expanded','false').addClass('collapsed');
			$(this).find('[aria-labelledby]').removeClass('show');
		});
	}
	$(this).click(function(evt){
		//evt.preventDefault();
		var parent = $($(this).attr('accordion-id'));	
		var child = parent.find('.collapsed');
		if ($(this).hasClass('active'))
		{
			$(this).removeClass('active');
			as_hide_all(parent);
		}else
		{
			$(this).addClass('active');
			as_show_all(parent);
		}
		
	});
}
$('.toggle-accordion').as_accordion();

$(document).on('click','[type="reset"]',function(e){
	
	setTimeout(function(e){
		
		$(e.target).closest('form').find('.not_empty').each(function(c,e){
			
			ele_valid_chk(e);
			
		});
		
		$(e.target).closest('form').find(".selectpicker").selectpicker("refresh");
		
	},500,e);
	
	
	
});

function errorWrapper(msg)
{
	$('#errorWraper,#successWraper').stop().hide();
	if (msg.error)
	{
		if ( $('#errorWraper').length )
		{
			$('#errorWraper').html('<div class="alert alert-danger" role="alert"><button type="button" class="close" aria-label="Close" onclick="$(this).closest(\'#errorWraper\').hide();"><span aria-hidden="true">&times;</span></button>' + msg.error + '</div>');
		}else
		{
			$('body').append('<div id="errorWraper"><div class="alert alert-danger" role="alert"><button type="button" class="close" aria-label="Close" onclick="$(this).closest(\'#errorWraper\').hide();"><span aria-hidden="true">&times;</span></button>' + msg.error + '</div></div>');
		}
		
		$('#errorWraper').stop().show();
	}
	
	if (msg.msg)
	{
		if ( $('#successWraper').length )
		{
			$('#successWraper').html('<div class="alert alert-success" role="alert"><button type="button" class="close" aria-label="Close" onclick="$(this).closest(\'#successWraper\').hide();"><span aria-hidden="true">&times;</span></button>' + msg.msg + '</div>');
		}else
		{
			$('body').append('<div id="successWraper"><div class="alert alert-success" role="alert"><button type="button" class="close" aria-label="Close" onclick="$(this).closest(\'#successWraper\').hide();"><span aria-hidden="true">&times;</span></button>' + msg.msg + '</div></div>');
		}
		
		$('#successWraper').stop().show();
	}
	
	clearTimeout( window.setTimeoutErrorMsg );
	window.setTimeoutErrorMsg = window.setTimeout(function () {
		$("#successWraper,#errorWraper").stop().slideUp();
	}, window.aterMessageDisplayTime);
	
};




function getCookieValue(cname) { // cname is nothing but the cookie value which 
			 //contains the value
var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
	var c = ca[i];
	while (c.charAt(0) == ' ') {
	  c = c.substring(1);
	}
	if (c.indexOf(name) == 0) {
	  return c.substring(name.length, c.length);
	}
  }
  return "";
};

$('[role="presentation"].active a').trigger('click');

function check(input) {  
	var req_msg = $(input).data('req_msg')?$(input).data('req_msg'):$(input).attr('data-req_msg');
	//console.log( input.checkValidity() );
	if (req_msg && $.trim(req_msg) !== '')
	{
		if(input.checkValidity()){  
			input.setCustomValidity("");
		}  
		else {  
			input.setCustomValidity( req_msg );
		}   
	}              
}