/* Minification failed. Returning unminified contents.
(1592,13,1605,14): run-time error JS1314: Implicit property name must be identifier: success(data) {
                var msg = data.Message,
                    url = data.Url;

                if (data.Success == true) {
                    $('.loader-container, .constructor-header, .standard-content').remove();
                    $('#frmContractorPortalDefectUpdate > section').html('<div class="ui container" style="padding: 20px 0;"><h2 style="color: #222">'  + msg + ' (' + serviceOrderId + ').</h2>Please <a href="#" id="reloadPage" style="text-decoration: underline;">click here </a> to view the defects assigned to you on this house.</div>');
                }

                if (data.Success == false) {
                    $('.loader-container, .constructor-header, .standard-content').remove();
                    $('#frmContractorPortalDefectUpdate > section').html('<div class="ui container" style="padding: 20px 0;"><h2 style="color: #222">'  + msg + ' (' + serviceOrderId + ').</h2>Please <a href="#" id="reloadPage" style="text-decoration: underline;">click here </a> to view the defects assigned to you on this house.</div>');
                }
            }
(1606,13,1612,14): run-time error JS1314: Implicit property name must be identifier: error(err) {
                // $(_loader).find("loading").addClass('error');
                // setTimeout(function(){$(_loader).removeClass('loading')}, 100);
                console.warn(err.statusText);
                $('.loader-container, .constructor-header, .standard-content').remove();
                $('#frmContractorPortalDefectUpdate > section').html('<div class="ui container" style="padding: 20px 0;"><h2>Error occured</h2>Please <a href="#" id="reloadPage" style="text-decoration: underline;">click here </a> to view the defects assigned to you on this house.</div>');
            }
 */
/**
 * Basic structure: TC_Class is the public class that is returned upon being called
 * 
 * So, if you do
 *      var tc = $(".timer").TimeCircles();
 *      
 * tc will contain an instance of the public TimeCircles class. It is important to
 * note that TimeCircles is not chained in the conventional way, check the
 * documentation for more info on how TimeCircles can be chained.
 * 
 * After being called/created, the public TimerCircles class will then- for each element
 * within it's collection, either fetch or create an instance of the private class.
 * Each function called upon the public class will be forwarded to each instance
 * of the private classes within the relevant element collection
 **/
(function($) {

    window.timeCircle = function() {}

    var useWindow = window;

    // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
    if (!Object.keys) {
        Object.keys = (function() {
            'use strict';
            var hasOwnProperty = Object.prototype.hasOwnProperty,
                hasDontEnumBug = !({
                    toString: null
                }).propertyIsEnumerable('toString'),
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            return function(obj) {
                if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
                    throw new TypeError('Object.keys called on non-object');
                }

                var result = [],
                    prop, i;

                for (prop in obj) {
                    if (hasOwnProperty.call(obj, prop)) {
                        result.push(prop);
                    }
                }

                if (hasDontEnumBug) {
                    for (i = 0; i < dontEnumsLength; i++) {
                        if (hasOwnProperty.call(obj, dontEnums[i])) {
                            result.push(dontEnums[i]);
                        }
                    }
                }
                return result;
            };
        }());
    }

    // Used to disable some features on IE8
    var limited_mode = false;
    var tick_duration = 200; // in ms

    var debug = (location.hash === "#debug");

    function debug_log(msg) {
        if (debug) {
            console.log(msg);
        }
    }

    var allUnits = ["Days", "Hours", "Minutes", "Seconds"];
    var nextUnits = {
        Seconds: "Minutes",
        Minutes: "Hours",
        Hours: "Days",
        Days: "Years"
    };
    var secondsIn = {
        Seconds: 1,
        Minutes: 60,
        Hours: 3600,
        Days: 86400,
        Months: 2678400,
        Years: 31536000
    };

    /**
     * Converts hex color code into object containing integer values for the r,g,b use
     * This function (hexToRgb) originates from:
     * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
     * @param {string} hex color code
     */
    function hexToRgb(hex) {
        // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }

    function isCanvasSupported() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    }

    /**
     * Function s4() and guid() originate from:
     * http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
     */
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }

    /**
     * Creates a unique id
     * @returns {String}
     */
    function guid() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    }

    /**
     * Array.prototype.indexOf fallback for IE8
     * @param {Mixed} mixed
     * @returns {Number}
     */
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(elt /*, from*/ ) {
            var len = this.length >>> 0;

            var from = Number(arguments[1]) || 0;
            from = (from < 0) ?
                Math.ceil(from) :
                Math.floor(from);
            if (from < 0)
                from += len;

            for (; from < len; from++) {
                if (from in this &&
                    this[from] === elt)
                    return from;
            }
            return -1;
        };
    }

    function parse_date(str) {
        var match = str.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{1,2}:[0-9]{2}:[0-9]{2}$/);
        if (match !== null && match.length > 0) {
            var parts = str.split(" ");
            var date = parts[0].split("-");
            var time = parts[1].split(":");
            return new Date(date[0], date[1] - 1, date[2], time[0], time[1], time[2]);
        }
        // Fallback for different date formats
        var d = Date.parse(str);
        if (!isNaN(d))
            return d;
        d = Date.parse(str.replace(/-/g, '/').replace('T', ' '));
        if (!isNaN(d))
            return d;
        // Cant find anything
        return new Date();
    }

    function parse_times(diff, old_diff, total_duration, units, floor) {
        var raw_time = {};
        var raw_old_time = {};
        var time = {};
        var pct = {};
        var old_pct = {};
        var old_time = {};

        var greater_unit = null;
        for (var i = 0; i < units.length; i++) {
            var unit = units[i];
            var maxUnits;

            if (greater_unit === null) {
                maxUnits = total_duration / secondsIn[unit];
            } else {
                maxUnits = secondsIn[greater_unit] / secondsIn[unit];
            }

            var curUnits = (diff / secondsIn[unit]);
            var oldUnits = (old_diff / secondsIn[unit]);

            if (floor) {
                if (curUnits > 0) curUnits = Math.floor(curUnits);
                else curUnits = Math.ceil(curUnits);
                if (oldUnits > 0) oldUnits = Math.floor(oldUnits);
                else oldUnits = Math.ceil(oldUnits);
            }

            if (unit !== "Days") {
                curUnits = curUnits % maxUnits;
                oldUnits = oldUnits % maxUnits;
            }

            raw_time[unit] = curUnits;
            time[unit] = Math.abs(curUnits);
            raw_old_time[unit] = oldUnits;
            old_time[unit] = Math.abs(oldUnits);
            pct[unit] = Math.abs(curUnits) / maxUnits;
            old_pct[unit] = Math.abs(oldUnits) / maxUnits;

            greater_unit = unit;
        }

        return {
            raw_time: raw_time,
            raw_old_time: raw_old_time,
            time: time,
            old_time: old_time,
            pct: pct,
            old_pct: old_pct
        };
    }

    var TC_Instance_List = {};

    function updateUsedWindow() {
        if (typeof useWindow.TC_Instance_List !== "undefined") {
            TC_Instance_List = useWindow.TC_Instance_List;
        } else {
            useWindow.TC_Instance_List = TC_Instance_List;
        }
        initializeAnimationFrameHandler(useWindow);
    };

    function initializeAnimationFrameHandler(w) {
        var vendors = ['webkit', 'moz'];
        for (var x = 0; x < vendors.length && !w.requestAnimationFrame; ++x) {
            w.requestAnimationFrame = w[vendors[x] + 'RequestAnimationFrame'];
            w.cancelAnimationFrame = w[vendors[x] + 'CancelAnimationFrame'];
        }

        if (!w.requestAnimationFrame || !w.cancelAnimationFrame) {
            w.requestAnimationFrame = function(callback, element, instance) {
                if (typeof instance === "undefined")
                    instance = {
                        data: {
                            last_frame: 0
                        }
                    };
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - instance.data.last_frame));
                var id = w.setTimeout(function() {
                    callback(currTime + timeToCall);
                }, timeToCall);
                instance.data.last_frame = currTime + timeToCall;
                return id;
            };
            w.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
        }
    };


    var TC_Instance = function(element, options) {
        this.element = element;
        this.container;
        this.listeners = null;
        this.data = {
            paused: false,
            last_frame: 0,
            animation_frame: null,
            interval_fallback: null,
            timer: false,
            total_duration: null,
            prev_time: null,
            drawn_units: [],
            text_elements: {
                Days: null,
                Hours: null,
                Minutes: null,
                Seconds: null
            },
            attributes: {
                canvas: null,
                context: null,
                item_size: null,
                line_width: null,
                radius: null,
                outer_radius: null
            },
            state: {
                fading: {
                    Days: false,
                    Hours: false,
                    Minutes: false,
                    Seconds: false
                }
            }
        };

        this.config = null;
        this.setOptions(options);
        this.initialize();
    };

    TC_Instance.prototype.clearListeners = function() {
        this.listeners = {
            all: [],
            visible: []
        };
    };

    TC_Instance.prototype.addTime = function(seconds_to_add) {
        if (this.data.attributes.ref_date instanceof Date) {
            var d = this.data.attributes.ref_date;
            d.setSeconds(d.getSeconds() + seconds_to_add);
        } else if (!isNaN(this.data.attributes.ref_date)) {
            this.data.attributes.ref_date += (seconds_to_add * 1000);
        }
    };

    TC_Instance.prototype.initialize = function(clear_listeners) {
        // Initialize drawn units
        this.data.drawn_units = [];
        for (var i = 0; i < Object.keys(this.config.time).length; i++) {
            var unit = Object.keys(this.config.time)[i];
            if (this.config.time[unit].show) {
                this.data.drawn_units.push(unit);
            }
        }

        // Avoid stacking
        $(this.element).children('div.time_circles').remove();

        if (typeof clear_listeners === "undefined")
            clear_listeners = true;
        if (clear_listeners || this.listeners === null) {
            this.clearListeners();
        }
        this.container = $("<div>");
        this.container.addClass('time_circles');
        this.container.appendTo(this.element);

        // Determine the needed width and height of TimeCircles
        var height = this.element.offsetHeight;
        var width = this.element.offsetWidth;
        if (height === 0)
            height = $(this.element).height();
        if (width === 0)
            width = $(this.element).width();

        if (height === 0 && width > 0)
            height = width / this.data.drawn_units.length;
        else if (width === 0 && height > 0)
            width = height * this.data.drawn_units.length;

        // Create our canvas and set it to the appropriate size
        var canvasElement = document.createElement('canvas');
        canvasElement.width = width;
        canvasElement.height = height;

        // Add canvas elements
        this.data.attributes.canvas = $(canvasElement);
        this.data.attributes.canvas.appendTo(this.container);

        // Check if the browser has browser support
        var canvasSupported = isCanvasSupported();
        // If the browser doesn't have browser support, check if explorer canvas is loaded
        // (A javascript library that adds canvas support to browsers that don't have it)
        if (!canvasSupported && typeof G_vmlCanvasManager !== "undefined") {
            G_vmlCanvasManager.initElement(canvasElement);
            limited_mode = true;
            canvasSupported = true;
        }
        if (canvasSupported) {
            this.data.attributes.context = canvasElement.getContext('2d');
        }

        this.data.attributes.item_size = Math.min(width / this.data.drawn_units.length, height);
        this.data.attributes.line_width = this.data.attributes.item_size * this.config.fg_width;
        this.data.attributes.radius = ((this.data.attributes.item_size * 0.8) - this.data.attributes.line_width) / 2;
        this.data.attributes.outer_radius = this.data.attributes.radius + 0.5 * Math.max(this.data.attributes.line_width, this.data.attributes.line_width * this.config.bg_width);

        // Prepare Time Elements
        var i = 0;
        for (var key in this.data.text_elements) {
            if (!this.config.time[key].show)
                continue;

            var textElement = $("<div>");
            textElement.addClass('textDiv_' + key);
            textElement.css("top", Math.round(0.35 * this.data.attributes.item_size));
            textElement.css("left", Math.round(i++ * this.data.attributes.item_size));
            textElement.css("width", this.data.attributes.item_size);
            textElement.appendTo(this.container);

            var headerElement = $("<h4>");
            headerElement.text(this.config.time[key].text); // Options
            headerElement.css("font-size", Math.round(this.config.text_size * this.data.attributes.item_size));
            headerElement.css("line-height", Math.round(this.config.text_size * this.data.attributes.item_size) + "px");
            headerElement.appendTo(textElement);

            var numberElement = $("<span>");
            numberElement.css("font-size", Math.round(3 * this.config.text_size * this.data.attributes.item_size));
            numberElement.css("line-height", Math.round(this.config.text_size * this.data.attributes.item_size) + "px");
            numberElement.appendTo(textElement);

            this.data.text_elements[key] = numberElement;
        }

        this.start();
        if (!this.config.start) {
            this.data.paused = true;
        }

        // Set up interval fallback
        var _this = this;
        this.data.interval_fallback = useWindow.setInterval(function() {
            _this.update.call(_this, true);
        }, 100);
    };

    TC_Instance.prototype.update = function(nodraw) {
        if (typeof nodraw === "undefined") {
            nodraw = false;
        } else if (nodraw && this.data.paused) {
            return;
        }

        if (limited_mode) {
            //Per unit clearing doesn't work in IE8 using explorer canvas, so do it in one time. The downside is that radial fade cant be used
            this.data.attributes.context.clearRect(0, 0, this.data.attributes.canvas[0].width, this.data.attributes.canvas[0].hright);
        }
        var diff, old_diff;

        var prevDate = this.data.prev_time;
        var curDate = new Date();
        this.data.prev_time = curDate;

        if (prevDate === null)
            prevDate = curDate;

        // If not counting past zero, and time < 0, then simply draw the zero point once, and call stop
        if (!this.config.count_past_zero) {
            if (curDate > this.data.attributes.ref_date) {
                for (var i = 0; i < this.data.drawn_units.length; i++) {
                    var key = this.data.drawn_units[i];

                    // Set the text value
                    this.data.text_elements[key].text("0");
                    var x = (i * this.data.attributes.item_size) + (this.data.attributes.item_size / 2);
                    var y = this.data.attributes.item_size / 2;
                    var color = this.config.time[key].color;
                    this.drawArc(x, y, color, 0);
                }
                this.stop();
                return;
            }
        }

        // Compare current time with reference
        diff = (this.data.attributes.ref_date - curDate) / 1000;
        old_diff = (this.data.attributes.ref_date - prevDate) / 1000;

        var floor = this.config.animation !== "smooth";

        var visible_times = parse_times(diff, old_diff, this.data.total_duration, this.data.drawn_units, floor);
        var all_times = parse_times(diff, old_diff, secondsIn["Years"], allUnits, floor);

        var i = 0;
        var j = 0;
        var lastKey = null;

        var cur_shown = this.data.drawn_units.slice();
        for (var i in allUnits) {
            var key = allUnits[i];

            // Notify (all) listeners
            if (Math.floor(all_times.raw_time[key]) !== Math.floor(all_times.raw_old_time[key])) {
                this.notifyListeners(key, Math.floor(all_times.time[key]), Math.floor(diff), "all");
            }

            if (cur_shown.indexOf(key) < 0)
                continue;

            // Notify (visible) listeners
            if (Math.floor(visible_times.raw_time[key]) !== Math.floor(visible_times.raw_old_time[key])) {
                this.notifyListeners(key, Math.floor(visible_times.time[key]), Math.floor(diff), "visible");
            }

            if (!nodraw) {
                // Set the text value
                this.data.text_elements[key].text(Math.floor(Math.abs(visible_times.time[key])));

                var x = (j * this.data.attributes.item_size) + (this.data.attributes.item_size / 2);
                var y = this.data.attributes.item_size / 2;
                var color = this.config.time[key].color;

                if (this.config.animation === "smooth") {
                    if (lastKey !== null && !limited_mode) {
                        if (Math.floor(visible_times.time[lastKey]) > Math.floor(visible_times.old_time[lastKey])) {
                            this.radialFade(x, y, color, 1, key);
                            this.data.state.fading[key] = true;
                        } else if (Math.floor(visible_times.time[lastKey]) < Math.floor(visible_times.old_time[lastKey])) {
                            this.radialFade(x, y, color, 0, key);
                            this.data.state.fading[key] = true;
                        }
                    }
                    if (!this.data.state.fading[key]) {
                        this.drawArc(x, y, color, visible_times.pct[key]);
                    }
                } else {
                    this.animateArc(x, y, color, visible_times.pct[key], visible_times.old_pct[key], (new Date()).getTime() + tick_duration);
                }
            }
            lastKey = key;
            j++;
        }

        // Dont request another update if we should be paused
        if (this.data.paused || nodraw) {
            return;
        }

        // We need this for our next frame either way
        var _this = this;
        var update = function() {
            _this.update.call(_this);
        };

        // Either call next update immediately, or in a second
        if (this.config.animation === "smooth") {
            // Smooth animation, Queue up the next frame
            this.data.animation_frame = useWindow.requestAnimationFrame(update, _this.element, _this);
        } else {
            // Tick animation, Don't queue until very slightly after the next second happens
            var delay = (diff % 1) * 1000;
            if (delay < 0)
                delay = 1000 + delay;
            delay += 50;

            _this.data.animation_frame = useWindow.setTimeout(function() {
                _this.data.animation_frame = useWindow.requestAnimationFrame(update, _this.element, _this);
            }, delay);
        }
    };

    TC_Instance.prototype.animateArc = function(x, y, color, target_pct, cur_pct, animation_end) {
        if (this.data.attributes.context === null)
            return;

        var diff = cur_pct - target_pct;
        if (Math.abs(diff) > 0.5) {
            if (target_pct === 0) {
                this.radialFade(x, y, color, 1);
            } else {
                this.radialFade(x, y, color, 0);
            }
        } else {
            var progress = (tick_duration - (animation_end - (new Date()).getTime())) / tick_duration;
            if (progress > 1)
                progress = 1;

            var pct = (cur_pct * (1 - progress)) + (target_pct * progress);
            this.drawArc(x, y, color, pct);

            //var show_pct =
            if (progress >= 1)
                return;
            var _this = this;
            useWindow.requestAnimationFrame(function() {
                _this.animateArc(x, y, color, target_pct, cur_pct, animation_end);
            }, this.element);
        }
    };

    TC_Instance.prototype.drawArc = function(x, y, color, pct) {
        if (this.data.attributes.context === null)
            return;

        var clear_radius = Math.max(this.data.attributes.outer_radius, this.data.attributes.item_size / 2);
        if (!limited_mode) {
            this.data.attributes.context.clearRect(
                x - clear_radius,
                y - clear_radius,
                clear_radius * 2,
                clear_radius * 2
            );
        }

        if (this.config.use_background) {
            this.data.attributes.context.beginPath();
            this.data.attributes.context.arc(x, y, this.data.attributes.radius, 0, 2 * Math.PI, false);
            this.data.attributes.context.lineWidth = this.data.attributes.line_width * this.config.bg_width;

            // line color
            this.data.attributes.context.strokeStyle = this.config.circle_bg_color;
            this.data.attributes.context.stroke();
        }

        // Direction
        var startAngle, endAngle, counterClockwise;
        var defaultOffset = (-0.5 * Math.PI);
        var fullCircle = 2 * Math.PI;
        startAngle = defaultOffset + (this.config.start_angle / 360 * fullCircle);
        var offset = (2 * pct * Math.PI);

        if (this.config.direction === "Both") {
            counterClockwise = false;
            startAngle -= (offset / 2);
            endAngle = startAngle + offset;
        } else {
            if (this.config.direction === "Clockwise") {
                counterClockwise = false;
                endAngle = startAngle + offset;
            } else {
                counterClockwise = true;
                endAngle = startAngle - offset;
            }
        }

        this.data.attributes.context.beginPath();
        this.data.attributes.context.arc(x, y, this.data.attributes.radius, startAngle, endAngle, counterClockwise);
        this.data.attributes.context.lineWidth = this.data.attributes.line_width;

        // line color
        this.data.attributes.context.strokeStyle = color;
        this.data.attributes.context.stroke();
    };

    TC_Instance.prototype.radialFade = function(x, y, color, from, key) {
        // TODO: Make fade_time option
        var rgb = hexToRgb(color);
        var _this = this; // We have a few inner scopes here that will need access to our instance

        var step = 0.2 * ((from === 1) ? -1 : 1);
        var i;
        for (i = 0; from <= 1 && from >= 0; i++) {
            // Create inner scope so our variables are not changed by the time the Timeout triggers
            (function() {
                var delay = 50 * i;
                var rgba = "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", " + (Math.round(from * 10) / 10) + ")";
                useWindow.setTimeout(function() {
                    _this.drawArc(x, y, rgba, 1);
                }, delay);
            }());
            from += step;
        }
        if (typeof key !== undefined) {
            useWindow.setTimeout(function() {
                _this.data.state.fading[key] = false;
            }, 50 * i);
        }
    };

    TC_Instance.prototype.timeLeft = function() {
        if (this.data.paused && typeof this.data.timer === "number") {
            return this.data.timer;
        }
        var now = new Date();
        return ((this.data.attributes.ref_date - now) / 1000);
    };

    TC_Instance.prototype.start = function() {
        useWindow.cancelAnimationFrame(this.data.animation_frame);
        useWindow.clearTimeout(this.data.animation_frame)

        // Check if a date was passed in html attribute or jquery data
        var attr_data_date = $(this.element).data('date');
        if (typeof attr_data_date === "undefined") {
            attr_data_date = $(this.element).attr('data-date');
        }
        if (typeof attr_data_date === "string") {
            this.data.attributes.ref_date = parse_date(attr_data_date);
        }
        // Check if this is an unpause of a timer
        else if (typeof this.data.timer === "number") {
            if (this.data.paused) {
                this.data.attributes.ref_date = (new Date()).getTime() + (this.data.timer * 1000);
            }
        } else {
            // Try to get data-timer
            var attr_data_timer = $(this.element).data('timer');
            if (typeof attr_data_timer === "undefined") {
                attr_data_timer = $(this.element).attr('data-timer');
            }
            if (typeof attr_data_timer === "string") {
                attr_data_timer = parseFloat(attr_data_timer);
            }
            if (typeof attr_data_timer === "number") {
                this.data.timer = attr_data_timer;
                this.data.attributes.ref_date = (new Date()).getTime() + (attr_data_timer * 1000);
            } else {
                // data-timer and data-date were both not set
                // use config date
                this.data.attributes.ref_date = this.config.ref_date;
            }
        }

        // Start running
        this.data.paused = false;
        this.update.call(this);
    };

    TC_Instance.prototype.restart = function() {
        this.data.timer = false;
        this.start();
    };

    TC_Instance.prototype.stop = function() {
        if (typeof this.data.timer === "number") {
            this.data.timer = this.timeLeft(this);
        }
        // Stop running
        this.data.paused = true;
        useWindow.cancelAnimationFrame(this.data.animation_frame);
    };

    TC_Instance.prototype.destroy = function() {
        this.clearListeners();
        this.stop();
        useWindow.clearInterval(this.data.interval_fallback);
        this.data.interval_fallback = null;

        this.container.remove();
        $(this.element).removeAttr('data-tc-id');
        $(this.element).removeData('tc-id');
    };

    TC_Instance.prototype.setOptions = function(options) {
        if (this.config === null) {
            this.default_options.ref_date = new Date();
            this.config = $.extend(true, {}, this.default_options);
        }
        $.extend(true, this.config, options);

        // Use window.top if use_top_frame is true
        if (this.config.use_top_frame) {
            useWindow = window.top;
        } else {
            useWindow = window;
        }
        updateUsedWindow();

        this.data.total_duration = this.config.total_duration;
        if (typeof this.data.total_duration === "string") {
            if (typeof secondsIn[this.data.total_duration] !== "undefined") {
                // If set to Years, Months, Days, Hours or Minutes, fetch the secondsIn value for that
                this.data.total_duration = secondsIn[this.data.total_duration];
            } else if (this.data.total_duration === "Auto") {
                // If set to auto, total_duration is the size of 1 unit, of the unit type bigger than the largest shown
                for (var i = 0; i < Object.keys(this.config.time).length; i++) {
                    var unit = Object.keys(this.config.time)[i];
                    if (this.config.time[unit].show) {
                        this.data.total_duration = secondsIn[nextUnits[unit]];
                        break;
                    }
                }
            } else {
                // If it's a string, but neither of the above, user screwed up.
                this.data.total_duration = secondsIn["Years"];
                console.error("Valid values for TimeCircles config.total_duration are either numeric, or (string) Years, Months, Days, Hours, Minutes, Auto");
            }
        }
    };

    TC_Instance.prototype.addListener = function(f, context, type) {
        if (typeof f !== "function")
            return;
        if (typeof type === "undefined")
            type = "visible";
        this.listeners[type].push({
            func: f,
            scope: context
        });
    };

    TC_Instance.prototype.notifyListeners = function(unit, value, total, type) {
        for (var i = 0; i < this.listeners[type].length; i++) {
            var listener = this.listeners[type][i];
            listener.func.apply(listener.scope, [unit, value, total]);
        }
    };

    TC_Instance.prototype.default_options = {
        ref_date: new Date(),
        start: true,
        animation: "smooth",
        count_past_zero: true,
        circle_bg_color: "#60686F",
        use_background: true,
        fg_width: 0.1,
        bg_width: 1.2,
        text_size: 0.07,
        total_duration: "Auto",
        direction: "Clockwise",
        use_top_frame: false,
        start_angle: 0,
        time: {
            Days: {
                show: true,
                text: "Days",
                color: "#FC6"
            },
            Hours: {
                show: true,
                text: "Hours",
                color: "#9CF"
            },
            Minutes: {
                show: true,
                text: "Minutes",
                color: "#BFB"
            },
            Seconds: {
                show: true,
                text: "Seconds",
                color: "#F99"
            }
        }
    };

    // Time circle class
    var TC_Class = function(elements, options) {
        this.elements = elements;
        this.options = options;
        this.foreach();
    };

    TC_Class.prototype.getInstance = function(element) {
        var instance;

        var cur_id = $(element).data("tc-id");
        if (typeof cur_id === "undefined") {
            cur_id = guid();
            $(element).attr("data-tc-id", cur_id);
        }
        if (typeof TC_Instance_List[cur_id] === "undefined") {
            var options = this.options;
            var element_options = $(element).data('options');
            if (typeof element_options === "string") {
                element_options = JSON.parse(element_options);
            }
            if (typeof element_options === "object") {
                options = $.extend(true, {}, this.options, element_options);
            }
            instance = new TC_Instance(element, options);
            TC_Instance_List[cur_id] = instance;
        } else {
            instance = TC_Instance_List[cur_id];
            if (typeof this.options !== "undefined") {
                instance.setOptions(this.options);
            }
        }
        return instance;
    };

    TC_Class.prototype.addTime = function(seconds_to_add) {
        this.foreach(function(instance) {
            instance.addTime(seconds_to_add);
        });
    };

    TC_Class.prototype.foreach = function(callback) {
        var _this = this;
        this.elements.each(function() {
            var instance = _this.getInstance(this);
            if (typeof callback === "function") {
                callback(instance);
            }
        });
        return this;
    };

    TC_Class.prototype.start = function() {
        this.foreach(function(instance) {
            instance.start();
        });
        return this;
    };

    TC_Class.prototype.stop = function() {
        this.foreach(function(instance) {
            instance.stop();
        });
        return this;
    };

    TC_Class.prototype.restart = function() {
        this.foreach(function(instance) {
            instance.restart();
        });
        return this;
    };

    TC_Class.prototype.rebuild = function() {
        this.foreach(function(instance) {
            instance.initialize(false);
        });
        return this;
    };

    TC_Class.prototype.getTime = function() {
        return this.getInstance(this.elements[0]).timeLeft();
    };

    TC_Class.prototype.addListener = function(f, type) {
        if (typeof type === "undefined")
            type = "visible";
        var _this = this;
        this.foreach(function(instance) {
            instance.addListener(f, _this.elements, type);
        });
        return this;
    };

    TC_Class.prototype.destroy = function() {
        this.foreach(function(instance) {
            instance.destroy();
        });
        return this;
    };

    TC_Class.prototype.end = function() {
        return this.elements;
    };

    $.fn.TimeCircles = function(options) {
        return new TC_Class(this, options);
    };

}(jQuery));;
 window.dcp = window.dcp || {};

 (function($) {
     window.dcp.auto_scroll = function() {

         var model,

             addScrollEffect = function() {
                 $(model.container).not('[href="#"]').not('[href="#0"]').click(function(event) {
                     if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                         // Figure out element to scroll to
                         var target = $(this.hash);
                         target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                         // Does a scroll target exist?
                         if (target.length) {
                             // Only prevent default if animation is actually gonna happen
                             event.preventDefault();
                             $('html, body').animate({
                                 scrollTop: target.offset().top
                             }, 1000, function() {
                                 // Callback after animation
                                 // Must change focus!
                                 var $target = $(target);
                                 $target.focus();
                                 if ($target.is(":focus")) { // Checking if the target was focused
                                     return false;
                                 } else {
                                     $target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
                                     $target.focus(); // Set focus again
                                 }
                             });
                         }
                     }
                 });
             },

             init = function(args) {
                 args = args || {};
                 model = {
                     init: function() {
                         this.container = args.container || 'a.addanimation[href*="#"]';
                     }
                 };

                 // On document ready
                 model.init();
                 addScrollEffect();

             };

         return {
             init: init
         };
     };

     $(function() {
         var auto_scroll = new dcp.auto_scroll();
         auto_scroll.init();
     });

 })(jQuery);
