var allowHide = true;
var thisTimer;
var lastScrollTop = 0;

var scrollNewsIncrement = 3; 
var scrollNewsNextDelay = 9000;
var allowNewsScroll = [true, true,true,true,true,true];
var timerMenu;
$(document).ready(function() { 
	$("body").on("click",".link-roster-show-more",function(e) {
		e.preventDefault();
		$(this).parent("div").next().removeClass("hidden");
		$(this).addClass("hidden");
		$(this).parent("div").next(".")
	});
	$("body").on("click",".main-nav *",function(e) {
		e.stopPropagation();
		//console.log("test");
		clearTimeout(timerMenu);
		//alert("Test");
	});
	$("html").on("click",":not(.main-nav *)",function(e) {
		//e.stopPropagation();
		timerMenu = setTimeout(function(){
			$(".main-nav").find(".has-submenu").removeClass("show-menu");
			//console.log("tester");

		//alert("Test");
		},100);
	});	

	//Emmatt's custom Lazy load
	$(window).scroll(function(e) {
		
		setTimeout(function() {
			$("img[data-lazy-src]").each(function() {
				
				if($(this).isInViewport()) {
					console.log("scrolling src in view " + $(this).attr("data-lazy-src"));
					
					$(this).closest("a").css("opacity", "0.0");
					$(this).attr("src",$(this).attr("data-lazy-src"));
					$(this).removeAttr("data-lazy-src");
					//$(this).css("border", "1px blue solid");
					
					
					var thisImg = $(this);
					setTimeout(function() {
						thisImg.closest("a").css("transition","all 0.7s");
						thisImg.closest("a").css("opacity", "1.0");	
					},100);
					
					


				}
			});
			
		}, 450);
	});
	$(window).trigger("scroll");
	$("body").on("click",".km-slider-nav .slide-next",function(e) {
		var thisSlider = $(this).parents(".km-wide-slider");

		var curSlide = thisSlider.attr("data-cur-slide");
		if(typeof curSlide == "undefined") {
			curSlide = 1;
		}
		curSlide++;
		$(this).parents(".km-wide-slider").attr("data-cur-slide",curSlide);
		var maxSlides = thisSlider.find(".slide").length;
		var slideWidth = $(".km-wide-slides .slide")[0].offsetWidth; 
		console.log(curSlide + "-" + maxSlides);
		//if(curSlide  maxSlides) {
			//alert("test");
		//	return false;
		//}
		//else {

			$(".km-wide-slides .slide").animate({"left": "-=" + slideWidth + "px"}, 
												"slow",
												function(){
													$(this).parents(".km-wide-slider").find(".slide").each(function() {
														var thisLeft = $(this).position().left;
														if(thisLeft < 0) {
															//setTimeout(function() {
																//$(this).css("left",$(this).parents(".km-wide-slider").find(".slide").last().offset().left + "px");	
															$(this).css("left",(maxSlides * slideWidth) + "px");	
															//},100);
															
														}
														else {
															console.log(thisLeft);
														}
													});
												}
				//alert("complete");



			);
		//}

		//alert("test");
	

    });
    
	$("ul.submenu").each(function() {
		$(this).parents("li").addClass("has-submenu");
	});

	$("body").on("click",".main-nav ul li a",function(e) {
		//$(".main-nav ul li").removeClass("show-menu");
		if($(this).parent("li").hasClass("has-submenu")) {
			e.preventDefault();

			$(this).parents("ul").find("a").not(this).parent("li").removeClass("show-menu");

			$(this).parent("li").toggleClass("show-menu");
		}
	});
	/*
	$("body").on("click",".search-menu .search-button",function(e) {
		e.preventDefault();

	});
	*/
	$("body").on("click",".search-dropdown a",function(e){
		$(".search-dropdown a").not(this).next().removeClass("show-menu");
		$(this).next().toggleClass("show-menu");
	});

	$(".scroll-vertical").each(function(index) {

		$(this).find("ul.list-scroller").css("top", $(this)[0].offsetHeight - 25 + "px");
	});
	setInterval(scrollNews, 42);

	$(".menu-toggle").click(function() {
		if($(".main-nav").hasClass("show")) { 
			$(".main-nav").removeClass("show");
		}
		else {
			$(".main-nav").addClass("show");
		}
	});  

	//Hide the second scrollbar, but force-show it on Firefox

	if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
    	$(".search-dropdown-menu").css("overflow-y","scroll");
	}
	/*
	window.setTimeout(function() {
		twttr.widgets.resize();
	},2000);	
	*/

	$("#link-refresh-captcha").click();

	if($(".form-secured").length > 0 ) {
		ajaxFormSubmit("process.php","action=getSecurityCode",$(".button-submit"));
	}

	$(".button-hover").mouseenter(function() {
		$(this).css("opacity","0.7");
	}).mouseleave(function() {
		$(this).css("opacity","1.0");
	});

	$(".link-popup-publication").click(function(e) {
		var thisPopupContent = $(this).next(".container-popup-publication").html();

		if($(this).hasClass("encode")) {
			thisPopupContent = atob(thisPopupContent);
		}

		$popupBackground = $("<div class='popup-background'></div>");
		$popupBackground.hide();
		$popupBox = $("<div class='container-popup'><a class='button-close'>X</a><div class='popup-inner'></div></div>");

		$popupBox.find(".popup-inner").html(thisPopupContent);
		$popupBox.find(".button-close").click(function() {
			$(".container-popup,.popup-background").remove();
			$("body").removeClass("popup-visible");
		});

		$("body").append($popupBackground);
		$("body").append($popupBox);
		$(".popup-background").fadeIn(500);

		window.setTimeout(function() {
			$("body").find(".container-popup").addClass("popup-visible");
			$("body").addClass("popup-visible");
			},200);


	});


	

	$("body").on("click","a.popup-you",function(e) {

		e.preventDefault();

		var thisHref = parseYoutubeUrl($(this).attr("href"));

		var thisIframe = "<iframe allow='autoplay;' frameborder=0 src='" + thisHref + "/?&autoplay=1' allow='autoplay'></iframe>";

		if($(".container-speaker-hero").length > 0) {
			$(".container-speaker-hero").find("img,.container-hero-video,.link-play-video").fadeOut(500,function() {
				$(".container-speaker-hero").find("img,.container-hero-video,.link-play-video,.embed-container").remove();
				$(".container-speaker-hero").append("<div class='container-hero-video'><div class='embed-container'>" + thisIframe + "</div></div><div class='mobile-only text-play-mobile container-hero-video'>Click the Play icon above to start the video</div>");			
				setTimeout(function() {
					$(".text-play-mobile").fadeOut(500, function() {
						$(".text-play-mobile").remove();
					});
				},7000);
			});

		}
		else {
			$("body").append("<div class='popup-background'></div><div class='popup-youtube'><div><a title='Close' class='popup-close'>X</a>" + thisIframe + "</div></div>");			

		}
		setTimeout(function() {
			var element_to_scroll_to = $('.container-speaker-hero')[0];
			element_to_scroll_to.scrollIntoView();
		},300);
		//window.scrollTo(0,0);
	});

	$(".popup-youtube a").live("click",function(e) {

		e.preventDefault();

		$(".popup-youtube,.popup-background").remove();

	});	

	$("a.popup-flv").click(function() { 

  

		var box_height = $(this).attr("vidheight")/ 1;

		var box_width = $(this).attr("vidwidth") / 1;   

		//alert("*" + box_width + "*"); 

     

		$.fancybox({

		'padding'             : 0,

		'autoScale'   : false,

		'transitionIn'        : 'elastic',

		'transitionOut'       : 'elastic',

		'title'               : this.title,

		'width'               : box_width+15,

		'height'              : box_height+15,

		'overlayColor' : '#000000',

		'href'                : '/embed-flv.php?filename=' + this.href +"&width=" + box_width + "&height="+box_height,

		'type'                : 'iframe'

		});                  

		return false;              

	});  

	$("body").on("click",".container-audio-close",function(e) {
		e.preventDefault();
		$("audio").each(function() {
			$(this)[0].pause();
			$(this)[0].currentTime = 0;
			//$(this).attr("src","zzz");
			$(this)[0].play();
			$(this).remove();

		});
		//alert($("audio").length);
		//$("audio")[0].pause();
		//$("audio")[0].currentTime = 0;
		//$("audio").attr("src","");

		$(".container-audio,.container-audio-back").remove();
	});
	$("a.popup-mp3").click(function() { 
		$(".container-audio,.container-audio-back").remove();
		$("body").append("<div class='container-audio-back'></div><div class='container-audio'><a href='javascript:' class='container-audio-close'>x</a><audio  controls preload><source src='" + this.href + "' type='audio/mpeg'></div>");
  
  		setTimeout(function() {
  			$("audio")[0].play();
  		},1000);

		var box_height = 20;

		var box_width = 390;   

		return false;              

	});  

	var defaultSearch = "Enter search text";

	$("#search_keyword").focus(function(){

		if($(this).val() == defaultSearch) { $(this).val(""); }

	}).blur(function() { 

		if($(this).val() == "") { $(this).val(defaultSearch); }

	}).blur()

	.keypress(function(event){

		if (event.which == '13') { 

			$("#button_search_keyword").click(); 

		}



	});

	$("#button_search_keyword").click(function(){ 

		var keyword = $("#search_keyword").val();

		if(keyword == defaultSearch || keyword == "") { keyword = ""; }  

		document.location.href = "https://www.kmprod.com/search.php?keyword=" + keyword;  

	});


	$('#btn_advanced_search').click(function() {

		display = $(this).next().css("display");			

		$(this).next().toggle(100);

		if(display == "block") { $(this).removeClass("accordion-down"); $(this).addClass("accordion-side"); $(this).html("Click Here for Advanced Search"); }

		else { $(this).removeClass("accordion-side"); $(this).addClass("accordion-down"); $(this).html("Hide Advanced Search");}

		return false;

	}).parent().children(".speaker-content").hide();

	$('span.email').mailme();

	$("body").on("click",".btn-fee-range", function() {
		_statcounter.push({"tags": {"event_name": "Fee Range click"}});
		_statcounter.record_pageview();
		
	});
	

	$('.accordion .head').click(function() {

		//alert("test");

		display = $(this).parent().children(".speaker-content").css("display");			

		$(this).parent().children(".speaker-summary").toggle();

		$(this).parent().children(".speaker-content").toggle();



		if(display == "block") { $(this).removeClass("accordion-down"); $(this).addClass("accordion-side"); }

		else { $(this).removeClass("accordion-side"); $(this).addClass("accordion-down"); }

		return false;

	}).parent().children(".speaker-content").hide();

	$('.read-more').click(function() {

		$(this).parents(".speaker-content-area").children(".accordion .head").click();

	});

	$(".link-lesslink").live("click",function() {

	}); 

	$(".link-lesslink-internal").live("click",function() {

		$(this).parents("p,ul,ol").hide().prevUntil(":not(.morecontent)","p, ul, ol, div, table, h3").hide();

		$(".link-morelink").show();

		$("html").scrollTop(lastScrollTop);

		console.log(lastScrollTop);

		

	});	

	$(".link-morelink").live("click",function() {

		lastScrollTop = $("html").scrollTop();

		$(this).parents("p, ul, ol, div, table, h3").nextUntil(":not(.morecontent)","p, ul, ol, div, table").show();//show();

		$(this).hide();//html("[less...]");

	});	

	$("input, select, textarea").change(function() { 

		if($(this).hasClass("errorfield")) { 

			$(this).removeClass("errorfield").next(".errortext").remove();

		}

	});

	$("input, select, textarea").keydown(function(e) {

		if($(this).parents("tr").hasClass("disabled")) {

			e.preventDefault();

		}

		if($(this).parents("tr, div").hasClass("readonly")) {

			e.preventDefault();

		}		

	});		

	$("input, select, textarea").mousedown(function(e) {

		if($(this).parents("tr").hasClass("disabled")) {

			e.preventDefault();

		}

		if($(this).parents("tr, div").hasClass("readonly")) {

			e.preventDefault();

		}

	});		

	$("input, select, textarea").click(function(e) {

		if($(this).parents("tr").hasClass("disabled")) {

			e.preventDefault();

		}

		if($(this).parents("tr, div").hasClass("readonly")) {

			e.preventDefault();

		}



	});		

	$(".required-radio").change(function() { 

		if($(this).attr("checked")) {

			$("input[name=" + $(this).attr("name") + "]").next("label").addClass("no-print");

			$(this).next("label").removeClass("no-print");

		}

	});

	$(".required-radio").each(function() {

		$(this).change();

	});

	$(".required").parent("td").prev("td").children(".asterisk").css("visibility","visible");

	$(".required").prevAll(".asterisk").css("visibility","visible");

	$(".required-radio").prevAll(".asterisk").css("visibility","visible");

	$(".required-check").prevAll(".asterisk").css("visibility","visible");

	$("input[type=radio]").addClass("no-print");

	

	$(".button-submit").click(function() { 

		$('html, body').animate({ 

			//scrollTop: $(document).height()-$(window).height()

			},  1);	

		$(this).attr("disabled","true");

		var thisButton = $(this)

		thisButton.hide();

		var thisForm = $(this).parents("form"); //$($(this).attr("submitform"));

		if(thisButton.attr("progresstext")) {

			thisForm.find(".progress").html(thisButton.attr("progresstext"));

		}

		thisForm.find(".progress").show();

		modalProgress(true);

		if(checkForm(thisForm)) { 

			$.ajax({

				url: "/process.php",

				type: "post",

				data: thisForm.serialize(),

				success: function (theResponse) {

					

					try {

						responses = $.parseJSON(theResponse);

						thisButton.removeAttr("disabled");

						thisForm.find(".progress").hide();	

						if(responses['status'] == "success") { 

							

							if(responses['message']) { 

								$(".status-message").html(responses['message']);

							}

					        if (typeof(window[responses['callback']]) === "function") { 

					            window[responses['callback']](responses);

					        }									

							if(responses['redirect']) {

								location.href= responses['redirect'];

							}

							else if (typeof(window[thisButton.attr("submitsuccess")]) === "function") { 

								

								window[thisButton.attr("submitsuccess")](responses,thisForm);

							}

							if(responses['override']) { 

								$(".override-content").html(responses['override']);

							}

							

							//$('html, body').animate({ scrollTop: 0 }, 0);

						}

						else {

							if (typeof(window[thisButton.attr("submiterror")]) === "function") { 

								window[thisButton.attr("submiterror")](responses,thisForm);

							}

						}

						modalProgress(false);

					} 

					catch (err) {

						alert("ERROR: " + err.message + "\n RESPONSE: " + theResponse);

						thisButton.removeAttr("disabled");

						modalProgress(false);

						thisButton.show();

					}

				},

				error: function( jqXHR, textStatus, errorThrown) {

					alert("ERROR: " + textStatus);

					

					thisButton.removeAttr("disabled");

					thisForm.find(".progress").hide();	

					modalProgress(false);

					thisButton.show();

				}

							

			

			});

		} 

		else {

			thisButton.removeAttr("disabled");

			thisForm.find(".progress").hide();	

			modalProgress(false);

			thisButton.show();

		}

	});

	$(".toggle-next").click(function() {

		if($(this).next(".container-next").hasClass("next-hidden")) {

			$(this).next(".container-next").removeClass("next-hidden");

		}

		else {

			$(this).next(".container-next").addClass("next-hidden");

		}

		//alert("text");

	});

	$(".container-flyout-image").each(function() {

		

		$(this).attr("originalheight",$(this).height() + 30);

		$(this).hide();

	});

	$(".container-flyout-image").mouseenter(function() {

		allowHide = false;

	});

	$(".link-flyout-image").mouseenter(function() {

		$(".container-flyout-image").hide();

	});

	$(".link-flyout-image, .container-flyout-image").mouseenter(function() {

		if($(this).hasClass("container-flyout-image")) {

			var thisImage = $(this).prev(".link-flyout-image");

		}

		else {

			var thisImage = $(this);

		}

		$(".link-flyout-image").find("img").stop(true,true).css("opacity","1.0");

		thisImage.find("img").animate({

				opacity: 0.5

			},500);

		var thisContainer = thisImage.next(".container-flyout-image");

		

		var thisLink = thisImage.find("img");

		var thisLeft = (thisLink.position().left - thisContainer.width() + 24);

		var thisTop = (thisLink.position().top) + (thisLink.height());

		

		if(!thisContainer.is(":visible")) {

		

			thisContainer.css("left",thisLeft + "px").css("top",thisTop+"px").css("height","1px");

			$(".container-flyout-image").stop(true,true);

			

			thisContainer.animate({

					height: thisContainer.attr("originalheight")

				},500,function() {

					

				});

			//alert(thisLeft);

			//thisContainer.css("left",thisLeft + "px" )

			thisContainer.show();

		}

		allowHide = false;

		

	});

	



	$(".link-flyout-image, .container-flyout-image").mouseleave(function() {

		if($(this).hasClass("container-flyout-image")) {

			var thisImage = $(this).prev(".link-flyout-image");

		}

		else {

			var thisImage = $(this);

		}

		

		thisImage.find("img").animate({

				opacity: 1.0

			},500);	

		thisTimer = setTimeout(function() {

			if(allowHide) { 

				$('.container-flyout-image').hide();

			}

		},200);

		allowHide = true;

		

	});

});





