var isMobile = false;
var gtag;
var ge = {};
var players = [];
var homeTimeout;

//Detect Mobile Browser in Javascript
//
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;

//Check for youtube embed within iframe
//
var ytemb = new RegExp('(http|https)?:\/\/(www[\.]|)?[\.]?youtube[\.]?com\/embed\/.*$');

//Email Regex
var er = new RegExp('^((?:(?:(?:[a-zA-Z0-9][\\.\\-\\+_]?)*)[a-zA-Z0-9])+)\\@((?:(?:(?:[a-zA-Z0-9][\\.\\-_]?){0,62})[a-zA-Z0-9])+)\\.([a-zA-Z0-9]{2,})$');

//Add more event track actions here so that they become consistant for each event we track.
//Call within the track event function as 'ge.click' which will populate the event action with the value from this array
//
ge.click = "click";
ge.videoplay = "video-play";
ge.videopause = "video-paused";
ge.videoend = "video-end";

$(window).scroll(function () {
	scrollHeader();
});
	
function scrollHeader() {

	var height 	= $("header").outerHeight();
	var scroll = $(window).scrollTop();
	
	//console.log("scroll " + scroll)
	//console.log("height " + height)

	if (scroll>height){
		// add the scroll menu
		
		
		if (!$("header").hasClass("active")){
			$("header").addClass("active");
		}
		
	} else {
		if ($("header").hasClass("active")){
			$("header").removeClass("active");
		}
	
	}

}


$(document).ready(function () {
   if (typeof Sys !== "undefined") {
      // Event handler for ASPs Page Request Manager.
      // We are looking to see when an UpdatePanel has been updated.
      //
      Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(SF_beginRequest);
      Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(SF_pageLoaded);
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SF_endRequest);
   }

	// Play the home video
	//
	/*
	if($("#home").length){
		var v = document.getElementById("home");
		v.play();
	}
   	*/
	
	// scroll up the cover
	// 
    clearTimeout(homeTimeout);
	homeTimeout = setTimeout(function () {
        ScrollHomeOverlay();
    }, 3000);
	
	
	
	
	
	$('.match-row').matchHeight();	

	$('.menu-toggle').click(function () {
        $("nav").toggleClass('open');

        if ($("nav").hasClass("open")) {
            $("html,body").css({
                "overflow-y": "hidden"
            });
			$(".nav-icon").addClass('open');
			
        } else {
            $("html,body").removeAttr("style");
			$(".nav-icon").removeClass('open');

        }
	});
	
    //GA Event Tracking for every 'a' and 'area' click.
    $(document).on("click", "a,area", function (e) {

        try {

            var t = $(this);
            var tHref = t.attr("href");
            var tTarget = t.attr("target");
            var linkType = "Internal";
            var tagName = $(this).prop("tagName").toLowerCase();
            var trackLink = true;
            var eventLabel = "";

            //Check we have a link to track
            //
            if (tHref != null && typeof tHref != "undefined" && tHref.length > 0) {

                tHref = tHref.toLowerCase();
                eventLabel = t.attr("href");

                //Check which type of link this is (mailto,http etc)
                //
                if (tHref == "#") {
                    if (tagName == "area") {
                        if (t.attr("alt") != null && typeof t.attr("alt") != "undefined" && t.attr("alt").length > 0) {
                            eventLabel = t.attr("alt");
                            linkType = "Image Map"
                        } else {
                            trackLink = false;
                        }
                    } else {
                        trackLink = false;
                    }
                } else if ((tHref.length > 1) && (tHref.indexOf("#") > -1) && (tHref.indexOf("http") == -1)) {
                    linkType = "Anchor";
                } else if ((tHref.length > 1) && (tHref.toLowerCase().indexOf("mailto:") > -1)) {
                    linkType = "Mail";
                } else {
                    if (tHref.indexOf("http://") > -1 || tHref.indexOf("https://") > -1) {
                        if (tTarget != null && typeof tTarget != "undefined") {
                            if (tTarget == "_blank") {
                                linkType = "External New Window";
                            } else {
                                linkType = "External Same Window";
                            }
                        }
                        else {
                            linkType = "External Same Window";
                        }
                    }
                }

                if (trackLink) {
                    AM_TrackEvent(ge.click, "Link (" + linkType + ")", eventLabel);
                }

            }

        } catch (message) {

        }

    });
    //


    //Cookie Policy
    $(".cookieBar .acceptBtn").click(function (e) {
        $(this).parent().slideUp();
        e.preventDefault();
    });
    //

    //Social Sharing
    $(".share-toggle").click(function (e) {
        $(".share-lightbox").fadeToggle();
        e.preventDefault();
    });

    $(".share-fade").click(function () {
        $(".share-lightbox").fadeToggle();
    });
    //


    //Play HTML5 Video
    $(".play-page-video").click(function (e) {

        var t = $(this);
        var tID = t.attr("data-id");
        var video;

        if (tID != null && typeof tID != "undefined") {
            t.hide();
            video = document.getElementById(tID);
            AM_PlayVideo(video);
        }

        e.preventDefault();
    });
    //

    //Check for Youtube Video Embed Iframe on this page
    //
    if (AM_YoutubeEmbed()) {

        try {
            var tag = document.createElement('script');
            tag.id = 'ytapi';
            tag.src = 'https://www.youtube.com/iframe_api';
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            //Go to: onYouTubeIframeAPIReady()

        } catch (message) {

        }
    }


    //if ($(window).scrollTop >= $(".jumbotron").height()) {
    //    ScrollHomeOverlay();
    //}

    FadeScrollMouse();

});