//Generate the HTML for fix header
function stickyHamburger() {
    if ($("#fixtop").length < 1) {
        if ($('header .main-nav .twelve.column a').length > 0 && $("body.myp-bg").length < 1) {
            $("body > .pusher").prepend('<div id="fixtop" class="fixtop" />');
            $("#fixtop").html('<a href="#" class="hamburger open-sidebar"></a>');
            var logoImg = $(".header-search").find(" > a").html();
            var pageUrl = $(".header-search").find(" > a").attr("href");
            $("#fixtop .hamburger").after('<a href="" />');
            $("#fixtop > a:nth-child(2)").attr("href", pageUrl).html(logoImg);
        }
    }
}

//set position of hamburger menu
function scrollFunction() {
    if ($("#fixtop").length > 0) {
        //new code
        var lastScrollTop = 0;
        $(window).scroll(function(event) {
            var st = $(this).scrollTop();
            if (st > lastScrollTop) {
                // downscroll code
                if (document.body.scrollTop > 155 || document.documentElement.scrollTop > 155) {
                    // Setup isScrolling variable
                    var isScrolling;
                    var stickyShow = '';

                    // Listen for scroll events
                    window.addEventListener('scroll', function(event) {

                        // Clear our timeout throughout the scroll
                        window.clearTimeout(isScrolling);

                        // Set a timeout to run after scrolling ends
                        isScrolling = setTimeout(function() {
                            if (document.body.scrollTop > 155 || document.documentElement.scrollTop > 155) {
                                // Run the callback
                                document.getElementById("fixtop").style.top = "0";
                                document.getElementById("fixtop").style.opacity = "1";
                            } else {
                                document.getElementById("fixtop").style.top = "-160px";
                                document.getElementById("fixtop").style.opacity = "0";
                            }

                        }, 100);

                    }, false);
                }
            } else {
                // upscroll code
                var offSet = $("header").offset().top;
                var w = $(window);

                if (offSet - w.scrollTop() > -155) {
                    document.getElementById("fixtop").style.top = "-160px";
                    document.getElementById("fixtop").style.opacity = "0";
                } else {
                    document.getElementById("fixtop").style.top = "0";
                    document.getElementById("fixtop").style.opacity = "1";
                }
            }
            lastScrollTop = st;
        });
    }
}

function isIE() {
    ua = navigator.userAgent;
    var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
    return is_ie;
}

$(document).ready(function() {
    if (!$('body').hasClass("member")) {
        stickyHamburger();
    }

    // for IE smooth scroll 
    if (isIE()) {
        if ($("header.sticky").length && $(window).width() > 1024) {
            if ($("header.sticky .properties-carousel").length) {
                document.body.addEventListener('scroll', function() {
                    if (document.body.scrollTop > $("header.sticky .properties-carousel").height()) {
                        $("header .main-nav").addClass("stick");
                    } else {
                        $("header .main-nav").removeClass("stick");
                    }
                });
            } else {
                document.body.addEventListener('scroll', function() {
                    if (document.body.scrollTop > 250) {
                        $("header .main-nav").addClass("stick");
                    } else {
                        $("header .main-nav").removeClass("stick");
                    }
                });
            }
        }
    }

    if ($('.ui.sidebar.property-sidebar').hasClass('hideStickyNav')) {
        $(window).scroll(function() {
            if (!$('body').hasClass("member")) {
                scrollFunction();
            }
        });
    }
});
$(document).ready(function(){
    var collectionLinksContainer = $(".the-collection-module"),
    collectionLinks = collectionLinksContainer.find(".button-list .column a[style]");
    collectionLinksContainer.each( function(){
        collectionLinks.each( function(){
            var linkColor = collectionLinks.attr("datacolors"),
            linkBgcolor = collectionLinks.attr("databgcolor"),
            defaultColor = collectionLinks.css("color"),
            defaultBgcolor = collectionLinks.css("background-color");
            $(this).hover(
                function(){
                    $(this).css('background-color', linkBgcolor).css('color',linkColor);
                },
                function(){
                    $(this).css('background-color', defaultBgcolor).css('color', defaultColor);
                }
            );
        });
    });   
  });

 
var filesURL = [];
var fileNames = [];
var _thisInput; //each input file upload element

$(document).ready(function() {
    if (window.File && window.FileReader && window.FormData) {
        $('.defect-section').each(function() {

            // toggle buttong
            var _this = $(this),
                switchBtn = _this.find('.switch');

            // Toggle button click
            $(switchBtn).click(function() {
                event.stopPropagation();
                // adding toggle functionality
                if (_this.hasClass('active')) {
                    $(_this).find('.readyToClose input').attr("value", "false");

                } else {

                    $(_this).find('.readyToClose input').attr("value", "true");

                    // IF slide is open
                    var getinputThisId = '#' + _this.find('.uploaded input').attr('id');

                    $(getinputThisId).on('change', function(e) {

                        event.stopPropagation();
                        var file = e.target.files[0];



                        var uploadedImgRev = _this.find('.upload-new-photo .uploaded-anchors .newImage');

                        _thisInput = _this.find('.uploaded input').attr('id');


                        if (file) {
                            if (uploadedImgRev != undefined && uploadedImgRev != null) {
                                uploadedImgRev.remove();
                            }
                            if (/^image\//i.test(file.type)) {
                                ConstructorreadFile(file);
                            } else {
                                alert('Not a valid image!');
                            }
                        }

                        // //
                        var inputFileTemp = e.target;
                        var inputFileType = file.type;
                        var inputFileName = file.name;
                        $(inputFileTemp).attr('dataType', inputFileType);
                        $(inputFileTemp).attr('dataName', inputFileName);


                    });
                }

                // Adding and removing toggle button
                _this.toggleClass('active');
            });
        });

    } else {
        alert("File upload is not supported!");
    }

    $("section.quick-links .row > .column").each(function(i) {
        $(this).addClass("item" + i);
    });

    if (iOS()) {
        $('#iOS-padding').css("display", "block");
    }

    // open model constructor-popup
    $('.uploaded-photo').click(function() {

        var _this = $(this).parent().find('.uploaded-anchors').html(),
            firstAnchor = $(_this)[0],
            model = $('.constructor-popup').find('.uploaded-sm-images'),
            lgImgInside = $('.constructor-popup').find('.uploaded-lg-images');

        if (!$.trim($(_this).html()).length) {

        } else {
            $('.ui.modal').modal({
                centered: true
            }).modal('show');

            // Added defect photos
            $(lgImgInside).html(firstAnchor);
            $(model).html(_this);


            //slider click show to show
            $('.uploaded-sm-images a').on('click', function(e) {
                e.stopPropagation();
                var _this = $(this).html(),
                    largeImg = $('.uploaded-lg-images');
                $(largeImg).html(_this);
            });
        }

        // temp code only for testing
        //$('.uploaded-sm-images a:first-child').attr("data-vendor", "true");
    });

    // IF no image upload image has been disabled
    addDisableImage();
    // Get dropdown input value form each row
    getInputVal();


    $("#showComplete").click(function() {
        console.log('show button has been click');
        $('#div-complete').show();
    });
    $("#hideComplete").click(function() {
        $('#div-complete').hide();
    });
    // Editable icon
    $('.add-description input').keyup(function() {
        var _this = $(this),
            inputValue = _this.val(),
            inputValueTextArea = _this.parents('td').find('.input-textarea');

        inputValueTextAreaVal = inputValueTextArea.val();
        inputValueTextArea.text(inputValue);
    });

    // INPUT FOCUS
    $('.add-description input').focus(function() {
        var _this = $(this),
            inputValue = _this.val(),
            editableIcon = _this.parents('td').find('.editable-icon'),
            editIcon = _this.parents('td').find('.edit-icon');
        editIcon.fadeOut();
        editableIcon.fadeIn();
    });

    // INPUT BLUR
    $('.add-description .editable-icon').click(function() {
        var _this = $(this),
            inputValue = _this.val(),
            editableIcon = _this.parents('td').find('.editable-icon'),
            editIcon = _this.parents('td').find('.edit-icon');
        editIcon.fadeIn();
        editableIcon.fadeOut();
    });

    $('.defect-description input').focus(function() {
        var _this = $(this),
            inputValue = _this.val(),
            editableIcon = _this.parents('td').find('.editable-icon'),
            editIcon = _this.parents('td').find('.edit-icon');
        editIcon.fadeOut();
        editableIcon.fadeIn();
    });

    // Show dropdown for 4 secound only INPUT TEXT
    $('.add-description .editable-icon, .defect-description .editable-icon').click(function() {
        var _this = $(this);
        _this.parents('td').find('.input-textarea').fadeIn();
        setTimeout(function() {
            _this.parents('td').find('.input-textarea').fadeOut();
        }, 3500);
    });
});



function getInputVal() {
    $('.default-description').each(function() {
        var _this = $(this),
            DefectInputVal = _this.find('.defect-description input').val(),
            DefectTextArea = _this.find('.input-textarea');

        DefectTextArea.text(DefectInputVal);
    });
}

function addDisableImage() {
    $('.uploaded-photo').each(function() {

        var _thisHtml = $(this).parent().find('.uploaded-anchors');
        _this = $(this).parent().find('.uploaded-anchors').html();

        // Checking if there is no image adding disable feature 
        if (!$.trim($(_this).html()).length) {
            _thisHtml.parent().addClass('disable-image');
        } else {
            _thisHtml.parent().removeClass('disable-image');
        }
    });
}

// Read and process the file information
function ConstructorreadFile(file) {
    var reader = new FileReader();
    reader.onloadend = function() {
        ConstructorProcessFile(reader.result, file.name, file.type);
    };
    reader.onerror = function() {
        alert('There was an error reading the file!');
    };
    reader.readAsDataURL(file);
}

// Resize the file and draw thumbnail on screen
function ConstructorProcessFile(dataURL, filename, fileType, currentElm) {
    var maxWidth = 800;
    var maxHeight = 800;

    var image = new Image();
    image.src = dataURL;

    image.onload = function() {

        var width = image.width;
        var height = image.height;

        // Create Canvas and set its default width height to the image
        var canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;

        // Resize the image to fit the max width and height
        var shouldResize = (width > maxWidth) || (height > maxHeight);
        if (shouldResize) {
            var newWidth;
            var newHeight;

            if (width > height) {
                newHeight = height * (maxWidth / width);
                newWidth = maxWidth;
            } else {
                newWidth = width * (maxHeight / height);
                newHeight = maxHeight;
            }
            canvas.width = newWidth;
            canvas.height = newHeight;
        }
        var context = canvas.getContext('2d');
        context.drawImage(this, 0, 0, canvas.width, canvas.height);

        dataURL = canvas.toDataURL("image/jpeg", 0.5);
        filesURL.push(dataURL);
        fileNames.push(filename);
        currentElm = filesURL.length - 1;
        ConstructorUpdateView(currentElm);
    };

    image.onerror = function() {
        alert('There was an error processing your file!');
    };
}

// Remove the file 
function ConstructorRemove(thisId) {
    event.stopPropagation();
    //filesURL.splice(index, 1);
    //fileNames.splice(index, 1);

    // Update the view to remove the image from screen
    clearPhotoUpdate(thisId);
}

// Clear photo on close button
function clearPhotoUpdate(currentImg) {
    var getItemId = currentImg.id,
        getItemIdNum = getItemId.substring(5, getItemId.length);
    $("#requestitemedit li#" + getItemIdNum).html("");
    var imgHolder = document.createElement('span');
    imgHolder.innerHTML = '<i class="photo icon"></i>';
    $("#requestitemedit li#" + getItemIdNum).append(imgHolder);
    //$("#requestitemedit li#" + getItemIdNum).parent().find('input').attr('value', '');
    $("#requestitemedit li#" + getItemIdNum).parent().next().attr('value', '');
}

// Update the image as a Binary
function ConstructorUpdateView(currentElm) {
    $("#requestitemedit input[data-image-thumb]").remove();
    $("#requestitemedit input[data-image-thumb-name]").remove();

    // Clear the elements
    $("#requestitemedit li#" + _thisInput).html("");


    // Adding image into upload container
    var idName = "Thumb" + _thisInput;

    var fileURL = filesURL[currentElm];
    var span = document.createElement('span');
    var thisList = $("#requestitemedit li#" + _thisInput.substr(4, _thisInput.length));
    // span.innerHTML = '<img id=' + idName + ' class="thumb" src="' + fileURL + '"/>';
    span.innerHTML += '<img data-id=' + idName + ' class="remove-button" src="/resources/Assets/image/delete-icon.svg" onclick="ConstructorRemove(' + idName + ')"/>';
    // $(thisList).append(span);
    $(".columns").append("<input type='hidden' data-image-thumb name='thumbs[]' value='" + fileURL + "' />");
    $(".columns").append("<input type='hidden' data-image-thumb-name name='thumbNames[]' value='" + fileNames[_thisInput] + "' />");


    thisList.find('.upload-photo img').attr('src', fileURL);

    var blankImage = "<a href='#!' data-vendor='True' class='newImage'><img src=\'" + fileURL + "\' alt='Uploaded Photo'></a>",
        photoUploadIcon = thisList.parents('.defect-section.active').find('.upload-new-photo .uploaded-anchors').html(),
        combinePhotos = photoUploadIcon += blankImage;

    thisList.parents('.defect-section.active').find('.upload-new-photo .uploaded-anchors').html(combinePhotos);

    // input change
    //$(thisList).parents('ul').next().attr('value', fileURL);
    // input value adding
    //$("#" + _thisInput).attr('value', fileURL);
    //adding class on photo icon
    setTimeout(function() {
        (thisList).parents('.defect-section').find('.uploaded-photo').addClass('new-img');
    }, 300);

    // img icon change
    var dataTypeThis = $(thisList).parent().find('li').eq(1).find('input').attr('datatype');
    var dataNameThis = $(thisList).parent().find('li').eq(1).find('input').attr('dataname');

    $(thisList).parents('td').find('>input.imagemimetype').val(dataTypeThis);
    $(thisList).parents('td').find('>input.imagename').val(dataNameThis);
    $(thisList).parents('td').find('>input.imagethumb').val(fileURL);

    addDisableImage();
}

function iOS() {

    var iDevices = [
        'iPad Simulator',
        'iPhone Simulator',
        'iPod Simulator',
        'iPad',
        'iPhone',
        'iPod'
    ];

    if (!!navigator.platform) {
        while (iDevices.length) {
            if (navigator.platform === iDevices.pop()) {
                return true;
            }
        }
    }
    return false;
}

$(function() {
    var countUpload = 0;
    var updateDefect;
    var updateDefectList;
    $(document).on('click', '#submitCP', function(evt) {
        evt.preventDefault();
        countUpload = 0;
        updateDefectList = [];
        const fileData = new FormData();
        var rowList = $("#requestitemedit .defect-section-table").find('tbody'); // Eeach row

        // Which row has a image
        var activeRow = $(rowList).find('.defect-section');
        for (var i = 0; i < rowList.length; i++) {
            if ($(activeRow).eq(i).hasClass('active')) {
                countUpload += 1;
                $(activeRow).eq(i).parent().addClass('readyData' + countUpload);
                $(activeRow).eq(i).parent().prevUntil('thead').addClass('theadB' + countUpload);
                $(activeRow).eq(i).parent().prevAll('thead').eq(0).prev().addClass('theadT' + countUpload);
                $(activeRow).eq(i).parent().find('>span').remove();
            }
        }

        showLoader();

        var getModelJson = $("#modelJson").html(),
            updateDefectRequest = JSON.parse(getModelJson),
            serviceOrderId = "";
            serviceOrderIdCond = true;

        //check stage information
        if (updateDefectRequest.QaDefectsStage !== null && updateDefectRequest.QaDefectsStage.QaDefectLots !== null) {

            //QaDefectsLot loop    
            for (var lot = 0; lot < updateDefectRequest.QaDefectsStage.QaDefectLots.length; lot++) {

                if (updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader == null) { continue; }
                //QaDefectsHeader loop 
                for (var h = 0; h < updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader.length; h++) {

                    if (updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems == null) { continue; }

                    //Item loop
                    for (var itm = 0; itm < updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems.length; itm++) {
						updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].Photos = [];
                        if(serviceOrderIdCond){serviceOrderId = updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].ServiceOrderId;}
                        serviceOrderIdCond = false;
                        for (var update = 0; update < countUpload; update++) {
                            var imgPathElemt = '.readyData' + (update + 1);

                            if (updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].ItemGuid !== $(imgPathElemt).find('.itemguid-hid').val()) { continue; }

                            var imgName = $(imgPathElemt).find('input[type=file]').attr('dataname'),
                                imgType = $(imgPathElemt).find('input[type=file]').attr('datatype'),
                                vendorTxt = $(imgPathElemt).find('.vendortxt-hid').val();

                            if (imgType !== undefined && imgType !== undefined) { 

                                var dataUri = $(imgPathElemt).find('.upload-photo img').attr('src'),
                                    imgPath = dataURIToBlob(dataUri, imgName),
                                    dataBytes = dataUri.substring(dataUri.lastIndexOf(',') + 1);

                                //update each file
                                //Upadating the file, which row has image.
                                fileData.append('file', imgPath, imgName);
                                updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].ImageName = imgName;
                                updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].ImageMimeType = imgType;

                            }

                            // update each array 
                            updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].VendorTxt = vendorTxt == null ? "" : vendorTxt;

                            updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].IsReadyToClose = true;
                            updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].Thumb = "";
                            /* updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].Photos = [{
                                DefectItemAttachmentData: dataBytes,
                                DefectItemAttachmentMimeType: imgType,
                                DefectItemAttachmentName: imgName,
                                DefectItemAttachmentSize: dataBytes.length,
                                DefectItemGuid: updateDefectRequest.QaDefectsStage.QaDefectLots[lot].QaDefectsHeader[h].QaDefectItems[itm].ItemGuid
                            }];*/
							 

                        }


                    }
                }
            }
        }

        fileData.append('updateDefectRequest', JSON.stringify(updateDefectRequest));
        $.ajax({
            url: `${window.location.protocol}//${window.location.host}/CreateDefect`,
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success(data) {
                var msg = data.Message,
                    url = data.Url;

                if (data.Success == true) {
                    $('.loader-container, .constructor-header, .standard-content').remove();
                    $('#frmContractorPortalDefectUpdate > section').html('<div class="ui container" style="padding: 20px 0;"><h2 style="color: #222">'  + msg + ' (' + serviceOrderId + ').</h2>Please <a href="#" id="reloadPage" style="text-decoration: underline;">click here </a> to view the defects assigned to you on this house.</div>');
                }

                if (data.Success == false) {
                    $('.loader-container, .constructor-header, .standard-content').remove();
                    $('#frmContractorPortalDefectUpdate > section').html('<div class="ui container" style="padding: 20px 0;"><h2 style="color: #222">'  + msg + ' (' + serviceOrderId + ').</h2>Please <a href="#" id="reloadPage" style="text-decoration: underline;">click here </a> to view the defects assigned to you on this house.</div>');
                }
            },
            error(err) {
                // $(_loader).find("loading").addClass('error');
                // setTimeout(function(){$(_loader).removeClass('loading')}, 100);
                console.warn(err.statusText);
                $('.loader-container, .constructor-header, .standard-content').remove();
                $('#frmContractorPortalDefectUpdate > section').html('<div class="ui container" style="padding: 20px 0;"><h2>Error occured</h2>Please <a href="#" id="reloadPage" style="text-decoration: underline;">click here </a> to view the defects assigned to you on this house.</div>');
            }
        });

        function dataURIToBlob(dataurl, filename) {
            var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), 
            n = bstr.length, 
            u8arr = new Uint8Array(n);
                
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            
            return new File([u8arr], filename, {type:mime});
        }

        $(document).on('click', '#reloadPage', function(evt) {
            location.reload();
        });
    });


});
$(window).on('load', function(){
    if  (typeof  timeCircle ==  'function')  {
        $(".countdown").TimeCircles({
            "start": true, //start immediately
            "count_past_zero": false, // This option is only really useful for when counting down. What it does is either give you the option to stop the timer, or start counting up after you've hit the predefined date (or your stopwatch hits zero). 
            "fg_width": 0.0, //The width is set relative to the size of the circle as a whole. A value of 0.1 means 10%, so if your TimeCircles are 100 pixels high, the foreground circle will be 10 percent of that (10 pixels). 
            "bg_width": 0.0,
            "use_background": false,
            "animation": "ticks", //smooth
            "start_angle": 0,
            "time": {
                "Days": {
                    "text": "",
                    "color": "#5C6BC0",
                    "show": false
                },
                "Hours": {
                    "text": "",
                    "color": "#FFCA28",
                    "show": true
                },
                "Minutes": {
                    "text": "",
                    "color": "#66BB6A",
                    "show": true
                },
                "Seconds": {
                    "text": "",
                    "color": "#EF5350",
                    "show": true
                }
            }
        });
        $(".countdown").TimeCircles().start().addListener(OnStart);
        $(".countdown .textDiv_Hours, .countdown .textDiv_Minutes").append("<span>:</span>");
    }
});

function OnStart(unit, value, total) {
    if (total === 0) {

        var type = $("#countDownClockType").val();
        if (type === "FixedTime" || type === "TimeRange") {
            //console.log("Fixed or Range");
            window.location.href = GetExpiredURL();
        }
        if (type === "Loop") {
            var infiniteLoop = $("#infiniteLoop").val();
            if (typeof infiniteLoop != 'undefined' && infiniteLoop === "True") {
                //console.log("Infinite loop");
                $(".countdown").TimeCircles().restart();
            } else {
                var loopCount = $("#loopCount").val();
                if (typeof loopCount !== 'undefined') {
                    var count = parseInt(loopCount);
                    if (count > 0) {
                        //console.log("LoopCount");
                        var currentLoopCount = $("#currentLoopCount").html();
                        if (typeof currentLoopCount != 'undefined' && currentLoopCount !== "" && currentLoopCount != null) {
                            var currentCount = parseInt(currentLoopCount) - 1;
                            $("#currentLoopCount").html(currentCount);
                            if (currentCount > 0) {
                                //console.log(currentCount);
                                $(".countdown").TimeCircles().restart();
                            } else {
                                //console.log(currentCount);
                                $(".countdown").TimeCircles().stop();
                                window.location.href = GetExpiredURL();
                            }
                        }
                    }
                }
            }
        }
    }
}

//http changed to https
function GetURL() {
    var path = window.location.pathname + window.location.search;
    var currentUrl = window.location.href;
    var urlArray = currentUrl.split("/");
    var urlProto = urlArray[0];
    var url = urlProto + "//" + window.location.hostname + path;
    return url;
}