function modalProgress(thisShow) { 

	if(thisShow == true) {

		$("#ajax-loading,.container-progress").show();

		//$("#modal-progress").modal({

		//	backdrop: 'static'

		//});

		//$(".modal-backdrop, .modal-backdrop.fade.in").css("opacity",0.1);

	} 

	else {

		$("#ajax-loading,.container-progress").hide();

		//$("#modal-progress").modal('hide');

	}

}





function replaceLinks(text) {

	var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

	return text.replace(exp,"<a target='_blank' href='$1'>$1</a>"); 

}

function checkForm(thisForm) {

	thisError = false;

	var thisIncludeError="";

	

	$(".errortext").remove();

	$(".errorfield").removeClass(".errorfield");

	thisForm.find(".required").each(function() { 

		//alert($(this).hasAncestor(".disabled"));

		if(!$(this).val() && $(this).hasAncestor(".disabled") == 0 && $(this).hasAncestor(".hidden") == 0 && $(this).hasAncestor(".hidden-step")== 0) {

			$(this).addClass("errorfield").after("<span class='errortext'>This field is required</span>");

			thisError = true;

			thisIncludeError += "," + $(this).attr("id");

		}

	});

	thisForm.find(".required-radio").each(function() {

		if($("input[name=" + $(this).attr("name") + "]:checked").length == 0 && $(this).hasAncestor(".disabled") == 0 && $(this).hasAncestor(".hidden")== 0 && $(this).hasAncestor(".hidden-step")== 0) {

			//alert("Must check a value " + $(this).attr("name"));

			$(this).addClass("errorfield");

			$(".error-" + $(this).attr("name")).html("<span class='errortext'>You must select an option</span>");

			thisError = true;

			thisIncludeError += "," + $(this).attr("id");

		}

		else {

			$(this).removeClass("errorfield");

		}

	});

	thisForm.find(".required-check").each(function() { 

		

		if(!$(this).prop("checked") && $(this).hasAncestor(".disabled") == 0 && $(this).hasAncestor(".hidden") == 0 && $(this).hasAncestor(".hidden-step")== 0) {

			$(this).addClass("errorfield").after("<span class='errortext'>You must check this option to continue</span>");

			thisError = true;

			thisIncludeError += "," + $(this).attr("id");

		}

	});

	thisForm.find(".required-email").each(function() { 

		//alert($(this).hasAncestor(".disabled"));

		

		if(!isValidEmail($(this).val()) && $(this).hasAncestor(".disabled") == 0 && $(this).hasAncestor(".hidden") == 0 && $(this).hasAncestor(".hidden-step")== 0) {

			$(this).addClass("errorfield");

			if(!$(this).hasClass("required-notext")) {

				$(this).after("<span class='errortext'>Please format your email address correctly (ie:name@example.com)</span>");

			}

			thisError = true;

			thisIncludeError += "," + $(this).attr("id");

		}

	});		

	

	//alert(thisIncludeError);

	if(thisError) { 

		$(".errorfield:first").focus();

		alert("There were errors, please check all of the fields above and try again.");

		return false;

		

	}

	else {

		return true;

	}

}