$(window).on("load", function () {

});

$(window).on("scroll", function () {
    clearTimeout(homeTimeout);
    ScrollHomeOverlay();
    FadeScrollMouse();

});

function AM_TrackEvent(eventAction, eventCategory, eventLabel, eventValue) {
    var tagarray = [];
    //Function that tracks an event click and sends to Google (if a GA Code is present)
    //
    //<action>*     = the string that will appear as the event action in Google Analytics Event reports.
    //<category>    = the string that will appear as the event category.
    //<label>       = the string that will appear as the event label.
    //<value>       = a non-negative integer that will appear as the event value.
    //* = Required attribute.

    //Example template of gtag event tracking:
    //gtag('event', <action>, {'event_category': <category>, 'event_label': <label>, 'value':<value>});

    //Example Events below:
    //gtag('event', 'download', {'event_category': 'PDF', 'event_label': '/salesForms/orderForm1.pdf', 'value':<value>});

    if (gtag) {

        var data = {};
        if (eventCategory) { data.event_category = eventCategory; }
        if (eventLabel) { data.event_label = eventLabel; }
        if (eventValue) { data.value = eventValue; }
        tagarray.push(data);
        gtag('event', eventAction, data);

    }

    //More info:    
    //https://developers.google.com/analytics/devguides/collection/gtagjs/events
    //https://support.google.com/analytics/answer/1033068#Anatomy

}

function AM_PlayVideo(video) {

    //Function that plays a HTML5 video when the play button is clicked
    //
    //Add the controls to the video and start playing.
    video.setAttribute("controls", "controls");
    video.play();
}

function AM_RestartVideo(video) {

    //Function that restarts the video once it has finished playing.
    //
    //Once the video as finished reload it so it can be played again.
    var restartVideo = document.getElementById(video);
    restartVideo.removeAttribute("controls");
    restartVideo.load();
    $(".play-page-video[data-id=" + video + "]").show();
}

function AM_RestartAllVideos() {

    //Function that loops through each video on the page that is NOT a background video, and stops them playing and reloads ready to play again.
    //
    $("video.video-html5").each(function () {
        $(this)[0].load();
        $(this)[0].removeAttribute("controls");
        $(this).prev(".play-page-video").show();
    });

}

function AM_YoutubeEmbed() {
    //Function that checks to see if a youtube embed iframe exists on this page.
    //If it does, we can set up video event tracking (if GA Code present)
    //
    var exists = false;
    if (gtag) {
        for (var e = document.getElementsByTagName("iframe"), x = 0; x < e.length; x++) {

            if (ytemb.test(e[x].src)) {
                //If this tag has no id then we can add one
                if (e[x].id == null || typeof e[x].id == "undefined" || e[x].id.length < 1) {
                    e[x].setAttribute("id", "ytemb" + x);
                }

                var src = e[x].src;
                if (src.indexOf("enablejsapi") === -1) {
                    //append to end of querystring
                    //
                    if (src.indexOf("?") > -1) {
                        src = src + "&enablejsapi=1";
                    } else {
                        src = src + "?enablejsapi=1";
                    }

                    e[x].setAttribute("src", src);

                }

                exists = true;
            }
        }
    }
    return exists;
}

function onPlayerStateChange(event) {
    try {
		
		var player = players[event.target.a.id][0];
		var videoData = player.getVideoData();
		var eventLabel = videoData.title;
		
        if (eventLabel != null && typeof eventLabel != "undefined") {
            var videoAction = "";

            //Fire GA Event to track what the user is doing with the video
            if (event.data == YT.PlayerState.ENDED) {
                videoAction = ge.videoend;
            } else if (event.data == YT.PlayerState.PAUSED) {
                videoAction = ge.videopause;
            } else if (event.data == YT.PlayerState.PLAYING) {
                videoAction = ge.videoplay;
            }

            AM_TrackEvent(videoAction, "Video (YouTube)", eventLabel);
        }
    } catch (message) {

    }
}