function GetExpiredURL() {
    var url = GetURL();
    if (window.location.search === "") {
        url += "?Expired=1";
    } else {
        url += "&Expired=1";
    }
    return url;
}
$(document).ready(function() {

    $('section.brochure').each(function() {

        var b_id = '#' + $(this).attr('id');
        var h_limit = $(this).data('head-limit');
        var desc_limit = $(this).data('desc-limit');
        if (b_id.length > 0) {
            brochureTextTrim(b_id, h_limit, desc_limit);
        }

    });
    $('section.static-brochure').each(function() {

        var b_id = '#' + $(this).attr('id');
        if (b_id.length > 0) {
            staticBrochureTextTrim(b_id);
        }

    });
    $('section.brochure-carousel').each(function() {

        var b_id = '#' + $(this).attr('id');
        if (b_id.length > 0) {
            brochureCarouselTextTrim(b_id);
        }

    });
    $('section.full-size-brochure').each(function() {

        var b_id = '#' + $(this).attr('id');
        if (b_id.length > 0) {
            fullSizeBrochureTextTrim(b_id);
        }

    });
});

function brochureTextTrim(id, h_limit, desc_limit) {
    // check for the param in URL for editor mode sitecore
    if (getParameterByName('sc_mode') !== 'edit') {
        // expanded brochure char limits
        //console.log(id);
        //var exBrochureHeadingSpanLimit = 50;
        // var exBrochureDescriptionLimit = 200;
        var exBrochureHeadingSpan = $(id + '.brochure .title').find('h2 span.copy-text');
        var exBrochureDescription = $(id + '.brochure .title').find('p');
        exBrochureHeadingSpan.text(trimChar(0, exBrochureHeadingSpan.text(), h_limit));
        exBrochureDescription.text(trimChar(0, exBrochureDescription.text(), desc_limit));

    }
}

function staticBrochureTextTrim(id) {
    // check for the param in URL for editor mode sitecore
    if (getParameterByName('sc_mode') !== 'edit') {
        // expanded brochure char limits
        //console.log(id);

        // static left brochure char limits
        var staticLeftHeadingLimit = 35;
        var staticLeftDescriptionLimit = 100;
        var staticLeftHeading = $(id + '.static-brochure .brochure h2');
        var staticLeftDescription = $(id + '.static-brochure .brochure p');
        staticLeftHeading.text(trimChar(0, staticLeftHeading.text(), staticLeftHeadingLimit));
        staticLeftDescription.text(trimChar(0, staticLeftDescription.text(), staticLeftDescriptionLimit));

        // static right brochure char limits
        var staticHeadingLimit = 35;
        var staticDescriptionLimit = 110;
        var staticHeading = $(id + '.static-brochure .content h3');
        var staticDescription = $(id + '.static-brochure .description p');
        staticHeading.text(trimChar(0, staticHeading.text(), staticHeadingLimit));
        staticDescription.text(trimChar(0, staticDescription.text(), staticDescriptionLimit));

    }
}

function brochureCarouselTextTrim(id) {
    // check for the param in URL for editor mode sitecore
    if (getParameterByName('sc_mode') !== 'edit') {

        // brochure carousel description limit with 4 in row.
        var carouselBrochureHeadingLimit = 50;
        var carouselBrochureDescLimit = 90;
        $(id + ' .brochure-carousel:not(.two-in-row) article').each(function(index, el) {
            $(this).find(' .copy-text .featured-property-title').text(trimChar(0,
                $(this).find('.copy-text .featured-property-title').text(),
                carouselBrochureHeadingLimit));
            $(this).find(' .copy-text p')
                .text(trimChar(0, $(this).find('.copy-text p').text(), carouselBrochureDescLimit));
        });

        // brochure carousel description limit with 2 in row.
        var carouselBrochureHeadingLimit2 = 50;
        var carouselBrochureDescLimit2 = 300;
        var carouselBrochureHeadingLimittab2 = 30;
        var carouselBrochureDescLimittab2 = 180;
        $(id + ' .brochure-carousel.two-in-row article').each(function(index, el) {
            if ($(window).width() > 1199) {
                $(this).find(' .copy-text .featured-property-title').text(trimChar(0,
                    $(this).find('.copy-text .featured-property-title').text(),
                    carouselBrochureHeadingLimit2));
                $(this).find(' .copy-text p')
                    .text(trimChar(0, $(this).find('.copy-text p').text(), carouselBrochureDescLimit2));
            } else {
                $(this).find(' .copy-text .featured-property-title').text(trimChar(0,
                    $(this).find('.copy-text .featured-property-title').text(),
                    carouselBrochureHeadingLimittab2));
                $(this).find(' .copy-text p').text(trimChar(0,
                    $(this).find('.copy-text p').text(),
                    carouselBrochureDescLimittab2));
            }
        });

    }
}

function fullSizeBrochureTextTrim(id) {
    // check for the param in URL for editor mode sitecore
    if (getParameterByName('sc_mode') !== 'edit') {
        // standalone page heading 
        var fullPageHeadingLimit = 50;
        $(id + ' .full-size-brochure h3')
            .text(trimChar(0, $(id + ' .full-size-brochure h3').text(), fullPageHeadingLimit));
    }
}
$(document).ready(function() {

    var fbSlideContainer = $('#fb-post .four-media-carousel');
    if (fbSlideContainer.length > 0) {
        ///getFbPosts();
        fbSlideContainer.not('.slick-initialized').slick(getSocialSliderSettings());
        //setTimeout(fbSlideContainer.slick(getSocialSliderSettings()), 5000);
    }
});

function getFbPosts() {
    var itemId = $("#txt_id").val();
    $.ajax({
        url: "/facebookpost/indexjsonresult",
        type: "GET",
        data: {},
        context: this,
        success: function(data) {

        },
        error: function(data) {
            console.log("error", data);
        }
    });
}
window.dcp = window.dcp || {};

(function($) {
  function isScriptAlreadyIncluded(src_file) {
    var scripts = document.getElementsByTagName("script");
    for (var i = 0; i < scripts.length; i++) {
        var tempSrc = scripts[i].getAttribute('src');
        if (tempSrc != null && tempSrc.toLowerCase().indexOf(src_file) >= 0) return true;
    }
    return false;
}

window.dcp.injectJSReference  = function(srcFile, srcPath){
	
	if(typeof srcPath === "undefined" || srcPath.length <= 0) return;
	
    if (isScriptAlreadyIncluded(srcFile)) return;

    var jsScriptTag = document.createElement('script');
    jsScriptTag.type = 'text/javascript';
    jsScriptTag.src = srcPath;
    document.body.appendChild(jsScriptTag);
};
})(jQuery);
window.dcp.RegisterSingleGoal = function(id, fxn) {
    var contexturl = window.location.pathname;
    jQuery.ajax({
        type: "POST",
        url: '/evbase/registersinglegoal',
        data: {
            "contextItemPath": contexturl,
            "goalId": id
        },
        success: function (data) {
            debugger;
            console.log(id);
            console.log(data.Errors);
           
          
        },
        error: function (data) {
            debugger;
            console.log(id + "failed to register");
            console.log(data.Errors);
        
        },
        complete: function (data) {
            debugger;
            console.log(id + "processed");
            console.log(data.Errors);
            if (typeof fxn !== "undefined") {
                fxn();
            }
        },
        dataType: 'json'
    });
};
$(function() {
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function(searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }
});
 window.dcp = window.dcp || {};

 (function($) {
     window.dcp.full_width_banner = function() {

         var model,

             actualHeight = function() {
                 $(model.container).each(function() {
                     var _this = $(this),
                         backgroundImg = changeBg(_this),
                         bgImg = $("<img/>"),
                         bg_urls = /^url\((['"]?)(.*)\1\)$/.exec(backgroundImg),
                         bg_url = bg_urls ? bg_urls[2] : "";

                     bgImg.css('width', '100%');
                     bgImg.hide();
                     $(this).prepend(bgImg);
                     bgImg.attr('src', bg_url);

                     if ($(window).width() < 1024) {
                         bgImg.show();
                     }

                     bgImg.bind('load', function() {
                         var _thisBg = $(this),
                             newHeight = _thisBg.outerHeight(),
                             textAreaContaner = _this.find('.container'),
                             textArea = textAreaContaner.find('h2,p');
                             

                         _thisBg.parent(".full-height").css('min-height', newHeight - 2);

                        if (!$.trim($(textArea).html()).length) {
                            //textAreaContaner.remove();
                             _thisBg.parent(".full-height").height(newHeight - 2).css('min-height', '0');
                             _thisBg.parent(".full-height").find('img').css('position', 'absolute');
                        }

                     });
                 });
             },

             changeBg = function(bg) {
                 if ($(window).width() < 1024) {
                     return bg.find('.full-banner-bg-mobile').css('background-image');

                 } else {
                     return bg.find('.full-banner-bg').css('background-image');
                 }
             },

             actualHeightIfCond = function() {
                 if ($(model.container).length > 0) {
                     $(model.container).each(function() {
                         $(this).find("img").remove();
                     });
                     actualHeight();
                 }
             },

             customColor = function(){
                if ($(model.container).length > 0) {
                    $(model.container).each(function() {
                        if($(this).find("div.inline-styling").attr("style").length>0){
                            var newVal = $(this).find("div.inline-styling").css("color");
                            $(this).find("p, li").css("color", newVal);
                        }  
                    });
                }
             },

             init = function(args) {
                 args = args || {};
                 model = {
                     init: function() {
                         this.container = args.container || '.full-width-banner';
                     }
                 };

                 // On document ready
                 model.init();
                 customColor();
                 $(window).on('load',function() {
                     actualHeightIfCond();
                 });

                 $(window).resize(function() {
                     actualHeightIfCond();
                 });
             };

         return {
             init: init
         };
     };


     $(function() {
         var full_width_banner = new dcp.full_width_banner();
         full_width_banner.init();
     });

 })(jQuery);
$(function(){
    const gaId = $('head [data-ga-id]').data('data-ga-id');
    window.dataLayer = window.dataLayer || [];
    track('js', new Date());
    //global parameters
    track('config', {
      page_title: $('title').text(),
      page_location: window.location.href,
      site_name: $(".property-homepage-header .top-nav > span").text().split(" ").slice(0, -1).join(" "),
      site_type: 'Residential'
    });
});
  
function track(name, data = {}) {
   if (window.dataLayer && typeof window.dataLayer.push === 'function') {
      const eventObj = data;
      eventObj['event'] = name;
      window.dataLayer.push(eventObj);
    }
}

$(function(){

    //header tracking
    $('.property-homepage-header .top-nav a.icons').on('click', function() {
        track('header', { text: $(this).find("img").attr("alt")});
    });

    $('.property-homepage-header .ui.container.header-search > a').on('click', function() {
        track('header', { text: 'logo', url: $(this).prop('href')});
    });

    //main menu tracking
    $('.property-homepage-header .main-nav a').not('a.nav-ico.ico-tel').on('click', function() {
        track('main_menu', { text: $(this).clone().children().remove().end().text().trim(), url: $(this).prop('href') });
    });

    $('.property-homepage-header .main-nav a.nav-ico.ico-tel').on('click', function(){
        track('main_menu', { text: 'call', url: $(this).prop('href') });
    });


    //tracking footer
    $('.homepage-footer-nav .column a').on('click', function(){
        track('footer', { text: $(this).text(), url: $(this).prop('href'), type: $(this).parents(".accordion").find(".title").text() });
    });

    //Stock search interaction tracking
    $(".property-price-filter .range-slider").on("change", function() {
        track('price_filter', { price: '$' + $(this).val().split(",")[0]+ '-' +'$' + $(this).val().split(",")[1], view: 'Search widget'});
    });

    $(".property-price-filter .column:nth-of-type(5) .menu .item").on("click", function(){
        track('land_size_filter', {land_size: $(this).text(), view: 'Search widget'});
    });

    $(".property-price-filter .column:nth-of-type(6) .menu .item").on("click", function(){
        track('frontage_filter', {frontage: $(this).text(), view: 'Search widget'});
    });

    $(".property-price-filter .column:nth-of-type(2) .menu .item").on("click", function(){
        track('bedroom_filter', {bedrooms: $(this).text(), view: 'Search widget'});
    });

    $(".property-price-filter .column:nth-of-type(3) .menu .item").on("click", function(){
        track('bathroom_filter', {bathrooms: $(this).text(), view: 'Search widget'});
    });

    $(".property-price-filter .column:nth-of-type(4) .menu .item").on("click", function(){
        track('car_space_filter', {car_spaces: $(this).text(), view: 'Search widget'});
    });

    //land Stock Search tool click tracking
    $(".property-price-filter .column:nth-of-type(7) a.btn").on("click", function(){
        track('search_tool_search', {price: '$' + $(".range-slider").val().split(",")[0]+ '-' +'$' + $(".range-slider").val().split(",")[1], land_size: $(this).parents(".price-filter-land").find(".column:nth-of-type(5) .menu .item.active.selected").text(), frontage: $(this).parents(".price-filter-land").find(".column:nth-of-type(6) .menu .item.active.selected").text(), view:'Search widget'})
    });

    //apartment stock search
    $(".property-price-filter .column:nth-of-type(5) a.btn").on("click", function(){
        track('search_tool_search', {price: '$' + $(".range-slider").val().split(",")[0]+ '-' +'$' + $(".range-slider").val().split(",")[1], bedrooms: $(this).parents(".price-filter-land").find(".column:nth-of-type(2) .menu .item.active.selected").text(), bathrooms: $(this).parents(".price-filter-land").find(".column:nth-of-type(3) .menu .item.active.selected").text(), car_spaces: $(this).parents(".price-filter-land").find(".column:nth-of-type(4) .menu .item.active.selected").text(), view:'Search widget'})
    });

    //collection links tracking
    $(".the-collection-module .column a").on("click", function(){
        track('site_body', {text : $(this).text(), type:'collection links'});
    });

    //standard image left tracking
    $(".explore-image-content .column a").on("click", function(){
        track('site_body', {text : $(this).find(".bottom-link ").text(), type:'image content', feature:'Standard image left'});
    });

    //properties video tracking
    $(".properties-big-image a").on("click", function(){
        track('site_body', {text : 'video clicked', type:'video', feature:'SMP top banner'});
    });

    //Tile carousel tracking
    $(".about-us-property-module .small-media-carousel-wrap .small-media-carousel .small-media-item a").on("click", function(){
        track('site_body', {text : $(this).find(".title").text(), url: $(this).prop('href'), type:'Carousel', feature:'Latest News'});
    });

    $('.about-us-property-module .slick-slider').on('swipe', () => {
        track('site_body', {text : 'carousel swiped', type:'Carousel', feature:'Latest News'});
    });

    //fetuared news tracking
    $(".featured-news-module .small-media-carousel-wrap .small-media-carousel .small-media-item a").on("click", function(){
        track('site_body', {text : $(this).find(".featured-property-title").text(), url: $(this).prop('href'), type:'Carousel', feature:'Featured News'});
    });

    $('.featured-news-module .slick-slider').on('swipe', () => {
        track('site_body', {text : 'carousel swiped', type:'Carousel', feature:'Featured News'});
    });

    //quick links tracking
    $(".quick-links .column a").not('.column.link-list a').on("click", function(){
        track('site_body', {text : $(this).parent(".column").find("h5").text(), url: $(this).prop('href'), type:'links', feature:'Quick links'});
    });

    $(".quick-links .column.link-list li a").on("click", function(){
        track('site_body', {text : $(this).text(), url: $(this).prop('href'), type:'links', feature:'Quick links'});
    });

    //full width banner tracking
    $(".full-width-banner .ui.container .content-wrapper .content a").on("click", function(){
        track('site_body', {text : $(this).text(), url: $(this).prop('href'), type:'banner', feature:'Full width banner'});
    });
});
$(document).ready(function() {
    globalAccordion();
});

function globalAccordion() {
    $(".global-accordion").each(function() {
        $(this).find('.ui.accordion').accordion(
            {
                exclusive: false
            }
        );
    });
}
 window.dcp = window.dcp || {};

 (function($) {
     window.dcp.parallax_container_bg = function() {

         var model,
             timeout,


             moveMouseAnimate = function() {
                 var innerCont = $(model.container).find('.parallax-container-inner');
                 $(innerCont).mousemove(function(e) {
                     if (timeout) clearTimeout(timeout);
                     setTimeout(callParallax.bind(null, e), 200);
                 });
             },

             revchild = function() {
                 $(model.container).parent().removeClass('child-page');
             },

             callParallax = function(e) {

                 var bgSlide0 = $('.bg-slide-0').attr('data-speed'),
                     bgSlide1 = $('.bg-slide-1').attr('data-speed'),
                     bgSlide2 = $('.bg-slide-2').attr('data-speed');

                 parallaxIt(e, '.bg-slide-0', bgSlide0);
                 parallaxIt(e, '.bg-slide-1', bgSlide1);
                 parallaxIt(e, '.bg-slide-2', bgSlide2);
             },

             // dataSpeed = function(speed) {
             //     var _this = $(speed);
             //     return _this.attr('data-speed');
             // },

             parallaxIt = function(e, target, movement) {
                 var $this = $('.parallax-container-inner');
                 var relX = e.pageX - $this.offset().left;
                 var relY = e.pageY - $this.offset().top;

                 TweenMax.to(target, 1, {
                     x: (relX - $this.width() / 2) / $this.width() * movement,
                     y: (relY - $this.height() / 2) / $this.height() * movement,
                     ease: Power2.easeOut
                 });
             },

             callTweenMax = function() {
                 var imported = document.createElement('script');
                 imported.src = '/Resources/Assets/scripts/TweenMax.min.js';
                 document.head.appendChild(imported);
             },


             init = function(args) {
                 args = args || {};
                 model = {
                     init: function() {
                         this.container = args.container || '.parallax-container-bg';
                     }
                 };

                 // On document ready
                 model.init();
                 callTweenMax();
                 moveMouseAnimate();
                 revchild();

             };

         return {
             init: init
         };
     };

     $(function() {
         var parallax_container_bg = new dcp.parallax_container_bg();
         parallax_container_bg.init();
     });

 })(jQuery);
$(document).ready(function() {
	$(".hotspot-module").each( function(){

		//activate tab
		$(this).find('.menu .item').tab();

		//activate hotspot popup
		$(this).find('.line-container .circle').popup({
			hoverable  : true,
			preserve: true,
			boundary: $(this).closest('.hotspot-module')
		});
		
	});

	//show popup on click in EE
	$(".hotspot-module.editfix").each( function(){
		$(this).find('.line-container .circle').popup({
		    on    : 'click',
		    closable: true
		});

	});

	showItemContainer();
	backToStart();
	closeNav();
	openNav();
	switchMobileContainer();
	switchDesktopContainer();
	lineAnimation();
	setZIndex();
	hidingDropdown();
	getCordinate();
	hideInstrPopup();
	//Detect touch device
	if ("ontouchstart" in document.documentElement){
		$(".hotspot-module .desktop-view .inner-container .item-container .hotspot-container .image-container").css("overflow","auto").css("max-height", "954px");
	} 
	else{
	 	$(".hotspot-module .desktop-view .inner-container .item-container .hotspot-container .image-container").css("overflow","hidden").css("max-height", "none");
	}

	sidebarActiveContent();
	scrollingBar();
});

//desktop switch between container
function switchDesktopContainer(){
	$(".hotspot-module").each( function(){
		$(this).find('.item-container').hide();
		if($(this).find('.desktop-view .navigation .dropdown').length){ 
			$(this).find('.desktop-view .navigation .dropdown .item').on("click", function(){
			    if($(this).parents(".dropdown").find('input').val() != "" || $(this).parents(".dropdown").find('input').val() != "undefined"){
			    	$(this).closest('.desktop-view').find('.item-container').show();
			    	$(this).parents(".hotspot-module").find(".instr-overlay").fadeIn(1500);
					$(this).closest('.desktop-view').find('.title-container').hide();
					if($(this).closest('.desktop-view').find('.item-container').length){
						$(this).on("click", function(){
							$(this).parents(".hotspot-module").find(".instr-overlay").fadeOut(1500, function(){$(this).remove();});
						});
					}
			    	
			    } else {
			    	$(this).closest('.desktop-view').find('.item-container').hide();
			    	$(this).closest('.desktop-view').find('.title-container').show();
				}
			});
		}
	});
}


//mobile switch between container
function switchMobileContainer(){
	$(".hotspot-module").each( function(){
		$(this).find('.hotspot-carousel').hide(); 
    	$(this).find('.mobile-view .dropdown .item').on("click", function(){
	    	$(this).closest('.mobile-view').find('.hotspot-carousel').show();
	    	$(this).closest('.mobile-view').find('.title-container-mobile').hide();
	    	$(this).closest('.mobile-view').find('.segment.active').each( function(){
				$(this).find('.inner-container').not('.slick-initialized').slick({
					dots: true,
					responsive: [
				        {
				            breakpoint: 9999,
				            settings: "unslick"
				        },
				        {
				            breakpoint: 1023,
			             	settings: {
			                    slidesToShow: 1,
			                    slidesToScroll: 1,
			                    infinite: true,
			                    mobileFirst: true
			                }
				        }
				    ]
				});
			});
    	});
	});
}


//show item container on click for desktop
function showItemContainer(){
	$(".hotspot-module").each( function(){
		if($(this).find('.vertical.menu .item').length){
			$(this).find('.vertical.menu .item').on('click', function(){
				$('.vertical.menu .item').removeClass('active');
				$(this).addClass('active');
				$(this).closest('.inner-container').find('.item-container').fadeIn();
				$(this).parents(".hotspot-module").find(".instr-overlay").fadeIn(1500);
				if($(this).closest('.inner-container').find('.item-container').length){
					$('.vertical.menu .item').on("click", function(){
						$(this).parents(".hotspot-module").find(".instr-overlay").fadeOut(1500, function(){$(this).remove();});
					});
				}
				$(this).closest('.inner-container').find('.title-container').fadeOut();
				$(this).closest('.inner-container').find(".segment").find('.hotspot-side-nav').css('left', '0');
				$(this).closest('.inner-container').find('.open-sidenav').css('left', '-40px');
				$(this).closest('.inner-container').find('.close-sidenav').css('left', '325px');
			});
		}
	});
}


//go back to title slide
function backToStart(){
	$(".hotspot-module").each( function(){
		var oldText = $(this).find('.desktop-view .navigation .dropdown .default').text();
		var oldMobText = $(this).find('.mobile-view .dropdown div.default').text();
		var TitleDescriptionBack = $(this).find('.desktop-view .title-container .side-nav').html();
		$(this).find('.back-to-start').on('click', function(){
			$(this).closest('.inner-container').find('.title-container').fadeIn();
			$(this).closest('.inner-container').find('.item-container').fadeOut();
			$(this).closest(".inner-container").find('.navigation').css('left', '0');
			$(this).closest(".inner-container").find('.navigation .menu .item').removeClass('active');
			$(this).closest(".inner-container").find('.navigation .dropdown .item').removeClass('selected');
			$(this).closest(".inner-container").find('.navigation .dropdown input').removeAttr("value");
			$(this).closest(".inner-container").find('.navigation .dropdown .text').text(oldText);
			$(this).parents(".hotspot-module").find('.mobile-view').find('.title-container-mobile').show();
			$(this).parents(".hotspot-module").find(".mobile-view").find('.mobile-view .dropdown .text').text(oldMobText);
			$(this).parents(".hotspot-module").find('.mobile-view').find('.hotspot-carousel').hide();
			$(this).parents(".hotspot-module").find(".navigation div:not([class])").remove();
			$(this).parents(".hotspot-module").find(".navigation").prepend(TitleDescriptionBack);
			setTimeout(function(){$(".navigation").getNiceScroll().resize()}, 1000);
		});
	});

}

// side nav open 
function openNav() {
	$(".hotspot-module").each( function(){
		$(this).find('.open-sidenav').on('click', function(){
			$(this).siblings(".segment").find('.hotspot-side-nav').css('left', '0');
			$(this).css('left', '-40px');
			$(this).siblings('.close-sidenav').css('left', '325px');
			$(this).closest(".inner-container").find('.navigation').css('left', '0');
		});
	});
}

// side nav close 
function closeNav() {
	$(".hotspot-module").each( function(){
	  	$(this).find('.close-sidenav').on('click', function(){
			$(this).siblings(".segment").find('.hotspot-side-nav').css('left', '-372px');
			$(this).css('left', '-400px');
			$(this).siblings('.open-sidenav').css('left', '20px');
			$(this).closest(".inner-container").find('.navigation').css('left', '-372px');
		});
	});
}


//draw line using cordinates
function linedraw(ax,ay,bx,by){
	$(".hotspot-module").each(function(){
			$(this).find(".hotspot-container .segment.active").each(function(){
				$(this).find(".line-container").each( function(){
					ax = $(this).find(".line").attr("data-left1");
					ay = $(this).find(".line").attr("data-top1");
					bx = $(this).find(".line").attr("data-left2");
					by = $(this).find(".line").attr("data-top2");
				    var setHeight= Math.sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by));	
				    				    
				    if((50 > ax || ax > 1880)){
				    	$(this).css("display","none");
				    } else {
					    if(ax === bx && by > ay){
					    	$(this).find(".line").css({"height": setHeight, "top": ay, "left": ax});
							$(this).find(".circle").css("display","block").css("left", bx-12).css("top", by-12);
							$(this).find(".blinking-circle").css("display","block").css("left", bx-21).css("top", by-21);
					    } else if(ax === bx && ay > by){
					    	$(this).find(".line").css({"height": setHeight, "top": by, "left": ax});
							$(this).find(".circle").css("display","block").css("left", bx-12).css("top", by-12);
							$(this).find(".blinking-circle").css("display","block").css("left", bx-21).css("top", by-21);
					    } else if(ay === by && bx > ax){ 
					    	$(this).find(".line").css({"width": setHeight, "top": ay, "left": ax});
							$(this).find(".circle").css("display","block").css("left", bx-12).css("top", by-12);
							$(this).find(".blinking-circle").css("display","block").css("left", bx-21).css("top", by-21);
					    } else if(ay === by && ax > bx){
					    	$(this).find(".line").css({"width": setHeight, "top": ay, "left": bx});
							$(this).find(".circle").css("display","block").css("left", bx-12).css("top", by-12);
							$(this).find(".blinking-circle").css("display","block").css("left", bx-21).css("top", by-21);
					    } else if(ax === bx && ay === by){
					    	$(this).find(".line").css({"height": setHeight, "top": ay, "left": ax});
							$(this).find(".circle").css("display","block").css("left", bx-12).css("top", by-13);
							$(this).find(".blinking-circle").css("display","block").css("left", bx-21).css("top", by-22);
					    } else if(ax === bx === ay === by){
					    	$(this).find(".line").css({"height": setHeight, "top": ay, "left": ax});
							$(this).find(".circle").css("display","block").css("left", bx-12).css("top", by-12);
							$(this).find(".blinking-circle").css("display","block").css("left", bx-21).css("top", by-21);
					    } else {
					    	$(this).css("display","none");
					    } 
					}
				    
				});
			});
		
	});
}


// line draw with animation
function lineAnimation(){
	$(".hotspot-module").each( function(){
		if($(this).find(".desktop-view .vertical.menu").length){
			$(this).find(".desktop-view .vertical.menu .item").each(function(){
				$(this).on("click", function(){
					if($(this).attr("data-tab") == $(this).parents(".inner-container").find(".segment.active").attr("data-tab")){
						setTimeout(linedraw, 100);
					   	//animateEffect();
				  	}
				});
			});
		} else {
			$(this).find('.desktop-view .navigation .dropdown').on("click", function(){
			    if($(this).find('input').val() != "" || $(this).find('input').val() != "undefined"){
			    	setTimeout(linedraw, 100);
					//animateEffect();
			    }
			});
		}

	});
}

// set z-index
function setZIndex(){ 
	$(".hotspot-module").each(function(){
		if($(this).find(".item-container").length){
			$(this).find(".hotspot-container .segment img").each(function(){
				$(this).closest(".image-container").find(".line-container .circle").each( function(){
					$(this).hover(function(){
						$(this).parent().css("z-index", 4);
						$(this).parents(".image-container").find(".line-container").not($(this).parent()).css("z-index", 3);
					});	
				});
			});
		}
	});
}

//hide dropdown in IE browser
function hidingDropdown() {
	$(".hotspot-module").each(function(){
	    if ($(this).find('.navigation .dropdown').length > 0) {
	        $(document).on('click', '.navigation .dropdown .item', function(e) {
	            $(this).parent().removeClass('visible').removeAttr('style');
	        });
	    }
	});
}


//get co-ordinates on click
function getCordinate(){
	$(".hotspot-module.editfix").each(function(){
		if($(this).find(".item-container").length){
			$(this).find(".hotspot-container .segment").each(function(){
				$(this).find('.image-container img').on("click", function(e) {
				   	var offset = $(this).offset();
				   	$(".cordinates").css("display", "block");
				   	$('.x-axis').html(e.pageX - offset.left);
				   	$('.y-axis').html(e.pageY - offset.top);
				});
			});
		}
	});	
}

//hide instruction popup
function hideInstrPopup(){
	$(".hotspot-module").each(function(){
		$(this).find(".instr-overlay").hide();
		$(this).find(".segment").on("click", function(){
			$(this).parents(".hotspot-module").find(".instr-overlay").fadeOut(1500, function(){$(this).remove();});
		});

		$(this).find(".segment .circle").on("mouseover", function(){
			$(this).parents(".hotspot-module").find(".instr-overlay").fadeOut(1500, function(){$(this).remove();});
		});
	});
}

$(window).resize(function(){
	//setTimeout(defineDynamicHeight, 100);
	scrollingBar();
	if ("ontouchstart" in document.documentElement){
		$(".hotspot-module .desktop-view .inner-container .item-container .hotspot-container .image-container").css("overflow","auto").css("max-height", "954px");
	} else{
		$(".hotspot-module .desktop-view .inner-container .item-container .hotspot-container .image-container").css("overflow","hidden").css("max-height", "none");
	}

	if($(".hotspot-module").length){
		$(".hotspot-module").each(function(){
			var setNewMobileDropdownText = $(this).find(".mobile-view .reset-label").text();
			if($(window).width() < 1024 && ($(this).find(".desktop-view .inner-container .item-container").get(0).style.display == "block")){
				if($(this).find(".desktop-view .navigation .ui.dropdown").length){
					let setMobileDropdownText = $(this).find(".desktop-view .navigation .ui.dropdown .menu .active.item").text();
					$(this).find(".mobile-view .dropdown div.text").text(setMobileDropdownText);
					$(this).find(".mobile-view .dropdown .menu .item.active").addClass("selected");

				} else{
					let setMobileDropdownText = $(this).find(".desktop-view .navigation .ui.vertical .active.item").text();
					$(this).find(".mobile-view .dropdown div.text").text(setMobileDropdownText);
					$(this).find(".mobile-view .dropdown .menu .item.active").addClass("selected");
				}
				$(this).find(".mobile-view .hotspot-carousel").css("display", "block");
				$(this).find(".mobile-view .title-container-mobile").css("display", "none");
				$(this).find('.mobile-view').find('.segment.active').each( function(){
					$(this).find('.inner-container').not('.slick-initialized').slick({
						dots: true,
						responsive: [
							{
								breakpoint: 9999,
								settings: "unslick"
							},
							{
								breakpoint: 1023,
								settings: {
									slidesToShow: 1,
									slidesToScroll: 1,
									infinite: true,
									mobileFirst: true
								}
							}
						]
					});
				});
				
			} else if($(window).width() > 1023 && ($(this).find(".mobile-view .hotspot-carousel").get(0).style.display == "block")){
				var setDesktopDropdownText = $(this).find(".mobile-view .ui.dropdown .menu .active.item").text();
				$(this).find(".desktop-view .navigation .dropdown div.text").text(setDesktopDropdownText);
				$(this).find(".desktop-view .navigation .dropdown .menu .item.active").addClass("selected");
				$(this).find(".desktop-view .inner-container .title-container").css("display", "none");
				$(this).find(".desktop-view .inner-container .item-container").css("display", "block");
				setTimeout(linedraw, 10); 
				var NewTabDescription = $(this).find(".inner-container").find(".segment.active").find(".hotspot-side-nav").html();
				$(this).find(".navigation div:not([class])").remove();
				$(this).find(".navigation").prepend(NewTabDescription);
				$(this).find(".desktop-view .instr-overlay").fadeOut(1500, function(){$(this).remove();});

			} else if($(window).width() < 1024 && ($(this).find(".desktop-view .inner-container .item-container").get(0).style.display == "none")){
				$(this).find(".mobile-view .dropdown div.text").text(setNewMobileDropdownText);
			}
			
		});
	}
});

// $(window).load(function(){
// 	defineDynamicHeight();
// });

// function defineDynamicHeight(){
// 	$(".hotspot-module").each( function(){
// 		var setpanelHeight = $(this).find(".side-nav > div").height() + 100;
// 		if( setpanelHeight > 100){
// 			$(this).find(".navigation").css("top", setpanelHeight);
// 		} else{
// 			$(this).find(".navigation").css("top", "175px");
// 		}
		
// 	});
// }

function sidebarActiveContent(){
	$(".hotspot-module").each( function(){
		if($(this).find(".desktop-view .vertical.menu").length){
			$(this).find(".desktop-view .vertical.menu .item").each(function(){
				$(this).on("click", function(){
					var NewTabDescriptionBut = $(this).parents(".inner-container").find(".segment.active").find(".hotspot-side-nav").html();
					$(this).parents(".hotspot-module").find(".navigation div:not([class])").remove();
					$(this).parents(".navigation").prepend(NewTabDescriptionBut);
					setTimeout(function(){$(".navigation").getNiceScroll().resize()}, 1000);
				});
			});
		} else {
			$(this).find('.desktop-view .navigation .dropdown .item').on("click", function(){
			    if($(this).parents(".dropdown").find('input').val() != "" || $(this).parents(".dropdown").find('input').val() != "undefined"){
			    	var NewTabDescriptionDrop = $(this).parents(".inner-container").find(".segment.active").find(".hotspot-side-nav").html();
					$(this).parents(".hotspot-module").find(".navigation div:not([class])").remove();
					$(this).parents(".navigation").prepend(NewTabDescriptionDrop);
					setTimeout(function(){$(".navigation").getNiceScroll().resize()}, 1000);
			    }
			});
		}
	});
}

function scrollingBar() {
	$(".hotspot-module").each( function(){
		if ($(this).find(".desktop-view .navigation").length) {
			$(this).find(".desktop-view .navigation").niceScroll({
				autohidemode: false,
				smoothscroll: true,
				cursorborder:'none',
				cursorcolor:'#666',
				cursorwidth:"8px",
			});
		}
	});
}

// dragScroll plugin
/**
 * @fileoverview dragscroll - scroll area by dragging
 * @version 0.0.8
 * 
 * @license MIT, see http://github.com/asvd/dragscroll
 * @copyright 2015 asvd <heliosframework@gmail.com> 
 */
(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['exports'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.dragscroll = {}));
    }
}(this, function(exports) {
    var _window = window;
    var _document = document;
    var mousemove = 'mousemove';
    var mouseup = 'mouseup';
    var mousedown = 'mousedown';
    var EventListener = 'EventListener';
    var addEventListener = 'add' + EventListener;
    var removeEventListener = 'remove' + EventListener;
    var newScrollX, newScrollY;
    var dragged = [];
    var reset = function(i, el) {
        for (i = 0; i < dragged.length;) {
            el = dragged[i++];
            el = el.container || el;
            el[removeEventListener](mousedown, el.md, 0);
            _window[removeEventListener](mouseup, el.mu, 0);
            _window[removeEventListener](mousemove, el.mm, 0);
        }
        // cloning into array since HTMLCollection is updated dynamically
        dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
        for (i = 0; i < dragged.length;) {
            (function(el, lastClientX, lastClientY, pushed, scroller, cont) {
                (cont = el.container || el)[addEventListener](
                    mousedown,
                    cont.md = function(e) {
                        if (!el.hasAttribute('nochilddrag') ||
                            _document.elementFromPoint(
                                e.pageX, e.pageY
                            ) == cont
                        ) {
                            pushed = 1;
                            lastClientX = e.clientX;
                            lastClientY = e.clientY;
                            e.preventDefault();
                        }
                    }, 0
                );
                _window[addEventListener](
                    mouseup, cont.mu = function() {
                        pushed = 0;
                    }, 0
                );
                _window[addEventListener](
                    mousemove,
                    cont.mm = function(e) {
                        if (pushed) {
                            (scroller = el.scroller || el).scrollLeft -=
                                newScrollX = (-lastClientX + (lastClientX = e.clientX));
                            scroller.scrollTop -=
                                newScrollY = (-lastClientY + (lastClientY = e.clientY));
                            if (el == _document.body) {
                                (scroller = _document.documentElement).scrollLeft -= newScrollX;
                                scroller.scrollTop -= newScrollY;
                            }
                        }
                    }, 0
                );
            })(dragged[i++]);
        }
    };
    if (_document.readyState == 'complete') {
        reset();
    } else {
        _window[addEventListener]('load', reset, 0);
    }
    exports.reset = reset;
}));
$(document).ready(function() {
    iconCarouselSlider();
    chageSliderOnHover();
    iconCarouselAccordion();
    iconCarouselBg();
    eqalHeightCaption();
    multipleModal();
    removeGradient();
    sonarEffect();
    showIconsOnly();
});