function ajaxFormSubmit(thisServerScript, thisData, thisButton) { 

  modalProgress(true);



  $.ajax({

    url: thisServerScript,

    type: "post",

    enctype:"multipart/form-data",

    data: thisData,

    success: function (theResponse) {



      //alert(theResponse);

      

      try {

        responses = $.parseJSON(theResponse);

        thisButton.removeAttr("disabled");

        $(".progress").hide();	

        if(responses['status'] == "success") { 

          //alert(thisButton.attr("submitsuccess"));

          if(responses['error']) {

            for(thisErr in responses['error']) {

              //alert(responses['error'][thisErr]);

              $("#" + thisErr).addClass("errorfield").after("<span class='errortext'>" + responses['error'][thisErr] + "</span>");

              

            }

            

          }

          if(responses['message']) { 

            $(".status-message").html(responses['message']);

          }





          if(responses['override']) { 

            $(".override-content").html(responses['override']);

          }

          if (typeof(window[responses['callback']]) === "function") { 

            window[responses['callback']](responses);

          }							

          

          if(responses['redirect']) {

            location.href= responses['redirect'];

          }							

          //$('html, body').animate({ scrollTop: 0 }, 0);

        }

        else {

          if (typeof(window[thisButton.attr("submiterror")]) === "function") { 

            window[thisButton.attr("submiterror")](responses);

          }

        }

        modalProgress(false);

      } 

      catch (err) {

        alert("ERROR: " + err.message + "\n RESPONSE: " + theResponse);

        thisButton.removeAttr("disabled");

        modalProgress(false);

      }

    },

    error: function( jqXHR, textStatus, errorThrown) {

      //alert("ERROR: " + textStatus);

      

      thisButton.removeAttr("disabled");

      $(".progress").hide();	

      modalProgress(false);

    }

          

  

  });

}