function onYouTubeIframeAPIReady() {
    for (var e = document.getElementsByTagName("iframe"), x = 0; x < e.length; x++) {
        if (ytemb.test(e[x].src)) {
            var player = new YT.Player(e[x].id, { events: { 'onStateChange': onPlayerStateChange } });
            players.push(player);
        }
    }
}

function IsNull(obj) {
    if ((obj != null) && (typeof obj != "undefined") && (obj.length) > 0) {
        return false;
    } else {
        return true;
    }
}

// Raised before processing of an asynchronous postback starts and the postback is sent to the server.
// You can use this event to set request headers or to begin an animation that indicates that the page
// is processing.
//
function SF_beginRequest(sender, args) {
   // Need to delete any datepickers so it will remove the HTML that it adds for the popup picker.
   //
   unbindDatePickers();
}

// Raised after all content on the page is refreshed, as a result of either a synchronous or an
// asynchronous postback. You can use this event to provide a custom transition effect for updated
// content.
//
function SF_pageLoaded(sender, args) {
   // Page this file is included in can have a "pageLoaded" function defined.
   //
   if (typeof pageLoaded == "function") {
      pageLoaded(sender, args);
   }
}

// Raised after an asynchronous postback is finished and control has been returned to the browser.
// You can use this event to provide a notification to users or to log errors.
//
function SF_endRequest(sender, args) {
   rebindDatePickers();
   rebindTrackChanges();

   // Page this file is included in can have a "pageReloaded" function defined.
   //
   if (typeof endRequest == "function") {
      endRequest(sender, args);
   }
}

// Set up any date and date/time pickers.
//
function rebindDatePickers() {
   if (typeof $.fn.datetimepicker != "undefined") {
      $(".datetimepicker")
         .datetimepicker("destroy")
         .datetimepicker({
            format: "d/m/Y H:i:s",
            allowBlank: true/*,
            onChangeDateTime: function (e, f) {
               if (f.hasClass("track-change")) {
                  markFormChanged();
               }
            }*/
         });

      $(".datepicker")
         .datetimepicker("destroy")
         .off("focus")
         .on("focus", function (e) {
            // When getting focus, if this is the end date of a start/end group, then set the default date for the end date to the start date.
            //
            var self = $(this);

            var group = self.attr("data-datepicker-group");
            if (group != null) {
               var type = self.attr("data-datepicker-type");

               if (type == "end") {
                  var edt = $(".datepicker[data-datepicker-group='" + group + "'][data-datepicker-type=start]");

                  if (edt.length > 0 && edt.attr("data-new-date") !== "false") {
                     self.datepicker("option", "defaultDate", edt.datepicker("getDate"));
                     edt.attr("data-new-date", "false");
                  }
               }
            }
         })
         .off("blur")
         .on("blur", function (e) {
            // When losing focus, if this is the start date of a start/end group, then set a flag so that the end date field knows to get the current start date.
            //
            var self = $(this);

            var group = self.attr("data-datepicker-group");
            if (group != null) {
               var type = self.attr("data-datepicker-type");

               if (type == "start") {
                  self.attr("data-new-date", "true");
               }
            }
         }).datetimepicker({
            format: "d/m/Y",
            allowBlank: true,
            timepicker: false/*,
            onChangeDateTime: function (e, f) {
               if (f.hasClass("track-change")) {
                  markFormChanged();
               }
            }*/
         });
   }
}

// Undind datetimepickers.
// Need to do this otherwise it leaves the picker HTML code within the document.
//
function unbindDatePickers() {
   if (typeof $.fn.datetimepicker != "undefined") {
      $(".datetimepicker,.datepicker").datetimepicker("destroy");
   }
}

// Encode text that may contain HTML; < becomes &lt;    & becomes &amp;   etc.
//
function htmlEncode(html) {
   return document.createElement('a').appendChild(document.createTextNode(html)).parentNode.innerHTML;
};

// Decode text that is HTML encoded.
//
function htmlDecode(html) {
   var a = document.createElement('a'); a.innerHTML = html;
   return a.textContent;
};

// Get the selection start position within an <input> or <textarea>
//
function getSelectionStart(inputField) {
   if (inputField.createTextRange) {
      var r = document.selection.createRange().duplicate();
      r.moveEnd('character', inputField.value.length);

      if (r.text == '') return inputField.value.length;

      return inputField.value.lastIndexOf(r.text);
   }
   else
      return inputField.selectionStart;
}