$(window).resize(function() {
    $(".icon-carousel .slider-nav .item figure figcaption").css({
        'min-height': 'auto'
    });
    setTimeout(eqalHeightCaption, 100);
});

//set equal height to figcaption 
function eqalHeightCaption() {
    $(".icon-carousel").each(function() {
        var item = $(this).find(".slider-nav .item"),
            itemCaption = $(item).find("figure figcaption");
        $(itemCaption).css({
            'min-height': 0
        });
        var max = -1;
        $(item).each(function() {
            var h = $(this).find("figure figcaption").height();
            max = h > max ? h : max;
        });
        $(itemCaption).css({
            'min-height': max
        });
    });
}

//change background image on slide change

function iconCarouselBg() {
    $(".icon-carousel").each(function() {
        var item = $(this).find(".slider-nav .item"),
            prevBg = $(this).css("background-image");
        $(item).each(function() {
            var newId = $(this).attr("aria-describedby");
            if ($(this).css("background-image").indexOf("media") > 0) {
                var newBg = $(this).css("background-image");
                $(this).hover(function() {
                    $(item).removeClass("slick-current");
                    $(this).addClass("slick-current");
                    $(this).parents(".icon-carousel").css("background-image", newBg);
                    $(this).closest(".slider-nav").find(".slick-dots li").removeClass("slick-active");
                    $(this).closest(".slider-nav").find(".slick-dots li").each(function() {
                        if ($(this).attr("id") === newId) {
                            $(this).addClass("slick-active");
                        } else {
                            $(this).removeClass("slick-active");
                        }
                    });
                }, function() {
                    $(this).addClass("slick-current");
                    $(this).parents(".icon-carousel").css("background-image", newBg);
                    $(this).closest(".slider-nav").find(".slick-dots li").removeClass("slick-active");
                    $(this).closest(".slider-nav").find(".slick-dots li").each(function() {
                        if ($(this).attr("id") === newId) {
                            $(this).addClass("slick-active");
                        } else {
                            $(this).removeClass("slick-active");
                        }
                    });
                });
            } else {
                $(this).hover(function() {
                    $(item).removeClass("slick-current");
                    $(this).addClass("slick-current");
                    $(this).closest(".slider-nav").find(".slick-dots li").removeClass("slick-active");
                    $(this).closest(".slider-nav").find(".slick-dots li").each(function() {
                        if ($(this).attr("id") === newId) {
                            $(this).addClass("slick-active");
                        } else {
                            $(this).removeClass("slick-active");
                        }
                    });
                }, function() {
                    $(this).addClass("slick-current");
                    $(this).closest(".slider-nav").find(".slick-dots li").removeClass("slick-active");
                    $(this).closest(".slider-nav").find(".slick-dots li").each(function() {
                        if ($(this).attr("id") === newId) {
                            $(this).addClass("slick-active");
                        } else {
                            $(this).removeClass("slick-active");
                        }
                    });
                });
                $(this).parents(".icon-carousel").css("background-image", prevBg);
            }
        });
    });
}

// accordion mobile view
function iconCarouselAccordion() {
    $(".icon-carousel").each(function() {
        $(this).find('.ui.accordion').accordion();
    });
}

//change slide on rollover
function chageSliderOnHover() {
    $(".icon-carousel").each(function() {
        $(this).find('.slider-nav').on('mouseenter', '.slick-slide', function(e) {
            var $currTarget = $(e.currentTarget),
                index = $currTarget.data('slick-index'),
                slickObj = $(this).closest(".icon-carousel").find('.slider-for').slick('getSlick');
            slickObj.slickGoTo(index);
        });
    });
}

//desktop view Icon Carousel
function iconCarouselSlider() {
    $(".icon-carousel").each(function() {
        var sliderNavSlide = $(this).find('.slider-nav .slick-slide');
        $(this).find('.slider-for').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: false,
            fade: true,
            infinite: false,
            autoplay: false,
            draggable: false,
            asNavFor: $(this).closest(".icon-carousel").find('.slider-nav'),
            beforeChange: function(slickSlider, i) {
                $(sliderNavSlide).removeClass('slick-active');
                $(sliderNavSlide).eq(i).addClass('slick-active');
            }
        });

        $(sliderNavSlide).eq(0).addClass('slick-active');

        $(this).find('.slider-nav').slick({
            slidesToShow: 5,
            slidesToScroll: 1,
            //swipeToSlide: true,
            asNavFor: $(this).closest(".icon-carousel").find('.slider-for'),
            dots: true,
            focusOnSelect: true,
            speed: 1000,
            infinite: false,
            autoplay: false
        });
    });
}

function multipleModal() {
    $(".icon-carousel").each(function(i) {
        var oldVidAttr = $(this).find(".video-icon").data("target");
        var oldFrameAttr = $(this).find(".frame-content").data("target");
        $(this).find(".video-icon").attr("data-target", oldVidAttr + i);
        $(this).find(".modal.videoModals").removeClass("videoModals").addClass("videoModals" + i);
        $(this).find(".frame-content").attr("data-target", oldFrameAttr + i);
        $(this).find(".modal.frameModal").removeClass("frameModal").addClass("frameModal" + i);
    });
}

function removeGradient() {
    $(".icon-carousel").each(function() {
        if ($(this).css("background-image").indexOf("media") > 0) {
            $(this).find(".item-description").each(function() {
                if ($(this).text().trim().length === 0) {
                    $(this).parents(".icon-carousel").addClass("full-height");
                } else {
                    $(this).parents(".icon-carousel").removeClass("full-height");
                }
            });
        }
    });
}

// Adding Sonar Effect
function isOnScreen(elem) {
    // if the element doesn't exist, abort
    if (elem.length == 0) {
        return;
    }
    var $window = $(window);
    var viewport_top = $window.scrollTop();
    var viewport_height = $window.height();
    var viewport_bottom = viewport_top + viewport_height;
    var $elem = $(elem);
    var top = $elem.offset().top;
    var height = $elem.height();
    var bottom = top + height;

    return (top >= viewport_top && top < viewport_bottom) ||
        (bottom > viewport_top && bottom <= viewport_bottom) ||
        (height > viewport_height && top <= viewport_top && bottom >= viewport_bottom);
}

function sonarEffect() {
    var allMods = $(".icon-carousel");
    window.addEventListener('scroll', function(news) {
        $(allMods).each(function() {
            var sonar = false;
            if (isOnScreen($(this).find(".desktop")) && !sonar) { /* Pass element id/class you want to check */
                sonar = true;
                $(this).find(".slider-nav .item figure .sonar").not(".slider-nav .item:first-child figure .sonar").addClass("sonar-effect");
                $(this).find(".slider-nav .item figure").not(".slider-nav .item:first-child figure").hover(
                    function() {
                        $(this).find(".sonar").addClass("remove-sonar");

                    },
                    function() {
                        $(this).find(".sonar").addClass("remove-sonar");
                    }
                );
            }
        });

    });
}

function showIconsOnly() {
    $(".icon-carousel").each(function() {
        if ($(this).find(".slider-for").text().trim() == "") {
            $(this).find(".slider-for").hide();
            $(this).addClass("only-icons");
        }
    });
}
$(document).ready(function() {
	if ($(".comparison-slider")[0]) {
		let compSlider = $(".comparison-slider");
	
		//looping through the sliders and initialise
		compSlider.each(function() {
			let compSliderWidth = $(this).width() + "px";
			$(this).find(".resize img").css({ width: compSliderWidth });
			drags($(this).find(".divider"), $(this).find(".resize"), $(this));
		});

		$(window).on("resize", function() {
			let compSliderWidth = compSlider.width() + "px";
			compSlider.find(".resize img").css({ width: compSliderWidth });
		});
	}
});

// This is where all the magic happens
function drags(dragElement, resizeElement, container) {
	let touched = false;
	window.addEventListener('touchstart', function() {
		touched = true;
	});
	window.addEventListener('touchend', function() {
		touched = false;
	});
	
	dragElement.on("mousedown touchstart", function(e) {
		
			dragElement.addClass("dragging");
			resizeElement.addClass("resizable");
			//create vars
			let startX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
			let dragWidth = dragElement.outerWidth();
			let posX = dragElement.offset().left + dragWidth - startX;
			let containerOffset = container.offset().left;
			let containerWidth = container.outerWidth();
			let minLeft = containerOffset;
			let maxLeft = containerOffset + containerWidth - dragWidth;
			dragElement.parents().on("mousemove touchmove", function(e) {
				
				if ( touched === false ) {
					e.preventDefault();
				}
				
				let moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
				let leftValue = moveX + posX - dragWidth;

				// stop the divider from going over the limits of the container
				if (leftValue < minLeft) {
					leftValue = minLeft;
				} else if (leftValue > maxLeft) {
					leftValue = maxLeft;
				}

				let widthValue = (leftValue + dragWidth / 2 - containerOffset) * 100 / containerWidth + "%";

				$(".dragging").css("left", widthValue).on("mouseup touchend touchcancel", function() {
					$(this).removeClass("dragging");
					resizeElement.removeClass("resizable");
				});
				
				$(".resizable").css("width", widthValue);
				
			}).on("mouseup touchend touchcancel", function() {
				dragElement.removeClass("dragging");
				resizeElement.removeClass("resizable");
				
			});
		
		}).on("mouseup touchend touchcancel", function(e) {
			// stop clicping the image and move the slider
			dragElement.removeClass("dragging");
			resizeElement.removeClass("resizable");
		
		});
	
}

$(document).ready(function() {
    var winHeight = $(window).height();

    function staffpop() {
        var halfWinHeight = winHeight / 2;
        var staffPhotoHeight = $('.staff-profile-wrap .image-link');
        var staffDetailHeight = $('.staff-profile-wrap .person-details');
        staffPhotoHeight.height(halfWinHeight);
        staffDetailHeight.height(halfWinHeight);
        //console.log(staffPhotoHeight);
    }
    $('.person .see-profile').on('click', function(e) {
        e.preventDefault();

        if ($('.staff-profile-wrap  a.btn-close + div').length <= 0) {
            var index = $(this).data("staff-id");
            var moduleId = $(this).data("item-id");
            var carousel = $('#' + moduleId + ' #people-carousel-carousel-' + index);
            $('body').append('<div class="full-screen-lock"></div>');

            $('.staff-profile-wrap').addClass('display');
            carousel.clone().appendTo('.staff-profile');
            var startSlide = parseInt($(this).attr("data-staff-id"));
            staffpop();
            $(window).resize(function() {
                if ($(window).height() != winHeight) {
                    winHeight = $(window).height();
                    staffpop();
                }
            });

            if ($('.staff-profile-wrap').hasClass('display')) {

                $('.staff-profile  #people-carousel-carousel-' + index).slick({
                    slidesToShow: 1,
                    infinite: true,
                    dots: false,
                    arrows: true,
                    initialSlide: 0
                });
            } else {
                //console.log("invisible");
                $('.staff-profile  #people-carousel-carousel-' + index).slick('unslick');
            }

            $('.full-screen-lock,.staff-profile .btn-close').on('click', function(e) {
                e.preventDefault();
                $('.staff-profile-wrap').removeClass('display');
                $('.full-screen-lock').remove();
                //var sib = $('.staff-profile-wrap  a.btn-close').siblings();
                //sib.remove();
                $('.staff-profile-wrap  a.btn-close + div').remove();
            });
        }
    });
});




