 // decrypt helper function
function decryptCharcode(n,start,end,offset) {
  	n = n + offset;
  	if (offset > 0 && n > end) {
    	n = start + (n - end - 1);
  	} else if (offset < 0 && n < start) {
    	n = end - (start - n - 1);
	}
	return String.fromCharCode(n);
}
  // decrypt string
function decryptString(enc,offset) {
  	var dec = "";
  	var len = enc.length;
  	for(var i=0; i < len; i++) {
    	var n = enc.charCodeAt(i);
    	if (n >= 0x2B && n <= 0x3A) {
      		dec += decryptCharcode(n,0x2B,0x3A,offset);  // 0-9 . , - + / :
    	} else if (n >= 0x40 && n <= 0x5A) {
      		dec += decryptCharcode(n,0x40,0x5A,offset);  // A-Z @
    	} else if (n >= 0x61 && n <= 0x7A) {
      		dec += decryptCharcode(n,0x61,0x7A,offset);  // a-z
    	} else {
      		dec += enc.charAt(i);
    	}
  	}
	return dec;
}
  // decrypt spam-protected emails
function linkTo_UnCryptMailto(s) {
  	location.href = decryptString(s,-10);
}
//base64 decode, utf8 supported
var Base64 =
{
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input)
    {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input)
    {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string)
    {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext)
    {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;

    }
}

/**
 * 	Prevent window scroll if anchor is part of URL
 * */
if (location.hash) {
	setTimeout(function() {
		window.scrollTo(0, 0);
	}, 1);
}

/**
 *  set global var header Height
 * */
var headerHeight = 160;

/**
 * Layout specific initialization
 */