// Get the selection end position within an <input> or <textarea>
//
function getSelectionEnd(inputField) {
   if (inputField.createTextRange) {
      var r = document.selection.createRange().duplicate();

      r.moveStart('character', -inputField.value.length);

      return r.text.length;
   }
   else
      return inputField.selectionEnd;
}

// Set the caret position within an <input> or <textarea>
//
function setCaretPosition(inputField, position) {
   if (inputField != null) {
      if (inputField.createTextRange) {
         var range = inputField.createTextRange();
         range.move('character', position);
         range.select();
      }
      else if (inputField.selectionStart) {
         inputField.focus();
         inputField.setSelectionRange(position, position);
      }
      else
         inputField.focus();
   }
}

// Object to show a slide-out message to indicate an action has been performed.
// It requires a div which contains a span. The message will be placed in to the span, and then the div will be slid down.
// Depending on which function is called, it will also add the class "success" or "failed" to the div.
//
// actionStatus.success("Update successful");
// actionStatus.failed("Update failed");
//
var actionStatus = (function () {
   function ActionStatus() {
      var timer = null;
      var panel = null;
      var panelText = null;

      this.success = function (msg) {
         showMessage(true, msg);
      }

      this.failed = function (msg) {
         showMessage(false, msg);
      }

      var showMessage = function (success, msg) {
         if (panel == null) {
            // This will need to be created - probably in the master page, below the header.
            //
            panel = $("header").find(".action-status");
            panelText = panel.find("span");
         }

         if (timer != null) {
            clearTimeout(timer);
            timer = null;
         }

         panelText.text(msg);

         panel
            .removeClass("success failed")
            .addClass(success ? "success" : "failed")
            .slideDown(200);

         timer = setTimeout(function () { timer = null; panel.slideUp(200); }, 3000);
      };

      this.close = function () {
         if (timer != null) {
            clearTimeout(timer);
            timer = null;
         }

         panel.slideUp(200);

         return false;
      }
   }

   return new ActionStatus();
})();

// Object to show/hide a spinner when doing busy work.
//
var spinner = (function () {
   function Spinner() {
      var shown = false;
      var div = null;

      this.show = function () {
         if (!shown) {
            // CSS is used to position and spin this div.
            //
            div = $("<div class=\"lds-ring\"><div></div><div></div><div></div><div></div></div>").appendTo("body");
            shown = true;
         }
      }

      this.hide = function () {
         if (shown) {
            if (div != null) {
               div.remove();
               div = null;
            }
            shown = false;
         }
      }
   }

   return new Spinner();
})();


// Calculate an elements position in relation to the current view port.
// Determines if the element is above or below, and how far.
//
function calculateElementPositionInViewport(element, threshold) {
   threshold = threshold || 0;

   element = $(element);

   var elementPosition = element.offset();
   var elementHeight = element.height();
   var viewHeight = $(window).height();
   var scrollTop = $(window).scrollTop();

   var elementOffset = elementPosition.top - scrollTop;

   var above = (elementOffset + elementHeight - threshold) < 0;
   var below = (elementOffset + threshold) >= viewHeight;

   var distance = 0;

   if (above) {
      distance = -elementOffset + threshold;
   }
   else if (below) {
      distance = elementOffset - viewHeight + elementHeight + threshold;
   }

   var result = {
      scrollTop: scrollTop,
      elementTop: elementPosition.top,
      elementHeight: elementHeight,
      viewHeight: viewHeight,
      above: above,
      below: below,
      distance: distance
   };

   return result;
}

// Scroll the window so that the specified element is at or near the top of the window.
//
function scrollElementToTop(element, threshold) {
   threshold = threshold || 0;

   element = $(element);

   var result = calculateElementPositionInViewport(element, threshold);

   $(window).animate({ "scrollTop": result.elementTop - threshold }, 200);
}

// Scroll the window so that the specified element is at or near the bottom of the window.
//
function scrollElementToBottom(element, threshold) {
   threshold = threshold || 0;

   element = $(element);

   var result = calculateElementPositionInViewport(element, threshold);

   $(window).animate({ "scrollTop": result.elementTop - result.viewHeight + threshold }, 200);
}

function ScrollHomeOverlay() {

    if (!$(".hero-video-container").hasClass("slide")) {
        $(".hero-video-container").addClass("slide");
    }

}

function FadeScrollMouse() {
    var ww = $(window).scrollTop();

    if (ww > 50) {
        $(".jumbotron .scroll-down").css("opacity", "0");
    } else {
        $(".jumbotron .scroll-down").css("opacity", "1");
    }
}