$(function() {
    if ($('script[src*="bootstrap.min.js"]').length === 0) {
        if ($(".properties-news-module").length > 0 || $(".featured-news-module").length > 0 || $(".icon-carousel").length > 0) {
            //$('body').append('<script src="/Resources/Assets/scripts/modal.js"></script>');
            var modeljs = "/Resources/Assets/scripts/modal.js";
            window.dcp.injectJSReference(modeljs, modeljs);
        }
    }
    //set primary colour for play buttons
    setTimeout(function() {
        /*$('.standard-content .video-frame').append('<div class="play-button"></div>');*/

        $('.play-button').not(".properties-news-module .play-button, .featured-news-module .play-button").on('click', function(e) {

            // console.log('first');
            // console.log($(this).parent().find('div.video').attr('data-videoItemId'));
            var videoItemId = $(this).parent().find('div.video').attr('data-videoItemId'),
                $playButton = $(this),
                player = $(this).siblings('.video');
            if (player.length > 0 && typeof(YT) !== 'undefined' && typeof(YT.Player) !== 'undefined') {

                //stopVideos();
                YT.ready(function() {
                    var playerId = player[0].id;
                    var videoId = $(player[0]).data('id');
                    if (playerId !== 'undefined' && playerId !== '' && videoId !== 'undefined' && videoId !== '') {
                        var YTPlayer = YT.get(playerId);

                        var url = window.location.pathname;
                        //console.log(videoItemId + url);
                        RegisterGoal(url, videoItemId);

                        if (YTPlayer == undefined) {
                            YTPlayer = new YT.Player(playerId, {
                                videoId: videoId,
                                events: {
                                    'onReady': onPlayerReady,
                                    'onStateChange': onPlayerStateChange
                                },
                                playerVars: {
                                    rel: 0
                                }
                            });

                        } else {
                            if (typeof YTPlayer.playVideo === 'function') {
                                YTPlayer.playVideo();
                                $playButton.fadeOut('fast');
                                gaVideoClick(YTPlayer.a);
                            }
                        }
                    }
                });
            }
        });
        $('.play-button,.play-btn').addPlayButtonSVG(0, 0, 45, '.play-button-color');
    }, 500);
    initAccordion();
    /* if($('.find-property-looking-for-select').length > 0){ */
    initDropdowns();

    $(".find-property-looking-for-select").unbind("focus");
    $(".find-property-in-select").unbind("focus");

    accordionInit();

    $('.brochure .ui.accordion .title').click(function() {
        activeBrochure($(this));
    });
    

    (function PopulateHomepagePropertySearch() {
        if (typeof lookingForList != 'undefined') {
            //console.log('lookingForList');



            if ($('.find-property-looking-for-select > select').length) {
                for (var index in lookingForList) {
                    $('.find-property-looking-for-select > select').append('<option value="' + index + '">' + lookingForList[index].title + '</option>');
                }
            } else {
                for (var index2 in lookingForList) {
                    $('.find-property-in-select > select').append(
                        '<option value="' +
                        lookingForList[index2].url +
                        '" data-map="' +
                        lookingForList[index2].map +
                        '">' +
                        lookingForList[index2].title +
                        '</option>');
                }
            }

            $('.find-property-looking-for-select > select').on('change', function() {
                var isdefault = $("div.find-property-looking-for-select div.default.text");
                var index = this.value;
                $('.find-property-in-select>select>option').remove();
                if (index) {
                    $('.find-property-in-select>select').append('<option></option>');
                    var i = 0;
                    for (var state in lookingForList[index].items) {
                        var url = lookingForList[index].items[state].url || "/";
                        if (i == 0 && isdefault.length == 0) {
                            $('.find-property-in-select>select').append('<option selected value="' + url + '">' + lookingForList[index].items[state].title + '</option>');
                        } else {
                            $('.find-property-in-select>select').append('<option value="' + url + '">' + lookingForList[index].items[state].title + '</option>');
                        }
                        i++;
                    }
                    $('.ui.dropdown').dropdown("refresh");
                }
            });
            $(".find-property-looking-for-select").on('click', function() {
                //var isdefault = $("div.find-property-looking-for-select div.default.text");
                //if (isdefault.length == 0) {
                var title = $("div.find-property-in-select > select option:selected").text();

                //console.log("title" + title);
                $("div.find-property-in-select div.text").text(title);
                $("div.find-property-in-select div.item").removeClass('active').removeClass('selected');
                $("div.find-property-in-select div.item").first().addClass('active').addClass('selected');

                $('.find-property-wrap :submit').removeAttr('disabled');
                var url = $('.find-property-in-select > select option:selected').val();


                $('.find-property-wrap form').attr('action', url);

                if ($('.find-property-wrap #mapImg').length) {
                    var selectedMap = $('.find-property-in-select > select > option:selected').data('map');
                    var mapImgUrl = $('.find-property-wrap #mapImg');
                    selectedMap = selectedMap == undefined ? "" : selectedMap;
                    mapImgUrl.attr('src', selectedMap);
                }
                //}                    
            });

            $('.find-property-in-select > select').on('change', function(value, text, $selectedItem) {
                $('.find-property-wrap :submit').removeAttr('disabled');
                $('.find-property-wrap form').attr('action', this.value);

                if ($('.find-property-wrap #mapImg').length) {
                    var selectedMap = $('.find-property-in-select > select > option:selected').data('map');
                    var mapImgUrl = $('.find-property-wrap #mapImg');
                    selectedMap = selectedMap == undefined ? "" : selectedMap;
                    mapImgUrl.attr('src', selectedMap);
                }
            });

            // Embedding a hook into form on Submit
            var propertyWrap = jQuery(".find-property-wrap");
            var data = jQuery(".find-property-wrap").data();
            var form = propertyWrap.find("form").submit(function() {
                //console.log('Posting');
                jQuery.post(
                    '/contact/setfpafacet', {
                        lookingForSelection: JSON.stringify({
                            'propertyType': jQuery('.find-property-looking-for-select > select').val(),
                            'propertyLocation': jQuery('.find-property-in-select > select option:selected').text()
                        }),
                        contactid: data.contactid
                    }
                );
            });

            // And then on load, read the lookingForSelection if it's available
            if (typeof(data.lookingforselection === 'object')) {
                var location = data.lookingforselection.propertyLocation;
                var type = data.lookingforselection.propertyType;
                if (typeof(type) !== "undefined") {
                    setTimeout(function() {
                        //console.log('Selecting type', type)
                        propertyWrap.find(".find-property-looking-for-select > select").val(type).change();
                        if (typeof(location) !== "undefined") {
                            setTimeout(function() {
                                //console.log('Selecting location', location)
                                var propertyInSelect = propertyWrap.find(".find-property-in-select > select");
                                var selectedOptions = propertyInSelect.find("option")
                                    .toArray()
                                    .filter(function(o) {
                                        return o.innerText.trim().toUpperCase() == location.trim().toUpperCase();
                                    })
                                    .map(function(o) {
                                        return jQuery(o).attr('value');
                                    });
                                if (selectedOptions.length < 1) {
                                    return;
                                }
                                propertyInSelect.val(selectedOptions[0]).change();
                            }, 10);
                        }
                    }, 10);
                }
            }
        }
    })();

    if ($('.main-nav').find('.ui.dropdown').length > 0) {
        $('.main-nav .ui.dropdown').dropdown({
            on: 'hover',
            direction: 'downward'
        });

        var tab_menu = $(".tab-menu div");
        var tab_content = $('.main-nav .ui.tab');

        tab_menu.hover(function() {
            tab_content.hide();
            tab_menu.removeClass('active');
            tab_content.removeClass('active');
            $(this).addClass("active");

            var current = $(this).attr("data-tab");
            $(".ui.tab[data-tab='" + current + "']").addClass('active').stop(true, true).fadeIn();
            return false;
        });
        tab_menu.click(function(e) {
            var url = $(this).attr('data-url');
            if (url !== '') {
                window.location.href = url;
            }
            e.preventDefault();
        });
    }

    if ($('form.wffm-form').length > 0) {
        siteCoreRequired();
    }

    //Stick header
    var propertyStickyNav = $('.property-homepage-header .main-nav').not('.second');
    if (propertyStickyNav.length) {
        var propertyNavTop = propertyStickyNav.offset().top;
        if ($('.property-homepage-header').length > 0) {
            $(window).on('scroll', function() {
                var windowTop = $(window).scrollTop();
                if (windowTop >= propertyNavTop) {
                    propertyStickyNav.addClass('stick');
                    $(".staff-profile-wrap.display").css("top", "70px");
                } else {
                    propertyStickyNav.removeClass('stick');
                    $(".staff-profile-wrap.display").css("top", "0");
                }
            });
        }
    }

    //IT-756
    if ($(".property-homepage-header").length > 0) {
        $(".staff-profile-wrap").css("top", "70px");
    } else {
        $(".staff-profile-wrap").css("top", "0");
    }

    //It-877
    if ($('.property-price-filter li').length > 1) {
        if ($('.property-price-filter li').find('a').hasClass('active')) {
            $('.property-price-filter li').find('a.active').css("text-decoration", "underline");
        }
    }


    if ($('#green-listing').length > 0) {
        let green_list_js = $('#green-listing').data('js');
        window.dcp.injectJSReference(green_list_js, green_list_js);
    }

    if ($('.properties-news-module').length > 0) {
        let propertyNewsJs = $('.properties-news-module').data('js');
        window.dcp.injectJSReference(propertyNewsJs, propertyNewsJs);
    }

    //property search
    var propSearchType = '';
    if ($('.property-price-filter li').length > 1) {
        $('[data-apartment-selection]').on('click', function(e) {
            $('[data-land-selection]').removeClass('active').removeAttr('style');
            $('[data-homes-selection]').removeClass('active').removeAttr('style');
            $('[data-apartment-selection]').addClass('active').css('text-decoration', 'underline');
            $('[data-homeandland-selection]').removeClass('active').removeAttr('style');
            $('#price-filter-column').addClass("price-filter-home").css('text-decoration', 'underline');
            $('#price-filter-column').removeClass("price-filter-land").removeAttr('style');
            $("a[class*='land-option'],div[class*='land-option']").removeClass('show');
            $("a[class*='homes-option'],div[class*='homes-option']").addClass('show');
            propSearchType = $(this).data('searchType');
            $('input[name="SearchType"]').val(propSearchType);
        });
        $('[data-homes-selection]').on('click', function(e) {
            $('[data-land-selection]').removeClass('active').removeAttr('style');
            $('[data-apartment-selection]').removeClass('active').removeAttr('style');
            $('[data-homes-selection]').addClass('active').css('text-decoration', 'underline');
            $('[data-homeandland-selection]').removeClass('active').removeAttr('style');
            $('#price-filter-column').addClass("price-filter-home").css('text-decoration', 'underline');
            $('#price-filter-column').removeClass("price-filter-land").removeAttr('style');
            $("a[class*='land-option'],div[class*='land-option']").removeClass('show');
            $("a[class*='homes-option'],div[class*='homes-option']").addClass('show');
            propSearchType = $(this).data('searchType');
            $('input[name="SearchType"]').val(propSearchType);
        });


        $('[data-land-selection]').on('click', function(e) {
            $('[data-land-selection]').addClass('active').css('text-decoration', 'underline');
            $('[data-homes-selection]').removeClass('active').removeAttr('style');
            $('[data-apartment-selection]').removeClass('active').removeAttr('style');
            $('[data-homeandland-selection]').removeClass('active').removeAttr('style');
            $('#price-filter-column').removeClass("price-filter-home").removeAttr('style');
            $('#price-filter-column').addClass("price-filter-land").css('text-decoration', 'underline');
            $("a[class*='homes-option'],div[class*='homes-option']").removeClass('show');
            $("a[class*='land-option'],div[class*='land-option']").addClass('show');
            propSearchType = $(this).data('searchType');
            $('input[name="SearchType"]').val(propSearchType);
        });

        $('[data-homeandland-selection]').on('click', function(e) {
            $('[data-homeandland-selection]').addClass('active').css('text-decoration', 'underline');
            $('[data-homes-selection]').removeClass('active').removeAttr('style');
            $('[data-apartment-selection]').removeClass('active').removeAttr('style');
            $('#price-filter-column').addClass("price-filter-home").css('text-decoration', 'underline');
            $('#price-filter-column').removeClass("price-filter-land").removeAttr('style');
            $("a[class*='land-option'],div[class*='land-option']").removeClass('show');
            $("a[class*='homes-option'],div[class*='homes-option']").addClass('show');
            propSearchType = $(this).data('searchType');
            $('input[name="SearchType"]').val(propSearchType);
        });
    }
      
    //Heading with backing IT-1982 //
    if ($('body.shellcoverebrand2020water1').length > 0 || $('body.shellcoveexperiencetw').length > 0 || $('body.thepeninsulabeige').length > 0 ) {
        var heading_selector = $('section.our-properties-categories .ui.container .ui.grid.four .column');
        $.each(heading_selector, function(){
        shellCoveBg($(this).find('a h3'));
        });
       // console.log(heading_selector); 
    if ($('body.shellcoverebrand2020water1').length > 0 || $('body.shellcoveexperiencetw').length > 0 || $('body.thepeninsulabeige').length > 0) {
        var carousel_heading_selector = $('.properties-carousel2 .slider-2 .slick-content h2');
        $.each(carousel_heading_selector, function(){
        shellCoveBg($(this));
        }); 
        //console.log(carousel_heading_selector);         
    }  
    if ($('body.shellcoverebrand2020water1').length > 0 || $('body.shellcoveancora').length > 0 || $('body.shellcoveexperiencetw').length > 0 || $('body.thepeninsulabeige').length > 0) {
        var carousel_heading_selector_h1 = $('.properties-carousel2 .slider-2 .slick-content h1');
        $.each(carousel_heading_selector_h1, function(){
        shellCoveBg($(this));
        });
        //console.log(carousel_heading_selector_h1);         
    }   
    if ($('body.shellcoverebrand2020water1').length > 0 || $('body.shellcoveexperiencetw').length > 0 || $('body.thepeninsulabeige').length > 0) {
        var carousel_heading_selector_h2 = $('.the-collection-module h2.title');
        $.each(carousel_heading_selector_h2, function(){
        shellCoveBg($(this));
        });
       // console.log(carousel_heading_selector_h2);         
    } 
    
    if ($('body.thepeninsulabeige').length > 0) {
        var fullwidthBanner_heading_selector = $('.full-width-banner .ui.container .content-wrapper .content h2');
        $.each(fullwidthBanner_heading_selector, function(){
        shellCoveBg($(this));
        });
       // console.log(fullwidthBanner_heading_selector);         
    }

}



    $(function() {
        $('.lazy').lazy({
            threshold: 0,
            effect: 'fadeIn',
            eleLoader: function(element) {

                element.trigger("load");

            },
            onerror: function(element) {
                console.log("error");
            }
        });

        //lazy load for awards listing module
        $('.awards-module .select-year a, .awards-module a.load-more-link').each(function(){
            $(this).on('click', function() {
                $('.awards-module img.lazy').lazy({
                    threshold: 0,
                    bind: "event"
                });
            });
        });
    });
    

    $('.email-registration #email_address_submit').on('click', function() {
        $('.email-registration .email-registration-container').hide();
        $('.email-registration .result-container').show();
    });

    $('.mobile-carousel').slick({
        slidesToShow: 1,
        infinite: true,
        dots: true,
        arrows: true,
        fade: true,
        speed: 1600,
        autoplay: true,
        autoplaySpeed: 5000,
        //dotsClass: 'homepage-mobile-dots'
    });

    if ($('.icon-wechat').length > 0) {
        $('.top-nav .icon-wechat,.homepage-footer .icon-wechat,.footer-strip .icon-wechat').popup({
            inline: true,
            hoverable: true,
            delay: {
                show: 300,
                hide: 800
            }
        });
        $('body').on('click touch', function(e) {
            if ($(e.target).closest('.top-nav .popup,.homepage-footer .popup,.footer-strip .popup').length != 0 || $(e.target).closest('.icon-wechat').length != 0) {
                return false;
            }
            $('.top-nav .popup,.homepage-footer .popup,.footer-strip .popup').fadeOut('fast');
        });
    }
    if ($('.sidebar .icon-wechat').length > 0 || isMobile) {
        $('.sidebar .icon-wechat,.homepage-footer .icon-wechat,.footer-strip .icon-wechat').on('click', function(e) {
            e.preventDefault();
            $(this).siblings('.ui.popup').fadeToggle('fast');
            $(this).removeClass('inactive');
            if ($('.sidebar .popup,.homepage-footer .popup,.footer-strip .popup').length > 0) {
                setTimeout(function() {
                    $('.sidebar .popup,.homepage-footer .popup,.footer-strip .popup').fadeOut('fast');
                    $('.icon-wechat').addClass('inactive');
                }, 4000);
            }
        });
        /*$(document).on('click touch',function(e){
           if($(e.target).closest('.sidebar .popup,.homepage-footer .popup').length != 0 || $(e.target).closest('.icon-wechat').length != 0){
                return false;
           }              
           $('.sidebar .popup,.homepage-footer .popup').fadeOut('fast');
        });*/

    }

    /* if(('.properties-carousel').length > 0){
        propertyHeaderImg();
    }
*/
    if ($('.properties-carousel').length > 0 && $('.properties-carousel2').length > 0) {
        var $slick_carousel = $('.properties-carousel .slider-1');
        $slick_carousel.on('init', function(ev, slick) {
            var currentSlide = $(slick.$slider).find(".slick-current");
            if ($(slick.$slider).length == 1 || currentSlide.hasClass('autoplay-slide')) {
                var currentVideo = currentSlide.children().children('video');
                if (currentVideo.data('play') == "autoplay") {
                    currentVideo[0].play();
                }
            }
            $slick_carousel.find('.slick-current').removeClass('slick-active').addClass('reset-animation');
            setTimeout(function() {
                $slick_carousel.find('.slick-current').removeClass('reset-animation').addClass('slick-active');
            }, 1500);
        });

        $('.properties-carousel .slider-1').slick({
            dots: true,
            dotsClass: 'slick-dots',
            fade: true,
            speed: 1600,
            autoplay: true,
            autoplaySpeed: 5000,
            asNavFor: '.slider-2'
        });
        $('.properties-carousel2 .slider-2').slick({
            asNavFor: '.slider-1',
            fade: true,
            speed: 1600,
            autoplay: true,
            autoplaySpeed: 5000,
            arrows: false
        });

        $('.properties-carousel .slider-1').on('afterChange', function(event, slick) {
            var currentSlide = $(slick.$slider).find(".slick-current");

            if (currentSlide.hasClass('autoplay-slide')) {
                var currentVideo = currentSlide.children().children('video');
                if (currentVideo.data('play') == "autoplay") {
                    currentVideo[0].play();
                }
            } else {
                if ($('.properties-carousel .autoplay-slide').length > 0) {
                    $('.properties-carousel .autoplay-slide video')[0].pause();
                }
            }
        });
        $('.properties-carousel,.properties-carousel2').on('mouseenter touchstart', function() {
            $('.properties-carousel .slick-slider, .properties-carousel2 .slick-slider, .homepage-header .slick-slider').slick('slickPause');
        });
        $('.properties-carousel,.properties-carousel2').on('mouseleave touchend', function() {
            $('.properties-carousel .slick-slider, .properties-carousel2 .slick-slider, .homepage-header .slick-slider').slick('slickPlay');
        });

        /*$('.properties-carousel .not-autoplay').each(function () {
            var videoId = $(this).attr('data-id');
            $(this).children('.play-btn').on('click', function(){
                $('.fullscreen.modal')
                .modal({
                    onVisible: function() {
                        console.log(videoId);
                       $(videoId)[0].play();
                       $('.property-homepage-header .slick-slider').slick('slickPause');
                    },
                    onHidden: function() {
                       $(videoId)[0].pause();
                       $('.property-homepage-header .slick-slider').slick('slickPlay');
                    }
                  })
                .modal('show');
             });
        });*/
        $('.properties-carousel .not-autoplay .play-btn').on('click', function() {
            var videoId = $(this).parent().attr('data-id');
            //console.log(videoId);
            $('.fullscreen.modal')
                .modal({
                    onVisible: function() {
                        $(videoId).show();
                        $(videoId)[0].play();
                        $('.property-homepage-header .slick-slider').slick('slickPause');
                    },
                    onHidden: function() {
                        $(videoId).hide();
                        $(videoId)[0].pause();
                        $('.property-homepage-header .slick-slider').slick('slickPlay');
                    }
                })
                .modal('show');
        });
    }

    // Hide Carousel if no content 
    if ($('.properties-carousel').length > 0 && $('.properties-carousel2').length > 0) {
        hidecarousel2();
    }

    if ($('.secondary-nav-carousel').length > 0) {
        $('.secondary-nav-carousel').slick({
            centerMode: false,
            slidesToShow: 1,
            infinite: false,
            dots: false,
            arrows: false,
            variableWidth: true
        });
    }

    /* $('.media-carousel .media-item img').click(function() {
         console.log('clekjb');
         var image = $(this).attr('src');
         $('.img-modal').css("background", "#333 url(" + image + ") no-repeat center center fixed").fadeIn(200);
         return false;
     });*/

    $('.img-modal').click(function() {
        $(this).fadeOut(200);
    });

    $('#homepagebgvid').on('click', function() {
        vidplay();
    });

    var mobileOS = getMobileOperatingSystem();
    // Hamburger sidebar menu
    $(document).on('click', '.open-sidebar, .close-sidebar', function() {
        if ($('.pusher').hasClass('notransition')) {
            $('.pusher').removeClass('notransition');
        }
        var sidebar = $('.ui.sidebar');
        sidebar.sidebar('toggle');
        sidebar.toggleClass('open');
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        sidebar.attr('style', 'width:' + winWidth + 'px;' + 'height:' + winHeight + 'px!important');
        if (sidebar.hasClass('open')) {
            if (mobileOS == "Android") {
                $('html').attr('style', 'overflow:hidden');
            }
        } else {
            $('html').removeAttr('style');
        }
    });

    $('a[data-lightbox]').on('click', function() {
        $('.ui.sidebar').css('z-index', '1');
        $('.lb-close').on('click', function() {
            $('.ui.sidebar').css('z-index', '102');
        });
    });
    if (typeof lightbox !== 'undefined') {
        lightbox.option({
            'wrapAround': true
        });
    }

    $('.ui.sidebar .search-wrap i.search').on('click', function() {
        $('.ui.sidebar .search-wrap form').submit();
    });

    if ($('.isAnchor').length > 0) {
        var smpSidebar = $('.ui.sidebar');
        $('.sticky-buttons .isAnchor').on('click', function(e) {
            e.preventDefault();
            smpSidebar.sidebar('hide');
            smpSidebar.removeClass('open');
            $('html').removeAttr('style');
            var sectionName = $(this).attr("href");
            //console.log(sectionName);
            var sectionOffsetTop = $(sectionName).offset().top - 70;
            //console.log(sectionOffsetTop);
            $("html, body").animate({
                scrollTop: sectionOffsetTop
            }, 1000);
        });
    }



    if ($('.ui.sidebar').find('.has-subnav').length > 0) {
        $('.item.has-subnav .ui.subnavitem i').click(function(e) {
            e.preventDefault();
            $(this).parent().siblings('ul').slideToggle();
            $(this).parent().toggleClass('open');
        });
    }

    // Global search
    $('.top-nav .search-button').on('click', function() {
        /*$('.top-nav a').not('a.search-button').fadeOut();*/
        $('.top-nav a').fadeOut();
        $('.top-nav span').fadeOut();
        $('.search-wrap').fadeIn();
        $('.search-wrap input.search').focus();
    });

    $('.close-search').on('click', function() {
        $('.top-nav a').fadeIn();
        $('.top-nav span').fadeIn();
        $('.search-wrap').fadeOut();
        $(this).siblings('input.search').val('');
    });

    if ($('.standard-content .video-frame').length > 0) {
        initYouTube();
    }


    $('.media-carousel-wrap').each(function(index) {
        var _this = $(this);
        var currentMediaWrap = _this.addClass('item-no-' + index);
        if ($(this).hasClass('media-carousel-single')) {} else {
            var mediaCarousel = currentMediaWrap.find('.media-carousel');
            var carousel = mediaCarousel.not('.sceditor');

            carousel.on('init', function(event, slick) {
                initYouTube();
            });

            carousel.not('.sceditor').slick({
                centerMode: true,
                centerPadding: '450px',
                slidesToShow: 1,
                infinite: true,
                appendArrows: mediaCarousel,
                lazyLoad: 'ondemand',
                autoplay: true,
                autoplaySpeed: 6000,
                speed: 2000,
                adaptiveHeight: false,
                responsive: [{
                    breakpoint: 2000,
                    settings: {
                        centerPadding: '400px'
                    }
                }, {
                    breakpoint: 1800,
                    settings: {
                        centerPadding: '300px'
                    }
                }, {
                    breakpoint: 1600,
                    settings: {
                        centerPadding: '200px'
                    }
                }, {
                    breakpoint: 1400,
                    settings: {
                        centerPadding: '150px'
                    }
                }, {
                    breakpoint: 1200,
                    settings: {
                        centerPadding: '100px'
                    }
                }, {
                    breakpoint: 1024,
                    settings: {
                        centerPadding: '15px'
                    }
                }]
            });

            var mediaPlayBtn = currentMediaWrap.find('.play-button');
            var mediaArrows = currentMediaWrap.find('.slick-arrow');
            var pause = false;

            $(mediaPlayBtn).on('click', function() {
                mediaCarouselPause(mediaCarousel);
            });

            mediaCarousel.not('.sceditor').on("beforeChange", function(event, slick) {
                var currentSlide, slideType, player, command;


                //find the current slide element and decide which player API we need to use.
                currentSlide = $(slick.$slider).find(".slick-current");

                //determine which type of slide this, via a class on the slide container. This reads the second class, you could change this to get a data attribute or something similar if you don't want to use classes.
                slideType = currentSlide.attr("class").split(" ")[1];

                //get the iframe inside this slide.
                //player = currentSlide.find("iframe").get(0);
                if (slideType == "vimeo") {
                    command = {
                        "method": "pause",
                        "value": "true"
                    };
                } else {
                    command = {
                        "event": "command",
                        "func": "pauseVideo"
                    };
                }
                mediaCarouselPlay(mediaCarousel);
                mediaPlayBtn.fadeIn();
                stopVideos(mediaCarousel);
            });
        }
    });


    var smallMediaCarousel = $('.small-media-carousel');
    if (smallMediaCarousel.hasClass('small-media-carousel-popup')) {
        smallMediaCarousel.slick(getSliderPopupSettings());
        var property_category = smallMediaCarousel.siblings("ul.property-category").find(".active").data("property-category");
        update_properties_popup(property_category);

        $('.property-category li, .secondary-nav-carousel a').on('click', function() {
            var property_category = $(this).attr('data-property-category');
            /* console.log(property_category);*/
            update_properties_popup(property_category);
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
        });
    } else {

        smallMediaCarousel.slick(getSliderSettings());
        var property_category = 'residential';
        update_properties(property_category);
        $('.property-category li, .secondary-nav-carousel a').on('click', function() {
            var property_category = $(this).attr('data-property-category');
            /* console.log(property_category);*/
            update_properties(property_category);
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
        });
    }

    if (('.featured-news-module-blog').length > 0) {
        featuredNewsBlog();
        $(window).on('resize',function() {
            featuredNewsBlog();
        });
    }

    if (('.properties-news-module').length > 0) {
        descCharMax();
        $(window).on('resize',function() {
            descCharMax();
        });
    }

    //4 brochure carousel
    var brochureCarousel = $('.brochure-carousel .small-media-carousel');
    brochureCarousel.slick('unslick');
    brochureCarousel.slick(getBrochureSliderSettings());

    //2 brochure carousel
    var brochureCarousel2 = $('.brochure-carousel.two-in-row .small-media-carousel');
    brochureCarousel2.slick('unslick');
    brochureCarousel2.slick(get2BrochureSliderSettings());



    if ($('.people-photos').length > 0) {
        var testimonialCarousel = $('.people-photos');
        var testimonialInfoCarousel = $('.people-info');
        testimonialCarousel.not('.sceditor').each(function(idx, item) {
            var carouselId = $(this).attr('id');
            var navForId = "navfor_" + carouselId;
            var prevId = "prev_" + carouselId;
            var nextId = "next_" + carouselId;
            $(this).slick({
                slide: "#" + carouselId + " .media-item",
                prevArrow: '#' + prevId,
                nextArrow: '#' + nextId,
                dots: true,
                //dotsClass: 'people-dots',
                slidesToShow: 1,
                infinite: true,
                fade: true,
                asNavFor: '#' + navForId,
                autoplay: true,
                autoplaySpeed: 5000,
                speed: 1500,
                adaptiveHeight: true,
                responsive: [{
                    breakpoint: 769,
                    settings: {
                        slidesToShow: 1,
                        infinite: true,
                        fade: false,
                    }
                }]
            });
        });

        testimonialInfoCarousel.not('.sceditor').each(function(idx, item) {
            var navForId = $(this).attr('id');
            var carouselId = navForId.replace("navfor_", "");
            $(this).slick({
                slide: "#" + navForId + " .people-info-item",
                centerMode: true,
                /* centerPadding: '0',*/
                slidesToShow: 1,
                slidesToScroll: 1,
                asNavFor: '#' + carouselId,
                arrows: false,
                fade: true,
                autoplay: true,
                autoplaySpeed: 5000,
                speed: 1500,
                adaptiveHeight: true
            });
        });

        $('.homepage-people').on('mouseenter touchstart', function() {
            $('.homepage-people .slick-slider').slick('slickPause');
        });
        $('.homepage-people').on('mouseleave touchend', function() {
            $('.homepage-people .slick-slider').slick('slickPlay');
        });
        $('.testimonials').on('mouseenter touchstart', function() {
            $('.testimonials .slick-slider').slick('slickPause');
        });
        $('.testimonials').on('mouseleave touchend', function() {
            $('.testimonials .slick-slider').slick('slickPlay');
        });
    }

    $('.award-tab').on('click', function(e) {
        e.preventDefault();
        $('.award-tab').removeClass('red-content');
        $(this).addClass('red-content');
        var award_year = $(this).attr('data-award-tab');
        update_awards(award_year);
    });

    $('.award-list .load-more-link').on('click', function(e) {
        //console.log('more');
        e.preventDefault();
        $(this).hide();
        $(this).siblings('.more').show();
    });

    $('.back-to-top, .top-icon').on('click', function(e) {
        e.preventDefault();
        scroll_to_top();
    });

    if ($('.range-slider')) {
        $('.range-slider').each(function(idx) {
            var min = $(this).data("range-min"),
                max = $(this).data("range-max");
            if (!min)
                min = 0;
            if (!max)
                max = 1000000;
            $(this).jRange({
                from: min,
                to: max,
                step: 50000,
                format: function(value, pointer) {
                    return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
                },
                //width: 235,
                showLabels: true,
                showScale: false,
                isRange: true,
                theme: 'theme-purple',
                ondragend: function(newVal) {

                    var vals = newVal.split(',');
                    if (vals && vals.length) {
                        var min = parseInt(vals[0]),
                            max = parseInt(vals[1]);
                        $('[name="MinPrice"]').val(min);
                        $('[name="MaxPrice"]').val(max);
                    }

                }

            });
        });
    }

    if ($('.range-slider-input input.text-box')) {
        $('.range-slider-input input.text-box').each(function(idx) {
            var min = $(this).data("range-min"),
                max = $(this).data("range-max");
            if (!min)
                min = 0;
            if (!max)
                max = 1000;
            $(this).jRange({
                from: min,
                to: max,
                step: 100,
                format: '%s',
                //width: 235,
                showLabels: true,
                showScale: false,
                isRange: true,
                theme: 'theme-purple',
                ondragend: function(newVal) {
                    var vals = newVal.split(',');
                    if (vals && vals.length) {
                        var min = parseInt(vals[0] * 1000),
                            max = parseInt(vals[1] * 1000);
                        $('[name="MinPrice"]').val(min);
                        $('[name="MaxPrice"]').val(max);
                    }

                }
            });
        });
    }

    $('.simple-radio .radio label').click(function() {
        $(this).children('span').addClass('input-checked');
        $(this).parent('.radio').siblings('.radio').children('label').children('span').removeClass('input-checked');
    });

    $('.price-filter-radio .radio label').click(function() {
        $(this).children('span').addClass('input-checked');
        $(this).parent('.radio').siblings('.radio').children('label').children('span').removeClass('input-checked');
    });

    $('.price-filter .ui.dropdown').dropdown('show');

    if ($('.four-media-carousel').length > 0) {
        if (!$('body').hasClass('edsquare')) {
            $('.four-media-carousel').not('.slick-initialized').slick(getSocialSliderSettings());
        }
    }
    if ($('.secondary-nav').find('.title').length > 0) {
        regionFilter();

        var windowWidth = $(window).width();
        $(window).on('resize',function() {
            if ($(window).width() != windowWidth) {
                windowWidth = $(window).width();
                regionFilter();
            }
        });
    }


    // Search result load more
    if ($('#getUpdatedContent .search-result').length > 0) {
        //lazyLoad();
        // $(window).resize(function() {
        //     lazyLoad();
        // });

        $('.secondary-nav .list-view a').on('click', function(e) {
            e.preventDefault();
            $(".secondary-nav .list-view a.active").removeClass("active");
            var currentView = $(this).attr('data-view');
            $(this).addClass('active');
            $('#getUpdatedContent .search-result ul.search-view-list').removeClass().addClass(currentView + '-view');

            if (currentView == "map") {
                $('#getUpdatedContent .search-result').addClass('map-search-result');
                $('.search-result #loadMore').hide();

                mapDetails();
                $(window).on('resize',function() {
                    mapDetails();
                });

            } else {
                $('#getUpdatedContent .search-result').removeClass('map-search-result');
                // Load More button only displayed in mobile view, 
                // keep this logic for future if mobile view can swtich dispaly mode
                if ($(".search-result li").length > 6 && $(".search-result li:hidden").length !== 0) {
                    $('.search-result #loadMore').show();
                }
            }
        });
    }

    if ($('.secondary-nav').find('.title').length > 0) {
        regionFilter();
        $(window).on('resize',function() { 
            regionFilter();
        });
    }

    if ($('.category-filter').length > 0) {
        newsCategoryFilter();
        var windowW = $(window).width();
        $(window).on('resize',function() {
            if ($(window).width() != windowW) {
                windowW = $(window).width();
                newsCategoryFilter();
            }
        });
    }


    if ($('#newsList').length > 0) {

        setupNewsPropertyView();
        $(window).on('resize',function() {
            setupNewsPropertyView();
        });

        //for the grid and filter berwick
        $('.list-news').on('click', function(e) {
            e.preventDefault();
            $('#newsList').removeClass('grid');
            $('#newsList').addClass('list');
            $('.grid-news').removeClass('active');
            $('.list-news').addClass('active');
        });

        $('.grid-news').on('click', function(e) {
            e.preventDefault();
            $('#newsList').removeClass('list');
            $('#newsList').addClass('grid');
            $('.list-news').removeClass('active');
            $('.grid-news').addClass('active');
        });
    }

    /* $(".four-media-carousel .body-copy p").shorten({
         "showChars" : 88
     });*/

    /*
    if($('.homepage-header').length > 0){        
        homeHeaderHeight();
        var windowHeight = $(window).height();
        // Resize Event
        $(window).resize(function(){
            if ($(window).height() != windowHeight) {
                windowHeight = $(window).height();
                homeHeaderHeight();
            }
        });
    }*/

    if ($('.ui.sidebar').length > 0) {
        sidebarSize();
        var windowWidth = $(window).width();
        // Resize Event
        $(window).on('resize',function() {
            if ($(window).width() != windowWidth) {
                windowWidth = $(window).width();
                sidebarSize();
            }
        });
    }

    if ($('.maps-type-list').length > 0) {
        var typeList = $('.maps-type-list ul');
        var typeHeader = $('.maps-type-list h5');

        typeHeader.on('click', function(e) {
            e.preventDefault();
            if ($(window).width() < 768) {
                /*typeList.hide();*/
                $(this).siblings('ul').slideToggle();
            }
        });
        if ($(window).width() >= 768) {
            typeList.show();
        }

        $(window).on('resize',function() {
            if ($(window).width() < 768) {
                typeList.hide();
            }
            if ($(window).width() >= 768) {
                typeList.show();
            }
        });
    }

    $(window).on('load', function() {
        if ($('.testimonials').length > 0 || $('.loyalty-reward-module').length > 0) {
            testimonialHeight();
            rewardHeight();
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            // Resize Event
            $(window).on('resize',function() {
                if ($(window).width() != windowHeight) {
                    windowWidth = $(window).width();
                    testimonialHeight();
                    rewardHeight();
                }
            });
        }
    });

    if ($('.hotspot').length > 0) {
        popUp();
    }

    if ($('.property-popup-header').length > 0) {
        headerPop();
    }

    // removing shadow for our-properties-categories module 
    var fourBoxShadow = $('section.our-properties-categories .ui.container .ui.grid.four .column');
    $(fourBoxShadow).each(function() {
        if ($(this).find('a h3').text().length > 0) {
            $(this).find('a').removeClass('remove-shadow');
        } else {
            $(this).find('a').addClass('remove-shadow');
        }
    });

    // check for the param in URL for editor mode sitecore
    /*if (getParameterByName('sc_mode') !== 'edit') {
        // expanded brochure char limits

        var exBrochureHeadingSpanLimit = 50;
        var exBrochureDescriptionLimit = 200;
        var exBrochureHeadingSpan = $('.brochure .title').find('h2 span.copy-text');
        var exBrochureDescription = $('.brochure .title').find('p');
        exBrochureHeadingSpan.text(trimChar(0, exBrochureHeadingSpan.text(), exBrochureHeadingSpanLimit));
        exBrochureDescription.text(trimChar(0, exBrochureDescription.text(), exBrochureDescriptionLimit));

        // static left brochure char limits
        var staticLeftHeadingLimit = 35;
        var staticLeftDescriptionLimit = 100;
        var staticLeftHeading = $('.static-brochure .brochure h2');
        var staticLeftDescription = $('.static-brochure .brochure p');
        staticLeftHeading.text(trimChar(0, staticLeftHeading.text(), staticLeftHeadingLimit));
        staticLeftDescription.text(trimChar(0, staticLeftDescription.text(), staticLeftDescriptionLimit));

        // static right brochure char limits
        var staticHeadingLimit = 35;
        var staticDescriptionLimit = 110;
        var staticHeading = $('.static-brochure .content h3');
        var staticDescription = $('.static-brochure .description p');
        staticHeading.text(trimChar(0, staticHeading.text(), staticHeadingLimit));
        staticDescription.text(trimChar(0, staticDescription.text(), staticDescriptionLimit));

        // brochure carousel description limit with 4 in row.
        var carouselBrochureHeadingLimit = 50;
        var carouselBrochureDescLimit = 90;
        $('.brochure-carousel:not(.two-in-row) article').each(function(index, el) {
            $(this).find('.copy-text .featured-property-title').text(trimChar(0, $(this).find('.copy-text .featured-property-title').text(), carouselBrochureHeadingLimit));
            $(this).find('.copy-text p').text(trimChar(0, $(this).find('.copy-text p').text(), carouselBrochureDescLimit));
        });

        // brochure carousel description limit with 2 in row.
        var carouselBrochureHeadingLimit2 = 50;
        var carouselBrochureDescLimit2 = 300;
        var carouselBrochureHeadingLimittab2 = 30;
        var carouselBrochureDescLimittab2 = 180;
        $('.brochure-carousel.two-in-row article').each(function(index, el) {
            if ($(window).width() > 1199) {
                $(this).find('.copy-text .featured-property-title').text(trimChar(0, $(this).find('.copy-text .featured-property-title').text(), carouselBrochureHeadingLimit2));
                $(this).find('.copy-text p').text(trimChar(0, $(this).find('.copy-text p').text(), carouselBrochureDescLimit2));
            } else {
                $(this).find('.copy-text .featured-property-title').text(trimChar(0, $(this).find('.copy-text .featured-property-title').text(), carouselBrochureHeadingLimittab2));
                $(this).find('.copy-text p').text(trimChar(0, $(this).find('.copy-text p').text(), carouselBrochureDescLimittab2));
            }
        });

        // standalone page heading 
        var fullPageHeadingLimit = 50;
        $('.full-size-brochure h3').text(trimChar(0, $('.full-size-brochure h3').text(), fullPageHeadingLimit))
    }*/


    $("a").not(".hotspot-module a").click(function(eventObject) {

        if ($(this).href != undefined || $(this).href != null) {

            var hostname = location.hostname,
                elem = $(this),
                linkHref = elem.attr("href"),
                isExternal = !linkHref.startsWith(hostname),
                isExternalPdf = isExternal && linkHref.match(/.pdf/),
                isIssuuPdf = linkHref.startsWith("https://issuu.com"),
                isRunWayIssuuPdf = linkHref.startsWith("https://frasersproperty-staging.runway.com.au/");
            isRunWayProdPdf = linkHref.startsWith("https://frasersproperty.runway.com.au/");

            if (isIssuuPdf || isRunWayIssuuPdf || isRunWayProdPdf) {
                var linkWidthGoal = $('#divlinkWithGoal');
                if (linkWidthGoal !== '') {
                    var dataSourceItemId = $('#divlinkWithGoal').attr('data-dataSourceItemId');
                    if (dataSourceItemId != undefined && dataSourceItemId !== '') {
                        var url = window.location.pathname;
                        console.log(dataSourceItemId + url);
                        RegisterGoal(url, dataSourceItemId);
                    }
                }
            }
        }
    });

});
// check for the param value in URL
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function featuredNewsBlog() {
    var descChar = $('.featured-news-module-blog .featured-property-desc');
    if ($(window).width() > 1023) {
        $('.featured-news-module-blog .small-media-carousel').slick('unslick');
        descCharLimit(descChar);
    } else {
        $('.featured-news-module-blog .small-media-carousel').slick(getSliderSettings());
    }
}