var layout = {
	/**
	 * Main init function
	 */
	init: function() {
		// call all init... methods
		for (var name in this) {
			// if method name start with text 'init'
			if((/^init.+/).test(name)) {
				this[name]();
			}
		}
	},
	getHeadersHeight: function(){
		$("#top").addClass('sticky');
		var headerHeight = parseInt($('#top').outerHeight()) + 50;
		$("#top").removeClass('sticky');
	},
	initLinks: function(){
		$('a[rel*=external]').on('click',function(e){
			e.preventDefault();
			window.open($(this).attr('href'));
		});
	},
	initForms: function(){
		$('#footer').add($('.input-a')).add($('#top')).find('label:not(.hidden) + :input:not(select,button)').each(function(){
			$(this).attr('placeholder', $(this).parent().children('label').text()).parent().children('label').addClass('hidden');
		});

		$('.module-box').each(function(){
			if($(this).is('.a')){
				$(this).find('label:not(.hidden) + :input:not(select,button)').each(function(){
					$(this).attr('placeholder',$(this).parent().children('label').text()).parent().children('label').addClass('hidden');
				});
			}
		});

		$('input[type="checkbox"], input[type="radio"]').each(function(){
			if($(this).is('[checked]')){
				$(this).prop('checked',true).parent('label').addClass('active');
			} else {
				$(this).prop('checked',false).removeAttr('checked');
			}
		});

		$('.checklist-a').add($('.check-a')).find('label').append('<div class="input"></div>').each(function(){
			$(this).addClass($(this).children('input').attr('type'));
		}).children('input').addClass('hidden').on('click',function(){
			if($(this).parent().hasClass('radio')) {
				$(this).parent('label').parents('p,ul').find('label').removeClass('active');
			}
			$(this).parent('label').toggleClass('active');
		});

 	},
	initTop: function(){
		$('#nav').add($('#top')).find('li > ul, li > div').parent().addClass('sub').append('<span class="toggle"></span>').children('span.toggle').on('click',function(){
			
			if($(this).parent().is('.toggle')){
				$(this).parent().removeClass('toggle');
			} else {
				$(this).parents('ul:first').children('li.toggle').removeClass('toggle');
				$(this).parent().addClass('toggle');
			}
			return false;
		});
		$('#top').find('.search > a').on('click',function(){
			$('html').removeClass('lang-active menu-active').toggleClass('search-active');
			if ($('html.search-active').length == 1) {
				$("input#sa, input#sword").focus();
			}
			$("#share ul li").removeClass("toggle");
			//$('html.lang-active').removeClass('lang-active');
			return false;
		});
		$('#top').append('<div class="menu"></div>').parent().append('<nav id="mobile"></nav><div id="shadow"></div>');
		$('#top').find('ul.lang').each(function(){
			$('#top').append('<a class="lang"></a>').children('a.lang').on('click',function(){
				$('html').removeClass('search-active menu-active').toggleClass('lang-active');

				$("#share ul li").removeClass("toggle");
			});
		});
		$('#nav').children().clone().appendTo('#mobile');
		$('#mobile').find('li.sub > span.toggle').on('click',function(){
			$(this).parent().toggleClass('toggle');
			return false;
		});
		$('#shadow').add($('#top').children('.menu')).on('click',function(){
			$('html').removeClass('search-active lang-active').toggleClass('menu-active');
			return false;
		});
	},
	initMiscellaneous: function(){
		$('#featured').add($('.module-featured')).find('figure').add($('.image-wide')).add($('.module-wide').find('.background')).each(function(){
			$(this).css({'background-image':'url("'+$(this).find('img').attr('src')+'")'});
		});
		$('.list-news').add($('.list-resources')).find('li').each(function(){
			$(this).find('a.clone').parents('li:first').addClass('has-link').find('.clone *').remove();
		});
		$('.list-resources').children('li').addClass('item');

		$('.list-center').wrapInner('<div class="inner"></div>');
		$('.module-featured').each(function(){
			$(this).find(':header').addClass('desktop-only').clone().removeClass('desktop-only').addClass('desktop-hide m20').prependTo($(this));
		});
	},
	initCss : function() {
		$('html').each(function(){
			if($(this).is('.lt-ie11')){ $('input[placeholder], textarea[placeholder]').placeholder(); }
			if($(this).is('.lt-ie9')){
				$('body').append('<p class="lt-ie9">Your browser is ancient! Please <a target="_blank" href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>').css('padding-top','28px');
				$(':last-child').addClass('last-child');
			}
		});
	},
	/**
	 * Init checkbox/radio buttons - style
	 * @param string selector
	 */
	initCheckboxRadioButtons: function(selector) {
		if (typeof selector == 'undefined') {
			selector = $("body");
		}

		selector.find('input[type=checkbox], input[type=radio]').each(function() {
			$(this).after( "<span class='fake-input'></span>" );
			$(this).parents("label").addClass("wb-input-wrap");
		});
	},
	/**
	 *  Init select 2 - plugin select 2
	 *  @param string selector
	 */
	initSelect2: function(selector) {
		if (typeof selector == 'undefined') {
			selector = $("body");
		}

		selector.find('select:not(.disable-select2)').each(function() {
			$(this).select2({
				minimumResultsForSearch: 4
			});
		});
	},
	/**
	 * Init fancybox - plugin fancybox
	 * @param string selector
	 */
	initFancybox: function(selector) {
		if (typeof selector === 'undefined'){
			selector = ".fancybox";
		}

		if (typeof $.fn.fancybox == 'function' ) {
 			$(selector).fancybox({
				'hideOnContentClick': true,
				'transitionIn'	:	'fade',
				'transitionOut'	:	'fade',
				'speedIn'		:	600,
				'padding'   	: 	10,
				'speedOut'		:	200
			});

			/* Apply fancybox to multiple items */
			$("a.fancybox-gallery").fancybox({
				'transitionIn'	:	'fade',
				'transitionOut'	:	'fade',
				'padding'   	: 	10,
				theme : 'light',

				closeBtn  : true,
				arrows    : true,
				nextClick : true,

				caption : {
					type : 'inside'
				},
 				helpers : {
					thumbs : true
				}
			});
		}

		$('.popup-video').fancybox({
				'hideOnContentClick': true,
				'transitionIn'	:	'fade',
				'transitionOut'	:	'fade',
				'speedIn'		:	600,
				'padding'   	: 	10,
				'speedOut'		:	200
		});

		$('.video-link-popup a').fancybox({
				'hideOnContentClick': true,
				'transitionIn'	:	'fade',
				'transitionOut'	:	'fade',
				'speedIn'		:	600,
				'padding'   	: 	10,
				'speedOut'		:	200
		});
		
	},
	/**
	 * Init tabs
	 */
	initTabs: function() {
		$(".tabs ul.tabs-nav li").on("click", function() {
			$(this).parent().find("li").removeClass("open");
			$(this).addClass("open");

			$(this).parents(".tabs").find("> .a-body").removeClass("open");
			$(this).parents(".tabs").find(".tab-" + $(this).attr("data-tab")).addClass("open");
		});
	},
	/**
	 * Init accordions
	 */
	initAccordions: function() {
		$(".accordion .a-h ").on("click", function(event) {
			//hide all
			var currentActive = $(this).hasClass("open");
			$(this).parents(".accordion").find(".a-body.open").slideToggle(function() {
				$(this).removeClass("open").removeAttr("style");
			});
			$(this).parents(".accordion").find(".a-h.open").removeClass("open");

			if (currentActive != true) {
				$(this).next(".a-body").slideToggle(function() {
					$(this).addClass("open");
				}).addClass("open");
				$(this).addClass("open");
			}
		});

		$(".accordion .a-h").each(function() {
			$(this).append('<span class="arrow"></span>');
		});
	},
 	/**
	 * Init table wrap - style
	 */
	initTableWrap: function() {
		$('#root .article table').each(function() {
			$(this).wrap("<div class='table-wrap'></div>");
		});
	},
	/**
	 * Init clickable area
	 * @param string selector
	 */
	initClickableArea: function(selector) {
		if (typeof selector === 'undefined') {
			selector = $("body");
		}
		$(selector).find(".clickable-area").click(function(event) {
			if (event.target.nodeName.toLowerCase() !== 'a') {
				var block = $(this).hasClass("clickable-area") ? $(this) : $(this).parents(".clickable-area");
				var href = '';
				var host = '';
				var target = '';

				if ( block.find("a").length > 0) {
					href = block.find("a").first().attr("href");
					target = block.find("a").first().attr("target");
				} else if ( block.parent().find("a").length > 0) {
					href = block.parent().find("a").first().attr("href");
			        target = block.parent().find("a").first().attr("target");
				}

				if (! /^(f|ht)tps?:\/\//i.test(href)) {
					var location = 'https://' + window.location.hostname + '/' + href;
				} else {
					var location = href;
				}

				if (target == "_blank") {
					event.preventDefault();
					window.open(location,target);
				} else {
					window.location = location;
				}
			}
		});
	},
	/**
	 * Init print page
	 */
	initPrintPage: function() {
		$(document).on("click","#print", function() {
			window.print();
		});
	},
	/**
	 * Search input field
	 */
	initSearchInput: function() {
 		$(".header .submit").mouseenter(function(){
		    $(this).parent().find(".sword").show();
		});
		$(".header .input-search-box").mouseleave(function(){
		    $(this).parent().find(".sword").hide();
		});
 	},
	/**
	 *  Scroll to an element
	 *  @param sting element
	 *  @param int offsetUpper
	 *  @param int duration
	 *  @param bool findForm
	 */
	scrollToElement: function(element, offsetUpper, duration, findForm) {
		$('html, body').animate({
	        scrollTop: $(element).offset().top - offsetUpper
		}, duration, function() {
			if (findForm === true) {
				var formItem = $(element).find("form");
				if (formItem.length == 1) {
					if (formItem.find("input").val().length > 1){
						var inputNew = formItem.find("input");
					    var len = inputNew.val().length;
					    inputNew[0].focus();
					    inputNew[0].setSelectionRange(len, len);
					} else {
						formItem.find("input").eq(0).focus();
					}
				}
			}
		});

		return false;
	},
	/**
	 * Sticky header
	 */
	stickyHeader: function() {
 		if ($('.extend-view').length == 1) {
			startFrom = $('.extend-view').outerHeight();
		}

 		if ($(window).scrollTop() > 170) {
 			$('#root').addClass("header-sticky");
  		} else {
			$('#root').removeClass("header-sticky");
  		}

 		if ($(window).scrollTop() > 340) {
 			$('#root').addClass("header-sticky-active");
 		}
 		if ($(window).scrollTop() < 340) {
			$('#root').removeClass("header-sticky-active");
		}
	},
	/**
	 * Init news load more - News plugin (Ajax)
	 */
	initNewsLoadMore: function() {
		if($('.list-news-cnt').length < 1) {
			return;
		}
		var container = $('.list-news-cnt'),
			button = $('.load-more-news'),
			pagination = $('.f3-widget-paginator'),
			newsToLoad = [];

		if (pagination.length < 1) {
			button.hide();
		}
		pagination.find('li:not([class])').each(function() {
			newsToLoad.push($(this).find('a').attr('href'));
		});

		button.not('.loading').on('click', function(e) {
			e.preventDefault();
		    e.stopImmediatePropagation();
		    e.stopPropagation();

			if(button.hasClass('loading')){
				return;
			}
			button.addClass('loading');
			$.ajax({
				async: 'true',
				url: newsToLoad[0],
				type: 'POST',
				dataType: 'html',
				success: function (data) {
					var $newItems = $(data).find(".ajax-container .news-list-item");

					container.isotope().append( $newItems ).isotope( 'appended', $newItems );
					container.imagesLoaded().progress( function() {
						container.isotope('layout');
					});

 					newsToLoad.shift();
					button.removeClass('loading');
					if(newsToLoad.length == 0) {
						button.remove();
					}
				},
				error: function (error) {
					button.removeClass('loading');
				}
			});
		});
	},
	/**
	 * init Relatead pages layout
 	 */
	initRelatedPagesLayout: function() {
		$('.nav-regions').attr('data-elements', $('.nav-regions ul > li').length);
	},
	/**
	 * Init anchor list
	 */
	initAnchorList: function() {
		$(".anchor-item a").click(function(event) {
			event.preventDefault();
		    event.stopImmediatePropagation();
		    event.stopPropagation();

		    scrollToElement = "#" + $(this).parent().attr("id").split('-')[1];
		    $('.header').addClass("sticky");
		    layout.scrollToElement(scrollToElement, $('.header').outerHeight(), 450, 0);
		});
	},
	/**
	 * Validate email
	 * @param string $email
	 */
	validateEmail: function($email) {
		var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return emailReg.test($email);
	},
	/**
	 * Init subscribe teaser
	 */
	initSubscribeTeaser: function() {
 		$(".external-form").on('submit', function(event) {
			event.preventDefault();
		    event.stopImmediatePropagation();
		    event.stopPropagation();

		    var target = "_blank",
		    defaultTarget = $(this).attr('action'),
		    emailAddress = $(this).find('.email-address'),
		    location = defaultTarget + '&' + emailAddress.attr('name') + '=' + emailAddress.val();

		    if (layout.validateEmail(emailAddress.val())) {
		    	
		    	window.open(location,target);
		    	emailAddress.removeClass('with-error');
 		    } else {
		    	$(this).focus();
		    	emailAddress.addClass('with-error');
		    	emailAddress.focus();
		    }
 		});
	},
	/**
	 *  Init members - plugin
	 */
	initMembersPlugin: function() {
 		$("#member-country").on('change', function() {
			var location = $(this).val(),
			target = "_top";
 			window.open(location,target);
		});

 		// Autocomplete search for members plugin
 		if ($('.members-filter-module').length) {
 			$('.sword-country').keyup(function() {
 				var searchParameter = $(this).val().toLowerCase();
 				$('.sword-country').not($(this)).val($(this).val());
 	 			if (searchParameter.length >= 2) {
 	 				$('.script-country .country-name').each(function() {
 	 					var countryName = $(this).text().toLowerCase();
 	 					if (countryName.indexOf(searchParameter) != -1) {
 	 						$(this).parent().removeClass('hide');
 	 					} else {
 	 						$(this).parent().addClass('hide');
 	 					}
 	 				});
 	 			} else {
 	 				$('.script-country .country-name').parent().removeClass('hide');
 	 			}
 	 		});
 		}

 		// Filter country click scroll
 		$('.country-holder').click(function() {
 			var dataCountry = $(this).attr('data-country');
 			var selectedDataItem = $('.country-members-holder[data-country="' + dataCountry + '"] .a-h');
 			if (! selectedDataItem.hasClass('open')) {
 				selectedDataItem.trigger('click');
 			}

 			setTimeout(function() {
 				$('html, body').animate({
					scrollTop: selectedDataItem.offset().top - 140
	 			});
 			}, 400);
 		});
	},
	/**
	 * Init Map - plugin
	 */
	initMapPlugin: function() {
		var map = function() {
			if ($("#mapsvg").length) {

				if ($(".tx_wbmap-items .single-item").length) {
					var Regions = {};

					var Region = function () {
						this.id = 0;
						this.title = 0;
						this.gaugeValue;
						this.tooltip = "";
						this.popover = "";
						this.disabled;
					};

					numbers = new Array();
					$(".tx_wbmap-items .single-item").each(function(){
						var item = new Region();
					    item.id = $(this).attr("id");
					    item.title = $(this).find(".top-content .h3").first().text();
					    var sumTargAccid = Number($(this).attr("count")) + Number($(this).attr("accidental"));
					    item.gaugeValue = sumTargAccid;
					    item.disabled = false;
					    item.tooltip = $(this).find(".top-content .h3").first().text();
					    
					    var accidental = '';
					    if ($(this).attr("accidental") > 0) {
					    	accidental = accidentalKill + ': ' + $(this).attr("accidental");
					    }
					    var target = '';
					    if ($(this).attr("count") > 0) {
					    	target = targetedKill + ': ' + $(this).attr("count") + '<br>';
					    }
					    item.popover = '<span class="popup-title">' + $(this).find(".top-content .h3").first().text() + "</span><span class='popup-content'>" + target + accidental + "</span>";

					    Regions[item.id] = item;

					    numbers.push(item.gaugeValue);
					});

					var maxGaugeValue = Math.max.apply(null, numbers);
					var minGaugeValue = Math.min.apply(null, numbers);

					jQuery("#mapsvg").mapSvg({
						disableAll: true,
						colors: {
							baseDefault: "rgb(245,245,245)",
							background: "#fff",
							directory: "#fafafa",
							status: {},
							hover: -5,
							selected: -10
						},
						viewBox: [0,-0.17029702970296512,1009,665.3405940594059],
						scroll: {
							on: true,
							limit: false,
							background: false,
							spacebar: false
						},
						regions: Regions,
						zoom: {
							on: true,
							limit: [0,10],
							delta: 2,
							buttons: {
								on: true,
								location: "left"
							},
							mousewheel: true
						},
						tooltips: {
							mode: function(jQueryTooltipObj, mapObject, mapsvgInstance){
							    if(this.mapsvg_type == "region")
							        return this.title + ': ' + $(".tx_wbmap-items .single-item#" + this.id).attr("count");
							},
							on: true,
							priority: "local",
							position: "bottom-right"
						},
						popovers: {
							mode: "off",
							on: false,
							priority: "local",
							position: "top",
							centerOn: true
						},
						gauge: {
							on: true,
							labels: {
								low: minGaugeValue,
								high: maxGaugeValue
							},
							colors: {
								lowRGB: {
									r: 85,
									g: 0,
									b: 0,
									a: 1
								},
								highRGB: {
									r: 238,
									g: 0,
									b: 0,
									a: 1
								},
								low: "rgb(224, 198, 199)",
								high: "rgb(147, 9, 18)",
								diffRGB: {
									r: 153,
									g: 0,
									b: 0,
									a: 0
								}
							},
							min: 0,
							max: false
						},
						source: "typo3conf/ext/wb_map/Resources/Public/Maps/world.svg",
						title: "IFJ Safety",
						responsive: true,
						onClick: function(e,mapsvg){
						    var region = this;
						    $(".single-item#"+this.id).addClass("show").show().siblings().removeClass("show").hide();

						    //$(".tx-wb-map .cols-a").removeClass("n-p");
						    $(".tx-wb-map .cols-a > .map-content").removeClass("hidden");

						    // select
						    var current = $(".tx-wb-map .map-country .other-items span[data-country='#" + this.id + "']");
						    $(".tx-wb-map .map-country .default-name span").text(current.text());

						    current.hide().siblings().show();

						    mapsvg.setPopovers({centerOn: true});

						},
						afterLoad: function(){


						}
					});
				}

			}
		}
		map();
		$('body').on('click', '.map-country .other-items span', function(e) {
			$countryID = $(this).attr('data-country');
		    $appendText = $(this).text();

		    $(".map-country .append-active span").text($appendText);
		    $(".map-country .other-items span").show();
		    $("span[data-country='" + $countryID + "']").hide();
		    $(".tx_wbmap-items > .single-item").hide();

			if ($countryID == "#worldwide")	{
				//$(".tx-wb-map .cols-a").addClass("n-p");
			    $(".tx-wb-map .cols-a > .map-content").addClass("hidden");

			    $("#mapsvg").mapSvg().setViewBox([0,-0.17029702970296512,1009,665.3405940594059]);
			    $("#mapsvg").mapSvg().hidePopover();
			    $("#mapsvg").mapSvg().deselectRegion();
		   } else {
			   $(".single-item"+$countryID).addClass("show").show().siblings().removeClass("show").hide();
			   //$(".tx-wb-map .cols-a").removeClass("n-p");
			   $(".tx-wb-map .cols-a > .map-content").removeClass("hidden");

			   var replacedId = $countryID.replace("#", "");
			   var region = $("#mapsvg").mapSvg().getRegion(replacedId);
			   $("#mapsvg").mapSvg().showPopover(e, $("#mapsvg").mapSvg().getPopoverBody(region), null, region);

		   }
		});

		$('body').on('click', '.tx-wb-map .map-content .close-popup', function() {
			$(".map-country .other-items span[data-country='#worldwide']").click();
		});

		$('body').on('click', '.tx-wb-map .mapsvg-popover-close', function() {
			$(".map-country .other-items span[data-country='#worldwide']").click();
		});

		var loadMap = function() {
			if ($("#mapsvg div").length) {
				$("#mapsvg").mapSvg().destroy();
			}

			map();
			if ($("#mapsvg div").length) {
				$('.tx-wb-map > .map-container').removeClass('hide');
			} else {
				$('.tx-wb-map > .map-container').addClass('hide');
			}

			setTimeout(function() {
				$('.tx-wb-map .ajax-loader').removeClass('show');
			}, 20);
		};
		$('body').on('click', '.tx-wb-map .map-year .other-items a', function(e) {
			e.preventDefault();
			var current = $(this);
			$('.tx-wb-map .ajax-loader').addClass('show');
			$.ajax({
				async: 'true',
				url: current.attr('href'),
				type: 'POST',
				dataType: 'json',
				success: function (data) {
					var map = $(data);

					$('.tx-wb-map .map-year').html(map.find(".map-year").html());
					$('.tx-wb-map .map-country').html(map.find(".map-country").html());
					$('.tx-wb-map .map-container .map-content').html(map.find(".map-container .map-content").html()).addClass("hidden");

					loadMap();
 				},
				error: function (error) {
					$('.tx-wb-map .ajax-loader').removeClass('show');
				}
			});
		});
	},
	/**
	 * Init resources load more - Resources plugin (Ajax)
	 */
	resourcesLoadMore: function() {
		if($('.tx_wbresources .resources-items').length < 1) {
			return;
		}
		var container = $('.ajax-container'),
			button = $('.load-more-resources'),
			isotopeContainer = $('.list-resources'),
			pagination = $('.page-navigation'),
			resourcesToLoad = [];

		if (pagination.length < 1) {
			button.hide();
		}
		pagination.find('li:not([class])').each(function() {
			resourcesToLoad.push($(this).find('a').attr('href'));
		});
		button.not('.loading').on('click', function(e) {
			e.preventDefault();
		    e.stopImmediatePropagation();
		    e.stopPropagation();
			if(button.hasClass('loading')){
				return;
			}

			button.addClass('loading');
			$.ajax({
				async: 'true',
				url: resourcesToLoad[0],
				type: 'POST',
				dataType: 'html',
				success: function (data) {
					var $newItems = $(data).find(".ajax-container .resc-item");
					container.isotope().append( $newItems ).isotope( 'appended', $newItems );
					container.imagesLoaded().progress( function() {
						container.isotope('layout');
					});

					layout.initFancybox();
					resourcesToLoad.shift();
					button.removeClass('loading');
					if(resourcesToLoad.length == 0) {
						button.remove();
					}
				},
				error: function (error) {
					button.removeClass('loading');
				}
			});
		});
	},
	/**
	 * Load resource by category
	 * */
	initResourcesCategoryAjax: function() {
 		if ($('.tx_wbresources .resources-items').length < 1) {
			return;
		}
		var container = $('.tx-wb-resources');

		$('body').on('click', '.rs-cat-placeholder .ajax-call', function(e) {
			e.preventDefault();
		    e.stopImmediatePropagation();
		    e.stopPropagation();

			if($(this).hasClass('loading') || $(this).find('span').hasClass('btn-root') == true){
				return;
			}

 			container.find(".block-if-ajax-isInProgress").show();
			container.find(".load-resource-loader").addClass("ajax-in-progress");

 			$(this).addClass('loading');
			$.ajax({
				async: 'true',
				url: $(this).attr('data-url'),
				type: 'POST',
				dataType: 'html',
				success: function (data) {
					$(".resources-items, .rs-cat-placeholder > *").remove();
					container.find(".load-resource-loader").removeClass("ajax-in-progress");
					container.find(".block-if-ajax-isInProgress").hide();

					$(data).find(".rs-cat-placeholder").appendTo(container.find('.rs-cat-placeholder'));
 					$(data).find(".resources-items").appendTo(container.find('.tx_wbresources'));

 					var $transform = true;
 					if ($('html[lang="ar"]').length) {
 						$transform = false;
 					}

  					$('.list-resources img').on('load', function() {
						$('.list-resources').isotope({isOriginLeft: $transform, masonry: { columnWidth: 1 } });
					});

					layout.resourcesLoadMore();
					layout.initFancybox();
					layout.initCopyToClipboard();
				},
				error: function (error) {
					$(this).removeClass('loading');
				}
			});
		});
	},
	/**
	* Share posts on social net
	**/
	initShareSocial: function() {
		$('body').on('click', '.social-link.show-in-popup', function() {
		   window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=no,height=300,width=600');
		   return false;
		});
	 },
	 /**
	  * Email link cheat
	  * */
	 initEmailLinkCheat: function() {
		 $('a[href*="javascript:linkTo_UnCryptMailto"], a[href*="mailto:"], a.email').each(function() {
			    var text = $(this).text().split('@');
			    if (text[1]) {
				    $(this).addClass("cheated");
				    $(this).text("");
				    $(this).append('<span class="title">' + text[0] + '</span><span class="email-client">@' + text[1] + '</span>');
			    }
		 });
	 },
	 /**
	  *  Close shared item
	  **/
	 initCloseSharedItem: function() {
		 $('body').on('click', '.remove-extended-resource', function() {
			 $('.extend-view').fadeOut( "300", function() {
				 $('.extend-view').remove();
			 });
			 window.history.pushState({}, document.title, window.location.pathname);
		});

         $('.shared-resource-inner a').parents('.shared-resource-inner').find('img').addClass('c-p');

 		 $('body').on('click', '.shared-resource-inner figure', function() {
			if ($('.shared-resource-inner h3 a').length) {
				 $('.shared-resource-inner h3 a')[0].click();
			}
		 });
 	 },
	 /**
	  *  set the same min height to the slider items
	 **/
	 minHeightFeatureSliderItems: function() {
		 var minHeight = 0;
		 var sliderItems = $('#featured article');
		 var sliderTarget = $('#featured article header');

		if (sliderItems.length>1){

			sliderItems.addClass('script-helper');
			sliderTarget.css("min-height",'auto');

			sliderItems.each(function() {
				minHeight = $(this).find('header').outerHeight() > minHeight ? $(this).find('header').outerHeight() : minHeight;
 			});

			sliderItems.removeClass('script-helper');
			sliderTarget.css("min-height", minHeight);
		}
	 },
	 /**
	  *  init fix layout
	  **/
	 initLayoutFixes: function() {
		 $("#share a[href='#']").on('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
			var $parent = $(this).parent().first()

			if ($("html").hasClass("mobile")) {
				if ($parent.hasClass('toggle')) {
					$parent.removeClass('toggle');
				} else {
					$parent.addClass('toggle');
					$parent.siblings().removeClass('toggle');
				}
			}

			$('html').removeClass('lang-active');
			$('html').removeClass('search-active');
			$('html').removeClass('menu-active');
		 });
		 // Move list center to the main content
		 $("#content").prepend($("#featured").next(".list-center"));

		 $('#footer .frame-type-menu_pages ul').addClass('list-cols');

		 $('.latest-view li').each(function() {
			 $(this).find('img').show();
			 $(this).find('.news-img-wrap').css("background-image", 'url('+ $(this).find('img').attr('src')+')');
			 $(this).find('img').removeAttr('style');
		 });
 	 },
	 /**
	  * News category menu
	  **/
	 initNewsCategoryMenu: function() {
		 $(".news .parent-item > strong, .news .parent-item > .open-submenu").on('click', function(e) {
			 e.preventDefault();
			 e.stopPropagation();
			 e.stopImmediatePropagation();

			 $(this).parents('.parent-item').toggleClass('li-parent-active').find('ul').first().slideToggle();
 		 });
	 },
	 /**
	  * Expendable teaser
	  **/
	 initExpendableTeaser: function() {
 		 $('.script-expand').on('click', function() {
 			 var $parents = $(this).parents('.expendable-teaser');
 			 var $height = $parents.find('.script-data-height').outerHeight();
 			 var $toggleContainer = $parents.find('.expendable-content');

 			 $parents.toggleClass('show-content');

 			 if ($toggleContainer.hasClass('script-active')) {
 				 if (layout.windowSizes().width < 761) {
 					$toggleContainer.css("max-height", 200).removeClass('script-active');
 				 } else {
 					$toggleContainer.css("max-height", 195).removeClass('script-active');
 				 }
 			 } else {
 				$toggleContainer.css("max-height", $height).addClass('script-active');
   			 }
		 });
	 },
	 /**
	  * Expendable teaser function called on resize
	  **/
	 expendableTeaserHeight: function() {
		 $('.expendable-content').each(function() {
			 var $this = $(this);
			 if ($this.hasClass('script-active')) {
				 $this.height($this.find('.script-data-height').outerHeight())
			 }
		 });
	 },
	 /**
	  * Anchor list
	  **/
	 initAnchorList: function() {

		 $(document).on("click", "#featured ul li a, #featured p a, p.featured a", function(e) {
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();

			var anchor = this.href.split("#")[1];
			var location = "#" + anchor;
			var target = $(this).attr("target");

			if (!anchor || $(location).length == 0) {
				location = this.href;
 				if (target == "_blank") {
					window.open(location,target);
				} else {
					window.location = location;
				}
 			} else {
 				layout.scrollToElement(location, headerHeight, 800);
 			}
 		});
	 },
	 /**
	  *  Sticky social
	  **/
	 stickySocial: function() {
		 if (($('main#content').position().top - $('#share').outerHeight()) < $(window).scrollTop()) {
			$('#share').css('opacity',1);
		 } else if ( ($('main#content').position().top + $('#share').outerHeight()) > $(window).scrollTop()){
			$('#share').css('opacity',0);
		 }
	 },
	 /**
	  * File list
	  */
	 initFileList: function() {
		 // Check if active folder exist
		 if ($('.file-list li.active')) {
			 $('.file-list li.active').siblings().removeClass('hide');
			 var parents = $('.file-list li.active').parentsUntil('.module-box');
			 parents.each(function() {
				var childrens = $(this).children();
				childrens.each(function() {
					if (! $(this).hasClass('expand')) {
						$(this).removeClass('hide');
					} else {
						$(this).addClass('hide');
					}
				});
				$(this).siblings().removeClass('hide');
			 });
		 }

		 // Show/hide subfolders
		 $('.expand').on('click', function() {
			$(this).addClass('hide');
			$(this).next().removeClass('hide');
			var list = $(this).siblings('ul');
			list.each(function() {
				$(this).children().removeClass('hide');
			});
		 });

		 $('.collapse').on('click', function() {
			 $(this).addClass('hide');
			 $(this).prev().removeClass('hide');
			 var list = $(this).siblings('ul');
			 list.each(function() {
				 $(this).children().addClass('hide');
			 });
		 });
	},
 	/**
	 * Get windows width and height
	 */
	 windowSizes: function() {
	    var e = window, a = 'inner';
	    if (!('innerWidth' in window)) {
	         a = 'client';
	         e = document.documentElement || document.body;
	    }
		return {
			width: e[a + 'Width'],
			height: e[a + 'Height']
		};
	},
	/**
	 *  Donate form submit
	 */
	initDonateForm: function() {
 		$('a[rel="safety-form"]').on("click", function(e) {
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
 			$('.donate-through-paypal').submit();
		});
	},
	 /**
	  * groupOfElementsMinHeight
	  * Calculate height of the highest element in row, and add that value to all items
	  * */
	 groupOfElementsMinHeight: function(elementForCalculations, findElement) {
		 var thisElem = $(elementForCalculations);

		 if (findElement) {
			 var $findElement = findElement;
		 }

		 if (thisElem.length > 0) {
			 var currentTallest = 0,
			 currentRowStart = 0,
			 rowDivs = new Array(),
			 $el,
			 topPosition = 0;

		 	thisElem.each(function() {
		 		$el = $(this);

		 		if ($findElement) {
	 				$($el).find($findElement).css("min-height", "0");
	 			} else {
	 				$($el).css("min-height", "0");
	 			}
 		 		topPostion = $el.position().top;

		 		if (currentRowStart != topPostion) {
		 			for (currentDiv = 0; currentDiv < rowDivs.length ; currentDiv++) {
		 				rowDivs[currentDiv].css("min-height", currentTallest);
		 			}
		 			rowDivs.length = 0; // empty the array

		 			if ($findElement) {
		 				$el = $el.find($findElement);
		 			}

		 			currentRowStart = topPostion;
		 			currentTallest = $el.height();
		 			rowDivs.push($el);
		 		} else {
		 			if ($findElement) {
		 				$el = $el.find($findElement);
		 			}

		 			rowDivs.push($el);
		 			currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
		 		}

		 		for (currentDiv = 0; currentDiv < rowDivs.length ; currentDiv++) {
		 			rowDivs[currentDiv].css("min-height", currentTallest);
		 		}
		 	});
		 }
	 },
	 initLinkBoxShowHide: function() {
		 if ($('.link-box').length > 0) {
			 if ($('.link-box .clickable-area').length < 9) {
				 $('.link-box-button').hide();
			 } else {
				 $('.page-315 .link-box .clickable-area').each(function(index, element) {
					 var incrementIndex = index + 1;
					 if (incrementIndex > 9) {
						 $(this).hide();
					 }
				 });

				 $('.page-315 .link-box-button .load-more-links').on('click', function(e) {
					 e.preventDefault();
					 $(this).hide();
					 $('.page-315 .link-box .clickable-area:hidden').fadeIn(500);
				 });
			 }
		 }
	 },
	 fullWidthTeaser: function() {
		 $(".full-width-teaser").width($("html").width()).css("margin-left", ($("#footer").width() - $("html").width()) / 2 - parseInt($("#content > .cols-a").css("padding-left")));
		 $(".arabic-site .full-width-teaser").width($("html").width()).css("margin-right", ($("#footer").width() - $("html").width()) / 2 - parseInt($(".arabic-site #content > .cols-w").css("padding-left")));
	 },
	 initScrollToSection: function() {
		 $(".down-arrow").click(function() {
		    $('html, body').animate({
			        scrollTop: $(".down-arrow").offset().top
			}, 800)
		})
	 },
	 initCopyToClipboard: function() {
		 $('body, html').delegate('.resc-item .link-share', 'click', function() {
			 var copiedValue = $(this).attr("data-href");
			 var $temp = $("<input>");
			 $(this).append($temp);
			 $temp.val(copiedValue).select();
			 document.execCommand("copy");
			 $temp.remove();

			 $(".wb-clipboard").show();
			 setTimeout(function() {
				 $(".wb-clipboard").fadeOut();
			 }, 2500);

		})
	 },
	 initDigitalLibraryHeight: function() {
		 var minHeight = 0;
		 var digitalItem = $('.digital-library-item');

		 if (digitalItem.length > 1) {
			 digitalItem.css("min-height",'auto');

			 digitalItem.each(function() {
				 minHeight = $(this).outerHeight() > minHeight ? $(this).outerHeight() : minHeight;
			 });

			 digitalItem.css("min-height", minHeight);
		 }
	 },
	 initQuotationForm: function() {
		 if ($('.quotation-form').length) {
			 function getDateString(date){
				var month = date.getUTCMonth()+1;
				var day = date.getUTCDate();
				return [date.getUTCFullYear(), (month>9 ? '' : '0') + month, (day>9 ? '' : '0') + day ].join('-');
			}
			
			var hostCountries = [];
			var destinationCountries = [];
			var removableDestinationCountryDropdown = $('<div class="full-width"> <select class="destinationCountry full-width"> <option value="" disabled="disabled" selected="selected">Please choose a Country</option> </select> <span class="close-icon">&#10006;</span> <span class="close heavy"></span> </div>');
			var countryStateDropdown = $('<div class="fieldset" id="hostCountryStateContainer"> <div class="full-width"> <label id="stateTitle">State</label> </div> <div class="full-width"> <select id="hostCountryStateDropdown" class="full-width"></select> </div> </div>');
			var quote = "";
			
			// Set datepicker variables
			var today = new Date();
			today.setUTCHours(0,0,0,0);
			var minDate = getDateString(today);
			var maxStartDate = new Date();
			maxStartDate.setDate(today.getDate()+90);
			
			$("#startDate").datepicker({
				autoHide: true,
				format: 'yyyy-mm-dd'
			});
			$("#endDate").datepicker({
				autoHide: true,
				format: 'yyyy-mm-dd'
			});
			
			$("#startDate").attr("min", minDate);
			$("#startDate").attr("max", getDateString(maxStartDate));
			$("#endDate").attr("min", minDate);
			
			// Get host countries and destination countries
			var hostCountryRequest = new XMLHttpRequest();
			hostCountryRequest.open('GET', 'https://api.tangiersgroup.com/api/v1/site/1/product/7/host_country', true);
			hostCountryRequest.onload = function() {

			  var data = JSON.parse(this.response);

			  if (hostCountryRequest.status >= 200 && hostCountryRequest.status < 400) {
				hostCountries = data;
				$.each(data, function(index, value) {
					$("#hostCountryDropdown").append($("<option />").val(index).text(value.country.name));
				});
				
				var destinationCountryRequest = new XMLHttpRequest();
				destinationCountryRequest.open('GET', 'https://api.tangiersgroup.com/api/v1/site/1/product/7/destination_country', true);
				destinationCountryRequest.onload = function() {

				  var data = JSON.parse(this.response);
				  destinationCountries = data;

				  if (destinationCountryRequest.status >= 200 && destinationCountryRequest.status < 400) {
					//save to variable
					
					$.each(data, function(index, value) {
						$("#destinationCountryDropdown").append($("<option />").val(index).text(value.country.name));
						removableDestinationCountryDropdown.find('select').append($("<option />").val(index).text(value.country.name));
					});
					
				  } else {
					$("#errorText").show();
					$("#errorText>span").text("Error loading Resources, Try again later");
					return;
				  }
				}
				
				destinationCountryRequest.send();
				
			  } else {
				$("#errorText").show();
				$("#errorText>span").text("Error loading Resources, please try again later");
				return;
			  }
			}
			hostCountryRequest.send();
			
			$("#hostCountryDropdown").on("change", function(){
			
				var hostCountryArrayId = $("#hostCountryDropdown option:selected").val();
				var hostCountry = hostCountries[hostCountryArrayId];
				$("#hostCountryStateContainer").remove();
				
				if( hostCountry.country.country_states.length > 0 ){
				
					$("#hostCountryContainer").after(countryStateDropdown.clone());
					
					if( hostCountry.country_id === "CH" ){
					
						$("#stateTitle").text('Canton');
						$("#hostCountryStateContainer").find('select').append($('<option value="" disabled="disabled" selected="selected">Please choose a Canton</option>'));
					}else{
						$("#hostCountryStateContainer").find('select').append($('<option value="" disabled="disabled" selected="selected">Please choose a State</option>'));
					}
				
					$.each(hostCountry.country.country_states, function(index, value){
					
						$("#hostCountryStateContainer").find('select').append($("<option />").val(index).text(value.name));
					});
				}
			
			});
			
			$("#addCountryButton").on("click", function(e){
				e.preventDefault();
				removableDestinationCountryDropdown.clone().appendTo( "#destinationCountries" );
				$('.destinationCountry').select2();
			});
			
			$("#destinationCountries").on("click", '.close-icon', function(){
			
				$(this).closest('div').remove();		
			});
			
			$("#getQuoteButton").on("click", function(e){
				e.preventDefault();
				$(".warning-highlight").each(function(){
					$(this).removeClass("warning-highlight");
				});
				$("#errorText").hide();
				
				var selectedDestinationCountries = [];
				$("#destinationCountries select").each(function(){
				
					var destinationCountriesArrayId = $(this).val();
					
					if( destinationCountriesArrayId !== null && destinationCountriesArrayId !== "" ){
						selectedDestinationCountries.push(destinationCountries[destinationCountriesArrayId]);
					}
								
				});
				
				// Begin checks
				
				// Destination Country
				if( selectedDestinationCountries.length < 1){
					showError($("#destinationCountries").closest(".fieldset"), "Please select at least one Destination Country");
					return;
				}
				
				// Host Country & states
				
				if( $("#hostCountryDropdown").val() == "" || $("#hostCountryDropdown").val() == null ){
					showError($("#hostCountryDropdown").closest(".fieldset"), "Please select a Home Country");
					return;
				}
				
				var hostCountry = hostCountries[$("#hostCountryDropdown option:selected").val()];
				
				if( hostCountry.country.country_states.length > 1 ){

					var states = hostCountry.country.country_states;
					if( $("#hostCountryStateDropdown").val() == "" || $("#hostCountryStateDropdown").val() == null ){
						showError($("#hostCountryStateDropdown").closest(".fieldset"), "Please select a State or Canton");
						return;
					}else{
						var selectedState = states[$("#hostCountryStateDropdown").val()];
					}
				
				}else{
					var selectedState = "";
				}
				
				// Dates
				if( $("#startDate").val() == "" || $("#endDate").val() == "" ){
					showError($("#startDate").closest(".fieldset"),"Please select valid Departure and Return dates");
					return;
				}
				
				var todayDate = new Date()
				todayDate.setUTCHours(0,0,0,0);
				
				var startDate = new Date($('#startDate').val());
				var endDate = new Date($('#endDate').val());
				
				if ( startDate < today ) {
					showError($("#startDate").closest(".fieldset"), "Departure date cannot be before today");
					return;
				}
				
				if ( startDate > maxStartDate ) {
					showError($("#startDate").closest(".fieldset"), "Departure date cannot be more than 90 days from today");
					return;
				}
				
				if( endDate < startDate ){
					showError($("#startDate").closest(".fieldset"), "Return Date cannot be before departure date");
					return;
				}
				
				var diffTime = Math.abs(endDate - startDate);
				var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; 
				
				if( diffDays > 365 ){
					showError($("#startDate").closest(".fieldset"), "The Insured time cannot be longer 365 days both days inclusive");
					return;
				}
				
				// Age
				var age = $('#age').val();
				
				if ( age == "" ) {
					showError($("#age").closest(".half-width"), "Please insert a valid Age");
					return;
				}
				
				if ( age < 18 || age > 69 ) {
					showError($("#age").closest(".half-width"), "You must be between 18 and 69 years old to purchase this product");
					return;
				}
				
				// Press Card Number
				var pressCardNumber = $('#pressCardNumber').val();
				
				if( pressCardNumber != "" ){
				
					var pressCardValid = /^[a-zA-Z]{1,3}[0-9]{1,5}$/.test(pressCardNumber);
				
					if( !pressCardValid ){
						showError($("#pressCardNumber").closest(".half-width"), "Invalid press card number");
						return;
					}
				}
				
				// different countries
				var countries = [];
				countries.push($('#hostCountryDropdown').find(':selected').text());
				$('.destinationCountry').each(function() {
					countries.push($(this).find(':selected').text());
				});
				var countriesArray = countries.sort(); 
				var reportCountriesDuplicate = [];
				for (var i = 0; i < countriesArray.length - 1; i++) {
				    if (countriesArray[i + 1] == countriesArray[i]) {
				        reportCountriesDuplicate.push(countriesArray[i]);
				    }
				}
				if (reportCountriesDuplicate.length) {
					showError($("#destinationCountries").closest(".fieldset"), "Please select at least one Destination Country");
					return;
				}
				
				var testInput = {  
									"hostcountry":[ hostCountry ],
									"destinationcountry":selectedDestinationCountries,
									"country_state":selectedState,
									"age":age,
									"press_card_number":pressCardNumber,
									"start_date":startDate,
									"end_date":endDate,
									"currency_id":'EUR'
								}
				
				var quoteRequest = new XMLHttpRequest();
				quoteRequest.open('POST', 'https://api.tangiersgroup.com/api/v1/site/1/product/7/affiliate/79/getquote', true);
				quoteRequest.setRequestHeader("Content-type", "application/json");
				quoteRequest.onload = function() {
				
					quote = JSON.parse(this.response);
					
					if( typeof quote.error !== 'undefined' ){
						$("#errorText").show();
						$("#errorText>span").text("An Error has occurred, please try again later");
						return;
					}
					$("#totalCost").text("EUR "+quote.maincost.toFixed(2)+"*");
					$("#quickQuoteMain").hide();
					$("#quickQuoteDetails").removeClass('hide');
				};
				quoteRequest.send(JSON.stringify(testInput));
			});
			
			$("#clickAndBuyButton").on("click", function(){
				
				var url = 'https://www.battleface.com/quote/79/product/7/step1?quoteId='+quote.quotation_id;
				window.location.href = url;
			});
			
			function showError(element, errorMessage){
				element.addClass("warning-highlight");
				$("#errorText").show();
				$("#errorText>span").text(errorMessage);
			}
		 }
	 },
	 
	 initCongressIFJform: function() {
		 $('select#powermail_field_room_single_selection').attr('disabled',true);
		 $('.powermail_fieldwrap.powermail_fieldwrap_type_input.powermail_fieldwrap_second_preson.layout3 label').append('<span class="mandatory">*</span>');

		 var totalcost = function() {
			 $(".powermail_fieldset_14").show().css('opacity',1);

			 var type = 1;
			 if ($("input#powermail_field_assistancefund_2").prop("checked") === true) {
				 var type = 2;
			 }

		    if (type == 1) {
		    	$('.powermail_fieldwrap_room_single_selection, .powermail_fieldwrap_preferred_airport, .powermail_fieldwrap_marker_01, .powermail_fieldwrap_headline1').show();
		    	$('.powermail_fieldwrap_room_multiple_selection, .powermail_fieldwrap_flightnumber, .powermail_fieldwrap_marker_02, .powermail_fieldwrap_headline2').hide();
		    }  else {
		    	$('.powermail_fieldwrap_room_single_selection, .powermail_fieldwrap_preferred_airport, .powermail_fieldwrap_marker_01, .powermail_fieldwrap_headline1').hide();
		    	$('.powermail_fieldwrap_room_multiple_selection, .powermail_fieldwrap_flightnumber, .powermail_fieldwrap_marker_02, .powermail_fieldwrap_headline2').show();
		    }

		    var totalCosts = $("select#powermail_field_numberofnights").val() * $("select#powermail_field_room_single_selection").val();
		    if (type == 2) {
		    	var totalCosts = $("select#powermail_field_numberofnights").val() * $("select#powermail_field_room_multiple_selection").val();
		    }

		    $('input#powermail_field_totalcost').val(totalCosts);
		 }

		 $("input[name='tx_powermail_pi1[field][assistancefund]']").on("change", function() {
			 totalcost();
		 });

		 if ($("input#powermail_field_assistancefund_1").prop("checked") === true || $("input#powermail_field_assistancefund_2").prop("checked") === true) {
			 totalcost();
		 }

		  $("select#powermail_field_room_single_selection, select#powermail_field_room_multiple_selection").on("change", function() {
		    var roomCost = $(this).val(),
		    	nightsCosts = $("select#powermail_field_numberofnights").val(),
		    	totalCosts = roomCost * nightsCosts;

		    $('input#powermail_field_totalcost').val(totalCosts);
		  });

		  if (parseInt($("select#powermail_field_room_multiple_selection").val()) == 150) {
			  $(".powermail_fieldwrap_second_preson.layout3").show();
			  $('input#powermail_field_second_preson').attr('required','required');
		  } else {
			  $(".powermail_fieldwrap_second_preson.layout3").hide();
			  $('input#powermail_field_second_preson').attr('required', false);
		  }

		  $("select#powermail_field_room_multiple_selection").on("change", function() {
			  if (parseInt($(this).val()) == 150) {
				  $(".powermail_fieldwrap_second_preson.layout3").show();
				  $('input#powermail_field_second_preson').attr('required','required');
			  } else {
				  $(".powermail_fieldwrap_second_preson.layout3").hide();
				  $('input#powermail_field_second_preson').attr('required', false);
			  }
		  });

		  $("select#powermail_field_numberofnights").on("change", function() {
		      var nightsCosts = $(this).val(),
 		      	  roomCost = $("select#powermail_field_room_single_selection").val();

		      if ($("input#powermail_field_assistancefund_2").prop("checked") === true) {
		    	   var roomCost = $("select#powermail_field_room_multiple_selection").val();
		      }

		       var totalCosts = roomCost * nightsCosts;
		       $('input#powermail_field_totalcost').val(totalCosts);
		  });

	 },
	 initLayoutHacks: function() {
		 $(".template-7").parent("html").css("overflow", "auto");
		 $(".template-7 .tx_wbmap-items a").attr("target","_parent");
	 },
	 initDataPicker: function() {
		 
		// date picker
			var startDate = $('#news-minimumDate');
			var endDate = $('#news-maximumDate');
			var startValue = '';
			var endValue = '';
			
			if (endDate.val()) {
				endValue = endDate.datepicker('getDate');
			}
			if (startDate.val()) {
				startValue = startDate.datepicker('getDate');
			}
			startDate.datepicker({
				autoHide: true,
				format: 'mm/dd/yyyy',
				endDate: endValue
			});
			endDate.datepicker({
				autoHide: true,
				format: 'mm/dd/yyyy',
				startDate: startValue
			});

			startDate.on('change', function () {
				endDate.datepicker('setStartDate', startDate.datepicker('getDate'));
			});
			endDate.on('change', function () {
				startDate.datepicker('setEndDate', endDate.datepicker('getDate'));
			});
	 }
}