function successGetCode(responses) {

	//alert(responses['code']);

	$(".form-secured").append("<input type='text' style='display: none' name='code_input' value='" + responses['code'] + "'>");



}

function getFilename() {

	return location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

}
$.fn.isInViewport = function() {
	//console.log($(this).outerHeight(false));
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + parseInt($(this).outerHeight(false));

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

	//console.log(elementTop + " - " + elementBottom + " || " + viewportTop + " - " + viewportBottom);

	//elementTop = elementTop - 100;
	//console.log(elementTop + " - " +  viewportBottom);
    return elementTop > viewportTop  && elementTop < (viewportBottom  + 100) ;
	
	return elementTop < viewportBottom ;
};
$.fn.hasAncestor = function(a) {

    return $(this).closest(a).length;

};

if (!String.prototype.trim) {

	String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};



	String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};



	String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};

}	

function hideMenu(mnu)

{

	$.mnu.hide();

}

function parseYoutubeUrl(thisHref) {
	thisHref = thisHref.replace("watch?v=", 'embed/');
	thisHref = thisHref.replace("http://", 'https://');
	thisHref = thisHref.replace("&feature=youtu.be", "");	
	return thisHref;
}

function isValidEmail(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
}

jQuery.fn.mailme = function() {
    var at = / at /;
    var dot = / dot /g;

    this.each( function() {
        var addr = jQuery(this).text().replace(at,"@").replace(dot,".");
        var title = jQuery(this).attr('title')
        $(this)
            .after('<a href="mailto:'+addr+'" title="'+title+'">'+ addr +'</a>')
            .remove();
    });
};