function descCharMax(descChar) {
    var descChar = $('.properties-news-module .properties-news-desc');

    if ($(window).width() > 1023) {
        descCharLimit(descChar);
    } else {
        descCharNoLimit(descChar);
    }
}

function descCharLimit(descChar) {
    descChar.each(function() {
        var t = $(this).text();
        if (t.length > 150) {
            $(this).html(
                t.slice(0, 150) + '...' +
                '<span style="display:none;">' + t.slice(150, t.length) + '</span>'
            );
        }
    });
}

function descCharNoLimit(descChar) {
    descChar.each(function() {
        var t = $(this).text();
        //$(this).html(t);

        if (t.length > 100 && $(this).children('span').length > 0) {

            //console.log(t);
            $(this).html(
                t.slice(0, 100) + t.slice(106, t.length)
            );
        }
    });
}

// showLoader
function showLoader() {
    var loaderDiv = "<div class=\"loader-container\"><div id=\"loader\" style=\"display:block\"></div></div>";
    $('body').append(loaderDiv);
}


// character trim function
function trimChar(start, value, end) {
    var val;
    value = value.trim();
    if (value.length > end) {
        val = value.substr(start, end);
        // val=val +'...';
    } else {
        val = value;
    }

    return val;
}

function mediaCarouselPause(thisMediaCarouselPause) {
    thisMediaCarouselPause.not('.sceditor').slick('slickPause');
}

function mediaCarouselPlay(thisMediaCarouselPlay) {
    thisMediaCarouselPlay.not('.sceditor').slick('slickPlay');
}

function instaMediaCarousel() {
    if ($('.insta-media-carousel').length > 0) {
        if (!$('body').hasClass('edsquare')) {
            $('.insta-media-carousel').not('.slick-initialized').slick(getSocialSliderSettings());
        }
    }

}

function addClassInsta() {
    var imgCont = $('.join-social-facebook-module').find('.instagram-wrap .small-media-item');
    $(imgCont).each(function() {
        var imageWidth = $(this).find('img');
        if (imageWidth.width() > 199 && imageWidth.height() > 199) {
            imageWidth.next().addClass('with-image');
        }
    });
}

function initYouTube() {
    var youtube = $('.video');

    for (var i = 0; i < youtube.length; i++) {
        var source = "https://img.youtube.com/vi/" + $(youtube[i]).data('id') + "/sddefault.jpg";
        var hasImg = $(youtube[i]).data('append');
        if (hasImg != '1') {
            var image = new Image();
            image.src = source;
            image.className = 'youtube-thumbnail';
            image.addEventListener('load', function() {
                $(youtube[i]).parent().append(image);
            }(i));
        }
    }

    jQuery.getScript("https://www.youtube.com/iframe_api", function(data, status, jqxhr) {
        loadPlayer();
    });
}

function newsCategoryFilter() {
    var categoryFilter = $('.category-filter .filter ul');
    var categoryLead = $('.category-filter .show-filter');
    if ($(window).width() < 1023) {
        if (categoryFilter.is(":visible")) {
            categoryFilter.hide();
            categoryLead.show();
            categoryLead.removeClass('active');
        }
        categoryLead.unbind('click').click(function(e) {
            e.preventDefault();
            categoryFilter.slideToggle();
            $(this).toggleClass('active');
            $(this).children('span').text(function(i, v) {
                return v === 'Show filters' ? 'Hide filters' : 'Show filters';
            });
        });
    } else {
        categoryFilter.show();
        categoryLead.unbind('click');
        categoryLead.removeClass('active');
        categoryLead.children('span').text('Show filters');
    }
}

function loadPlayer() {
    if ($('.video').length > 0) {
        $('.video').each(function(index) {
            var videoId = $(this).attr('data-id');
            var playerId = $(this).attr('id');
            if (playerId === '') {
                playerId = 'player-' + index;
                $(this).attr('id', playerId);
            }
            //onYouTubeIframeAPIReady(playerId,videoId);
        });
    }
}

// function onYouTubeIframeAPIReady(playerId, videoId) {
//     var player;
//     YT.ready(function() {
//         var player = YT.get(playerId);
//         if (player) {
//             return player;
//         };
//         player = new YT.Player(playerId, {
//             videoId: videoId,
//             events: {
//                 'onReady': onPlayerReady,
//                 'onStateChange': onPlayerStateChange
//             }
//         });
//     });
//     return player;
// }

// IT-617
function symmetricalHeight() {

    $(".search-result .grid-view.property-listing").find('li:nth-child(3n + 1)').each(function() {
        if ($(this).find(".link").text().trim() === '') {
            if ($(window).width() > 1199) {
                if ($(this).find(".title").text().trim().length <= 29) {
                    $(this).add($(this).nextAll().slice(0, 3)).each(function() {
                        $(this).css("height", "315px");
                    });
                } else {
                    $(this).add($(this).nextAll().slice(0, 3)).each(function() {
                        $(this).css("height", "345px");
                    });
                }
            } else if ($(window).width() > 991 && $(window).width() < 1200) {
                $(this).add($(this).nextAll().slice(0, 3)).each(function() {
                    $(this).css("height", "265px");
                });
            } else {
                $(".search-result .grid-view.property-listing").find('li').css("height", "auto");
            }
        }
        // else {
        //     $(this).removeAttr('style');
        // }
    });

}

function onPlayerReady(event) {
    var _thisReady = event.target
    _thisReady.playVideo();
    $(_thisReady["f"]).parent().find('.youtube-thumbnail').fadeOut('fast');
    $(_thisReady["f"]).parent().find('.play-button').fadeOut('fast');
    gaVideoClick(_thisReady["f"]);
}

function onPlayerStateChange(event) {}

function playFullScreen(elem) {
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
        elem.webkitRequestFullscreen();
    }
}

function stopVideos(currentVideo) {

    if (typeof(YT) !== 'undefined' && typeof(YT.Player) !== 'undefined') {
        YT.ready(function() {
            var currentVid = currentVideo.find('.video');
            currentVid.each(function(index, element) {
                var player = YT.get($(element).attr('id'));
                if (player && typeof player.stopVideo === 'function') {
                    player.stopVideo();
                    $(this).siblings("img").css("opacity", "1").css("pointer-events", "auto");
                }
            });
        });
    }
}

function getMobileOperatingSystem() {
    var userAgent = navigator.userAgent || navigator.vendor || window.opera;

    // Windows Phone must come first because its UA also contains "Android"
    if (/windows phone/i.test(userAgent)) {
        return "Windows Phone";
    }

    if (/android/i.test(userAgent)) {
        return "Android";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "iOS";
    }

    return "unknown";
}

function setupNewsPropertyView() {
    if ($(window).width() < 769) {
        $('#newsList').removeClass('list');
        $('#newsList').addClass('grid');
        $('.list-news').css({
            display: "none"
        });
        $('.grid-news').css({
            display: "none"
        });
        $('.separator').css({
            display: "none"
        });
    } else {
        $('.list-news').css({
            display: "inline"
        });
        $('.grid-news').css({
            display: "inline"
        });
        $('.separator').css({
            display: "inline"
        });
    }
}

function update_properties(property_category) {

    var count = 0;

    $('.property-data').each(function() {

        if ($(this).attr('data-property-category') == property_category) {
            $('.latest-properties-module .small-media-carousel').slick('unslick');
            $('.latest-properties-module .small-media-carousel').children().remove();
            $(this).children().clone().appendTo('.latest-properties-module .small-media-carousel');
            $('.latest-properties-module .small-media-carousel').slick(getSliderSettings());
        }
    });
}

function update_properties_popup(property_category) {
    var count = 0;
    $('.property-data').each(function() {
        if ($(this).attr('data-property-category') == property_category) {
            $('.latest-properties-module .small-media-carousel').slick('unslick');
            $('.latest-properties-module .small-media-carousel').children().remove();
            $(this).children().clone().appendTo('.latest-properties-module .small-media-carousel');
            $('.latest-properties-module .small-media-carousel').slick(getSliderPopupSettings());
        }
    });
}

function update_awards(award_year) {
    $('.more').hide();
    $('.load-more-link').show();
    $('.award-list').removeClass('active');
    $('.award-list.year-' + award_year).addClass('active');
}

function scroll_to_top() {
    /*$('body').animate({
        scrollTop: 0
    }, 500);*/
    $('html, body').animate({
        scrollTop: 0
    }, 500);
}

//function scroll_to_form() {
    // $('html, body').animate({
    //     'scrollTop': $('#enquireform').offset().top - 70
    // }, 10);
//}

function sidebarSize() {
    var winWidth = $(window).width();
    var sidebar = $('.ui.sidebar');

    sidebar.width(winWidth);
}


function getSliderSettings() {
    return {
        /*centerMode: true,*/
        centerPadding: '0',
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: false,
        dots: true,
        lazyLoad: 'ondemand',
        //dotsClass: 'slick-dots',
        //appendArrows: '.small-media-carousel',
        //asNavFor: '.small-media-description-wrap',
        responsive: [{
            breakpoint: 769,
            settings: {
                dots: true,
                //dotsClass: 'slick-dots',
                centerPadding: '0',
                slidesToShow: 1,
                slidesToScroll: 1,
                infinite: true
            }
        }]
    };
}

function getSliderPopupSettings() {
    return {
        centerMode: true,
        centerPadding: '190px',
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: true,
        responsive: [{
            breakpoint: 1364,
            settings: {
                centerPadding: '80px',
                slidesToShow: 2
            }
        }, {
            breakpoint: 1199,
            settings: {
                centerPadding: '0',
                slidesToShow: 1
            }
        }]
    };
}

function getSocialSliderSettings() {
    return {
        dots: true,
        infinite: false,
        speed: 300,
        centerPadding: '0',
        slidesToShow: 4,
        slidesToScroll: 4,
        dotsClass: 'slick-dots',
        arrows: true,
        lazyLoad: 'ondemand',
        responsive: [{
            breakpoint: 769,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
                centerPadding: '0',
                centerMode: true,
                dotsClass: 'slick-dots',
            }
        }]
    };
}

function headerPop() {
    var popupHeader = $('.property-popup-header');
    var windowWidth = $(window).width();

    if (windowWidth > 1024) {
        $('#explore').on('click',function(e) {
            e.preventDefault();
            $(this).parent('.top-nav').toggleClass('active');
            popupHeader.toggleClass('active');
            $('body').toggleClass('popupshow');
        });
    } else {
        if ($('body').hasClass('popupshow')) {
            $('#explore').parent('.top-nav').removeClass('active');
            popupHeader.removeClass('active');
            $('body').removeClass('popupshow');
        }
    }
}

$(window).on('resize',function() {
    initAccordion();
    headerPop();
});

function expandAccordion() {
    $('.accordion > .content').not(".global-accordion .accordion > .content").not("#media-details .ui.accordion > .content").each(function() {
        $(this).addClass('active');
    });
}

function contractAccordion() {
    $('.accordion > .content').not(".global-accordion .accordion > .content").not("#media-details .ui.accordion > .content").each(function() {
        $(this).removeClass('active');
    });
}

function initAccordion() {
    if ($(window).width() < 768) {
        contractAccordion();
        $('.ui.accordion').not(".global-accordion .ui.accordion").not("#media-details .ui.accordion").accordion();
    } else {
        expandAccordion();
    }
    $('.brochure .ui.accordion').accordion(); //new module added
}

function activeBrochure(elem) {

    setTimeout(function() {
        if (elem.hasClass("active")) {

            elem.closest(".brochure").addClass("active");
        } else {
            elem.closest(".brochure").removeClass("active");
        }

    }, 100);

}

function vidplay() {
    var video = document.getElementById("homepagebgvid");
    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
}

function restart() {
    var video = document.getElementById("Video1");
    video.currentTime = 0;
}

function regionFilter() {
    var regionListItem = $('.secondary-nav-list ul li');
    var regionContainer = $('.secondary-nav-list');
    var regionLead = $('.secondary-nav-list ul li.title');
    var regionLeadArrow = $('.secondary-nav-list .icon');
    if ($(window).width() < 769) {
        if (regionListItem.is(":visible")) {
            regionListItem.hide();
            regionLead.show();
            regionContainer.removeClass('open');
        }
        regionLeadArrow.off('click').on('click',function() {
            $(this).siblings().children('li').not('.title').slideToggle();
            $(this).parent().toggleClass('open');
            return false;
        });
    } else {
        regionListItem.show();
        regionLeadArrow.off('click');
        regionContainer.removeClass('open');
    }
}

function lazyLoad() {
    $(".search-result li").slice(0, 6).show();
    $("#loadMore").on('click', function(e) {
        e.preventDefault();
        $(".search-result li:hidden").slice(0, 6).slideDown();
        if ($(".search-result li:hidden").length === 0) {
            $("#loadMore").fadeOut();
        }
    });
}


function radians(degrees) {
    return degrees * Math.PI / 180;
}

// Anchor links: Add anchor scroll effect to all link fields
function addScrollEffect() {
    $('a.addAnimation[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            // Figure out element to scroll to
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            // Does a scroll target exist?
            if (target.length) {
                // Only prevent default if animation is actually gonna happen
                event.preventDefault();
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000, function() {
                    // Callback after animation
                    // Must change focus!
                    var $target = $(target);
                    $target.focus();
                    if ($target.is(":focus")) { // Checking if the target was focused
                        return false;
                    } else {
                        $target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
                        $target.focus(); // Set focus again
                    }
                });
            }
        }
    });
}