$(document).ready(function(){
	layout.init();
	layout.stickyHeader();
	layout.stickySocial();
	layout.resourcesLoadMore();
	layout.minHeightFeatureSliderItems();
});

$(document).scroll(function() {
	layout.stickyHeader();
});

$(window).scroll(function() {
	layout.stickySocial();
	layout.fullWidthTeaser();
});

$(window).on('load',function(){
	layout.getHeadersHeight();
	layout.fullWidthTeaser();
	$('body').removeClass('js-off');

	if (location.hash != '') {
		 setTimeout(function() {
			 layout.scrollToElement(location.hash, headerHeight, 800)
		 }, 20);
	}

	if ($("#featured .wide").length>1){
		$(".sl-pager").html('');
		// $('#slideshow').cycle({
		// 	slides: '> div',
		// 	swipe: true,
	    //     swipeFx: 'scrollHorz',
	    //     fx:     'scrollHorz',
	    //     speed:  'slow',
	    //     pauseOnHover: true,
	    //     pagerEvent: 'mouseover',
	    //     timeout: 8000,
	    //     pause: 1,
	    //     prev: '#prev-slide',
		// 	next: '#next-slide',
	    //     pager:  '.sl-pager',
	    //     pagerTemplate: '<div class="sl-pager-item"><span>{{slideNum}}</span></div>',
	    //     log: false
	    // });

	    $('#slideshow').slick({
		  dots: true,
		  customPaging : function(slider, i) {
		  	var val = i + 1;
		    return '<div class="sl-pager-item"><span>' + val + '</span></div>';
		  },
		  dotsClass: "sl-pager",
		  infinite: true,
		  speed: 300,
		  slidesToShow: 1,
		  adaptiveHeight: false,
		  arrows: false
		})
		.on('setPosition', function (event, slick) {
		    slick.$slides.find('.wide').css('min-height', slick.$slideTrack.height() + 'px');
		});
	}

	var $transform = true;
	if ($('html[lang="ar"]').length) {
		$transform = false;
	}

	$('.list-resources').each(function(){
		$(this).isotope({isOriginLeft: $transform, masonry: { columnWidth: 1} });
	});

 	$('.cols-a').each(function(){
		$(this).find($('.list-news')).parents('.cols-a').addClass('has-list-news');
		if($(this).is('.has-list-news')){
			$(this).find($('.module-feed')).css('min-height',$(this).find($('.list-news')).outerHeight()-10);
		}
	});

	layout.groupOfElementsMinHeight('.w-50 .module-featured','.desktop-hide');
	layout.groupOfElementsMinHeight('.w-50 .module-featured','.desktop-only + p');
	layout.groupOfElementsMinHeight('.grid-2 .module-featured','.desktop-hide');
	layout.groupOfElementsMinHeight('.grid-2 .module-featured','.desktop-only + p');
 	layout.groupOfElementsMinHeight('.different-number-in-row li','h3');

 	(function(d, s, id){
 	    var js, fjs = d.getElementsByTagName(s)[0];
 	    if (d.getElementById(id)) return;
 	    js = d.createElement(s); js.id = id;
 	    js.async=true;
 	    js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=1788398694795121&version=v2.10";
 	    fjs.parentNode.insertBefore(js, fjs);
 	}(document, 'script', 'facebook-jssdk'));
});