function scrollNews() {
	$(".scroll-vertical").each(function(index) {

		var thisNewsTicker = $(this);
		if(allowNewsScroll[index] == true) {
			//alert("test");
			$(this).find('ul').animate({
				"top": "-=" + scrollNewsIncrement + "px"
				}, 10, function() {
	    			}
	    	);
	    }
	    var tickerHeight = thisNewsTicker[0].offsetHeight;
	    //console.log(tickerHeight);
		var scrollTickerHeight = thisNewsTicker.find("ul")[0].offsetHeight;

		var scrollTickerTop = thisNewsTicker.find("ul").position().top;	
		//$(this).find("ul.list-scroller > li.news-item").css("min-height",tickerHeight + "px");
		//$(this).find("ul.list-scroller > li.news-item").css("background-color","#EEE");
		
		if(scrollTickerTop <= (-1 * scrollTickerHeight)) {
			//console.log(scrollTickerTop + " , " + tickerHeight);
			var datetime = new Date();
			console.log("reset news height" + scrollTickerTop + " " + datetime);
			//console.log((tickerHeight - 5) + "px");
			
			allowNewsScroll[index] = false;
			setTimeout(function() {
				thisNewsTicker.find("ul").css("top",(tickerHeight - 5) + "px");
				allowNewsScroll[index] = true;
			},100);

			/*
			thisNewsTicker.find('ul').animate({
				"top": "" + (tickerHeight - 5 ) + "px"
				}, 1, function() {
					//console.log("tester");
	    		}
	    	);
	    	*/
		
			//$(".timeline .newsticker ul").position({top: tickerHeight +"px"});
		}

		thisNewsTicker.find("ul .n-pause").each(function() {
			var thisNewsPause = $(this);

			if(allowNewsScroll[index] == true) {
				var pauseOffsetTop = thisNewsPause.offset().top;
				//console.log(pauseOffsetTop);
				var tickerOffsetTop = thisNewsTicker.offset().top + 10;
				var tickerOffsetBottom = tickerOffsetTop + tickerHeight - 1;
				
				//if((pauseOffsetTop <= tickerOffsetTop + scrollNewsIncrement && pauseOffsetTop >= tickerOffsetTop) || (pauseOffsetTop <= tickerOffsetBottom + scrollNewsIncrement && pauseOffsetTop >= tickerOffsetBottom) ) {
				if((pauseOffsetTop <= tickerOffsetTop + scrollNewsIncrement && pauseOffsetTop >= tickerOffsetTop)) {
					allowNewsScroll[index] = false;

					//thisNewsTicker.find("ul").css("top",(thisNewsPause.offset().bottom - 35) + "px");

					//Increment a bit more to avoid double pauses
					thisNewsTicker.find('ul').animate({
						"top": "-=" + scrollNewsIncrement + "px"
						}, 5, function() {
							console.log(thisNewsTicker.find("ul").position());
			    		}
			    	);					
					//console.log("pause");
					setTimeout(function() {
						allowNewsScroll[index] = true;
						//console.log("unpause");

					},scrollNewsNextDelay);
				}


			}
			//console.log(pauseOffsetTop + " - " + tickerOffsetBottom);
		});		
	});

	
	
	//$('.timeline .newsticker ul').css({marginTop: '-=2px'});
}