$(function() {
    $.fn.addPlayButtonSVG = function(x, y, side, colorclass) {
        $('.media-carousel-wrap').append('<div class="play-button-color">&nbsp;</div>');
        $('.video-link,.video-frame').append('<div class="play-button-color">&nbsp;</div>');
        $('.new-modal .image-link, .new-modalvideo .small-media-wrap, .new-latestmodal .small-media-wrap').append('<div class="play-button-color">&nbsp;</div>');
        $('.icon-carousel .video-icon').append('<div class="play-button-color">&nbsp;</div>');
        var rgbValue = $(colorclass).css('background-color');
        var color = rgbValue;
        var adjacent = Math.cos(radians(30)) * side;
        var svgOuter = '<svg class="svg-play-outer"><circle cx="60" cy="60" r="60" fill="white" fill-opacity="0.9" /></svg>';
        var svg = '<svg class="svg-play" height="' + (y + side) + '" width="' + (x + adjacent) + '"><polygon points="' +
            x + ' ' + y + ', ' + (x + adjacent) + ' ' + (y + side / 2) + ', ' + x + ' ' + (y + side) + '" fill="' + color + '" stroke-width="1" /></svg>';
        this.append(svgOuter);
        this.append(svg);
        $('.svg-play-outer>circle, .svg-play').hover(function() {
            $(this).parents('.play-button').find('.svg-play-outer>circle').css({
                "fill": color,
                transition: "0.2s"
            });
            $(this).parents('.play-button').find('.svg-play>polygon').css({
                "fill": "white",
                transition: "0.2s"
            });
        }, function() {
            $(this).parents('.play-button').find('.svg-play>polygon').css({
                "fill": color,
                transition: "0.2s"
            });
            $(this).parents('.play-button').find('.svg-play-outer>circle').css({
                "fill": "white",
                transition: "0.2s"
            });
        });

        $(".burwood-brickworks-secondary-new .play-button .svg-play-outer>circle").css("fill", color);
        $(".burwood-brickworks-secondary-new .play-button .svg-play>polygon").css("fill", "white");
        $(".burwood-brickworks-secondary-new .svg-play-outer>circle, .burwood-brickworks-secondary-new .svg-play").hover(function() {
            $(this).parents(".play-button").find(".svg-play-outer>circle").css({
                fill: "white",
                transition: "0.2s"
            });
            $(this).parents(".play-button").find(".svg-play>polygon").css({
                fill: color,
                transition: "0.2s"
            })
        }, function() {
            $(this).parents(".play-button").find(".svg-play>polygon").css({
                fill: "white",
                transition: "0.2s"
            });
            $(this).parents(".play-button").find(".svg-play-outer>circle").css({
                fill: color,
                transition: "0.2s"
            })
        });
    };
}(jQuery));


function initDropdowns() {
    $('.ui.dropdown,select').not('.property-map-filter-select').dropdown();
    $('.ui.dropdownselection select').not('.property-map-filter-select').dropdown();
}



function showSustainability(view) {

    $("a[class*='show'],section[class*='show']").removeClass('show');

    switch (view) {
        case 1:
            $("a[class*='sus-view1'],section[class*='sus-view1']").addClass('show');
            break;

        case 2:
            $("a[class*='sus-view2'],section[class*='sus-view2']").addClass('show');
            break;

        case 3:
            $("a[class*='sus-view3'],section[class*='sus-view3']").addClass('show');
            break;
        default:
            break;
    }

    $('html, body').animate({
        scrollTop: $("a[class*='show'],section[class*='show']").offset().top
    }, 1000);

}

function mapDetails() {
    if ($(window).width() > 768) {
        $('ul.map-view li').each(function() {
            $(this).on('click', function() {
                $('.map-view-detail-panel').show();
                $('.button-close').on('click',function() {
                    $('.map-view-detail-panel').hide();
                });
                return false;
            });
        });
    } else {
        $('ul.map-view li').each(function() {
            $(this).on('click',function() {
                $('.map-view-detail-panel').hide();
                var url = $(this).children('a').attr('data-url');
                if (url !== '') {
                    window.location.href = url;
                }
                e.preventDefault();
            });
        });
    }
}

function homeHeaderHeight() {
    if ($(window).width() > 1023) {
        var homeHeroHeight = $('.homepage-header').height();
        var ctaHeight = $('.cta-strip').height();
        var winHeight = $(window).height();
        var findProperty = $('.homepage-header .find-property-wrap');

        homeHeroHeight = winHeight - ctaHeight - 100;
        $('.homepage-header').height(homeHeroHeight);

        if (winHeight <= 680) {
            findProperty.css({
                "position": "relative",
                "top": "auto"
            });
        }
    } else {
        $('.homepage-header').height('auto');
    }
}

function testimonialHeight() {
    var panelHeight = 0;
    if ($(window).width() >= 1024) {
        var panelHeight = $('.testimonials .people-photos').height();
        var infoHeight = $('.testimonials .people-info');
        infoHeight.height(panelHeight);
    }
}

function rewardHeight() {
    if ($(window).width() >= 1024) {
        var panelHeight = $('.loyalty-reward-module .loyalty-media').height();
        var infoHeight = $('.loyalty-reward-module .right-panel-content');
        infoHeight.height(panelHeight);
    }
}

function toggleQuery() {
    var selectionText = $('.opportunity-category .opportunity-selection').find(":selected").text();

    if (selectionText.toLowerCase().indexOf("marina") >= 0) {
        $(".common-query").css("display", "none");
        $(".corporate-query").css("display", "none");
        $(".marina-enquiry").css("display", "block");
    } else if ((selectionText.toLowerCase().indexOf("retail") >= 0) || (selectionText.toLowerCase().indexOf("commercial") >= 0) || (selectionText.toLowerCase().indexOf("office") >= 0) || (selectionText.toLowerCase().indexOf("business") >= 0)) {
        $(".common-query").css("display", "none");
        $(".marina-enquiry").css("display", "none");
        $(".corporate-query").css("display", "block");
    } else if ((selectionText.toLowerCase().indexOf("home") >= 0) || (selectionText.toLowerCase().indexOf("first") >= 0) || (selectionText.toLowerCase().indexOf("second") >= 0) || (selectionText.toLowerCase().indexOf("property") >= 0) || (selectionText.toLowerCase().indexOf("buyer") >= 0) || (selectionText.toLowerCase().indexOf("investor") >= 0)) {
        $(".marina-enquiry").css("display", "none");
        $(".common-query").css("display", "block");
        $(".corporate-query").css("display", "block");
    }
}

function popUp() {
    var moveLeft = 0;
    var moveDown = 0;
    var offset = $(".hotspot").offset();
    $('area.popper').hover(function(e) {
        var target = '#' + ($(this).attr('data-popbox'));
        $(target).show();

        moveLeft = $(this).outerWidth();
        moveDown = ($(target).outerHeight() / 2);

    }, function() {
        var target = '#' + ($(this).attr('data-popbox'));
        if (!($("area.popper").hasClass("show"))) {
            $(target).hide();
        }
    });

    $('area.popper').on('mousemove',function(e) {
        var target = '#' + ($(this).attr('data-popbox'));
        var boxWidth = $(target).outerWidth();
        var boxHeight = $(target).outerHeight();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        var thisOffset = $(this).offset();

        moveLeft = (boxWidth / 2);
        moveDown = (boxHeight / 5);

        //var relativeLeft = e.pageX - parseInt($('.hotspot .ui.container').css("marginLeft").replace('px', ''));
        var relativeLeft = e.pageX - parseInt($(this).closest("div").css("marginLeft").replace('px', ''));
        //console.log($(this).closest("div").css("marginLeft").replace('px', ''));
        var leftD = parseInt(relativeLeft - (moveLeft));

        // var maxRight = leftD - moveLeft;
        // if (windowWidth < maxRight) { leftD = parseInt(relativeLeft - boxWidth + (moveLeft)); }

        var relativeTop = e.pageY - thisOffset.top;
        var topD = relativeTop + moveDown;

        var maxBottom = parseInt(e.pageY + boxHeight + moveDown);
        var windowBotton = windowHeight + $(document).scrollTop();

        if (maxBottom > windowBotton) {
            topD = relativeTop - moveDown - boxHeight;
        }
        $(target).css('top', topD).css('left', leftD);

    });
}

// IT-608
function replaceVid() {
    var sourceImg = $('.homepage-video-wrap').attr("data-ie-image");
    $('.homepage-video-wrap video').replaceWith('<div class="homepage-header-poster">' + '<img src="' + sourceImg + '">' + '</div>');
}

// IT-713
function equalHeightTwoColumn() {
    if ($(window).width() > 767) {
        var max = -1,
            _self = $(".newgrid .column .equalheight");
        _self.each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        _self.css({
            'height': max + 25
        });
    }
}

// IT-712
function solidBtn() {
    if ($(".property-life-at").css("background").indexOf("image") >= 0) {
        $(".property-life-at").find(".form-submit-border .btn").addClass("solidBtn");
    } else {
        $(".property-life-at").find(".form-submit-border .btn").removeClass("solidBtn");
    }
}

// IT-715 
function removeBrushStroke() {
    $("h1, h2, h3, h4, h5, h6, .head-hand-drawn-line-center, .head-hand-drawn-line-left").each(function(e) {
        if ($(this).text().trim().length == 0) {
            $(this).hide();
        }
    });
}

//It-754
function scrollBody() {
    $(".property-homepage-header .main-nav").not(".edsquare .property-homepage-header .main-nav").find("a.isAnchor").click(function(e) {
        var section = $(this).attr("href");
        if (section.indexOf('#') != -1) {
            e.preventDefault();
            var sectionOffset = $(section).offset().top - 70;
            $("html, body").animate({
                scrollTop: sectionOffset
            }, 2000);
        }
    });
}

//It-632
function navigationIpad() {
    $('.property-homepage-header .main-nav a.ui.dropdown').each(function() {
        var count = 0;
        $(this).on('click touchend', function(e) {
            count += 1;
            if (e.type == 'touchend') {
                if ($(this).find(".menu").text().length == 0) {
                    window.location.href = $(this).attr("href");
                } else {
                    if (count == 1) {
                        e.stopPropagation();
                        $(this).addClass("visible");
                        $(this).find(".menu").addClass("visible").addClass("transition");
                    } else {
                        window.location.href = $(this).attr("href");
                    }
                }
            }
        });
    });
}

//it-821
function equalizeHeight() {
    $(".testimonials").each(function() {
        $(".people-info-item").each(function() {
            if ($(window).width() >= 1024 && $(window).width() < 1366) {
                if ($(this).find(".tagline").text().length >= 130) {
                    $(this).parents(".people-info").css("min-height", "392px");
                }
            }
        });
    });
}

//it-861
function hideDropdownIE() {
    if ($('.general-form .dropdown').length > 0) {
        $(document).on('click', '.general-form .dropdown .item', function(e) {
            $(this).parent().removeClass('visible').removeAttr('style');
        });
    }
}

//it-845
function wffmDropdownIE() {
    if ($('.property-enquire-form .dropdown').length > 0) {
        $(document).on('click', '.property-enquire-form .dropdown .item', function(e) {
            $(this).parent().removeClass('visible').removeAttr('style');
        });
    }
}

jQuery(function() {
    if ($('a.modaal').length > 0) {
        $(window).on('resize',function() {
            var container = $('.modaal-iframe .modaal-container');
            if (container.length > 0) {
                var newHeight = GetFrameHeigth('1.2', '200', container.width(), '240');
                $(container).height(newHeight);
                //console.log("yes container" + newHeight);
            }
        });
    }

    // if (!$('body').hasClass('edsquare')) {
    $('.property-reasons').each(function() {
        var propertyList = $(this).find('ul>li').length;
        if (propertyList) {
            var _this = 'property-list-' + propertyList;
            $(this).addClass(_this);
        }
    });

    if ($('form.wffm-form').length != 0) {

        let checkboxInp = $('form.wffm-form'),
            inputCheck = $(checkboxInp).find('.checkbox');

        $(inputCheck).each(function() {
            let _this = $(this),
                requiredCheck = _this.find("input[type='checkbox']"),
                requiredCheckAttr = requiredCheck.attr('data-val-ischecked');
				
            if (requiredCheckAttr != undefined) {
                if (requiredCheckAttr.length != 0) {
                    $(requiredCheck).attr('required', 'required');
                    $(requiredCheck).css('background', 'red');
                }
            }
        });
		
		// Remove * sign for all the checkboxes
		$('input[type="checkbox"]').each(function(){
			if($(this).data('val-ischecked')){
				$(this).parent().parent().addClass('required');
			}
			else{
				$(this).parent().parent().removeClass('required');
			}			
		});

        var remLoad,
        getValueF = "";

        function removeLoader() {
            var loaderContainer = $('body > .loader-container');

            if(loaderContainer.length > 0) {
                var getNewValueF = $("form.wffm-form .btn.btn-default").next().val();
                if(getValueF != getNewValueF) {
                    $('body > .loader-container').remove();
                    // var sectionFormOffset= $("form.wffm-form").offset().top - 150;
                    // $("html, body").animate({
                    //     scrollTop: sectionFormOffset
                    // }, 2000);
                    clearTimeout(remLoad);
                }
            } else {
               clearTimeout(remLoad); 
            }
        }

        $("form.wffm-form .btn.btn-default").click(function() {
             getValueF = $("form.wffm-form .btn.btn-default").next().val();
            setTimeout(function(){
                remLoad = setInterval(removeLoader, 3000);
            }, 500);
        });


    }
	


    if ($('.disclaimer-wrap').length > 0) {
        $('.disclaimer a').each(function() {
            $(this).popup();
        });
        $('.disclaimer a').on('click', function(e) {
            e.preventDefault();
        });
    }

    jQuery('img[src*="marker-development"]').each(function() {
        var $img = jQuery(this);
        var imgURL = $img.attr('src');

        jQuery.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Add replaced image's classes to the new SVG
            if (typeof imgClass == 'undefined') {
                $svg = $svg.attr('class', 'marker-development');
            }
            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');

            // Check if the viewport is set, else we gonna set it if we can.
            if (!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
                $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'));
            }

            // Replace image with new SVG
            $img.replaceWith($svg);

        }, 'xml');
    });

    jQuery('img.properties-icon').each(function() {
        var $img = jQuery(this);
        var imgURL = $img.attr('src');

        jQuery.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Add replaced image's classes to the new SVG
            if (typeof imgClass == 'undefined') {
                $svg = $svg.attr('class', 'properties-icon float-right');
            }
            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');

            // Check if the viewport is set, else we gonna set it if we can.
            if (!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
                $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'));
            }

            // Replace image with new SVG
            $img.replaceWith($svg);

        }, 'xml');

    });

    $(".rtemorecontent").click(function() {
        $(this).parent().next('.secondarycontent').toggle();
        $(this).toggle();
        return false;
    });
    $(".rtelesscontent").click(function() {
        $(this).parent('.secondarycontent').toggle();
        $(this).parent('.secondarycontent').prev('.primarycontent').find('.rtemorecontent').toggle();
        return false;
    });

    adjustImage();
    $(window).on('resize',function() {
        adjustImage();
    });


    // IT-617
    if ($('.search-result .grid-view.property-listing').length > 0) {
        symmetricalHeight();
        $(window).on('resize',function() {
            symmetricalHeight();
        });
    }

    // IT-608
    if (document.documentMode || /Edge/.test(navigator.userAgent)) {
        replaceVid();

        //It-861
        hideDropdownIE();

        //it-845
        wffmDropdownIE();
    }


    // IT-713
    if ($('.two-column.newgrid').length > 0) {
        equalHeightTwoColumn();
        $(window).on('resize',function() {
            equalHeightTwoColumn();
        });
    }


    //IT-712
    if ($(".property-life-at").length > 0) {
        solidBtn();
    }

    //IT-715
    removeBrushStroke();

    //It-754
    if ($(".property-homepage-header .main-nav a.isAnchor").length > 0) {
        scrollBody();
    }

    if ($('.sidebar .isAnchor').length > 0 && ($('.sidebar .isAnchor').attr("href").indexOf('#') != -1)) {
        $('.sidebar .isAnchor').on('click', function(e) {
            $('.pusher').addClass('notransition');
            $('.ui.sidebar').sidebar('hide');
            $('html').removeAttr('style');

            var section = $(this).attr("href");
            var sectionOffset = $(section).offset().top - 86;
            $("html, body").animate({
                scrollTop: sectionOffset
            }, 2000);
        });
    }

    //It-632
    if ($('.property-homepage-header .main-nav a.ui.dropdown').length > 0) {
        navigationIpad();
    }

    //it-821
    if ($(".testimonials").length > 0) {
        equalizeHeight();
        $(window).on('resize', function() {
            equalizeHeight();
        });
    }

    //add animation effect on anchor links globally
    if ($("a.addAnimation").length > 0) {
        addScrollEffect();
    }

    scrollBar();

    //fixed contact us form globally
    $(window).on('resize',function(argument) {
        equalizeHeightMapwithForm();
    });

});

var isMobile = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
var isiPad = navigator.userAgent.toLowerCase().indexOf("ipad");

function toggleAccordion(accordionId, index) {
    var accordion = $('#' + accordionId).find('> li').eq(index),
        accordionH;

    accordion.toggleClass('open');

    // Required fix for slow rendering on mobile browsers
    if (isMobile === true) {
        if (accordion.hasClass('open') === true) {
            accordion.css({
                'max-height': '800px'
            });
        } else {
            accordion.css({
                'max-height': accordion.attr('data-height-closed')
            });
        }
    } else if (isiPad != "-1") {
        if (accordion.hasClass('open') === true) {
            accordionH = accordion.attr('data-height-open');
            accordion.css('height', 'auto');
        } else {
            accordionH = accordion.attr('data-height-closed');
            accordion.css('height', '40px');
        }
    } else {
        accordionH = accordion.attr(accordion.hasClass('open') === true ? 'data-height-open' : 'data-height-closed');
        accordion.css('height', accordionH);
    }
}

function refreshAccordions() {
    $('.reactive-accordion > li').each(function() {
        if (isMobile !== true) {
            $(this).css('height', 'auto').attr('data-height-open', $(this).outerHeight() + 'px');

            if ($(this).hasClass('open') === true) {
                $(this).css('height', $(this).attr('data-height-open'));
            } else {
                $(this).css('height', $(this).attr('data-height-closed'));
            }
        }
    });
}

function configureAccordions(accordionId) {
    var accordion = $('#' + accordionId),
        accordionToggleButton = '<button class="accordion-toggle-button"><div class="inner"></div></button>',
        accordionHeightClosed = 0;

    if (accordion.hasClass('collection-list') === true) {
        accordionHeightClosed = 40;
    }

    $('#' + accordionId).find('> li').each(function(i) {
        if ($(this).find('.accordion-toggle-button').length === 0) {
            $(accordionToggleButton).prependTo(this);
        }

        $(this).css({
            'display': 'block',
            'height': 'auto'
        });

        var hOpen = $(this).outerHeight();

        $(this).attr({
            'data-height-open': hOpen + 'px',
            'data-height-closed': accordionHeightClosed + 'px'
        }).css('height', accordionHeightClosed + 'px');

        // toggleAccordion(accordionId, i); // Open accordions by default

        if (isMobile === true) {
            $(this).css({
                'height': 'auto',
                'max-height': accordionHeightClosed + 'px'
            });
        }
    });
}

function accordionInit() {
    var reactiveAccordion = $('.reactive-accordion');
    if (reactiveAccordion.length > 0) {
        var totalAccordionLists = 0;

        reactiveAccordion.each(function() {
            totalAccordionLists += 1;
            var accordionId = 'accordion-list-' + totalAccordionLists;
            $(this).attr('id', accordionId);

            configureAccordions(accordionId);

            // $('#' + accordionId).imagesLoaded(function () {
            //  configureAccordions(accordionId);
            // });
        });

        reactiveAccordion.find('.accordion-toggle-button, .title-bar').on('click', function(e) {
            refreshAccordions(); // Required to avoid issues with @font-face load delays and incorrect accordian heights
            e.stopPropagation();
            var accordionId = $(this).closest('.reactive-accordion').attr('id'),
                index = $(this).closest('li').index();
            toggleAccordion(accordionId, index);
        });

        // Required to link title bar and accordion toggle button hover effects
        /* reactiveAccordion.find('.title-bar').hover(function () {
             $(this).closest('li').addClass('hover');
         }, function () {
             $(this).closest('li').removeClass('hover');
         });*/

        $(window).on('resize', function() {
            refreshAccordions();
        });
    }
}

function ShowVid(id, videoURL) {
    var videoPnl = $("#" + id);
    var videoPlayer = $("#" + id + "-player");
    var imgPnl = $("#" + id + "+ .video-link");

    if ($(imgPnl)) {
        $(imgPnl).css("display", "none");
        //console.log('working.. self');
    }

    if ($(videoPnl)) {
        $(videoPnl).addClass("active");
        $(videoPnl).fadeIn(200);
        $(videoPlayer).attr("src", videoURL);
        $(videoPnl).css("display", "block");
    }
}

function HideVid(id) {
    var videoPnl = $("#" + id);
    var videoPlayer = $("#" + id + "-player");

    if ($(videoPlayer)) {
        $(videoPlayer).attr("src", "");
    }

    if ($(videoPnl)) {
        $(videoPnl).css("display", "none");
        $(videoPnl).fadeOut(200);
        $(videoPnl).removeClass("active");
    }

    var videoPlayButton = $("#play-button-" + id);
    if ($(videoPlayButton)) {
        $(videoPlayButton).css("display", "block");
    }
}

function GetFrameHeigth(imgRatio, navWidth, containerWidth, mobileExtraHeight) {
    var imgWidth;
    var imgHeight;

    var winWidth = $(window).width();
    if (winWidth > 815) {
        imgWidth = parseInt(containerWidth) - parseInt(navWidth);
        imgHeight = (parseInt(imgWidth) / parseFloat(imgRatio)) + parseInt(40);
    } else {
        imgWidth = parseInt(containerWidth);
        imgHeight = (parseInt(imgWidth) / parseFloat(imgRatio));
        imgHeight = parseFloat(imgHeight) + parseInt(mobileExtraHeight);
    }

    return imgHeight;
}


function readURL(input, imgid) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
            $('#' + imgid)
                .attr('src', e.target.result);
            //.width(150)
            //.height(200);
        };

        reader.readAsDataURL(input.files[0]);
        var lastChar = imgid.substr(imgid.length - 1);
        lastChar = lastChar - 1;
        $('#' + imgid + "+ a").css("display", "block");
        $($('.uploader .preview-tile')[lastChar]).css("display", "block");
        $('#uploadImg' + index + ' + a').css("display", "block");
    }
}

/*IT-2021*/
function equalizeHeightMapwithForm() {

    if ($(window).width() > 768) {
        var maxHeightCM = 0;
        $('.property-contact-us .general-form, .property-contact-us .map').each(function() {
            var thisHeight = $(this).height();
            if (thisHeight > maxHeightCM) {
                maxHeightCM = thisHeight;
            }
        });
        $('.property-contact-us .general-form, .property-contact-us .map').height(maxHeightCM + 100);
    } else {
        $('.property-contact-us .general-form, .property-contact-us .map').height('inherit');
    }
}

function clear_file_input(index) {
    var input = $("#File" + index);
    //clear fields
    input.replaceWith(input.val('').clone(true));
    $('#path' + index).val(input.val());
    $('#uploadImg' + index).attr('src', '/Resources/Australand/Projects/img/no-preview.jpg');
    $('#uploadImg' + index + ' + a').css("display", "none");
    //$('#uploadImg' + index + ' + a').css('display', 'none');
    var i = index - 1;
    $($('.uploader .preview-tile')[i]).css("display", "none");
    $($('.uploader .preview-tile')[i]).css("display", "block");
    //$fileInput = $("#" + controlId);
    //$fileInput.replaceWith($fileInput = $fileInput.clone(true));
}


function adjustImage() {
    var poster = $(".homepage-header .homepage-header-poster"),
        IMG_W = 1600,
        viewW = Number($(window).width());
    if (poster != null && poster.length > 0 && viewW < IMG_W) {
        var offset = (viewW - IMG_W) / 2;
        offset = offset + "px";
        poster.css("left", offset);
    }
}

function indentifyContact() {
    //console.log("inside identifier method");
    var email = $(".wc-webchat.wc-online #wc-email").val();
    var name = $(".wc-webchat.wc-online #wc-name").val();
    var itemId = $("#txt_id").val();
    if (email != "") {
        $.ajax({
            url: "/Identity/IdentifyContact",
            type: "POST",
            data: {
                email: email,
                name: name,
                itemId: itemId
            },
            context: this,
            success: function(data) {
                //console.log("data " + data);
                //console.log("identified sucessfully");
                //console.log("success", data);
            },
            error: function(data) {
                //console.log("error", data);
            }
        });
    } else {
        //console.log("email is empty");
    }
}


// hide carousel if caption is blank
function hidecarousel2() {
    $('.property-homepage-header .properties-carousel2').each(function() {
        if ($(this).children().text().trim() === '') {
            $(this).hide();
        } else {
            $(this).show();
        }
    });
}

function siteCoreRequired() {
    $(".wffm-form .form-group").each(function() {
        var req = $(this).find("[data-val-required]");

        if(!req.hasClass('not-required')) {
            var _thisForm = $(this);
            if (req.length > 0) {
                _thisForm.addClass("required");
            } 
        }
    }); 
}

$(function() {
    if ($('.modaal').length > 0) {

        $('.modaal').modaal({
            width: 200,
            height: ($(window).height() - 50)
        });
    }

    setTimeout(calcImgHeight, 100);
    $(window).on('resize',function() {
        setTimeout(calcImgHeight, 100);
    });

    if (document.documentMode || /Edge/.test(navigator.userAgent)) {
        setTimeout(function() {
            $("img.lazy").each(function() {
                var newSrc = $(this).attr("data-src");
                $(this).attr("src", newSrc)
            });
        }, 2000);
    }
});

function calcImgHeight() {
    var carslHeight = $('.mobile-carousel').css("height"),
        slideImgHeight = $('.mobile-carousel .slick-slide img').css("height"),
        newImgHeihgt = parseInt(slideImgHeight) - parseInt(carslHeight);
    $(".home-overlay").css("bottom", newImgHeihgt + 15);
}