$(window).on('resize',function(){
	layout.getHeadersHeight;
	$('.cols-a').each(function(){
		if($(this).is('.has-list-news')){
			$(this).find($('.module-feed')).css('min-height',$(this).find($('.list-news')).outerHeight()-10);
		}
	});
	layout.minHeightFeatureSliderItems();
	layout.expendableTeaserHeight();

	layout.groupOfElementsMinHeight('.w-50 .module-featured','.desktop-hide');
	layout.groupOfElementsMinHeight('.w-50 .module-featured','.desktop-only + p');
	layout.groupOfElementsMinHeight('.grid-2 .module-featured','.desktop-hide');
	layout.groupOfElementsMinHeight('.grid-2 .module-featured','.desktop-only + p');
 	layout.groupOfElementsMinHeight('.different-number-in-row li', 'h3');

 	layout.fullWidthTeaser();
 	layout.initDigitalLibraryHeight();
});


window.fbAsyncInit = function() {
	FB.init({
	    appId: '1788398694795121',
	    status: true,
	    cookie: true,
	    version: 'v2.10'
	});

	FB.AppEvents.logPageView();

	$('body').on('click', '.facebook-share', function(e) {
		e.preventDefault();
		e.stopPropagation();
		e.stopImmediatePropagation();
        FB.ui({
                method: 'share',
                href: $(this).attr('data-href'),
            },
            function (response) {}
        );
    })
}