var isMobile = false;
var gtag;
var ge = {};
var players = [];

//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";

var scrollRevealEnabled = false;

if (isMobile) {
	scrollRevealEnabled = false;
}


$(document).ready(function () {


	// minerals link
	//
	
	$(".minerals-btn").click( function() {
		window.open ("http://minerals.giant-capital.com");
	});
	



	
    $('.match-height').matchHeight({
        byRow: false,
        mobile: false
    });

    if ($("#cpBody_rprtInsightsContent").attr("data-more") !== "true") {
        $("#loadMoreBtn").hide();
    }

   //SCROLL REVEAL
    if (scrollRevealEnabled) {
       window.sr = ScrollReveal();
       sr.reveal(".icon-panel,.image-container,.content-bg h1, .right-col img, .right-col.centered h3, .right-col.centered p, .principals .col-3,  .line-chevron, .filter-container, .main-listing .col-3, .insights-container, .insights-container p", { duration: 1200, distance: '40px', scale: 1, reset: true });
    }

    //REMOVED 
	//.left-col p,.content-section h2,
	
   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);
   }

	// ************************************************************
	// Nav drop down

	$(".contact-toggle").click(function(e){
		$(".contact-popup").toggleClass("active");
		e.preventDefault();
	});
	
	$(".nav-toggle").click(function(e){
		$("nav").toggleClass("active");
		e.preventDefault();
	});    

	// This closes the drop down menu when clicking outside of it.
	// 
	$(document).mouseup(function(e) 
	{
        var navContainer = $("nav");
        var contactContainer = $(".contact-popup");

		// if the target of the click isn't the container nor a descendant of the container
		//
        if (!navContainer.is(e.target) && navContainer.has(e.target).length === 0) 
		{
            navContainer.removeClass("active");
        }

        if (!navContainer.is(e.target) && navContainer.has(e.target).length === 0)
        {
            navContainer.removeClass("active");
        }

        if (!contactContainer.is(e.target) && contactContainer.has(e.target).length === 0) {
            contactContainer.removeClass("active");
        }

        if (!contactContainer.is(e.target) && contactContainer.has(e.target).length === 0) {
            contactContainer.removeClass("active");
        }
	});


	// ************************************************************




    //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) {

        }
    }

});

$(window).on("load", function () {

});

$(window).scroll(function () {
    scrollHeader();
});

function scrollHeader() {

    var height = $("header").outerHeight() * 1.5;
    var scroll = $(window).scrollTop();

    //console.log("scroll " + scroll)
    //console.log("height " + height)

    if (scroll > height) {
        // add the scroll menu
        if (!$(".scroll-header").hasClass("active")) {
            $(".scroll-header").addClass("active");
        }

    } else {
        if ($(".scroll-header").hasClass("active")) {
            $(".scroll-header").removeClass("active");
        }

    }

}

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")
         .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();
})();


/********** Tiny MCE **********/

// Turn selected elements in to tinyMCE editors with a standard set of features.
//
function fullTinyMCE(selector) {
   tinymce.init({
      selector: selector,           //".tinymce",
      encoding: "xml",              // Tell tinyMCE to return XML encoded content.
      plugins: ["link", "hr"],
      menu: {
         insert: { title: "Insert", items: "link | hr" },
         edit: { title: "Edit", items: "undo redo | cut copy paste | selectall" },
         format: { title: "Format", items: "bold italic underline strikethrough superscript subscript | formats | removeformat" },
      },
      toolbar1: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent"
   });
}

// Turn selected elements in to tinyMCE editors with a limited set of features.
//
function miniTinyMCE(selector) {
   // Simpler tinymce, with only a simple toolbar and no status bar.
   //
   tinymce.init({
      selector: selector,           //".tinymce-min",
      encoding: "xml",              // Tell tinyMCE to return XML encoded content.
      plugins: ["link", "hr"],
      menu: {},
      toolbar1: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist link | outdent indent",
      statusbar: false
   });
}

// Forces all tinyMCE controls to update their original controls with the content.
//
function saveTinyMCEs() {
   tinyMCE.triggerSave();
}

function validateContactUsForm(t, tbName, tbEmail, tbPhone, tbMessage, scrollTopRtn, captchaID, pnlID) {

    var errorMessage = "Please make sure all form fields are compeleted and that you have entered a valid email address.";
    $("#" + pnlID).find(".form-error").children("p").empty();
    $("#" + pnlID).find(".form-error").hide();

    var nameField = $("#" + tbName).removeClass("error");
    var emailField = $("#" + tbEmail).removeClass("error");
    var telephoneField = $("#" + tbPhone).removeClass("error");
    var messageField = $("#" + tbMessage).removeClass("error");
    var captcha = $("#" + captchaID).find(".g-recaptcha-response");

    var name = nameField.val().replace(/^\s+|\s+$/g, "");
    var email = emailField.val().replace(/^\s+|\s+$/g, "");
    var telephone = telephoneField.val().replace(/^\s+|\s+$/g, "");
    var message = messageField.val().replace(/^\s+|\s+$/g, "");

    var valid = true;

    if (name === "" || name.length <= 1) {
        nameField.addClass("error");
        valid = false;
    }

    if (email === "" || !ValidateEmail(email)) {
        emailField.addClass("error");
        valid = false;
    }

    if (telephone === "" || telephone.length <= 1) {
        telephoneField.addClass("error");
        valid = false;
    }

    if (message === "" || message.length <= 1) {
        messageField.addClass("error");
        valid = false;
    }

    if (valid === false && scrollTopRtn === true) {
        $(".refer-popup.refer-form").animate({
            scrollTop: 0
        }, 0);
    }

    if (!valid) {
        $("#" + pnlID).find(".form-error").children("p").text(errorMessage);
        $("#" + pnlID).find(".form-error").show();
    } else {
        if (captcha.length) {

            if (captcha.val() === "" || captcha.val() === null || captcha.val().length < 1) {
                valid = false;
                errorMessage = "Please indicate you are not a robot";
                $("#" + pnlID).find(".form-error").children("p").text(errorMessage);
                $("#" + pnlID).find(".form-error").show();
            } else {
                $("#" + captchaID).prev("input[type=hidden]").val(captcha.val());
            }

        }
    }

    return valid;
}

function validateContactUsPageForm(captchaID) {

    var captcha = $("#" + captchaID).find(".g-recaptcha-response");

    if (captcha.length) {
        if (captcha.val() === "" || captcha.val() === null || captcha.val().length < 1) {
            valid = false;            
        } else {
            $("#" + captchaID).prev("input[type=hidden]").val(captcha.val());
        }
    }   

    return valid;
}


function ValidateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\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 re.test(String(email).toLowerCase());
}