function globalPlayVideo() {
    $('.play-button').not(".properties-news-module .play-button, .featured-news-module .play-button").on('click', function(e) {
        var $playButton = $(this);
        var player = $(this).siblings('.video');
        if (player.length > 0 && typeof(YT) !== 'undefined' && typeof(YT.Player) !== 'undefined') {

            //stopVideos();
            YT.ready(function() {
                var playerId = player[0].id;
                var videoId = $(player[0]).data('id');
                if (playerId !== 'undefined' && playerId !== '' && videoId !== 'undefined' && videoId !== '') {
                    var YTPlayer = YT.get(playerId);

                    if (YTPlayer == undefined) {
                        YTPlayer = new YT.Player(playerId, {
                            videoId: videoId,
                            events: {
                                'onReady': onPlayerReady,
                                'onStateChange': onPlayerStateChange
                            },
                            playerVars: {
                                rel: 0
                            }

                        });

                    } else {
                        if (typeof YTPlayer.playVideo === 'function') {
                            YTPlayer.playVideo();
                            $playButton.fadeOut('fast');
                            gaVideoClick(YTPlayer.a);
                        }
                    }
                }
            });
        }
    });
}



// 4 brochure carousel setting
function getBrochureSliderSettings() {
    return {

        centerPadding: '0',
        slidesToShow: 4,
        slidesToScroll: 4,
        infinite: false,
        dots: true,
        arrows: false,


        responsive: [{
            breakpoint: 769,
            settings: {
                dots: true,
                centerPadding: '0',
                slidesToShow: 1,
                slidesToScroll: 1,
                adaptiveHeight: true,
                infinite: true
            }
        }]
    };
}

// 2 brochure carousel setting
function get2BrochureSliderSettings() {
    return {

        centerPadding: '0',
        slidesToShow: 2,
        slidesToScroll: 2,
        infinite: false,
        dots: true,
        arrows: false,


        responsive: [{
            breakpoint: 769,
            settings: {
                dots: true,
                centerPadding: '0',
                slidesToShow: 1,
                slidesToScroll: 1,
                adaptiveHeight: true,
                infinite: true
            }
        }]
    };
}

function RegisterGoal(url, id) {
    jQuery.ajax({
        type: "POST",
        url: '/evbase/RegisterGoal',
        data: {
            "contextItemPath": url,
            "goalItemId": id
        },
        success: function(obj) {
            console.log(id);
        },
        dataType: 'json'
    });
}



function scrollBar() {
    if ($(".wffm-form .dropdown").length) {
        $(".wffm-form .dropdown .menu").niceScroll({
            autohidemode: false,
            smoothscroll: true,
            hidecursordelay: 10
        });
    }
}

// IT-1982 //
function shellCoveBg(heading_selector){
    var words = $(heading_selector).html().replace('<br>', ' ');
    $(heading_selector).empty();
    var words= words.split(' ');
        $.each(words, function(i, v) {
             $(heading_selector).append($("<span>").text(v));
        });
}
function shellCoveBg(carousel_heading_selector){
    var words = $(carousel_heading_selector).text().split(" ");
    $(carousel_heading_selector).empty();
    $.each(words, function(i, v) {
        if(v.trim().length!==0){
            $(carousel_heading_selector).append($("<span>").text(v));
        }       
      
    });
}
function shellCoveBg(carousel_heading_selector_h1){
    var words = $(carousel_heading_selector_h1).text().split(" ");
    $(carousel_heading_selector_h1).empty();
    $.each(words, function(i, v) {
        if(v.trim().length!==0){
            $(carousel_heading_selector_h1).append($("<span>").text(v));
        }       
      
    });
}
function shellCoveBg(carousel_heading_selector){
    var words = $(carousel_heading_selector).text().split(" ");
    $(carousel_heading_selector).empty();
    $.each(words, function(i, v) {
        if(v.trim().length!==0){
            $(carousel_heading_selector).append($("<span>").text(v));
        }
    });
}

function shellCoveBg(fullwidthBanner_heading_selector){
    var words = $(fullwidthBanner_heading_selector).text().split(" ");
    $(fullwidthBanner_heading_selector).empty();
    $.each(words, function(i, v) {
        if(v.trim().length!==0){
            $(fullwidthBanner_heading_selector).append($("<span>").text(v));
        }
    });
}

$(window).on('load', function(){
    setTimeout(calcImgHeight, 100);
    // IT-614 play video in modal
    $(document).on('click', 'a.new-modal', function() {
        var modelHtml = $(this).parent('.news-item').find('.embed-responsive'),
            modelId = modelHtml.attr("data-url");
        modelHtml.html("<iframe src=\"https://www.youtube.com/embed/" + modelId + "?rel=0&autoplay=1" + "\"></iframe>");
    });

    // IT-678 play video in modal
    $(".featured-news-module").each(function() {
        $(document).on('click', 'a.new-modalvideo', function() {
            var modelVidHtml = $(this).parents('.featured-news-module').find('.embed-responsive'),
                modelVidId = $(this).attr("data-video-url");
            modelVidHtml.html("<iframe src=\"https://www.youtube.com/embed/" + modelVidId + "?rel=0&autoplay=1" + "\"></iframe>");
        });
    });

    // IT-677 play video in modal
    $(".featured-news-module").each(function() {
        $(document).on('click', 'a.new-latestmodal', function() {
            var latestVidHtml = $(this).parents('.featured-news-module').find('.embed-responsive'),
                latestVidId = $(this).attr("data-latestvideo-url");
            latestVidHtml.html("<iframe src=\"https://www.youtube.com/embed/" + latestVidId + "?rel=0&autoplay=1" + "\"></iframe>");
        });
    });

    // Close video in modal
    $(".modal").on('hide.bs.modal', function() {
        var modelHtml = $(this).find('.embed-responsive');
        modelHtml.html("");
    });

    $(document).on('click', 'button.close', function() {
        var modelHtml = $(this).parent(".modal-body").find('.embed-responsive');
        modelHtml.html("");
    });

    $(".modal").not(".modal .modal-content").on('click', function() {
        var modelHtml = $(this).find('.embed-responsive');
        modelHtml.html("");
    });

    //Video modal for iconCarousel
    $(".icon-carousel").each(function() {
        $(document).on('click', 'a.video-icon', function() {
            var iconVidHtml = $(this).parents('.icon-carousel').find('.vidMod .embed-responsive'),
                iconVidId = $(this).attr("data-video-url");
            iconVidHtml.html("<iframe src=\"https://www.youtube.com/embed/" + iconVidId + "?rel=0&autoplay=1" + "\"></iframe>");
        });
    });

    //frame modal for iconCarousel
    $(".icon-carousel").each(function() {
        $(document).on('click', 'a.frame-content', function() {
            var iconframeHtml = $(this).parents('.icon-carousel').find('.frameMod .embed-responsive'),
                iconframeId = $(this).attr("data-frame-url");
            iconframeHtml.html("<iframe src=" + iconframeId + "></iframe>");
        });
    });
});

window.onload = window.setTimeout(removeBrushStroke, 1000);


//Lazyload Fix for IE
$(window).on('load', function(){
    // var windowLocation = window.location.protocol+'//'+window.location.host,
    //     fpaLocation = windowLocation.includes('https://frasersproperty.com.au'),
    //     devLocation = windowLocation.includes('http://smlmsdaz.frasersproperty.com.au'),
    //     qaLocation = windowLocation.includes('https://smlmsqaaz.frasersproperty.com.au'),
    //     mqxLocation = windowLocation.includes('https://www.mqx.com.au'),
    //     mqxDevLocation = windowLocation.includes('https://smlms4daz.frasersproperty.com.au'),
 	// mqxQaLocation = windowLocation.includes('https://smlms4qaaz.frasersproperty.com.au'),
    //     cdEvn = $("#IsCd").length > 0
    //     cookieVal ='';
    
    // var IsFpa = fpaLocation || devLocation || qaLocation;
    // var IsMqx = mqxLocation || mqxDevLocation || mqxQaLocation;

    // if(IsFpa ) {
    //     cookieVal = '4e4e7fc0-d12b-4dce-9d05-cc1bad06cb15';
    // } 
    // else if (IsMqx) {
    //     cookieVal = 'e2172916-8eab-4022-a9e7-da8d5fb95612';
    // }

    // if((IsMqx || IsFpa  ) && cdEvn) {
    //     $("body").append('<script id="Cookiebot" src="https://consent.cookiebot.com/uc.js" data-cbid="'+cookieVal+'" data-blockingmode="auto" type="text/javascript"></script>');
    // } 

    if (document.documentMode || /Edge/.test(navigator.userAgent)) {
        $("img.lazy").each(function() {
            var newSrc = $(this).attr("data-src");
            $(this).attr("src", newSrc)
        });
    }

    if ($('body.shellcoveancora').length > 0 || $('body.shellcovevela').length > 0) {
        var carousel_heading_selector_h1 = $('.properties-carousel2 .slider-2 .slick-content h1');
        $.each(carousel_heading_selector_h1, function(){
        shellCoveBg($(this));
        });
        //console.log(carousel_heading_selector_h1);         
    } 

    if ($('body.shellcoveancora').length > 0 || $('body.shellcovevela').length > 0) {
        var carousel_heading_selector = $('.properties-carousel2 .slider-2 .slick-content h2');
        $.each(carousel_heading_selector, function(){
        shellCoveBg($(this));
        });
        //console.log(carousel_heading_selector);         
    }
});

$(document).ready(function() {
    
    // code moved here from PropertySearch.cshtml 
    if ($(".search-result-secondary-header.property-header").length > 0) {
        window.dcp.injectJSReference("property-filter.js", "/Resources/Assets/scripts/property-filter.js");
    }

    // code moved here from PropertyListing.cshtml and MediaGallery.cshtml and PortfolioListing.cshtml
    if ($('.search-result').length > 0 || $(".gallery-banner").length > 0 || $(".property-map-commercial").length > 0) {
        window.dcp.injectJSReference("plugins.js", "/Resources/Australand/Projects/js/plugins.js");
    }

    // code moved here from PropertyListing.cshtml and MediaGallery.cshtml
    if ($('.search-result.propertySearch').length > 0 || $(".gallery-banner").length > 0) {
        window.dcp.injectJSReference("property-map-list.js", "/Resources/Assets/scripts/property-map-list.js");
    }


    // code moved here from PortfolioListing.cshtml
    if ($(".property-map-commercial").length > 0) {
        window.dcp.injectJSReference("main.js", "/Resources/Australand/Projects/js/main.js");
    }

    //code moved here from SmpTopBanner.cshtml and StandardVideoLeft.cshtml and StandardVideoRight.cshtml
    var vid = $("section.properties-big-image, section.explore-image-content").data("img");
    $("#" + vid).on("click", function(e) {
        e.preventDefault()
        ShowVid($(this).data("vid"), $(this).attr("href"));
    });

    //code moved here from GeneralEnquiry.cshtml
    var selectionText = $('.opportunity-category .opportunity-selection').find(":selected").text();
    $(".number-of-bedrooms").css("display", "");
    var propertyType = $('.property-type .propertyType-selection').find(":selected").text();
    if (propertyType.toLowerCase().indexOf("land") >= 0) {
        $(".number-of-bedrooms").css("display", "none");
    }
    $('.property-type .propertyType-selection').change(function() {
        var propertyType = $('.property-type .propertyType-selection').find(":selected").text();
        if (propertyType.toLowerCase().indexOf("land") >= 0) {
            $(".number-of-bedrooms").css("display", "none");
        } else {
            $(".number-of-bedrooms").css("display", "");
        }
    });

    $(".marina-enquiry").css("display", "none");
    if (selectionText.toLowerCase().indexOf("marina") >= 0) {
        $(".common-query").css("display", "none");
        $(".corporate-query").css("display", "none");
        $(".marina-enquiry").css("display", "block");
    } else if ((selectionText.toLowerCase().indexOf("retail") >= 0) || (selectionText.toLowerCase().indexOf("commercial") >= 0) || (selectionText.toLowerCase().indexOf("office") >= 0) || (selectionText.toLowerCase().indexOf("business") >= 0)) {
        $(".common-query").css("display", "none");
        $(".marina-enquiry").css("display", "none");
        $(".corporate-query").css("display", "block");
    } else if ((selectionText.toLowerCase().indexOf("home") >= 0) || (selectionText.toLowerCase().indexOf("first") >= 0) || (selectionText.toLowerCase().indexOf("second") >= 0) || (selectionText.toLowerCase().indexOf("property") >= 0) || (selectionText.toLowerCase().indexOf("buyer") >= 0) || (selectionText.toLowerCase().indexOf("investor") >= 0)) {
        $(".marina-enquiry").css("display", "none");
        $(".common-query").css("display", "block");
        $(".corporate-query").css("display", "block");
    }


    //code moved here from Smp.cshtml
    if ($(".property-enquire-form").length > 0) {
        var property_form_js = $(".property-enquire-form").data("js");
        window.dcp.injectJSReference(property_form_js, property_form_js);
    }


    if ($('#submit')) {
        $('#submit').click(function(e) {
            e.preventDefault();
            $('.form-1').hide();
            $('.form-2').show();
            $('.steps li.step1').removeClass('active');
            $('.steps li.step2').addClass('active');
        });
        $('#back').click(function() {
            $('.form-2').fadeOut();
            $('.form-1').fadeIn();
            $('.steps li.step1').addClass('active');
            $('.steps li.step2').removeClass('active');
        });
    }

    // code moved here from WebCallBackButton.cshtml
    var url;
    var refUrl = window.location.pathname; //document.referrer;
    refUrl.replace("/", "_");

    if ($('#sc-callback-btn').length > 0) {

        url = $('#sc-callback-btn').attr("href");
        url = url + "?ref=" + refUrl;
        console.log(refUrl);
        $('#sc-callback-btn').attr("href", "#");
    }
    $('#sc-callback-btn').click(function() {
        //var url = window.location.protocol + '//' + window.location.hostname + '/Contact-Us/Request-A-Call';
        var height = 526;
        var width = 400;

        var left = (screen.width - width) / 2;
        var top = (screen.height - height) / 2;

        window.open(url, "Web Call Back", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
    });


    //code moved here from HotSpotImage.cshtml and HotSpots.cshtml
    if ($("section.sustainability").length > 0) {
        var sustain_js = $("section.sustainability").data('js');
        window.dcp.injectJSReference(sustain_js, sustain_js);
        //hide all three col matrix panels x
        $('[id^=threeColMatrix]').css("display", "none");
    }

    if (!$('body').hasClass('member')) {
        if ($('script[src*="vendor"]').length > 0) {
            $('img[usemap]').rwdImageMaps();
        }
    }


    //code moved here from OurPeople.cshtml
    var winHeight = $(window).height();

    function staffpop() {
        var halfWinHeight = winHeight / 2;
        var staffPhotoHeight = $('.staff-profile-wrap .image-link');
        var staffDetailHeight = $('.staff-profile-wrap .person-details');
        staffPhotoHeight.height(halfWinHeight);
        staffDetailHeight.height(halfWinHeight);
        console.log(staffPhotoHeight);
    }

    $('.people-main[id]').find(".person .see-profile").on('click', function(e) {
        e.preventDefault();
        $('body').append('<div class="full-screen-lock"></div>');
        $('.staff-profile-wrap').addClass('display');

        $('.people-main[id]').find("#people-carousel").clone().appendTo('.staff-profile');

        var startSlide = parseInt($(this).attr("data-staff-id"));
        staffpop();
        $(window).on('resize',function() {
            if ($(window).height() != winHeight) {
                winHeight = $(window).height();
                staffpop();
            }
        });

        if ($('.staff-profile-wrap').hasClass('display')) {
            //console.log("visible");
            $('.staff-profile-wrap #people-carousel').slick({
                slidesToShow: 1,
                infinite: true,
                dots: false,
                arrows: true,
                initialSlide: startSlide
            });
        } else {
            //console.log("invisible");
            $('.staff-profile-wrap #people-carousel').slick('unslick');
        }


        $('.full-screen-lock,.staff-profile .btn-close').on('click', function(e) {
            e.preventDefault();
            $('.staff-profile-wrap').removeClass('display');
            $('.full-screen-lock').remove();
            $('.staff-profile-wrap #people-carousel').remove();
        });
    });


    //code moved here from PropertyMap.cshtml
    if ($("section.maps-api").length > 0) {
        //var map_apijs = $("section.maps-api").data('js');
       // window.dcp.injectJSReference("property-map.js", "/Resources/Assets/scripts/property-map.js");
        $("body").append('<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDTkZauLKxFmJ3qW2jKsgjLvgt30kqJ3AM&callback=initMap"></script>');
        jQuery(function() {
            $('.maps-api .checkbox :checkbox').change(function () {
                deleteMarkers();
                $(".maps-api input:checkbox").each(function () {
                    //console.log('maps');
                    for (var i in mapdata.places) {
                        if (mapdata.places[i].type == this.name) {
                            if (this.checked) {
                                //console.log('checking');
                                mapdata.places[i].visible = true;
                            } else {
                                mapdata.places[i].visible = false;
                            }
                        }
                    }
                });
                plotMap(mapdata);
            });
            //$('.maps-type-list').draggable();
        });
    }

    // if($('script[src*="property-map.js"]').length === 0){
    //     if ($("section.maps-api").length > 0 ){
    //         $("body").append('<script src="/Resources/Assets/scripts/property-map.js"></script>');
    //     }
    // }

    //code moved here from GlobalMessage.cshtml 
    if ($(".msg-container").length > 0) {
        var yetVisited = localStorage['visited'];
        if (yetVisited) {
            $(".msg-container").css("display", "none");
        } else {
            $(".msg-container").css("display", "table-cell");
        }

        function closePromoPopup() {
            localStorage['visited'] = "yes";
            $(".msg-container").slideUp();
        }
    }


    //code moved here from PromotionPopup.cshtml
    function closePromoPopup() {
        $(".pop-up-container").css("display", "none");
        $(".pop-up-container-bg").css("display", "none");
    }


    //code moved here from MasterPlan.cshtml
    if ($('#maps').length > 0) {
        var map_js = $('#maps').data('js');
        window.dcp.injectJSReference(map_js, map_js);
    }


    //code moved here from TwoColumnsExpandableContent.cshtml
    if ($(".two-column-expandable").length > 0) {
        $("#btn_show_more").click(function() {
            $("#extended_content").slideToggle("slow");
            $(".extended_buttons").slideToggle("slow");
            $("#btn_show_more").slideToggle("slow");
            //$("#bottomleft-social-share").slideToggle("slow");
            $("section.two-column-expandable").focus();
        });
        $("#btn_show_less").click(function() {
            $("#extended_content").slideToggle("slow");
            $(".extended_buttons").slideToggle("slow");
            $("#btn_show_more").slideToggle("slow");
            //$("#bottomleft-social-share").slideToggle("slow");
            $("section.two-column-expandable").focus();
        });
    }


    //code moved here from CreateHouseAndLandDesign.cshtml
    $('.explore-image-content-with-logo').each(function() {
        var _this = $(this);
        var imgLogo = _this.find('.logo-holder img').length;
        if (imgLogo > 0) {
            _this.addClass('explore-logo-space');
        }
    });


    //code moved here from StickyNavSecondary.cshtml
    if ($('#sticky-nav-secondary').length > 0) {
        var second_nav_js = $('#sticky-nav-secondary').data('js');
        window.dcp.injectJSReference(second_nav_js, second_nav_js);
    }


    //code moved here from ResultsFilters.cshtml
    if ($('section.property-price-filter').length > 0) {
        if ($('section.property-price-filter').data('setPrice')) {
            $('section.property-price-filter').find('.range-slider').each(function(idx) {
                $(this).jRange('setValue', setPrice);
            });
        }
    }


    //code moved here from Header.cshtml inside project folder
    if ($('.property-sidebar').length > 0) {
        var header_js = $('.property-sidebar').data('js');
        window.dcp.injectJSReference(header_js, header_js);
    }

    //code moved here from PageLoadingBanner.cshtml
    if ($('#page-loading-banner').length > 0) {
        PageLoadingBanner(jQuery);
    }

    //code moved here from IframeModule.cshtml
    if ($("#iframe-module").length > 0) {
        var iframe_module_js = $('#iframe-module').data('js');
        window.dcp.injectJSReference(iframe_module_js, iframe_module_js);
    }

    //code moved here from LightboxPopup.cshtml
    if ($('#light-box-popup-2').length > 0) {
        var light_box_popup_js = $('#light-box-popup-2').data('js');
        window.dcp.injectJSReference(light_box_popup_js, light_box_popup_js);
    }

    //code moved here from WebCallBackFroms.cshtml
    if ($('#callback-iframe').length > 0) {
        let src_js = $('#callback-iframe').data('js');
        window.dcp.injectJSReference(src_js, src_js);
    }


    //code moved here from SearchResults.cshtml
    if ($('#propertyList').length > 0) {
        var propertyList = $('#propertyList').data('js');
        window.dcp.injectJSReference(propertyList, propertyList);
    }


  //code moved here from DisplayInstagramPost.cshtml
    if ($("section.join-social-facebook-module").length > 0) {
        var token = $("section.join-social-facebook-module").data('token'); // '1536183168.e994813.726db8e3123a49d3995f877f8d0302ad',
        var num_photos = $("section.join-social-facebook-module").data('numofphotos');
        //num_photos = 12

        $.ajax({
            url: `https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,thumbnail_url,timestamp,permalink&access_token=${token}`,
            dataType: 'jsonp',
            type: 'GET',
            data: { access_token: token, count: num_photos },
            success: function(data) {

                for (x in data.data) {
                    $('.instagram-wrap').append('<article class="small-media-item"><div class="media-wrap">' +
                        '<a target="_blank" href="' +
                        data.data[x].permalink +
                        '"><div class="social-icon"><i class="instagram icon"></i></div>' +
                        '<img src="' +
                        data.data[x].media_url +
                        '" height="341" width="260">' +
                        '<div class="text-content">' +
                        '<div class="h7">' +
                        Date(data.data[x].timestamp).substring(4, 10) +
                        '</div>' +
                        '<div class="body-copy">' +
                        '<p>' +
                        data.data[x].caption.substring(0, 175) +
                        '...' +
                        '</p><br><span class="link">' +
                        $('#templateCtaText').html() +
                        '</span></div></div>' +
                        '</a>' +
                        '</div></article>');
                }
                instaMediaCarousel();
                addClassInsta();
            },
            error: function(data) {
                console.log(data);
            }
        });
    }

    //code moved here from MatrixHolder.cshtml
    if ($('section.prosperity-member-module').length > 0) {
        var member_Module = $('section.prosperity-member-module').data('js');
        window.dcp.injectJSReference(member_Module, member_Module);
    }

    //code moved here from _WebChat.cshtml
    if ($('#webChatTrigger').length > 0) {
        var webChatWindowObjectReference = null;
        $('#webChatTrigger').on('click',function() {

            if (webChatWindowObjectReference == null || webChatWindowObjectReference.closed) {
                var itemId = $("#txt_id").val();
                itemId = encodeURIComponent(itemId);
                var url = $('#webchatpg').val();
                url += '?ref=' + window.location.pathname + "&id=" + itemId;
                console.log(url);
                var height = 475;
                var width = 445;

                //var left = (screen.width / 2) - (width / 2);
                //var top = (screen.height / 2) - (height / 2);
                var top = screen.height - height - (height / 2);
                var left = screen.width - width - (width / 2);

                //window.open(url, "Live Chat", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
                window.open(url, "Live Chat", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
            } else { webChatWindowObjectReference.focus(); }
        });

        setTimeout(function() { $("#webChatButtonDiv").css('display', 'block'); }, 10000);
    }


    //code moved here from JoinProsperityForm.cshtml and ReferralForm.cshtml
    if ($('.purchase-property').length > 0) {
        window.dcp.injectJSReference("scripts.js", "/Resources/Prosperity/js/scripts.js");
    }

    
    //load fullwidth carousel
    $(".full-width-carousel .slick-slider").slick("refresh");
    
    //code moved here from JoinProsperityForm.cshtml and ReferralForm.cshtml
    if ($('.full-width-banner').length > 0 || $('.hotspot-module').length > 0 || $('.full-size-image-promo').length > 0 || $('.explore-image-content').length > 0 || $('.matrix-item').length > 0 || $('.column.lazy').length > 0 || $('.the-collection-module').length > 0) {
        window.dcp.injectJSReference("jstriggergoal.js", "/Resources/Assets/scripts/jstriggergoal.js");
    }

    //scroll animation to form section on submit
    if($("form.wffm-form").length > 0) {
        var resetAnimate,
        getValueIn = "";
        var formSelector = $("form.wffm-form"),
        sectionFormOffset = formSelector.offset().top - 150;
        function startFormAnimation() {
            if(formSelector.length > 0) {
                var getNewInValue = $("form.wffm-form .btn-default").next().val();
                if(getValueIn != getNewInValue) {
                    $("html, body").animate({
                        scrollTop: sectionFormOffset
                    }, 2000);
                    clearTimeout(resetAnimate);
                }
            } else {
                clearTimeout(resetAnimate); 
            }
        }

        $("form.wffm-form .btn-default").click(function() {
            getValueIn = $("form.wffm-form .btn-default").next().val();
            setTimeout(function(){
                resetAnimate = setInterval(startFormAnimation, 4000);
            }, 1000);
        });
    }

    //fix for hiding play button and image while playing video
    $(".media-carousel-wrap .media-carousel").each(function(){
        $(this).find(".media-item").each(function(){
            $(this).find(".play-button").on("click", function(){
                $(this).fadeOut('fast');
                $(this).parent().find('img').fadeOut('fast');
            });
        });
    });

    $(".media-carousel-wrap .media-carousel").each(function(){
        $(this).find(".slick-arrow").on("click", function(){
            $(this).parent().find(".media-wrap img.youtube-thumbnail").fadeIn('fast');
            $(this).parent().find(".media-wrap img").fadeIn('fast');
        });
    });

    $(".media-carousel-wrap .media-carousel").each(function(){
        $(this).on("beforeChange", function(event, slick) {
            $(this).find(".media-wrap img.youtube-thumbnail").fadeIn('fast');
            $(this).find(".media-wrap img").fadeIn('fast');
        });
    });

    //hack for loading images if user as declined cookie
    window.addEventListener('CookiebotOnDecline', function (e) {
        // check if user has responded to cookies option
        if (Cookiebot.hasResponse) {
            //re-initialize your lazy
            $(window).scroll(function(){
                setTimeout(function() {
                    $("img.lazy").each(function() {
                        var newSrc = $(this).attr("data-src");
                        $(this).attr("src", newSrc)
                    });
                }, 1000);
            });
        }
    }, false);

});

    ;
